test.cc 852 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // A valid numeric prefix does not make the entire quality value valid.
  892. EXPECT_FALSE(detail::parse_accept_header(
  893. "text/html;q=0.5junk,application/json", result));
  894. // Empty quality value
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("text/html;q=,application/json", result));
  897. // Invalid media type format (no slash and not wildcard)
  898. EXPECT_FALSE(
  899. detail::parse_accept_header("invalidtype,application/json", result));
  900. // Valid cases should still work
  901. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*/*");
  904. EXPECT_TRUE(detail::parse_accept_header("*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*");
  907. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "text/*");
  910. }
  911. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  912. // elements, so a leading, trailing or doubled comma is a legal Accept value
  913. // and must not be answered with 400 Bad Request.
  914. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  915. struct {
  916. const char *value;
  917. std::vector<std::string> expected;
  918. } cases[] = {
  919. {",application/json", {"application/json"}},
  920. {"text/html,", {"text/html"}},
  921. {"text/html,,*/*", {"text/html", "*/*"}},
  922. // An empty element may be spelled with whitespace in it
  923. {"text/html, , application/json", {"text/html", "application/json"}},
  924. // Nothing but empty elements is an empty list, which means the same
  925. // thing as no Accept header at all
  926. {",,,", {}},
  927. // Quality values still apply across ignored empty elements
  928. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  929. };
  930. for (const auto &c : cases) {
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  933. << "value: " << c.value;
  934. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  935. }
  936. // An invalid entry is still rejected when empty elements surround it
  937. std::vector<std::string> result;
  938. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  939. }
  940. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  941. Server svr;
  942. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  943. EXPECT_EQ(req.accept_content_types.size(), 3U);
  944. EXPECT_EQ(req.accept_content_types[0], "application/json");
  945. EXPECT_EQ(req.accept_content_types[1], "text/html");
  946. EXPECT_EQ(req.accept_content_types[2], "*/*");
  947. res.set_content("ok", "text/plain");
  948. });
  949. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  950. EXPECT_TRUE(false);
  951. res.set_content("bad request", "text/plain");
  952. });
  953. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  954. auto se = detail::scope_exit([&] {
  955. svr.stop();
  956. listen_thread.join();
  957. ASSERT_FALSE(svr.is_running());
  958. });
  959. svr.wait_until_ready();
  960. Client cli("localhost", PORT);
  961. {
  962. auto res = cli.Get(
  963. "/accept_ok",
  964. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  966. EXPECT_EQ(StatusCode::OK_200, res->status);
  967. }
  968. {
  969. auto res = cli.Get("/accept_bad_request",
  970. Headers{{"Accept", "text/html;q=abc,application/json"}});
  971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  972. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  973. }
  974. }
  975. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  976. Server svr;
  977. svr.Get("/", [](const Request & /*req*/, Response &res) {
  978. res.set_content("ok", "text/plain");
  979. });
  980. std::atomic<int> start_count{0};
  981. std::atomic<bool> running_when_called{false};
  982. svr.set_start_handler([&]() {
  983. running_when_called = svr.is_running();
  984. start_count++;
  985. });
  986. auto port = svr.bind_to_any_port(HOST);
  987. std::thread t([&]() { svr.listen_after_bind(); });
  988. auto se = detail::scope_exit([&] {
  989. svr.stop();
  990. t.join();
  991. ASSERT_FALSE(svr.is_running());
  992. });
  993. svr.wait_until_ready();
  994. // A successful request proves the accept loop is running, which the start
  995. // handler precedes; so by now the handler must have run exactly once.
  996. Client cli(HOST, port);
  997. cli.set_connection_timeout(std::chrono::seconds(5));
  998. auto res = cli.Get("/");
  999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1000. EXPECT_EQ(StatusCode::OK_200, res->status);
  1001. EXPECT_EQ(1, start_count.load());
  1002. EXPECT_TRUE(running_when_called.load());
  1003. }
  1004. TEST(DivideTest, DivideStringTests) {
  1005. auto divide = [](const std::string &str, char d) {
  1006. std::string lhs;
  1007. std::string rhs;
  1008. detail::divide(str, d,
  1009. [&](const char *lhs_data, std::size_t lhs_size,
  1010. const char *rhs_data, std::size_t rhs_size) {
  1011. lhs.assign(lhs_data, lhs_size);
  1012. rhs.assign(rhs_data, rhs_size);
  1013. });
  1014. return std::make_pair(std::move(lhs), std::move(rhs));
  1015. };
  1016. {
  1017. const auto res = divide("", '=');
  1018. EXPECT_EQ(res.first, "");
  1019. EXPECT_EQ(res.second, "");
  1020. }
  1021. {
  1022. const auto res = divide("=", '=');
  1023. EXPECT_EQ(res.first, "");
  1024. EXPECT_EQ(res.second, "");
  1025. }
  1026. {
  1027. const auto res = divide(" ", '=');
  1028. EXPECT_EQ(res.first, " ");
  1029. EXPECT_EQ(res.second, "");
  1030. }
  1031. {
  1032. const auto res = divide("a", '=');
  1033. EXPECT_EQ(res.first, "a");
  1034. EXPECT_EQ(res.second, "");
  1035. }
  1036. {
  1037. const auto res = divide("a=", '=');
  1038. EXPECT_EQ(res.first, "a");
  1039. EXPECT_EQ(res.second, "");
  1040. }
  1041. {
  1042. const auto res = divide("=b", '=');
  1043. EXPECT_EQ(res.first, "");
  1044. EXPECT_EQ(res.second, "b");
  1045. }
  1046. {
  1047. const auto res = divide("a=b", '=');
  1048. EXPECT_EQ(res.first, "a");
  1049. EXPECT_EQ(res.second, "b");
  1050. }
  1051. {
  1052. const auto res = divide("a=b=", '=');
  1053. EXPECT_EQ(res.first, "a");
  1054. EXPECT_EQ(res.second, "b=");
  1055. }
  1056. {
  1057. const auto res = divide("a=b=c", '=');
  1058. EXPECT_EQ(res.first, "a");
  1059. EXPECT_EQ(res.second, "b=c");
  1060. }
  1061. }
  1062. TEST(SplitTest, ParseQueryString) {
  1063. string s = "key1=val1&key2=val2&key3=val3";
  1064. Params dic;
  1065. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1066. [&](const char *b, const char *e) {
  1067. string key, val;
  1068. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1069. if (key.empty()) {
  1070. key.assign(b2, e2);
  1071. } else {
  1072. val.assign(b2, e2);
  1073. }
  1074. });
  1075. dic.emplace(key, val);
  1076. });
  1077. EXPECT_EQ("val1", dic.find("key1")->second);
  1078. EXPECT_EQ("val2", dic.find("key2")->second);
  1079. EXPECT_EQ("val3", dic.find("key3")->second);
  1080. }
  1081. TEST(SplitTest, ParseInvalidQueryTests) {
  1082. {
  1083. string s = " ";
  1084. Params dict;
  1085. detail::parse_query_text(s, dict);
  1086. EXPECT_TRUE(dict.empty());
  1087. }
  1088. {
  1089. string s = " = =";
  1090. Params dict;
  1091. detail::parse_query_text(s, dict);
  1092. EXPECT_TRUE(dict.empty());
  1093. }
  1094. }
  1095. TEST(ParseQueryTest, ParseQueryString) {
  1096. {
  1097. std::string s = "key1=val1&key2=val2&key3=val3";
  1098. Params dic;
  1099. detail::parse_query_text(s, dic);
  1100. EXPECT_EQ("val1", dic.find("key1")->second);
  1101. EXPECT_EQ("val2", dic.find("key2")->second);
  1102. EXPECT_EQ("val3", dic.find("key3")->second);
  1103. }
  1104. {
  1105. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1106. Params dic;
  1107. detail::parse_query_text(s, dic);
  1108. EXPECT_EQ("", dic.find("key1")->second);
  1109. EXPECT_EQ("val1", dic.find("key2")->second);
  1110. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1111. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1112. }
  1113. }
  1114. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1115. Params dic;
  1116. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1117. dic.emplace("key1", "val1");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1119. dic.emplace("key2", "val2");
  1120. dic.emplace("key3", "val3");
  1121. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1122. }
  1123. // Joins every entry of a Headers or Params into "key=value " so a whole
  1124. // traversal can be compared in one assertion. Both are instantiations of the
  1125. // same insertion-ordered container, so one helper serves both.
  1126. template <typename Map> static std::string entries_to_string(const Map &m) {
  1127. std::string s;
  1128. for (const auto &entry : m) {
  1129. s += entry.first + "=" + entry.second + " ";
  1130. }
  1131. return s;
  1132. }
  1133. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1134. // Params used to be a std::multimap, which sorted by name and handed the
  1135. // caller's query back alphabetised. A client signing its query string could
  1136. // not reproduce the order it asked for.
  1137. Params dic;
  1138. dic.emplace("zulu", "1");
  1139. dic.emplace("alpha", "2");
  1140. dic.emplace("mike", "3");
  1141. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1142. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1143. }
  1144. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1145. Params dic;
  1146. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1147. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1148. }
  1149. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1150. Request req;
  1151. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1152. req.params);
  1153. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1154. EXPECT_EQ("first", req.get_param_value("tag"));
  1155. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1156. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1157. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1158. EXPECT_EQ("", req.get_param_value("tag", 3));
  1159. }
  1160. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1161. // Params shares its container with Headers, which matches field names
  1162. // case-insensitively. Parameter names must not pick that up.
  1163. Params dic;
  1164. dic.emplace("Key", "upper");
  1165. dic.emplace("key", "lower");
  1166. EXPECT_EQ(2U, dic.size());
  1167. EXPECT_EQ(1U, dic.count("Key"));
  1168. EXPECT_EQ(1U, dic.count("key"));
  1169. EXPECT_EQ("upper", dic.find("Key")->second);
  1170. EXPECT_EQ("lower", dic.find("key")->second);
  1171. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1172. }
  1173. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1174. Server svr;
  1175. std::string order;
  1176. svr.Get("/order", [&](const Request &req, Response &res) {
  1177. order = entries_to_string(req.params);
  1178. res.set_content("ok", "text/plain");
  1179. });
  1180. auto port = svr.bind_to_any_port(HOST);
  1181. thread t = thread([&] { svr.listen_after_bind(); });
  1182. auto se = detail::scope_exit([&] {
  1183. svr.stop();
  1184. t.join();
  1185. ASSERT_FALSE(svr.is_running());
  1186. });
  1187. svr.wait_until_ready();
  1188. Client cli(HOST, port);
  1189. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1190. ASSERT_TRUE(res);
  1191. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1192. }
  1193. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1194. Server svr;
  1195. std::string field_order, file_order;
  1196. svr.Post("/order", [&](const Request &req, Response &res) {
  1197. for (const auto &field : req.form.fields) {
  1198. field_order += field.first + "=" + field.second.content + " ";
  1199. }
  1200. for (const auto &file : req.form.files) {
  1201. file_order += file.first + "=" + file.second.filename + " ";
  1202. }
  1203. res.set_content("ok", "text/plain");
  1204. });
  1205. auto port = svr.bind_to_any_port(HOST);
  1206. thread t = thread([&] { svr.listen_after_bind(); });
  1207. auto se = detail::scope_exit([&] {
  1208. svr.stop();
  1209. t.join();
  1210. ASSERT_FALSE(svr.is_running());
  1211. });
  1212. svr.wait_until_ready();
  1213. UploadFormDataItems items = {
  1214. {"zulu", "1", "", ""},
  1215. {"alpha", "2", "", ""},
  1216. {"mike", "3", "", ""},
  1217. {"zebra", "z", "z.txt", "text/plain"},
  1218. {"apple", "a", "a.txt", "text/plain"},
  1219. };
  1220. Client cli(HOST, port);
  1221. auto res = cli.Post("/order", items);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1224. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1225. }
  1226. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1227. Server svr;
  1228. std::vector<std::string> values;
  1229. std::string first, second, out_of_range, order;
  1230. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1231. values = req.form.get_fields("tag");
  1232. first = req.form.get_field("tag", 0);
  1233. second = req.form.get_field("tag", 1);
  1234. out_of_range = req.form.get_field("tag", 2);
  1235. for (const auto &field : req.form.fields) {
  1236. order += field.first + "=" + field.second.content + " ";
  1237. }
  1238. res.set_content("ok", "text/plain");
  1239. });
  1240. auto port = svr.bind_to_any_port(HOST);
  1241. thread t = thread([&] { svr.listen_after_bind(); });
  1242. auto se = detail::scope_exit([&] {
  1243. svr.stop();
  1244. t.join();
  1245. ASSERT_FALSE(svr.is_running());
  1246. });
  1247. svr.wait_until_ready();
  1248. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1249. // not adjacent in the container.
  1250. UploadFormDataItems items = {
  1251. {"tag", "first", "", ""},
  1252. {"other", "x", "", ""},
  1253. {"tag", "second", "", ""},
  1254. };
  1255. Client cli(HOST, port);
  1256. auto res = cli.Post("/repeated", items);
  1257. ASSERT_TRUE(res);
  1258. ASSERT_EQ(2U, values.size());
  1259. EXPECT_EQ("first", values[0]);
  1260. EXPECT_EQ("second", values[1]);
  1261. EXPECT_EQ("first", first);
  1262. EXPECT_EQ("second", second);
  1263. // std::multimap already kept entries sharing a name in insertion order, so
  1264. // everything above passes without this change too. The whole traversal is
  1265. // what tells the two apart: sorting by name would hoist "other" to the front
  1266. // and the two "tag" parts would end up adjacent.
  1267. EXPECT_EQ("tag=first other=x tag=second ", order);
  1268. // Advancing past the last entry of a name used to run off the container;
  1269. // the container's saturating increment makes it return the default instead.
  1270. EXPECT_EQ("", out_of_range);
  1271. }
  1272. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1273. // Server::read_content() keeps a FormFields::iterator alive across the
  1274. // content callbacks that fill the part it points at. The container is
  1275. // vector-backed, so a later emplace can reallocate and invalidate an older
  1276. // iterator; 64 parts grow the vector through seven reallocations, which
  1277. // checks that every part's content still lands in its own entry.
  1278. const size_t part_count = 64;
  1279. // One formula for both the parts sent and the values expected back, so the
  1280. // two cannot drift apart.
  1281. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1282. auto content_of = [](size_t i) {
  1283. return std::string(64, static_cast<char>('a' + (i % 26)));
  1284. };
  1285. Server svr;
  1286. std::vector<std::pair<std::string, std::string>> received;
  1287. svr.Post("/many", [&](const Request &req, Response &res) {
  1288. for (const auto &field : req.form.fields) {
  1289. received.emplace_back(field.first, field.second.content);
  1290. }
  1291. res.set_content("ok", "text/plain");
  1292. });
  1293. auto port = svr.bind_to_any_port(HOST);
  1294. thread t = thread([&] { svr.listen_after_bind(); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. t.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. UploadFormDataItems items;
  1302. for (size_t i = 0; i < part_count; i++) {
  1303. items.push_back({name_of(i), content_of(i), "", ""});
  1304. }
  1305. Client cli(HOST, port);
  1306. auto res = cli.Post("/many", items);
  1307. ASSERT_TRUE(res);
  1308. ASSERT_EQ(part_count, received.size());
  1309. for (size_t i = 0; i < part_count; i++) {
  1310. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1311. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1312. }
  1313. }
  1314. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1315. string content_type = "multipart/form-data; boundary=something";
  1316. string boundary;
  1317. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1318. EXPECT_TRUE(ret);
  1319. EXPECT_EQ(boundary, "something");
  1320. }
  1321. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1322. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1323. string boundary;
  1324. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1325. EXPECT_TRUE(ret);
  1326. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1327. }
  1328. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1329. string content_type =
  1330. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1331. string boundary;
  1332. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1333. EXPECT_TRUE(ret);
  1334. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1335. }
  1336. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1337. string content_type =
  1338. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1339. string boundary;
  1340. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1341. EXPECT_TRUE(ret);
  1342. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1343. }
  1344. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1345. const string boundary(70, 'a');
  1346. string content_type = "multipart/form-data; boundary=" + boundary;
  1347. string parsed;
  1348. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1349. EXPECT_TRUE(ret);
  1350. EXPECT_EQ(parsed, boundary);
  1351. }
  1352. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1353. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1354. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1355. string parsed;
  1356. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1357. EXPECT_FALSE(ret);
  1358. }
  1359. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1360. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1361. // is 72 characters on the wire and still valid.
  1362. const string boundary(70, 'a');
  1363. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1364. string parsed;
  1365. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1366. EXPECT_EQ(parsed, boundary);
  1367. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1368. parsed.clear();
  1369. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1370. }
  1371. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1372. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1373. // The parameter parser must not treat that '=' as the key/value separator.
  1374. string content_type =
  1375. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1376. "charset=UTF-8";
  1377. string parsed;
  1378. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1379. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1380. }
  1381. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1382. // A ';' inside the quoted-string is part of the value, not a parameter
  1383. // separator, so it must not truncate the boundary.
  1384. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1385. string parsed;
  1386. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1387. EXPECT_EQ(parsed, "a;b");
  1388. }
  1389. TEST(ParseDispositionParamsTest, QuotedValues) {
  1390. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1391. // ';' and '=' are ordinary characters inside one.
  1392. struct {
  1393. const char *value;
  1394. std::vector<std::pair<const char *, const char *>> expected;
  1395. } cases[] = {
  1396. {"name=\"file1\"; filename=\"a.txt\"",
  1397. {{"name", "file1"}, {"filename", "a.txt"}}},
  1398. // Whitespace around '=' and ';' is still trimmed
  1399. {"name=\"file2\" ;filename = \"a.html\"",
  1400. {{"name", "file2"}, {"filename", "a.html"}}},
  1401. // '=' inside the value used to leave only the text after the last one
  1402. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1403. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1404. {"name=\"x=y\"", {{"name", "x=y"}}},
  1405. // ';' inside the value used to truncate the pair and leave a bogus one
  1406. {"name=\"file3\"; filename=\"a;b.txt\"",
  1407. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1408. // An unquoted value keeps working, and so does filename*
  1409. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1410. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1411. // A parameter with no key is dropped rather than turned into one whose
  1412. // key is the value
  1413. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1414. };
  1415. for (const auto &c : cases) {
  1416. Params params;
  1417. detail::parse_disposition_params(c.value, params);
  1418. for (const auto &kv : c.expected) {
  1419. auto it = params.find(kv.first);
  1420. ASSERT_NE(it, params.end())
  1421. << "value: " << c.value << ", key: " << kv.first;
  1422. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1423. }
  1424. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1425. }
  1426. }
  1427. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1428. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1429. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1430. Server svr;
  1431. std::string field_value, file_name, file_filename;
  1432. bool has_field = false, has_file = false;
  1433. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1434. has_field = req.form.has_field("x=y");
  1435. field_value = req.form.get_field("x=y");
  1436. has_file = req.form.has_file("file1");
  1437. const auto &file = req.form.get_file("file1");
  1438. file_name = file.name;
  1439. file_filename = file.filename;
  1440. res.set_content("ok", "text/plain");
  1441. });
  1442. auto port = svr.bind_to_any_port(HOST);
  1443. thread t = thread([&] { svr.listen_after_bind(); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. t.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. UploadFormDataItems items = {
  1451. {"x=y", "field-value", "", ""},
  1452. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1453. };
  1454. Client cli(HOST, port);
  1455. auto res = cli.Post("/quoted", items);
  1456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1457. ASSERT_EQ(StatusCode::OK_200, res->status);
  1458. EXPECT_TRUE(has_field);
  1459. EXPECT_EQ("field-value", field_value);
  1460. EXPECT_TRUE(has_file);
  1461. EXPECT_EQ("file1", file_name);
  1462. EXPECT_EQ("a;b=report.pdf", file_filename);
  1463. }
  1464. TEST(GetHeaderValueTest, DefaultValue) {
  1465. Headers headers = {{"Dummy", "Dummy"}};
  1466. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1467. EXPECT_STREQ("text/plain", val);
  1468. }
  1469. TEST(GetHeaderValueTest, DefaultValueInt) {
  1470. Headers headers = {{"Dummy", "Dummy"}};
  1471. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1472. EXPECT_EQ(100ull, val);
  1473. }
  1474. TEST(GetHeaderValueTest, RegularValue) {
  1475. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1476. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1477. EXPECT_STREQ("text/html", val);
  1478. }
  1479. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1480. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1481. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1482. EXPECT_STREQ("text/html", val);
  1483. }
  1484. TEST(GetHeaderValueTest, SetContent) {
  1485. Response res;
  1486. res.set_content("html", "text/html");
  1487. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1488. res.set_content("text", "text/plain");
  1489. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1490. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1491. }
  1492. TEST(GetHeaderValueTest, RegularValueInt) {
  1493. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1494. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1495. EXPECT_EQ(100ull, val);
  1496. }
  1497. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1498. Headers headers = {{"Content-Length", "x"}};
  1499. auto is_invalid_value = false;
  1500. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1501. is_invalid_value);
  1502. EXPECT_EQ(0ull, val);
  1503. EXPECT_TRUE(is_invalid_value);
  1504. }
  1505. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1506. // An all-digit value that overflows size_t must be reported as invalid, not
  1507. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1508. // a large length to a small one on 32-bit builds, leaving the framing length
  1509. // wrong while is_invalid_value stayed false.
  1510. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1511. auto is_invalid_value = false;
  1512. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1513. is_invalid_value);
  1514. EXPECT_TRUE(is_invalid_value);
  1515. // A well-formed length is unaffected.
  1516. Headers ok = {{"Content-Length", "1234"}};
  1517. is_invalid_value = false;
  1518. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1519. is_invalid_value);
  1520. EXPECT_EQ(1234ull, val);
  1521. EXPECT_FALSE(is_invalid_value);
  1522. }
  1523. TEST(GetHeaderValueTest, Range) {
  1524. {
  1525. Headers headers = {make_range_header({{1, -1}})};
  1526. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1527. EXPECT_STREQ("bytes=1-", val);
  1528. }
  1529. {
  1530. Headers headers = {make_range_header({{-1, 1}})};
  1531. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1532. EXPECT_STREQ("bytes=-1", val);
  1533. }
  1534. {
  1535. Headers headers = {make_range_header({{1, 10}})};
  1536. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1537. EXPECT_STREQ("bytes=1-10", val);
  1538. }
  1539. {
  1540. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1541. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1542. EXPECT_STREQ("bytes=1-10, 100-", val);
  1543. }
  1544. {
  1545. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1546. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1547. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1548. }
  1549. {
  1550. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1551. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1552. EXPECT_STREQ("bytes=0-0, -1", val);
  1553. }
  1554. }
  1555. TEST(BearerTokenAuthTest, SchemeValidation) {
  1556. // A value shorter than "Bearer " must not throw from the fixed-length
  1557. // substr, and a non-Bearer scheme must not be reported as a token.
  1558. struct {
  1559. const char *value;
  1560. const char *expected;
  1561. } cases[] = {
  1562. {"x", ""},
  1563. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1564. {"Bearer abc123", "abc123"},
  1565. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1566. };
  1567. for (const auto &c : cases) {
  1568. Request req;
  1569. req.set_header("Authorization", c.value);
  1570. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1571. }
  1572. }
  1573. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1574. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1575. // to depend on the standard library (libstdc++ handed back duplicates in
  1576. // reverse insertion order, libc++ in insertion order).
  1577. Request req;
  1578. req.set_header("Accept-Encoding", "gzip");
  1579. req.set_header("Accept-Encoding", "deflate");
  1580. req.set_header("Accept-Encoding", "br");
  1581. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1582. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1583. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1584. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1585. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1586. }
  1587. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1588. Request req;
  1589. req.set_header("X-Test", "only");
  1590. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1591. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1592. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1593. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1594. }
  1595. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1596. Headers headers;
  1597. headers.emplace("Host", "example.com");
  1598. headers.emplace("Accept-Encoding", "gzip");
  1599. headers.emplace("User-Agent", "test");
  1600. headers.emplace("Accept-Encoding", "deflate");
  1601. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1602. "Accept-Encoding=deflate ",
  1603. entries_to_string(headers));
  1604. }
  1605. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1606. Headers headers = {{"Content-Type", "text/html"},
  1607. {"CONTENT-TYPE", "text/xml"}};
  1608. EXPECT_EQ(2U, headers.count("content-type"));
  1609. auto it = headers.find("content-type");
  1610. ASSERT_TRUE(it != headers.end());
  1611. EXPECT_EQ("text/html", it->second);
  1612. }
  1613. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1614. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1615. // drop only those fields and leave everything positioned between them.
  1616. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1617. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1618. auto rng = headers.equal_range("a");
  1619. headers.erase(rng.first, rng.second);
  1620. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1621. }
  1622. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1623. Headers headers = {
  1624. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1625. EXPECT_EQ(3U, headers.erase("A"));
  1626. EXPECT_EQ(0U, headers.count("A"));
  1627. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1628. }
  1629. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1630. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1631. headers.emplace_front("Host", "example.com");
  1632. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1633. entries_to_string(headers));
  1634. }
  1635. TEST(ParseHeaderValueTest, Range) {
  1636. {
  1637. Ranges ranges;
  1638. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1639. EXPECT_TRUE(ret);
  1640. EXPECT_EQ(1u, ranges.size());
  1641. EXPECT_EQ(1u, ranges[0].first);
  1642. EXPECT_EQ(-1, ranges[0].second);
  1643. }
  1644. {
  1645. Ranges ranges;
  1646. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1647. EXPECT_TRUE(ret);
  1648. EXPECT_EQ(1u, ranges.size());
  1649. EXPECT_EQ(-1, ranges[0].first);
  1650. EXPECT_EQ(1u, ranges[0].second);
  1651. }
  1652. {
  1653. Ranges ranges;
  1654. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(1u, ranges.size());
  1657. EXPECT_EQ(1u, ranges[0].first);
  1658. EXPECT_EQ(10u, ranges[0].second);
  1659. }
  1660. {
  1661. Ranges ranges;
  1662. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1663. EXPECT_FALSE(ret);
  1664. }
  1665. {
  1666. Ranges ranges;
  1667. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1668. EXPECT_TRUE(ret);
  1669. EXPECT_EQ(2u, ranges.size());
  1670. EXPECT_EQ(1u, ranges[0].first);
  1671. EXPECT_EQ(10u, ranges[0].second);
  1672. EXPECT_EQ(100u, ranges[1].first);
  1673. EXPECT_EQ(-1, ranges[1].second);
  1674. }
  1675. {
  1676. Ranges ranges;
  1677. auto ret =
  1678. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1679. EXPECT_TRUE(ret);
  1680. EXPECT_EQ(3u, ranges.size());
  1681. EXPECT_EQ(1u, ranges[0].first);
  1682. EXPECT_EQ(10u, ranges[0].second);
  1683. EXPECT_EQ(100u, ranges[1].first);
  1684. EXPECT_EQ(200u, ranges[1].second);
  1685. EXPECT_EQ(300u, ranges[2].first);
  1686. EXPECT_EQ(400u, ranges[2].second);
  1687. }
  1688. {
  1689. Ranges ranges;
  1690. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1700. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1701. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1702. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1703. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1704. EXPECT_FALSE(
  1705. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1706. EXPECT_TRUE(ranges.empty());
  1707. }
  1708. {
  1709. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1710. // remainder of the representation, so it stays accepted.
  1711. Ranges ranges;
  1712. auto ret =
  1713. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1714. EXPECT_TRUE(ret);
  1715. ASSERT_EQ(1u, ranges.size());
  1716. EXPECT_EQ(0, ranges[0].first);
  1717. EXPECT_EQ(-1, ranges[0].second);
  1718. }
  1719. }
  1720. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1721. Request req;
  1722. req.set_header("Accept-Encoding", "gzip");
  1723. Response res;
  1724. res.set_header("Content-Type", "text/plain");
  1725. auto ret = detail::encoding_type(req, res);
  1726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1727. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1728. #else
  1729. EXPECT_TRUE(ret == detail::EncodingType::None);
  1730. #endif
  1731. }
  1732. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1733. Request req;
  1734. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1735. Response res;
  1736. res.set_header("Content-Type", "text/plain");
  1737. auto ret = detail::encoding_type(req, res);
  1738. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1739. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1740. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1741. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1742. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1743. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1744. #else
  1745. EXPECT_TRUE(ret == detail::EncodingType::None);
  1746. #endif
  1747. }
  1748. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1749. Request req;
  1750. req.set_header("Accept-Encoding",
  1751. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1752. Response res;
  1753. res.set_header("Content-Type", "text/plain");
  1754. auto ret = detail::encoding_type(req, res);
  1755. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1756. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1757. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1758. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1759. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1760. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1761. #else
  1762. EXPECT_TRUE(ret == detail::EncodingType::None);
  1763. #endif
  1764. }
  1765. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1766. // All supported encodings rejected with q=0 should return None
  1767. Request req;
  1768. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1769. Response res;
  1770. res.set_header("Content-Type", "text/plain");
  1771. auto ret = detail::encoding_type(req, res);
  1772. EXPECT_TRUE(ret == detail::EncodingType::None);
  1773. }
  1774. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1775. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1776. Request req;
  1777. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1778. Response res;
  1779. res.set_header("Content-Type", "text/plain");
  1780. auto ret = detail::encoding_type(req, res);
  1781. EXPECT_TRUE(ret == detail::EncodingType::None);
  1782. }
  1783. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1784. Request req;
  1785. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1786. Response res;
  1787. res.set_header("Content-Type", "text/plain");
  1788. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1789. }
  1790. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1791. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1792. Request req;
  1793. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1794. Response res;
  1795. res.set_header("Content-Type", "text/plain");
  1796. auto ret = detail::encoding_type(req, res);
  1797. EXPECT_TRUE(ret == detail::EncodingType::None);
  1798. }
  1799. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1800. // RFC 7231: Accept-Encoding values are case-insensitive
  1801. Request req;
  1802. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1803. Response res;
  1804. res.set_header("Content-Type", "text/plain");
  1805. auto ret = detail::encoding_type(req, res);
  1806. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1807. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1808. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1809. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1810. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1811. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1812. #else
  1813. EXPECT_TRUE(ret == detail::EncodingType::None);
  1814. #endif
  1815. }
  1816. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1817. // q value should determine priority, not hardcoded order
  1818. Request req;
  1819. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1820. Response res;
  1821. res.set_header("Content-Type", "text/plain");
  1822. auto ret = detail::encoding_type(req, res);
  1823. // gzip has highest q=1.0, so it should be selected even though
  1824. // br and zstd are also supported
  1825. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1826. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1827. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1828. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1829. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1830. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1831. #else
  1832. EXPECT_TRUE(ret == detail::EncodingType::None);
  1833. #endif
  1834. }
  1835. TEST(BufferStreamTest, read) {
  1836. detail::BufferStream strm1;
  1837. Stream &strm = strm1;
  1838. EXPECT_EQ(5, strm.write("hello"));
  1839. char buf[512];
  1840. EXPECT_EQ(2, strm.read(buf, 2));
  1841. EXPECT_EQ('h', buf[0]);
  1842. EXPECT_EQ('e', buf[1]);
  1843. EXPECT_EQ(2, strm.read(buf, 2));
  1844. EXPECT_EQ('l', buf[0]);
  1845. EXPECT_EQ('l', buf[1]);
  1846. EXPECT_EQ(1, strm.read(buf, 1));
  1847. EXPECT_EQ('o', buf[0]);
  1848. EXPECT_EQ(0, strm.read(buf, 1));
  1849. }
  1850. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1851. auto host = "www.httpwatch.com";
  1852. auto ip = hosted_at(host);
  1853. EXPECT_EQ("23.96.13.243", ip);
  1854. std::vector<std::string> addrs;
  1855. hosted_at(host, addrs);
  1856. EXPECT_EQ(1u, addrs.size());
  1857. }
  1858. #if 0 // It depends on each test environment...
  1859. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1860. auto host = "www.youtube.com";
  1861. std::vector<std::string> addrs;
  1862. hosted_at(host, addrs);
  1863. EXPECT_EQ(20u, addrs.size());
  1864. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1865. EXPECT_TRUE(it != addrs.end());
  1866. }
  1867. #endif
  1868. class ChunkedEncodingTest : public ::testing::Test {
  1869. protected:
  1870. ChunkedEncodingTest()
  1871. : cli_(HOST, PORT)
  1872. #ifdef CPPHTTPLIB_SSL_ENABLED
  1873. ,
  1874. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1875. #endif
  1876. {
  1877. cli_.set_connection_timeout(2);
  1878. #ifdef CPPHTTPLIB_SSL_ENABLED
  1879. cli_.enable_server_certificate_verification(false);
  1880. #endif
  1881. }
  1882. virtual void SetUp() {
  1883. read_file("./image.jpg", image_data_);
  1884. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1885. res.set_content("Hello World!", "text/plain");
  1886. });
  1887. svr_.Get(
  1888. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1889. res.set_chunked_content_provider(
  1890. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1891. size_t remaining = image_data_.size() - offset;
  1892. if (remaining == 0) {
  1893. sink.done();
  1894. } else {
  1895. constexpr size_t CHUNK_SIZE = 1024;
  1896. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1897. sink.write(&image_data_[offset], send_size);
  1898. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1899. }
  1900. return true;
  1901. });
  1902. });
  1903. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1904. svr_.wait_until_ready();
  1905. }
  1906. virtual void TearDown() {
  1907. svr_.stop();
  1908. if (!request_threads_.empty()) {
  1909. std::this_thread::sleep_for(std::chrono::seconds(1));
  1910. for (auto &t : request_threads_) {
  1911. t.join();
  1912. }
  1913. }
  1914. t_.join();
  1915. }
  1916. #ifdef CPPHTTPLIB_SSL_ENABLED
  1917. SSLClient cli_;
  1918. SSLServer svr_;
  1919. #else
  1920. Client cli_;
  1921. Server svr_;
  1922. #endif
  1923. thread t_;
  1924. std::vector<thread> request_threads_;
  1925. std::string image_data_;
  1926. };
  1927. TEST_F(ChunkedEncodingTest, NormalGet) {
  1928. auto res = cli_.Get("/chunked");
  1929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1930. std::string out;
  1931. read_file("./image.jpg", out);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. EXPECT_EQ(out, res->body);
  1934. }
  1935. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1936. std::string body;
  1937. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1938. body.append(data, data_length);
  1939. return true;
  1940. });
  1941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1942. std::string out;
  1943. read_file("./image.jpg", out);
  1944. EXPECT_EQ(StatusCode::OK_200, res->status);
  1945. EXPECT_EQ(out, body);
  1946. }
  1947. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1948. std::string body;
  1949. auto res = cli_.Get(
  1950. "/chunked",
  1951. [&](const Response &response) {
  1952. EXPECT_EQ(StatusCode::OK_200, response.status);
  1953. return true;
  1954. },
  1955. [&](const char *data, size_t data_length) {
  1956. body.append(data, data_length);
  1957. return true;
  1958. });
  1959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1960. std::string out;
  1961. read_file("./image.jpg", out);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. EXPECT_EQ(out, body);
  1964. }
  1965. TEST(RangeTest, FromHTTPBin_Online) {
  1966. auto host = "httpbingo.org";
  1967. auto path = std::string{"/range/32"};
  1968. #ifdef CPPHTTPLIB_SSL_ENABLED
  1969. auto port = 443;
  1970. SSLClient cli(host, port);
  1971. #else
  1972. auto port = 80;
  1973. Client cli(host, port);
  1974. #endif
  1975. cli.set_connection_timeout(5);
  1976. {
  1977. auto res = cli.Get(path);
  1978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1979. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1980. EXPECT_EQ(StatusCode::OK_200, res->status);
  1981. }
  1982. {
  1983. Headers headers = {make_range_header({{1, -1}})};
  1984. auto res = cli.Get(path, headers);
  1985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1986. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1988. }
  1989. {
  1990. Headers headers = {make_range_header({{1, 10}})};
  1991. auto res = cli.Get(path, headers);
  1992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1993. EXPECT_EQ("bcdefghijk", res->body);
  1994. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1995. }
  1996. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1997. // entire resource, while the original httpbin returned 200. Both are
  1998. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1999. {
  2000. Headers headers = {make_range_header({{0, 31}})};
  2001. auto res = cli.Get(path, headers);
  2002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2003. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2004. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2005. res->status == StatusCode::PartialContent_206);
  2006. }
  2007. {
  2008. Headers headers = {make_range_header({{0, -1}})};
  2009. auto res = cli.Get(path, headers);
  2010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2011. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2012. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2013. res->status == StatusCode::PartialContent_206);
  2014. }
  2015. // go-httpbin returns 206 with clamped range for over-range requests,
  2016. // while the original httpbin returned 416. Both behaviors are observed
  2017. // in real servers, so we only verify the request succeeds.
  2018. {
  2019. Headers headers = {make_range_header({{0, 32}})};
  2020. auto res = cli.Get(path, headers);
  2021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2022. }
  2023. }
  2024. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2025. auto host = "unresolvableaddress.local";
  2026. auto path = std::string{"/"};
  2027. #ifdef CPPHTTPLIB_SSL_ENABLED
  2028. auto port = 443;
  2029. SSLClient cli(host, port);
  2030. #else
  2031. auto port = 80;
  2032. Client cli(host, port);
  2033. #endif
  2034. cli.set_connection_timeout(1);
  2035. {
  2036. auto res = cli.Get(path);
  2037. ASSERT_FALSE(res);
  2038. }
  2039. std::this_thread::sleep_for(std::chrono::seconds(8));
  2040. }
  2041. #if defined(__linux__) && defined(__GLIBC__) && \
  2042. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2043. // Forward declaration: in split builds split.py strips `inline` and moves the
  2044. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2045. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2046. // against the symbol in both header-only and split builds.
  2047. namespace httplib {
  2048. namespace detail {
  2049. int getaddrinfo_with_timeout(const char *node, const char *service,
  2050. const struct addrinfo *hints,
  2051. struct addrinfo **res, time_t timeout_sec);
  2052. } // namespace detail
  2053. } // namespace httplib
  2054. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2055. //
  2056. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2057. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2058. // gai_suspend() call hits the connection timeout the function calls
  2059. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2060. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2061. // still alive and still references the now-destroyed stack frame.
  2062. //
  2063. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2064. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2065. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2066. // and runs them in a container.
  2067. namespace {
  2068. bool should_run_issue_2431_tests() {
  2069. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2070. return v && *v && std::string(v) != "0";
  2071. }
  2072. std::string unique_unresolvable_host(int n) {
  2073. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2074. // glibc still asks the configured nameserver — which is exactly the path
  2075. // we want to exercise. A unique label per call avoids the resolver cache.
  2076. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2077. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2078. std::to_string(n) + ".invalid";
  2079. }
  2080. } // namespace
  2081. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2082. if (!should_run_issue_2431_tests()) {
  2083. GTEST_SKIP()
  2084. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2085. }
  2086. for (int i = 0; i < 8; ++i) {
  2087. struct addrinfo hints;
  2088. memset(&hints, 0, sizeof(hints));
  2089. hints.ai_family = AF_UNSPEC;
  2090. hints.ai_socktype = SOCK_STREAM;
  2091. auto host = unique_unresolvable_host(i);
  2092. struct addrinfo *result = nullptr;
  2093. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2094. &result, /*timeout_sec=*/1);
  2095. if (rc == 0 && result) { freeaddrinfo(result); }
  2096. }
  2097. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2098. // stack region they still believe holds their gaicb.
  2099. std::this_thread::sleep_for(std::chrono::seconds(3));
  2100. }
  2101. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2102. if (!should_run_issue_2431_tests()) {
  2103. GTEST_SKIP()
  2104. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2105. }
  2106. std::atomic<bool> stop{false};
  2107. std::vector<std::thread> threads;
  2108. for (int t = 0; t < 8; ++t) {
  2109. threads.emplace_back([t, &stop] {
  2110. int i = 0;
  2111. while (!stop.load(std::memory_order_relaxed)) {
  2112. struct addrinfo hints;
  2113. memset(&hints, 0, sizeof(hints));
  2114. hints.ai_family = AF_UNSPEC;
  2115. hints.ai_socktype = SOCK_STREAM;
  2116. auto host = unique_unresolvable_host(t * 100000 + i++);
  2117. struct addrinfo *result = nullptr;
  2118. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2119. &result, /*timeout_sec=*/1);
  2120. if (rc == 0 && result) { freeaddrinfo(result); }
  2121. }
  2122. });
  2123. }
  2124. std::this_thread::sleep_for(std::chrono::seconds(8));
  2125. stop.store(true, std::memory_order_relaxed);
  2126. for (auto &th : threads) {
  2127. th.join();
  2128. }
  2129. std::this_thread::sleep_for(std::chrono::seconds(3));
  2130. }
  2131. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2132. if (!should_run_issue_2431_tests()) {
  2133. GTEST_SKIP()
  2134. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2135. }
  2136. std::atomic<bool> stop{false};
  2137. std::vector<std::thread> threads;
  2138. for (int t = 0; t < 8; ++t) {
  2139. threads.emplace_back([t, &stop] {
  2140. int i = 0;
  2141. while (!stop.load(std::memory_order_relaxed)) {
  2142. auto host = unique_unresolvable_host(t * 100000 + i++);
  2143. Client cli(host, 80);
  2144. cli.set_connection_timeout(1, 0);
  2145. cli.set_read_timeout(1, 0);
  2146. cli.set_write_timeout(1, 0);
  2147. (void)cli.Get("/");
  2148. }
  2149. });
  2150. }
  2151. std::this_thread::sleep_for(std::chrono::seconds(8));
  2152. stop.store(true, std::memory_order_relaxed);
  2153. for (auto &th : threads) {
  2154. th.join();
  2155. }
  2156. std::this_thread::sleep_for(std::chrono::seconds(3));
  2157. }
  2158. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2159. TEST(ConnectionErrorTest, InvalidHost) {
  2160. auto host = "-abcde.com";
  2161. #ifdef CPPHTTPLIB_SSL_ENABLED
  2162. auto port = 443;
  2163. SSLClient cli(host, port);
  2164. #else
  2165. auto port = 80;
  2166. Client cli(host, port);
  2167. #endif
  2168. cli.set_connection_timeout(std::chrono::seconds(2));
  2169. auto res = cli.Get("/");
  2170. ASSERT_TRUE(!res);
  2171. EXPECT_EQ(Error::Connection, res.error());
  2172. }
  2173. TEST(ConnectionErrorTest, InvalidHost2) {
  2174. auto host = "httpcan.org/";
  2175. #ifdef CPPHTTPLIB_SSL_ENABLED
  2176. SSLClient cli(host);
  2177. #else
  2178. Client cli(host);
  2179. #endif
  2180. cli.set_connection_timeout(std::chrono::seconds(2));
  2181. auto res = cli.Get("/");
  2182. ASSERT_TRUE(!res);
  2183. EXPECT_EQ(Error::Connection, res.error());
  2184. }
  2185. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2186. auto host = "httpcan.org/";
  2187. #ifdef CPPHTTPLIB_SSL_ENABLED
  2188. SSLClient cli(host);
  2189. #else
  2190. Client cli(host);
  2191. #endif
  2192. cli.set_connection_timeout(std::chrono::seconds(2));
  2193. auto res = cli.Get("/");
  2194. ASSERT_TRUE(!res);
  2195. stringstream s;
  2196. s << "error code: " << res.error();
  2197. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2198. }
  2199. TEST(ConnectionErrorTest, InvalidPort) {
  2200. auto host = "localhost";
  2201. auto port = 44380;
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. SSLClient cli(host, port);
  2204. #else
  2205. Client cli(host, port);
  2206. #endif
  2207. cli.set_connection_timeout(std::chrono::seconds(2));
  2208. auto res = cli.Get("/");
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_TRUE(Error::Connection == res.error() ||
  2211. Error::ConnectionTimeout == res.error());
  2212. }
  2213. TEST(ConnectionErrorTest, Timeout_Online) {
  2214. auto host = "google.com";
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. auto port = 44380;
  2217. SSLClient cli(host, port);
  2218. #else
  2219. auto port = 8080;
  2220. Client cli(host, port);
  2221. #endif
  2222. cli.set_connection_timeout(std::chrono::seconds(2));
  2223. // only probe one address type so that the error reason
  2224. // correlates to the timed-out IPv4, not the unsupported
  2225. // IPv6 connection attempt
  2226. cli.set_address_family(AF_INET);
  2227. auto res = cli.Get("/");
  2228. ASSERT_TRUE(!res);
  2229. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2230. }
  2231. TEST(CancelTest, NoCancel_Online) {
  2232. auto host = "httpbingo.org";
  2233. auto path = std::string{"/range/32"};
  2234. #ifdef CPPHTTPLIB_SSL_ENABLED
  2235. auto port = 443;
  2236. SSLClient cli(host, port);
  2237. #else
  2238. auto port = 80;
  2239. Client cli(host, port);
  2240. #endif
  2241. cli.set_connection_timeout(std::chrono::seconds(5));
  2242. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2244. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. }
  2247. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2248. // Use /bytes with a large payload so that the DownloadProgress callback
  2249. // (which only fires for Content-Length responses) is invoked before the
  2250. // entire body is received, giving cancellation a chance to fire.
  2251. auto host = "httpbingo.org";
  2252. auto path = std::string{"/bytes/524288"};
  2253. #ifdef CPPHTTPLIB_SSL_ENABLED
  2254. auto port = 443;
  2255. SSLClient cli(host, port);
  2256. #else
  2257. auto port = 80;
  2258. Client cli(host, port);
  2259. #endif
  2260. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2261. cli.set_connection_timeout(std::chrono::seconds(5));
  2262. ASSERT_TRUE(!res);
  2263. EXPECT_EQ(Error::Canceled, res.error());
  2264. }
  2265. TEST(CancelTest, WithCancelLargePayload_Online) {
  2266. auto host = "httpbingo.org";
  2267. auto path = std::string{"/bytes/524288"};
  2268. #ifdef CPPHTTPLIB_SSL_ENABLED
  2269. auto port = 443;
  2270. SSLClient cli(host, port);
  2271. #else
  2272. auto port = 80;
  2273. Client cli(host, port);
  2274. #endif
  2275. cli.set_connection_timeout(std::chrono::seconds(5));
  2276. uint32_t count = 0;
  2277. auto res =
  2278. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2279. ASSERT_TRUE(!res);
  2280. EXPECT_EQ(Error::Canceled, res.error());
  2281. }
  2282. TEST(CancelTest, NoCancelPost) {
  2283. Server svr;
  2284. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. Client cli(HOST, PORT);
  2295. cli.set_connection_timeout(std::chrono::seconds(5));
  2296. auto res =
  2297. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2298. "application/json", [](uint64_t, uint64_t) { return true; });
  2299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2300. EXPECT_EQ("Hello World!", res->body);
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. }
  2303. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2304. Server svr;
  2305. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2306. res.set_content("Hello World!", "text/plain");
  2307. });
  2308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2309. auto se = detail::scope_exit([&] {
  2310. svr.stop();
  2311. thread.join();
  2312. ASSERT_FALSE(svr.is_running());
  2313. });
  2314. svr.wait_until_ready();
  2315. Client cli(HOST, PORT);
  2316. cli.set_connection_timeout(std::chrono::seconds(5));
  2317. auto res =
  2318. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2319. "application/json", [](uint64_t, uint64_t) { return false; });
  2320. ASSERT_TRUE(!res);
  2321. EXPECT_EQ(Error::Canceled, res.error());
  2322. }
  2323. TEST(CancelTest, WithCancelLargePayloadPost) {
  2324. Server svr;
  2325. svr.set_payload_max_length(200 * 1024 * 1024);
  2326. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2327. res.set_content(LARGE_DATA, "text/plain");
  2328. });
  2329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2330. auto se = detail::scope_exit([&] {
  2331. svr.stop();
  2332. thread.join();
  2333. ASSERT_FALSE(svr.is_running());
  2334. });
  2335. svr.wait_until_ready();
  2336. Client cli(HOST, PORT);
  2337. cli.set_payload_max_length(200 * 1024 * 1024);
  2338. cli.set_connection_timeout(std::chrono::seconds(5));
  2339. auto res =
  2340. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2341. "application/json", [](uint64_t, uint64_t) { return false; });
  2342. ASSERT_TRUE(!res);
  2343. EXPECT_EQ(Error::Canceled, res.error());
  2344. }
  2345. TEST(CancelTest, NoCancelPut) {
  2346. Server svr;
  2347. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2348. res.set_content("Hello World!", "text/plain");
  2349. });
  2350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2351. auto se = detail::scope_exit([&] {
  2352. svr.stop();
  2353. thread.join();
  2354. ASSERT_FALSE(svr.is_running());
  2355. });
  2356. svr.wait_until_ready();
  2357. Client cli(HOST, PORT);
  2358. cli.set_connection_timeout(std::chrono::seconds(5));
  2359. auto res =
  2360. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2361. "application/json", [](uint64_t, uint64_t) { return true; });
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. EXPECT_EQ("Hello World!", res->body);
  2364. EXPECT_EQ(StatusCode::OK_200, res->status);
  2365. }
  2366. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2367. Server svr;
  2368. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2369. res.set_content("Hello World!", "text/plain");
  2370. });
  2371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2372. auto se = detail::scope_exit([&] {
  2373. svr.stop();
  2374. thread.join();
  2375. ASSERT_FALSE(svr.is_running());
  2376. });
  2377. svr.wait_until_ready();
  2378. Client cli(HOST, PORT);
  2379. cli.set_connection_timeout(std::chrono::seconds(5));
  2380. auto res =
  2381. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2382. "application/json", [](uint64_t, uint64_t) { return false; });
  2383. ASSERT_TRUE(!res);
  2384. EXPECT_EQ(Error::Canceled, res.error());
  2385. }
  2386. TEST(CancelTest, WithCancelLargePayloadPut) {
  2387. Server svr;
  2388. svr.set_payload_max_length(200 * 1024 * 1024);
  2389. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2390. res.set_content(LARGE_DATA, "text/plain");
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. Client cli(HOST, PORT);
  2400. cli.set_payload_max_length(200 * 1024 * 1024);
  2401. cli.set_connection_timeout(std::chrono::seconds(5));
  2402. auto res =
  2403. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2404. "application/json", [](uint64_t, uint64_t) { return false; });
  2405. ASSERT_TRUE(!res);
  2406. EXPECT_EQ(Error::Canceled, res.error());
  2407. }
  2408. TEST(CancelTest, NoCancelPatch) {
  2409. Server svr;
  2410. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2411. res.set_content("Hello World!", "text/plain");
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. Client cli(HOST, PORT);
  2421. cli.set_connection_timeout(std::chrono::seconds(5));
  2422. auto res =
  2423. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2424. "application/json", [](uint64_t, uint64_t) { return true; });
  2425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2426. EXPECT_EQ("Hello World!", res->body);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. }
  2429. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2430. Server svr;
  2431. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2432. res.set_content("Hello World!", "text/plain");
  2433. });
  2434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2435. auto se = detail::scope_exit([&] {
  2436. svr.stop();
  2437. thread.join();
  2438. ASSERT_FALSE(svr.is_running());
  2439. });
  2440. svr.wait_until_ready();
  2441. Client cli(HOST, PORT);
  2442. cli.set_connection_timeout(std::chrono::seconds(5));
  2443. auto res =
  2444. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2445. "application/json", [](uint64_t, uint64_t) { return false; });
  2446. ASSERT_TRUE(!res);
  2447. EXPECT_EQ(Error::Canceled, res.error());
  2448. }
  2449. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2450. Server svr;
  2451. svr.set_payload_max_length(200 * 1024 * 1024);
  2452. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2453. res.set_content(LARGE_DATA, "text/plain");
  2454. });
  2455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2456. auto se = detail::scope_exit([&] {
  2457. svr.stop();
  2458. thread.join();
  2459. ASSERT_FALSE(svr.is_running());
  2460. });
  2461. svr.wait_until_ready();
  2462. Client cli(HOST, PORT);
  2463. cli.set_payload_max_length(200 * 1024 * 1024);
  2464. cli.set_connection_timeout(std::chrono::seconds(5));
  2465. auto res =
  2466. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2467. "application/json", [](uint64_t, uint64_t) { return false; });
  2468. ASSERT_TRUE(!res);
  2469. EXPECT_EQ(Error::Canceled, res.error());
  2470. }
  2471. TEST(CancelTest, NoCancelDelete) {
  2472. Server svr;
  2473. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2474. res.set_content("Hello World!", "text/plain");
  2475. });
  2476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2477. auto se = detail::scope_exit([&] {
  2478. svr.stop();
  2479. thread.join();
  2480. ASSERT_FALSE(svr.is_running());
  2481. });
  2482. svr.wait_until_ready();
  2483. Client cli(HOST, PORT);
  2484. cli.set_connection_timeout(std::chrono::seconds(5));
  2485. auto res =
  2486. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2487. "application/json", [](uint64_t, uint64_t) { return true; });
  2488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2489. EXPECT_EQ("Hello World!", res->body);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. }
  2492. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2493. Server svr;
  2494. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2495. res.set_content("Hello World!", "text/plain");
  2496. });
  2497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2498. auto se = detail::scope_exit([&] {
  2499. svr.stop();
  2500. thread.join();
  2501. ASSERT_FALSE(svr.is_running());
  2502. });
  2503. svr.wait_until_ready();
  2504. Client cli(HOST, PORT);
  2505. cli.set_connection_timeout(std::chrono::seconds(5));
  2506. auto res =
  2507. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2508. "application/json", [](uint64_t, uint64_t) { return false; });
  2509. ASSERT_TRUE(!res);
  2510. EXPECT_EQ(Error::Canceled, res.error());
  2511. }
  2512. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2513. Server svr;
  2514. svr.set_payload_max_length(200 * 1024 * 1024);
  2515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2516. res.set_content(LARGE_DATA, "text/plain");
  2517. });
  2518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2519. auto se = detail::scope_exit([&] {
  2520. svr.stop();
  2521. thread.join();
  2522. ASSERT_FALSE(svr.is_running());
  2523. });
  2524. svr.wait_until_ready();
  2525. Client cli(HOST, PORT);
  2526. cli.set_payload_max_length(200 * 1024 * 1024);
  2527. cli.set_connection_timeout(std::chrono::seconds(5));
  2528. auto res =
  2529. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2530. "application/json", [](uint64_t, uint64_t) { return false; });
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. static std::string remove_whitespace(const std::string &input) {
  2535. std::string output;
  2536. output.reserve(input.size());
  2537. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2538. [](unsigned char c) { return !std::isspace(c); });
  2539. return output;
  2540. }
  2541. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2542. auto host = "httpbingo.org";
  2543. auto path = std::string{"/basic-auth/hello/world"};
  2544. #ifdef CPPHTTPLIB_SSL_ENABLED
  2545. auto port = 443;
  2546. SSLClient cli(host, port);
  2547. #else
  2548. auto port = 80;
  2549. Client cli(host, port);
  2550. #endif
  2551. {
  2552. auto res = cli.Get(path);
  2553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2554. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2555. }
  2556. {
  2557. auto res = cli.Get(
  2558. path, Headers{make_basic_authentication_header("hello", "world")});
  2559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2560. auto body = remove_whitespace(res->body);
  2561. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2562. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2563. EXPECT_EQ(StatusCode::OK_200, res->status);
  2564. }
  2565. {
  2566. cli.set_basic_auth("hello", "world");
  2567. auto res = cli.Get(path);
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. auto body = remove_whitespace(res->body);
  2570. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2571. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2572. EXPECT_EQ(StatusCode::OK_200, res->status);
  2573. }
  2574. {
  2575. cli.set_basic_auth("hello", "bad");
  2576. auto res = cli.Get(path);
  2577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2578. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2579. }
  2580. {
  2581. cli.set_basic_auth("bad", "world");
  2582. auto res = cli.Get(path);
  2583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2584. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2585. }
  2586. }
  2587. #ifdef CPPHTTPLIB_SSL_ENABLED
  2588. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2589. auto host = "httpbingo.org";
  2590. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2591. auto paths = std::vector<std::string>{
  2592. "/digest-auth/auth/hello/world/MD5",
  2593. "/digest-auth/auth/hello/world/SHA-256",
  2594. };
  2595. auto port = 443;
  2596. SSLClient cli(host, port);
  2597. {
  2598. auto res = cli.Get(unauth_path);
  2599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2600. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2601. }
  2602. {
  2603. cli.set_digest_auth("hello", "world");
  2604. for (const auto &path : paths) {
  2605. auto res = cli.Get(path.c_str());
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. auto body = remove_whitespace(res->body);
  2608. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2609. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. }
  2612. cli.set_digest_auth("hello", "bad");
  2613. for (const auto &path : paths) {
  2614. auto res = cli.Get(path.c_str());
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2617. }
  2618. }
  2619. }
  2620. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2621. // comma-separated list of challenges, and each challenge may itself carry a
  2622. // comma-separated auth-param list, so a server can legally offer Basic
  2623. // before Digest, either as two field lines or packed into one. Runs one 401
  2624. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2625. // value() joins them in receipt order) and checks that the retry carries a
  2626. // well-formed Digest Authorization header naming expected_realm.
  2627. static void
  2628. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2629. const std::string &expected_realm) {
  2630. std::atomic<int> hits{0};
  2631. Server svr;
  2632. svr.Get("/x", [&](const Request &req, Response &res) {
  2633. if (++hits == 1) {
  2634. res.status = StatusCode::Unauthorized_401;
  2635. for (const auto &challenge : challenges) {
  2636. res.set_header("WWW-Authenticate", challenge);
  2637. }
  2638. } else {
  2639. auto authorization = req.get_header_value("Authorization");
  2640. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2641. EXPECT_NE(std::string::npos,
  2642. authorization.find("realm=\"" + expected_realm + "\""));
  2643. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2644. res.set_content("ok", "text/plain");
  2645. }
  2646. });
  2647. auto port = svr.bind_to_any_port(HOST);
  2648. std::thread t([&]() { svr.listen_after_bind(); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. t.join();
  2652. });
  2653. svr.wait_until_ready();
  2654. Client cli(HOST, port);
  2655. cli.set_digest_auth("hello", "world");
  2656. auto res = cli.Get("/x");
  2657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2658. EXPECT_EQ(2, hits.load());
  2659. }
  2660. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2661. static const char *kDigestChallenge =
  2662. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2663. "algorithm=MD5";
  2664. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2665. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2666. "testrealm");
  2667. }
  2668. // Same challenge list with the schemes in the opposite order, to make sure
  2669. // the fix above didn't just special-case "Basic first".
  2670. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2671. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2672. "testrealm");
  2673. }
  2674. // A comma inside a quoted auth-param value must not be mistaken for the
  2675. // separator between two challenges (or two auth-params).
  2676. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2677. run_digest_challenge_list_test(
  2678. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2679. "algorithm=MD5"},
  2680. "test,realm");
  2681. }
  2682. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2683. // make_digest_authentication_header() dereferences both unconditionally, so
  2684. // a server sending a challenge missing either one must not be treated as
  2685. // usable -- doing so used to crash the client with std::out_of_range.
  2686. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2687. Server svr;
  2688. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2689. res.status = StatusCode::Unauthorized_401;
  2690. res.set_header("WWW-Authenticate", challenge);
  2691. });
  2692. auto port = svr.bind_to_any_port(HOST);
  2693. std::thread t([&]() { svr.listen_after_bind(); });
  2694. auto se = detail::scope_exit([&] {
  2695. svr.stop();
  2696. t.join();
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, port);
  2700. cli.set_digest_auth("hello", "world");
  2701. auto res = cli.Get("/x");
  2702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2703. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2704. }
  2705. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2706. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2707. }
  2708. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2709. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2710. }
  2711. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2712. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2713. }
  2714. #endif
  2715. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2716. auto host = "google.com";
  2717. auto another_host = "example.com";
  2718. auto wrong_ip = "0.0.0.0";
  2719. #ifdef CPPHTTPLIB_SSL_ENABLED
  2720. SSLClient cli(host);
  2721. #else
  2722. Client cli(host);
  2723. #endif
  2724. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2725. auto res = cli.Get("/");
  2726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2727. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2728. }
  2729. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2730. auto host = "google.com";
  2731. auto wrong_ip = "0.0.0.0";
  2732. #ifdef CPPHTTPLIB_SSL_ENABLED
  2733. SSLClient cli(host);
  2734. #else
  2735. Client cli(host);
  2736. #endif
  2737. cli.set_hostname_addr_map({{host, wrong_ip}});
  2738. auto res = cli.Get("/");
  2739. ASSERT_TRUE(!res);
  2740. EXPECT_EQ(Error::Connection, res.error());
  2741. }
  2742. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2743. // A mapped value that is not an IP literal must be resolved. "localhost"
  2744. // resolves from the hosts file, so this test needs no external DNS.
  2745. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2746. auto host = "target.invalid";
  2747. Server svr;
  2748. std::string received_host;
  2749. svr.Get("/hi", [&](const Request &req, Response &res) {
  2750. received_host = req.get_header_value("Host");
  2751. res.set_content("Hello World!", "text/plain");
  2752. });
  2753. auto port = svr.bind_to_any_port(HOST);
  2754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2755. auto se = detail::scope_exit([&] {
  2756. svr.stop();
  2757. thread.join();
  2758. ASSERT_FALSE(svr.is_running());
  2759. });
  2760. svr.wait_until_ready();
  2761. Client cli(host, port);
  2762. cli.set_hostname_addr_map({{host, HOST}});
  2763. auto res = cli.Get("/hi");
  2764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2765. EXPECT_EQ(StatusCode::OK_200, res->status);
  2766. // The mapping only redirects the connection; the identity stays host_.
  2767. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2768. }
  2769. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2770. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2771. auto host = "target.invalid";
  2772. Server svr;
  2773. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2774. res.set_content("Hello World!", "text/plain");
  2775. });
  2776. auto port = svr.bind_to_any_port("127.0.0.1");
  2777. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2778. auto se = detail::scope_exit([&] {
  2779. svr.stop();
  2780. thread.join();
  2781. ASSERT_FALSE(svr.is_running());
  2782. });
  2783. svr.wait_until_ready();
  2784. Client cli(host, port);
  2785. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2786. auto res = cli.Get("/hi");
  2787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2788. EXPECT_EQ(StatusCode::OK_200, res->status);
  2789. }
  2790. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2791. // An empty mapped value must leave host_ as the connection target. Without
  2792. // that guard the empty value would become the host argument, getaddrinfo
  2793. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2794. // loopback - silently connecting somewhere the caller never asked for.
  2795. // The server listens on loopback, so such a fallback would succeed and is
  2796. // therefore observable as a failure of this test.
  2797. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2798. Server svr;
  2799. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2800. res.set_content("Hello World!", "text/plain");
  2801. });
  2802. auto port = svr.bind_to_any_port(HOST);
  2803. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2804. auto se = detail::scope_exit([&] {
  2805. svr.stop();
  2806. thread.join();
  2807. ASSERT_FALSE(svr.is_running());
  2808. });
  2809. svr.wait_until_ready();
  2810. Client cli(blackhole, port);
  2811. cli.set_hostname_addr_map({{blackhole, ""}});
  2812. cli.set_connection_timeout(1);
  2813. auto res = cli.Get("/hi");
  2814. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2815. }
  2816. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2817. auto host = "httpbingo.org";
  2818. auto path = std::string{"/absolute-redirect/3"};
  2819. #ifdef CPPHTTPLIB_SSL_ENABLED
  2820. SSLClient cli(host);
  2821. #else
  2822. Client cli(host);
  2823. #endif
  2824. cli.set_follow_location(true);
  2825. auto res = cli.Get(path);
  2826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2827. EXPECT_EQ(StatusCode::OK_200, res->status);
  2828. }
  2829. TEST(RedirectTest, Redirect_Online) {
  2830. auto host = "httpbingo.org";
  2831. auto path = std::string{"/redirect/3"};
  2832. #ifdef CPPHTTPLIB_SSL_ENABLED
  2833. SSLClient cli(host);
  2834. #else
  2835. Client cli(host);
  2836. #endif
  2837. cli.set_follow_location(true);
  2838. auto res = cli.Get(path);
  2839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2840. EXPECT_EQ(StatusCode::OK_200, res->status);
  2841. }
  2842. TEST(RelativeRedirectTest, Redirect_Online) {
  2843. auto host = "httpbingo.org";
  2844. auto path = std::string{"/relative-redirect/3"};
  2845. #ifdef CPPHTTPLIB_SSL_ENABLED
  2846. SSLClient cli(host);
  2847. #else
  2848. Client cli(host);
  2849. #endif
  2850. cli.set_follow_location(true);
  2851. auto res = cli.Get(path);
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. }
  2855. TEST(TooManyRedirectTest, Redirect_Online) {
  2856. auto host = "httpbingo.org";
  2857. auto path = std::string{"/redirect/21"};
  2858. #ifdef CPPHTTPLIB_SSL_ENABLED
  2859. SSLClient cli(host);
  2860. #else
  2861. Client cli(host);
  2862. #endif
  2863. cli.set_follow_location(true);
  2864. auto res = cli.Get(path);
  2865. ASSERT_TRUE(!res);
  2866. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2867. }
  2868. #ifdef CPPHTTPLIB_SSL_ENABLED
  2869. TEST(YahooRedirectTest, Redirect_Online) {
  2870. Client cli("yahoo.com");
  2871. auto res = cli.Get("/");
  2872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2873. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2874. cli.set_follow_location(true);
  2875. res = cli.Get("/");
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2879. }
  2880. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2881. #define REDIR_HOST "httpbingo.org"
  2882. #define REDIR_PATH "/redirect-to"
  2883. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2884. SSLClient cli(REDIR_HOST);
  2885. cli.set_follow_location(true);
  2886. auto res =
  2887. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::OK_200, res->status);
  2890. }
  2891. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2892. SSLClient cli(REDIR_HOST);
  2893. cli.set_follow_location(true);
  2894. Params params;
  2895. params.emplace("url", "http://example.com");
  2896. params.emplace("status_code", "302");
  2897. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. EXPECT_EQ(StatusCode::OK_200, res->status);
  2900. }
  2901. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2902. SSLClient cli(REDIR_HOST);
  2903. cli.set_follow_location(true);
  2904. Params params;
  2905. params.emplace("url", "http://example.com");
  2906. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::OK_200, res->status);
  2909. }
  2910. TEST(UrlWithSpace, Redirect_Online) {
  2911. SSLClient cli("edge.forgecdn.net");
  2912. cli.set_follow_location(true);
  2913. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::OK_200, res->status);
  2916. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2917. }
  2918. #endif
  2919. #if !defined(_WIN32) && !defined(_WIN64)
  2920. TEST(ReceiveSignals, Signal) {
  2921. auto setupSignalHandlers = []() {
  2922. struct sigaction act;
  2923. sigemptyset(&act.sa_mask);
  2924. act.sa_flags = SA_SIGINFO;
  2925. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2926. switch (sig) {
  2927. case SIGINT:
  2928. default: break;
  2929. }
  2930. };
  2931. ::sigaction(SIGINT, &act, nullptr);
  2932. };
  2933. Server svr;
  2934. int port = 0;
  2935. auto thread = std::thread([&]() {
  2936. setupSignalHandlers();
  2937. port = svr.bind_to_any_port(HOST);
  2938. svr.listen_after_bind();
  2939. });
  2940. auto se = detail::scope_exit([&] {
  2941. svr.stop();
  2942. thread.join();
  2943. ASSERT_FALSE(svr.is_running());
  2944. });
  2945. svr.wait_until_ready();
  2946. ASSERT_TRUE(svr.is_running());
  2947. pthread_kill(thread.native_handle(), SIGINT);
  2948. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2949. ASSERT_TRUE(svr.is_running());
  2950. }
  2951. #endif
  2952. TEST(RedirectToDifferentPort, Redirect) {
  2953. Server svr1;
  2954. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2955. res.set_content("Hello World!", "text/plain");
  2956. });
  2957. int svr1_port = 0;
  2958. auto thread1 = std::thread([&]() {
  2959. svr1_port = svr1.bind_to_any_port(HOST);
  2960. svr1.listen_after_bind();
  2961. });
  2962. Server svr2;
  2963. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2964. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2965. });
  2966. int svr2_port = 0;
  2967. auto thread2 = std::thread([&]() {
  2968. svr2_port = svr2.bind_to_any_port(HOST);
  2969. svr2.listen_after_bind();
  2970. });
  2971. auto se = detail::scope_exit([&] {
  2972. svr2.stop();
  2973. thread2.join();
  2974. svr1.stop();
  2975. thread1.join();
  2976. ASSERT_FALSE(svr2.is_running());
  2977. ASSERT_FALSE(svr1.is_running());
  2978. });
  2979. svr1.wait_until_ready();
  2980. svr2.wait_until_ready();
  2981. Client cli("localhost", svr2_port);
  2982. cli.set_follow_location(true);
  2983. auto res = cli.Get("/2");
  2984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2985. EXPECT_EQ(StatusCode::OK_200, res->status);
  2986. EXPECT_EQ("Hello World!", res->body);
  2987. }
  2988. static void
  2989. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2990. Server svr1;
  2991. std::string captured_authorization;
  2992. svr1.Get("/target", [&](const Request &req, Response &res) {
  2993. captured_authorization = req.get_header_value("Authorization");
  2994. res.set_content("OK", "text/plain");
  2995. });
  2996. int svr1_port = 0;
  2997. auto thread1 = std::thread([&]() {
  2998. svr1_port = svr1.bind_to_any_port(HOST);
  2999. svr1.listen_after_bind();
  3000. });
  3001. Server svr2;
  3002. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3003. res.set_redirect(
  3004. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3005. });
  3006. int svr2_port = 0;
  3007. auto thread2 = std::thread([&]() {
  3008. svr2_port = svr2.bind_to_any_port(HOST);
  3009. svr2.listen_after_bind();
  3010. });
  3011. auto se = detail::scope_exit([&] {
  3012. svr2.stop();
  3013. thread2.join();
  3014. svr1.stop();
  3015. thread1.join();
  3016. ASSERT_FALSE(svr2.is_running());
  3017. ASSERT_FALSE(svr1.is_running());
  3018. });
  3019. svr1.wait_until_ready();
  3020. svr2.wait_until_ready();
  3021. Client cli("localhost", svr2_port);
  3022. cli.set_follow_location(true);
  3023. set_auth(cli);
  3024. auto res = cli.Get("/redir");
  3025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3026. EXPECT_EQ(StatusCode::OK_200, res->status);
  3027. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3028. EXPECT_TRUE(captured_authorization.empty());
  3029. }
  3030. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3031. TestDoNotForwardCredentialsOnRedirect(
  3032. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3033. }
  3034. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3035. TestDoNotForwardCredentialsOnRedirect(
  3036. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3037. }
  3038. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3039. Server svr1;
  3040. std::string captured_cookie;
  3041. bool target_hit = false;
  3042. svr1.Get("/target", [&](const Request &req, Response &res) {
  3043. captured_cookie = req.get_header_value("Cookie");
  3044. target_hit = true;
  3045. res.set_content("OK", "text/plain");
  3046. });
  3047. int svr1_port = 0;
  3048. auto thread1 = std::thread([&]() {
  3049. svr1_port = svr1.bind_to_any_port(HOST);
  3050. svr1.listen_after_bind();
  3051. });
  3052. Server svr2;
  3053. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3054. res.set_redirect(
  3055. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3056. });
  3057. int svr2_port = 0;
  3058. auto thread2 = std::thread([&]() {
  3059. svr2_port = svr2.bind_to_any_port(HOST);
  3060. svr2.listen_after_bind();
  3061. });
  3062. auto se = detail::scope_exit([&] {
  3063. svr2.stop();
  3064. thread2.join();
  3065. svr1.stop();
  3066. thread1.join();
  3067. ASSERT_FALSE(svr2.is_running());
  3068. ASSERT_FALSE(svr1.is_running());
  3069. });
  3070. svr1.wait_until_ready();
  3071. svr2.wait_until_ready();
  3072. Client cli("localhost", svr2_port);
  3073. cli.set_follow_location(true);
  3074. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3075. auto res = cli.Get("/redir", headers);
  3076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3077. EXPECT_EQ(StatusCode::OK_200, res->status);
  3078. EXPECT_TRUE(target_hit);
  3079. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3080. EXPECT_TRUE(captured_cookie.empty());
  3081. }
  3082. TEST(RedirectToSamePort, ForwardCookie) {
  3083. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3084. // header so that ordinary session flows keep working.
  3085. Server svr;
  3086. std::string captured_cookie;
  3087. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3088. res.set_redirect("/target", 302);
  3089. });
  3090. svr.Get("/target", [&](const Request &req, Response &res) {
  3091. captured_cookie = req.get_header_value("Cookie");
  3092. res.set_content("OK", "text/plain");
  3093. });
  3094. auto port = svr.bind_to_any_port(HOST);
  3095. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3096. auto se = detail::scope_exit([&] {
  3097. svr.stop();
  3098. thread.join();
  3099. ASSERT_FALSE(svr.is_running());
  3100. });
  3101. svr.wait_until_ready();
  3102. Client cli(HOST, port);
  3103. cli.set_follow_location(true);
  3104. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3105. auto res = cli.Get("/redir", headers);
  3106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3107. EXPECT_EQ(StatusCode::OK_200, res->status);
  3108. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3109. }
  3110. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3111. Server svr;
  3112. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3113. // Port number that overflows int — should not crash
  3114. res.set_redirect("http://localhost:99999999999999999999/target");
  3115. });
  3116. auto port = svr.bind_to_any_port(HOST);
  3117. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3118. auto se = detail::scope_exit([&] {
  3119. svr.stop();
  3120. thread.join();
  3121. ASSERT_FALSE(svr.is_running());
  3122. });
  3123. svr.wait_until_ready();
  3124. Client cli(HOST, port);
  3125. cli.set_follow_location(true);
  3126. auto res = cli.Get("/redir");
  3127. // Should fail gracefully, not crash (no valid response due to bad port)
  3128. EXPECT_FALSE(res);
  3129. }
  3130. TEST(RedirectFromPageWithContent, Redirect) {
  3131. Server svr;
  3132. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3133. res.set_content("___", "text/plain");
  3134. res.set_redirect("/2");
  3135. });
  3136. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3137. res.set_content("Hello World!", "text/plain");
  3138. });
  3139. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3140. auto se = detail::scope_exit([&] {
  3141. svr.stop();
  3142. th.join();
  3143. ASSERT_FALSE(svr.is_running());
  3144. });
  3145. svr.wait_until_ready();
  3146. {
  3147. Client cli("localhost", PORT);
  3148. cli.set_follow_location(true);
  3149. std::string body;
  3150. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3151. body.append(data, data_length);
  3152. return true;
  3153. });
  3154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3155. EXPECT_EQ(StatusCode::OK_200, res->status);
  3156. EXPECT_EQ("Hello World!", body);
  3157. }
  3158. {
  3159. Client cli("localhost", PORT);
  3160. std::string body;
  3161. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3162. body.append(data, data_length);
  3163. return true;
  3164. });
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::Found_302, res->status);
  3167. EXPECT_EQ("___", body);
  3168. }
  3169. }
  3170. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3171. Server svr;
  3172. auto port_str = std::to_string(PORT);
  3173. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3174. auto expected_host = "[::1]:" + port_str;
  3175. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3176. res.set_content("___", "text/plain");
  3177. // res.set_redirect("/2");
  3178. res.set_redirect(redirect_url);
  3179. });
  3180. svr.Get("/2", [&](const Request &req, Response &res) {
  3181. auto host_header = req.headers.find("Host");
  3182. ASSERT_TRUE(host_header != req.headers.end());
  3183. EXPECT_EQ(expected_host, host_header->second);
  3184. res.set_content("Hello World!", "text/plain");
  3185. });
  3186. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3187. auto se = detail::scope_exit([&] {
  3188. svr.stop();
  3189. th.join();
  3190. ASSERT_FALSE(svr.is_running());
  3191. });
  3192. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3193. // actually starts anything, so the condition !svr.is_running() will
  3194. // always remain true, and the loop never stops.
  3195. // This basically counts how many milliseconds have passed since the
  3196. // call to svr.listen(), and if after 5 seconds nothing started yet
  3197. // aborts the test.
  3198. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3199. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3200. ASSERT_LT(milliseconds, 5000U);
  3201. }
  3202. {
  3203. Client cli("::1", PORT);
  3204. cli.set_follow_location(true);
  3205. std::string body;
  3206. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3207. body.append(data, data_length);
  3208. return true;
  3209. });
  3210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3211. EXPECT_EQ(StatusCode::OK_200, res->status);
  3212. EXPECT_EQ("Hello World!", body);
  3213. }
  3214. {
  3215. Client cli("::1", PORT);
  3216. std::string body;
  3217. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3218. body.append(data, data_length);
  3219. return true;
  3220. });
  3221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3222. EXPECT_EQ(StatusCode::Found_302, res->status);
  3223. EXPECT_EQ("___", body);
  3224. }
  3225. }
  3226. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3227. Server svr;
  3228. svr.Get("/foo", [](const Request &req, Response &res) {
  3229. auto a = req.params.find("a");
  3230. if (a != req.params.end()) {
  3231. res.set_content((*a).second, "text/plain");
  3232. res.status = StatusCode::OK_200;
  3233. } else {
  3234. res.status = StatusCode::BadRequest_400;
  3235. }
  3236. });
  3237. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3238. auto se = detail::scope_exit([&] {
  3239. svr.stop();
  3240. thread.join();
  3241. ASSERT_FALSE(svr.is_running());
  3242. });
  3243. svr.wait_until_ready();
  3244. {
  3245. Client cli(HOST, PORT);
  3246. cli.set_path_encode(false);
  3247. auto res = cli.Get("/foo?a=explicitly+encoded");
  3248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3249. EXPECT_EQ(StatusCode::OK_200, res->status);
  3250. // This expects it back with a space, as the `+` won't have been
  3251. // url-encoded, and server-side the params get decoded turning `+`
  3252. // into spaces.
  3253. EXPECT_EQ("explicitly encoded", res->body);
  3254. }
  3255. }
  3256. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3257. // When path encoding is disabled the client must transmit the supplied
  3258. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3259. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3260. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3261. // than a space (0x20). Assert on the raw wire target to catch this.
  3262. Server svr;
  3263. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3264. svr.Get("/foo", [&](const Request &req, Response &res) {
  3265. EXPECT_EQ(expected_target, req.target);
  3266. res.status = StatusCode::OK_200;
  3267. });
  3268. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3269. auto se = detail::scope_exit([&] {
  3270. svr.stop();
  3271. thread.join();
  3272. ASSERT_FALSE(svr.is_running());
  3273. });
  3274. svr.wait_until_ready();
  3275. {
  3276. Client cli(HOST, PORT);
  3277. cli.set_path_encode(false);
  3278. auto res = cli.Get(expected_target.c_str());
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. }
  3282. }
  3283. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3284. // `open_stream()` used to skip the path encoding that the buffered send
  3285. // path applies, so the same `path` produced different bytes in the request
  3286. // line depending on which API was used. Assert the two agree.
  3287. Server svr;
  3288. std::string target;
  3289. svr.Get(".*", [&](const Request &req, Response &res) {
  3290. target = req.target;
  3291. res.status = StatusCode::OK_200;
  3292. });
  3293. auto port = svr.bind_to_any_port(HOST);
  3294. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3295. auto se = detail::scope_exit([&] {
  3296. svr.stop();
  3297. thread.join();
  3298. ASSERT_FALSE(svr.is_running());
  3299. });
  3300. svr.wait_until_ready();
  3301. struct {
  3302. const char *path;
  3303. const char *expected;
  3304. } cases[] = {
  3305. {"/a b?x=1", "/a%20b?x=1"},
  3306. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3307. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3308. };
  3309. for (const auto &c : cases) {
  3310. Client cli(HOST, port);
  3311. target.clear();
  3312. auto res = cli.Get(c.path);
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3315. auto buffered_target = target;
  3316. target.clear();
  3317. auto handle = cli.open_stream("GET", c.path);
  3318. EXPECT_TRUE(handle.is_valid())
  3319. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3320. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3321. }
  3322. }
  3323. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3324. // The `set_path_encode(false)` contract — transmit the supplied target
  3325. // verbatim — must hold for the streaming API too.
  3326. Server svr;
  3327. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3328. std::string target;
  3329. svr.Get("/foo", [&](const Request &req, Response &res) {
  3330. target = req.target;
  3331. res.status = StatusCode::OK_200;
  3332. });
  3333. auto port = svr.bind_to_any_port(HOST);
  3334. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3335. auto se = detail::scope_exit([&] {
  3336. svr.stop();
  3337. thread.join();
  3338. ASSERT_FALSE(svr.is_running());
  3339. });
  3340. svr.wait_until_ready();
  3341. {
  3342. Client cli(HOST, port);
  3343. cli.set_path_encode(false);
  3344. auto handle = cli.open_stream("GET", expected_target);
  3345. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3346. EXPECT_EQ(expected_target, target);
  3347. }
  3348. }
  3349. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3350. // With path encoding enabled a CR/LF in the target is percent-encoded
  3351. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3352. // write_request_line still backstops `set_path_encode(false)`, which is
  3353. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3354. Server svr;
  3355. // Captured before routing: the decoded path contains a newline, which a
  3356. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3357. std::string target;
  3358. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3359. target = req.target;
  3360. res.status = StatusCode::OK_200;
  3361. return Server::HandlerResponse::Handled;
  3362. });
  3363. auto port = svr.bind_to_any_port(HOST);
  3364. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3365. auto se = detail::scope_exit([&] {
  3366. svr.stop();
  3367. thread.join();
  3368. ASSERT_FALSE(svr.is_running());
  3369. });
  3370. svr.wait_until_ready();
  3371. {
  3372. Client cli(HOST, port);
  3373. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3374. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3375. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3376. }
  3377. }
  3378. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3379. // Nothing may reach the wire: a raw CR/LF target would split the request
  3380. // line and inject headers.
  3381. Server svr;
  3382. // Pre-routing so that "not called" means nothing reached the server at all,
  3383. // rather than merely failing to match a handler pattern.
  3384. auto handler_called = false;
  3385. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3386. handler_called = true;
  3387. res.status = StatusCode::OK_200;
  3388. return Server::HandlerResponse::Handled;
  3389. });
  3390. auto port = svr.bind_to_any_port(HOST);
  3391. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3392. auto se = detail::scope_exit([&] {
  3393. svr.stop();
  3394. thread.join();
  3395. ASSERT_FALSE(svr.is_running());
  3396. });
  3397. svr.wait_until_ready();
  3398. {
  3399. Client cli(HOST, port);
  3400. cli.set_path_encode(false);
  3401. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3402. EXPECT_FALSE(handle.is_valid());
  3403. EXPECT_EQ(Error::Write, handle.error);
  3404. EXPECT_FALSE(handler_called);
  3405. }
  3406. }
  3407. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3408. // Which of the two branches runs is decided by whether the query component
  3409. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3410. // an empty query and must still fall back to building one from
  3411. // `req.params`, while a non-empty query must win over `req.params`.
  3412. Server svr;
  3413. std::string target;
  3414. svr.Get("/foo", [&](const Request &req, Response &res) {
  3415. target = req.target;
  3416. res.status = StatusCode::OK_200;
  3417. });
  3418. auto port = svr.bind_to_any_port(HOST);
  3419. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3420. auto se = detail::scope_exit([&] {
  3421. svr.stop();
  3422. thread.join();
  3423. ASSERT_FALSE(svr.is_running());
  3424. });
  3425. svr.wait_until_ready();
  3426. {
  3427. // Trailing `?` -> empty query component -> `req.params` is used.
  3428. Client cli(HOST, port);
  3429. Request req;
  3430. req.method = "GET";
  3431. req.path = "/foo?";
  3432. req.params.emplace("a", "1");
  3433. target.clear();
  3434. auto res = cli.send(req);
  3435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3436. EXPECT_EQ("/foo?a=1", target);
  3437. }
  3438. {
  3439. // Non-empty query in `req.path` -> `req.params` is not appended.
  3440. Client cli(HOST, port);
  3441. Request req;
  3442. req.method = "GET";
  3443. req.path = "/foo?b=2";
  3444. req.params.emplace("a", "1");
  3445. target.clear();
  3446. auto res = cli.send(req);
  3447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3448. EXPECT_EQ("/foo?b=2", target);
  3449. }
  3450. }
  3451. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3452. Server svr;
  3453. svr.Get("/", [](const Request &req, Response &) {
  3454. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3455. });
  3456. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3457. auto se = detail::scope_exit([&] {
  3458. svr.stop();
  3459. thread.join();
  3460. ASSERT_FALSE(svr.is_running());
  3461. });
  3462. svr.wait_until_ready();
  3463. {
  3464. Client cli(HOST, PORT);
  3465. cli.set_path_encode(false);
  3466. auto res = cli.Get("/?something=%0A");
  3467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3468. EXPECT_EQ(StatusCode::OK_200, res->status);
  3469. }
  3470. }
  3471. TEST(BindServerTest, BindDualStack) {
  3472. Server svr;
  3473. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3474. res.set_content("Hello World!", "text/plain");
  3475. });
  3476. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3477. auto se = detail::scope_exit([&] {
  3478. svr.stop();
  3479. thread.join();
  3480. ASSERT_FALSE(svr.is_running());
  3481. });
  3482. svr.wait_until_ready();
  3483. {
  3484. Client cli("127.0.0.1", PORT);
  3485. auto res = cli.Get("/1");
  3486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3487. EXPECT_EQ(StatusCode::OK_200, res->status);
  3488. EXPECT_EQ("Hello World!", res->body);
  3489. }
  3490. {
  3491. Client cli("::1", PORT);
  3492. auto res = cli.Get("/1");
  3493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3494. EXPECT_EQ(StatusCode::OK_200, res->status);
  3495. EXPECT_EQ("Hello World!", res->body);
  3496. }
  3497. }
  3498. TEST(BindServerTest, BindAndListenSeparately) {
  3499. Server svr;
  3500. int port = svr.bind_to_any_port("0.0.0.0");
  3501. ASSERT_TRUE(svr.is_valid());
  3502. ASSERT_TRUE(port > 0);
  3503. svr.stop();
  3504. }
  3505. // Reports whether anything is still listening on a loopback port. A plain
  3506. // connect() is used instead of a Client request because a socket left bound by
  3507. // mistake accepts the connection into its backlog and never answers, which
  3508. // would hang the test instead of failing it.
  3509. static bool is_loopback_port_accepting(int port) {
  3510. sockaddr_in addr{};
  3511. addr.sin_family = AF_INET;
  3512. addr.sin_port = htons(static_cast<uint16_t>(port));
  3513. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3514. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3515. EXPECT_NE(sock, INVALID_SOCKET);
  3516. if (sock == INVALID_SOCKET) { return false; }
  3517. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3518. static_cast<socklen_t>(sizeof(addr)));
  3519. detail::close_socket(sock);
  3520. return ret == 0;
  3521. }
  3522. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3523. Server svr;
  3524. auto port = svr.bind_to_any_port("127.0.0.1");
  3525. ASSERT_TRUE(port > 0);
  3526. svr.stop();
  3527. // bind_to_any_port() already called listen(2), so until stop() closed the
  3528. // descriptor the port kept accepting connections into the backlog. ASSERT
  3529. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3530. // below blocks forever in the accept loop.
  3531. ASSERT_FALSE(is_loopback_port_accepting(port));
  3532. // Nothing is left to accept on, so listen_after_bind() must report failure
  3533. // instead of returning success without ever serving.
  3534. EXPECT_FALSE(svr.listen_after_bind());
  3535. // The failed listen marks the server decommissioned, so a waiter returns
  3536. // instead of spinning forever.
  3537. svr.wait_until_ready();
  3538. }
  3539. #ifdef CPPHTTPLIB_SSL_ENABLED
  3540. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3542. CLIENT_CA_CERT_DIR);
  3543. int port = svr.bind_to_any_port("0.0.0.0");
  3544. ASSERT_TRUE(svr.is_valid());
  3545. ASSERT_TRUE(port > 0);
  3546. svr.stop();
  3547. }
  3548. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3549. // or a rejected CustomRoute() registration would not stop the server binding.
  3550. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3552. CLIENT_CA_CERT_DIR);
  3553. ASSERT_TRUE(svr.is_valid());
  3554. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3555. EXPECT_FALSE(svr.is_valid());
  3556. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3557. }
  3558. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3559. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3560. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3561. int port = svr.bind_to_any_port("0.0.0.0");
  3562. ASSERT_TRUE(svr.is_valid());
  3563. ASSERT_TRUE(port > 0);
  3564. svr.stop();
  3565. }
  3566. TEST(BindServerTest, UpdateCertsPem) {
  3567. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3568. int port = svr.bind_to_any_port("0.0.0.0");
  3569. ASSERT_TRUE(svr.is_valid());
  3570. ASSERT_TRUE(port > 0);
  3571. // Read PEM files
  3572. std::string cert_pem, key_pem, ca_pem;
  3573. read_file(SERVER_CERT_FILE, cert_pem);
  3574. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3575. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3576. // Update server certificates using PEM API
  3577. ASSERT_TRUE(
  3578. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3579. ASSERT_TRUE(svr.is_valid());
  3580. svr.stop();
  3581. }
  3582. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3583. // Start server with client CA (enables client auth)
  3584. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3585. ASSERT_TRUE(svr.is_valid());
  3586. bool handler_called = false;
  3587. svr.Get("/test", [&](const Request &req, Response &res) {
  3588. handler_called = true;
  3589. // Verify client certificate is present
  3590. auto cert = req.peer_cert();
  3591. EXPECT_TRUE(static_cast<bool>(cert));
  3592. res.set_content("ok", "text/plain");
  3593. });
  3594. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3595. auto se = detail::scope_exit([&] {
  3596. svr.stop();
  3597. t.join();
  3598. ASSERT_FALSE(svr.is_running());
  3599. });
  3600. svr.wait_until_ready();
  3601. // Read PEM files
  3602. std::string cert_pem, key_pem, ca_pem;
  3603. read_file(SERVER_CERT_FILE, cert_pem);
  3604. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3605. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3606. // Update server certificates and client CA using PEM API while server running
  3607. ASSERT_TRUE(
  3608. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3609. // Connect with client certificate
  3610. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3611. cli.enable_server_certificate_verification(false);
  3612. cli.set_connection_timeout(30);
  3613. auto res = cli.Get("/test");
  3614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3615. ASSERT_EQ(StatusCode::OK_200, res->status);
  3616. ASSERT_TRUE(handler_called);
  3617. EXPECT_EQ("ok", res->body);
  3618. }
  3619. #endif
  3620. TEST(ErrorHandlerTest, ContentLength) {
  3621. Server svr;
  3622. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3623. res.status = StatusCode::OK_200;
  3624. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3625. "text/html"); // <= Content-Length still 13
  3626. });
  3627. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3628. res.set_content("Hello World!\n", "text/plain");
  3629. res.status = 524;
  3630. });
  3631. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3632. auto se = detail::scope_exit([&] {
  3633. svr.stop();
  3634. thread.join();
  3635. ASSERT_FALSE(svr.is_running());
  3636. });
  3637. svr.wait_until_ready();
  3638. {
  3639. Client cli(HOST, PORT);
  3640. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3642. EXPECT_EQ(StatusCode::OK_200, res->status);
  3643. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3644. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3645. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3646. }
  3647. }
  3648. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3649. TEST(ExceptionTest, WithoutExceptionHandler) {
  3650. Server svr;
  3651. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3652. throw std::runtime_error("exception...");
  3653. });
  3654. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3655. throw std::runtime_error("exception\r\n...");
  3656. });
  3657. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3658. auto se = detail::scope_exit([&] {
  3659. svr.stop();
  3660. listen_thread.join();
  3661. ASSERT_FALSE(svr.is_running());
  3662. });
  3663. svr.wait_until_ready();
  3664. Client cli("localhost", PORT);
  3665. {
  3666. auto res = cli.Get("/exception");
  3667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3668. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3669. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3670. }
  3671. {
  3672. auto res = cli.Get("/unknown");
  3673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3674. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3675. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3676. }
  3677. }
  3678. TEST(ExceptionTest, WithExceptionHandler) {
  3679. Server svr;
  3680. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3681. std::exception_ptr ep) {
  3682. EXPECT_FALSE(ep == nullptr);
  3683. try {
  3684. std::rethrow_exception(ep);
  3685. } catch (std::exception &e) {
  3686. EXPECT_EQ("abc", std::string(e.what()));
  3687. } catch (...) {}
  3688. res.status = StatusCode::InternalServerError_500;
  3689. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3690. "text/html"); // <= Content-Length still 13 at this point
  3691. });
  3692. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3693. res.set_content("Hello World!\n", "text/plain");
  3694. throw std::runtime_error("abc");
  3695. });
  3696. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3697. auto se = detail::scope_exit([&] {
  3698. svr.stop();
  3699. thread.join();
  3700. ASSERT_FALSE(svr.is_running());
  3701. });
  3702. svr.wait_until_ready();
  3703. for (size_t i = 0; i < 10; i++) {
  3704. Client cli(HOST, PORT);
  3705. for (size_t j = 0; j < 100; j++) {
  3706. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3708. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3709. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3710. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3711. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3712. }
  3713. cli.set_keep_alive(true);
  3714. for (size_t j = 0; j < 100; j++) {
  3715. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3717. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3718. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3719. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3720. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3721. }
  3722. }
  3723. }
  3724. TEST(ExceptionTest, AndErrorHandler) {
  3725. Server svr;
  3726. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3727. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3728. });
  3729. svr.set_exception_handler(
  3730. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3731. EXPECT_FALSE(ep == nullptr);
  3732. try {
  3733. std::rethrow_exception(ep);
  3734. } catch (std::exception &e) {
  3735. res.set_content(e.what(), "text/html");
  3736. } catch (...) {}
  3737. res.status = StatusCode::InternalServerError_500;
  3738. });
  3739. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3740. throw std::runtime_error("EXCEPTION");
  3741. });
  3742. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3743. res.set_content("ERROR", "text/html");
  3744. res.status = StatusCode::InternalServerError_500;
  3745. });
  3746. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3747. auto se = detail::scope_exit([&] {
  3748. svr.stop();
  3749. thread.join();
  3750. ASSERT_FALSE(svr.is_running());
  3751. });
  3752. svr.wait_until_ready();
  3753. Client cli(HOST, PORT);
  3754. {
  3755. auto res = cli.Get("/exception");
  3756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3757. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3758. EXPECT_EQ("EXCEPTION", res->body);
  3759. }
  3760. {
  3761. auto res = cli.Get("/error");
  3762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3763. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3764. EXPECT_EQ("ERROR", res->body);
  3765. }
  3766. {
  3767. auto res = cli.Get("/invalid");
  3768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3769. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3770. EXPECT_EQ("NOT_FOUND", res->body);
  3771. }
  3772. }
  3773. #endif
  3774. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3775. // process_request() wraps only routing() in a try/catch, so an exception from
  3776. // any other user callback used to unwind into the task queue - which does not
  3777. // catch - and terminate the process. Each test below runs the server on a
  3778. // single worker thread: a guard that catches the exception but still loses the
  3779. // thread would otherwise be hidden by a spare worker serving the follow-up
  3780. // request. Note that a regression here aborts the whole test binary rather
  3781. // than failing one test.
  3782. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3783. Server svr;
  3784. svr.new_task_queue = [] { return new ThreadPool(1); };
  3785. std::atomic<int> reported{0};
  3786. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3787. if (err == Error::UserCallbackException) { reported++; }
  3788. });
  3789. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3790. res.set_content_provider(
  3791. 1024, "text/plain",
  3792. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3793. sink.write("hello", 5);
  3794. throw std::runtime_error("from the content provider");
  3795. });
  3796. });
  3797. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3798. res.set_content("ok", "text/plain");
  3799. });
  3800. auto port = svr.bind_to_any_port(HOST);
  3801. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3802. auto se = detail::scope_exit([&] {
  3803. svr.stop();
  3804. listen_thread.join();
  3805. ASSERT_FALSE(svr.is_running());
  3806. });
  3807. svr.wait_until_ready();
  3808. {
  3809. Client cli(HOST, port);
  3810. cli.set_read_timeout(5, 0);
  3811. EXPECT_FALSE(cli.Get("/throw"));
  3812. }
  3813. EXPECT_TRUE(svr.is_running());
  3814. EXPECT_EQ(1, reported.load());
  3815. // A request on a fresh connection is still served.
  3816. {
  3817. Client cli(HOST, port);
  3818. auto res = cli.Get("/ok");
  3819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3820. EXPECT_EQ(StatusCode::OK_200, res->status);
  3821. EXPECT_EQ("ok", res->body);
  3822. }
  3823. }
  3824. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3825. Server svr;
  3826. svr.new_task_queue = [] { return new ThreadPool(1); };
  3827. std::atomic<bool> should_throw{true};
  3828. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3829. res.set_content("hi", "text/plain");
  3830. });
  3831. svr.set_post_routing_handler(
  3832. [&](const Request & /*req*/, Response & /*res*/) {
  3833. if (should_throw) {
  3834. throw std::runtime_error("from the post-routing handler");
  3835. }
  3836. });
  3837. auto port = svr.bind_to_any_port(HOST);
  3838. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3839. auto se = detail::scope_exit([&] {
  3840. svr.stop();
  3841. listen_thread.join();
  3842. ASSERT_FALSE(svr.is_running());
  3843. });
  3844. svr.wait_until_ready();
  3845. {
  3846. Client cli(HOST, port);
  3847. cli.set_read_timeout(5, 0);
  3848. EXPECT_FALSE(cli.Get("/hi"));
  3849. }
  3850. EXPECT_TRUE(svr.is_running());
  3851. should_throw = false;
  3852. {
  3853. Client cli(HOST, port);
  3854. auto res = cli.Get("/hi");
  3855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3856. EXPECT_EQ(StatusCode::OK_200, res->status);
  3857. EXPECT_EQ("hi", res->body);
  3858. }
  3859. }
  3860. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3861. // The guard reports the caught exception through the error logger, which is
  3862. // a user callback too. A logger that throws has to be contained as well, or
  3863. // the process would terminate from inside the catch.
  3864. Server svr;
  3865. svr.new_task_queue = [] { return new ThreadPool(1); };
  3866. std::atomic<int> reported{0};
  3867. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3868. if (err == Error::UserCallbackException) {
  3869. reported++;
  3870. throw std::runtime_error("from the error logger");
  3871. }
  3872. });
  3873. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3874. res.set_content_provider(
  3875. 1024, "text/plain",
  3876. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3877. sink.write("hello", 5);
  3878. throw std::runtime_error("from the content provider");
  3879. });
  3880. });
  3881. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3882. res.set_content("ok", "text/plain");
  3883. });
  3884. auto port = svr.bind_to_any_port(HOST);
  3885. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3886. auto se = detail::scope_exit([&] {
  3887. svr.stop();
  3888. listen_thread.join();
  3889. ASSERT_FALSE(svr.is_running());
  3890. });
  3891. svr.wait_until_ready();
  3892. {
  3893. Client cli(HOST, port);
  3894. cli.set_read_timeout(5, 0);
  3895. EXPECT_FALSE(cli.Get("/throw"));
  3896. }
  3897. EXPECT_TRUE(svr.is_running());
  3898. EXPECT_EQ(1, reported.load());
  3899. {
  3900. Client cli(HOST, port);
  3901. auto res = cli.Get("/ok");
  3902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3903. EXPECT_EQ(StatusCode::OK_200, res->status);
  3904. EXPECT_EQ("ok", res->body);
  3905. }
  3906. }
  3907. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3908. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3909. // so the exception unwinds through the ws::WebSocket object on its way to
  3910. // the guard. None of the HTTP cases above cross that.
  3911. Server svr;
  3912. svr.new_task_queue = [] { return new ThreadPool(1); };
  3913. std::atomic<int> reported{0};
  3914. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3915. if (err == Error::UserCallbackException) { reported++; }
  3916. });
  3917. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3918. throw std::runtime_error("from the WebSocket handler");
  3919. });
  3920. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3921. res.set_content("ok", "text/plain");
  3922. });
  3923. auto port = svr.bind_to_any_port(HOST);
  3924. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3925. auto se = detail::scope_exit([&] {
  3926. svr.stop();
  3927. listen_thread.join();
  3928. ASSERT_FALSE(svr.is_running());
  3929. });
  3930. svr.wait_until_ready();
  3931. {
  3932. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3933. "/ws");
  3934. auto res = client.connect();
  3935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3936. // The server dropped the connection instead of dying.
  3937. std::string msg;
  3938. EXPECT_FALSE(client.read(msg));
  3939. client.close();
  3940. }
  3941. EXPECT_TRUE(svr.is_running());
  3942. EXPECT_EQ(1, reported.load());
  3943. {
  3944. Client cli(HOST, port);
  3945. auto res = cli.Get("/ok");
  3946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3947. EXPECT_EQ(StatusCode::OK_200, res->status);
  3948. EXPECT_EQ("ok", res->body);
  3949. }
  3950. }
  3951. #ifdef CPPHTTPLIB_SSL_ENABLED
  3952. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3953. // SSLServer::process_and_close_socket() is a separate overload with its own
  3954. // guard, so it is exercised on its own.
  3955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3956. ASSERT_TRUE(svr.is_valid());
  3957. svr.new_task_queue = [] { return new ThreadPool(1); };
  3958. std::atomic<int> reported{0};
  3959. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3960. if (err == Error::UserCallbackException) { reported++; }
  3961. });
  3962. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3963. res.set_content_provider(
  3964. 1024, "text/plain",
  3965. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3966. sink.write("hello", 5);
  3967. throw std::runtime_error("from the content provider");
  3968. });
  3969. });
  3970. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3971. res.set_content("ok", "text/plain");
  3972. });
  3973. auto port = svr.bind_to_any_port(HOST);
  3974. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3975. auto se = detail::scope_exit([&] {
  3976. svr.stop();
  3977. listen_thread.join();
  3978. ASSERT_FALSE(svr.is_running());
  3979. });
  3980. svr.wait_until_ready();
  3981. {
  3982. SSLClient cli(HOST, port);
  3983. cli.enable_server_certificate_verification(false);
  3984. cli.set_read_timeout(5, 0);
  3985. EXPECT_FALSE(cli.Get("/throw"));
  3986. }
  3987. EXPECT_TRUE(svr.is_running());
  3988. EXPECT_EQ(1, reported.load());
  3989. {
  3990. SSLClient cli(HOST, port);
  3991. cli.enable_server_certificate_verification(false);
  3992. auto res = cli.Get("/ok");
  3993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3994. EXPECT_EQ(StatusCode::OK_200, res->status);
  3995. EXPECT_EQ("ok", res->body);
  3996. }
  3997. }
  3998. #endif
  3999. #endif
  4000. TEST(NoContentTest, ContentLength) {
  4001. Server svr;
  4002. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4003. res.status = StatusCode::NoContent_204;
  4004. });
  4005. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4006. auto se = detail::scope_exit([&] {
  4007. svr.stop();
  4008. thread.join();
  4009. ASSERT_FALSE(svr.is_running());
  4010. });
  4011. svr.wait_until_ready();
  4012. {
  4013. Client cli(HOST, PORT);
  4014. auto res = cli.Get("/hi");
  4015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4016. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4017. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4018. }
  4019. }
  4020. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4021. #ifdef CPPHTTPLIB_SSL_ENABLED
  4022. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4023. ASSERT_TRUE(svr.is_valid());
  4024. #else
  4025. Server svr;
  4026. #endif
  4027. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4028. if (req.path == "/routing_handler") {
  4029. res.set_header("PRE_ROUTING", "on");
  4030. res.set_content("Routing Handler", "text/plain");
  4031. return httplib::Server::HandlerResponse::Handled;
  4032. }
  4033. return httplib::Server::HandlerResponse::Unhandled;
  4034. });
  4035. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4036. res.set_content("Error", "text/html");
  4037. });
  4038. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4039. if (req.path == "/routing_handler") {
  4040. res.set_header("POST_ROUTING", "on");
  4041. }
  4042. });
  4043. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4044. res.set_content("Hello World!\n", "text/plain");
  4045. });
  4046. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4047. auto se = detail::scope_exit([&] {
  4048. svr.stop();
  4049. thread.join();
  4050. ASSERT_FALSE(svr.is_running());
  4051. });
  4052. svr.wait_until_ready();
  4053. {
  4054. #ifdef CPPHTTPLIB_SSL_ENABLED
  4055. SSLClient cli(HOST, PORT);
  4056. cli.enable_server_certificate_verification(false);
  4057. #else
  4058. Client cli(HOST, PORT);
  4059. #endif
  4060. auto res = cli.Get("/routing_handler");
  4061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4062. EXPECT_EQ(StatusCode::OK_200, res->status);
  4063. EXPECT_EQ("Routing Handler", res->body);
  4064. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4065. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4066. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4067. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4068. }
  4069. {
  4070. #ifdef CPPHTTPLIB_SSL_ENABLED
  4071. SSLClient cli(HOST, PORT);
  4072. cli.enable_server_certificate_verification(false);
  4073. #else
  4074. Client cli(HOST, PORT);
  4075. #endif
  4076. auto res = cli.Get("/hi");
  4077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4078. EXPECT_EQ(StatusCode::OK_200, res->status);
  4079. EXPECT_EQ("Hello World!\n", res->body);
  4080. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4081. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4082. }
  4083. {
  4084. #ifdef CPPHTTPLIB_SSL_ENABLED
  4085. SSLClient cli(HOST, PORT);
  4086. cli.enable_server_certificate_verification(false);
  4087. #else
  4088. Client cli(HOST, PORT);
  4089. #endif
  4090. auto res = cli.Get("/aaa");
  4091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4092. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4093. EXPECT_EQ("Error", res->body);
  4094. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4095. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4096. }
  4097. }
  4098. TEST(RequestHandlerTest, PreRequestHandler) {
  4099. auto route_path = "/user/:user";
  4100. Server svr;
  4101. svr.Get("/hi", [](const Request &, Response &res) {
  4102. res.set_content("hi", "text/plain");
  4103. });
  4104. svr.Get(route_path, [](const Request &req, Response &res) {
  4105. res.set_content(req.path_params.at("user"), "text/plain");
  4106. });
  4107. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4108. if (req.matched_route == route_path) {
  4109. auto user = req.path_params.at("user");
  4110. if (user != "john") {
  4111. res.status = StatusCode::Forbidden_403;
  4112. res.set_content("error", "text/html");
  4113. return Server::HandlerResponse::Handled;
  4114. }
  4115. }
  4116. return Server::HandlerResponse::Unhandled;
  4117. });
  4118. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4119. auto se = detail::scope_exit([&] {
  4120. svr.stop();
  4121. thread.join();
  4122. ASSERT_FALSE(svr.is_running());
  4123. });
  4124. svr.wait_until_ready();
  4125. Client cli(HOST, PORT);
  4126. {
  4127. auto res = cli.Get("/hi");
  4128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4129. EXPECT_EQ(StatusCode::OK_200, res->status);
  4130. EXPECT_EQ("hi", res->body);
  4131. }
  4132. {
  4133. auto res = cli.Get("/user/john");
  4134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4135. EXPECT_EQ(StatusCode::OK_200, res->status);
  4136. EXPECT_EQ("john", res->body);
  4137. }
  4138. {
  4139. auto res = cli.Get("/user/invalid-user");
  4140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4141. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4142. EXPECT_EQ("error", res->body);
  4143. }
  4144. }
  4145. // The pre-request handler must run before the request body is read, so a
  4146. // rejected request never forces the server to buffer a (potentially large)
  4147. // body. Here the posted body is larger than the payload limit: if the body
  4148. // were read first the server would answer 413, but because the pre-request
  4149. // handler runs first it answers 403 and the body is never read.
  4150. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4151. Server svr;
  4152. svr.set_payload_max_length(8);
  4153. auto handler_ran = false;
  4154. svr.Post("/reject", [&](const Request &req, Response &res) {
  4155. handler_ran = true;
  4156. res.set_content(req.body, "text/plain");
  4157. });
  4158. svr.Post("/accept", [](const Request &req, Response &res) {
  4159. res.set_content(req.body, "text/plain");
  4160. });
  4161. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4162. if (req.matched_route == "/reject") {
  4163. res.status = StatusCode::Forbidden_403;
  4164. res.set_content("denied", "text/plain");
  4165. return Server::HandlerResponse::Handled;
  4166. }
  4167. return Server::HandlerResponse::Unhandled;
  4168. });
  4169. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4170. auto se = detail::scope_exit([&] {
  4171. svr.stop();
  4172. thread.join();
  4173. ASSERT_FALSE(svr.is_running());
  4174. });
  4175. svr.wait_until_ready();
  4176. Client cli(HOST, PORT);
  4177. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4178. // rejects with 403 before the body is read, so 413 is never reached.
  4179. {
  4180. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4182. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4183. EXPECT_EQ("denied", res->body);
  4184. EXPECT_FALSE(handler_ran);
  4185. }
  4186. // An approved route still reads the body and enforces the payload limit.
  4187. {
  4188. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4190. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4191. }
  4192. }
  4193. TEST(UserDataTest, BasicOperations) {
  4194. httplib::UserData ud;
  4195. // Initially empty
  4196. EXPECT_FALSE(ud.has("key"));
  4197. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4198. // set and get
  4199. ud.set("key", 42);
  4200. EXPECT_TRUE(ud.has("key"));
  4201. auto *p = ud.get<int>("key");
  4202. ASSERT_NE(nullptr, p);
  4203. EXPECT_EQ(42, *p);
  4204. // Type mismatch → nullptr
  4205. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4206. // Overwrite with different type
  4207. ud.set("key", std::string("hello"));
  4208. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4209. auto *s = ud.get<std::string>("key");
  4210. ASSERT_NE(nullptr, s);
  4211. EXPECT_EQ("hello", *s);
  4212. // erase
  4213. ud.erase("key");
  4214. EXPECT_FALSE(ud.has("key"));
  4215. // clear
  4216. ud.set("a", 1);
  4217. ud.set("b", 2);
  4218. ud.clear();
  4219. EXPECT_FALSE(ud.has("a"));
  4220. EXPECT_FALSE(ud.has("b"));
  4221. }
  4222. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4223. struct AuthCtx {
  4224. std::string user_id;
  4225. };
  4226. Server svr;
  4227. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4228. res.user_data.set("auth", AuthCtx{"alice"});
  4229. return Server::HandlerResponse::Unhandled;
  4230. });
  4231. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4232. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4233. ASSERT_NE(nullptr, ctx);
  4234. res.set_content("Hello " + ctx->user_id, "text/plain");
  4235. });
  4236. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4237. auto se = detail::scope_exit([&] {
  4238. svr.stop();
  4239. thread.join();
  4240. ASSERT_FALSE(svr.is_running());
  4241. });
  4242. svr.wait_until_ready();
  4243. Client cli(HOST, PORT);
  4244. auto res = cli.Get("/me");
  4245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4246. EXPECT_EQ(StatusCode::OK_200, res->status);
  4247. EXPECT_EQ("Hello alice", res->body);
  4248. }
  4249. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4250. struct RoleCtx {
  4251. std::string role;
  4252. };
  4253. Server svr;
  4254. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4255. res.user_data.set("role", RoleCtx{"admin"});
  4256. return Server::HandlerResponse::Unhandled;
  4257. });
  4258. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4259. auto *ctx = res.user_data.get<RoleCtx>("role");
  4260. ASSERT_NE(nullptr, ctx);
  4261. res.set_content(ctx->role, "text/plain");
  4262. });
  4263. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4264. auto se = detail::scope_exit([&] {
  4265. svr.stop();
  4266. thread.join();
  4267. ASSERT_FALSE(svr.is_running());
  4268. });
  4269. svr.wait_until_ready();
  4270. Client cli(HOST, PORT);
  4271. auto res = cli.Get("/role");
  4272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4273. EXPECT_EQ(StatusCode::OK_200, res->status);
  4274. EXPECT_EQ("admin", res->body);
  4275. }
  4276. TEST(InvalidFormatTest, StatusCode) {
  4277. Server svr;
  4278. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4279. res.set_content("Hello World!\n", "text/plain");
  4280. res.status = 9999; // Status should be a three-digit code...
  4281. });
  4282. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4283. auto se = detail::scope_exit([&] {
  4284. svr.stop();
  4285. thread.join();
  4286. ASSERT_FALSE(svr.is_running());
  4287. });
  4288. svr.wait_until_ready();
  4289. {
  4290. Client cli(HOST, PORT);
  4291. auto res = cli.Get("/hi");
  4292. ASSERT_FALSE(res);
  4293. }
  4294. }
  4295. TEST(URLFragmentTest, WithFragment) {
  4296. Server svr;
  4297. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4298. EXPECT_TRUE(req.target == "/hi");
  4299. });
  4300. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4301. auto se = detail::scope_exit([&] {
  4302. svr.stop();
  4303. thread.join();
  4304. ASSERT_FALSE(svr.is_running());
  4305. });
  4306. svr.wait_until_ready();
  4307. {
  4308. Client cli(HOST, PORT);
  4309. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4310. EXPECT_TRUE(res);
  4311. EXPECT_EQ(StatusCode::OK_200, res->status);
  4312. res = cli.Get("/hi%23key1=val1=key2=val2");
  4313. EXPECT_TRUE(res);
  4314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4315. }
  4316. }
  4317. TEST(HeaderWriter, SetHeaderWriter) {
  4318. Server svr;
  4319. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4320. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4321. return detail::write_headers(strm, hdrs);
  4322. });
  4323. svr.Get("/hi", [](const Request &req, Response &res) {
  4324. auto it = req.headers.find("CustomClientHeader");
  4325. EXPECT_TRUE(it != req.headers.end());
  4326. EXPECT_EQ(it->second, "CustomClientValue");
  4327. res.set_content("Hello World!\n", "text/plain");
  4328. });
  4329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4330. auto se = detail::scope_exit([&] {
  4331. svr.stop();
  4332. thread.join();
  4333. ASSERT_FALSE(svr.is_running());
  4334. });
  4335. svr.wait_until_ready();
  4336. {
  4337. Client cli(HOST, PORT);
  4338. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4339. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4340. return detail::write_headers(strm, hdrs);
  4341. });
  4342. auto res = cli.Get("/hi");
  4343. EXPECT_TRUE(res);
  4344. EXPECT_EQ(StatusCode::OK_200, res->status);
  4345. auto it = res->headers.find("CustomServerHeader");
  4346. EXPECT_TRUE(it != res->headers.end());
  4347. EXPECT_EQ(it->second, "CustomServerValue");
  4348. }
  4349. }
  4350. class ServerTest : public ::testing::Test {
  4351. protected:
  4352. ServerTest()
  4353. : cli_(HOST, PORT)
  4354. #ifdef CPPHTTPLIB_SSL_ENABLED
  4355. ,
  4356. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4357. #endif
  4358. {
  4359. #ifdef CPPHTTPLIB_SSL_ENABLED
  4360. cli_.enable_server_certificate_verification(false);
  4361. #endif
  4362. // Allow LARGE_DATA (100MB) responses
  4363. cli_.set_payload_max_length(200 * 1024 * 1024);
  4364. }
  4365. virtual void SetUp() {
  4366. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4367. svr_.set_payload_max_length(200 * 1024 * 1024);
  4368. svr_.set_mount_point("/", "./www");
  4369. svr_.set_mount_point("/mount", "./www2");
  4370. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4371. svr_.Get("/hi",
  4372. [&](const Request & /*req*/, Response &res) {
  4373. res.set_content("Hello World!", "text/plain");
  4374. })
  4375. .Get("/file_content",
  4376. [&](const Request & /*req*/, Response &res) {
  4377. res.set_file_content("./www/dir/test.html");
  4378. })
  4379. .Get("/file_content_with_content_type",
  4380. [&](const Request & /*req*/, Response &res) {
  4381. res.set_file_content("./www/file", "text/plain");
  4382. })
  4383. .Get("/invalid_file_content",
  4384. [&](const Request & /*req*/, Response &res) {
  4385. res.set_file_content("./www/dir/invalid_file_path");
  4386. })
  4387. .Get("/http_response_splitting",
  4388. [&](const Request & /*req*/, Response &res) {
  4389. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4390. EXPECT_EQ(0U, res.headers.size());
  4391. EXPECT_FALSE(res.has_header("a"));
  4392. res.set_header("a", "1\nSet-Cookie: a=1");
  4393. EXPECT_EQ(0U, res.headers.size());
  4394. EXPECT_FALSE(res.has_header("a"));
  4395. res.set_header("a", "1\rSet-Cookie: a=1");
  4396. EXPECT_EQ(0U, res.headers.size());
  4397. EXPECT_FALSE(res.has_header("a"));
  4398. res.set_header("a\r\nb", "0");
  4399. EXPECT_EQ(0U, res.headers.size());
  4400. EXPECT_FALSE(res.has_header("a"));
  4401. res.set_header("a\rb", "0");
  4402. EXPECT_EQ(0U, res.headers.size());
  4403. EXPECT_FALSE(res.has_header("a"));
  4404. res.set_header("a\nb", "0");
  4405. EXPECT_EQ(0U, res.headers.size());
  4406. EXPECT_FALSE(res.has_header("a"));
  4407. res.set_redirect("1\r\nSet-Cookie: a=1");
  4408. EXPECT_EQ(0U, res.headers.size());
  4409. EXPECT_FALSE(res.has_header("Location"));
  4410. })
  4411. .Get("/slow",
  4412. [&](const Request & /*req*/, Response &res) {
  4413. std::this_thread::sleep_for(std::chrono::seconds(4));
  4414. res.set_content("slow", "text/plain");
  4415. })
  4416. #if 0
  4417. .Post("/slowpost",
  4418. [&](const Request & /*req*/, Response &res) {
  4419. std::this_thread::sleep_for(std::chrono::seconds(2));
  4420. res.set_content("slow", "text/plain");
  4421. })
  4422. #endif
  4423. .Get("/remote_addr",
  4424. [&](const Request &req, Response &res) {
  4425. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4426. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4427. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4428. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4429. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4430. #endif
  4431. res.set_content(req.remote_addr, "text/plain");
  4432. })
  4433. .Get("/local_addr",
  4434. [&](const Request &req, Response &res) {
  4435. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4436. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4437. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4438. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4439. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4440. #endif
  4441. auto local_addr = req.local_addr;
  4442. auto local_port = std::to_string(req.local_port);
  4443. res.set_content(local_addr.append(":").append(local_port),
  4444. "text/plain");
  4445. })
  4446. .Get("/endwith%",
  4447. [&](const Request & /*req*/, Response &res) {
  4448. res.set_content("Hello World!", "text/plain");
  4449. })
  4450. .Get("/a\\+\\+b",
  4451. [&](const Request &req, Response &res) {
  4452. ASSERT_TRUE(req.has_param("a +b"));
  4453. auto val = req.get_param_value("a +b");
  4454. res.set_content(val, "text/plain");
  4455. })
  4456. .Get("/", [&](const Request & /*req*/,
  4457. Response &res) { res.set_redirect("/hi"); })
  4458. .Post("/1",
  4459. [](const Request & /*req*/, Response &res) {
  4460. res.set_redirect("/2", StatusCode::SeeOther_303);
  4461. })
  4462. .Get("/2",
  4463. [](const Request & /*req*/, Response &res) {
  4464. res.set_content("redirected.", "text/plain");
  4465. res.status = StatusCode::OK_200;
  4466. })
  4467. .Post("/person",
  4468. [&](const Request &req, Response &res) {
  4469. if (req.has_param("name") && req.has_param("note")) {
  4470. persons_[req.get_param_value("name")] =
  4471. req.get_param_value("note");
  4472. } else {
  4473. res.status = StatusCode::BadRequest_400;
  4474. }
  4475. })
  4476. .Put("/person",
  4477. [&](const Request &req, Response &res) {
  4478. if (req.has_param("name") && req.has_param("note")) {
  4479. persons_[req.get_param_value("name")] =
  4480. req.get_param_value("note");
  4481. } else {
  4482. res.status = StatusCode::BadRequest_400;
  4483. }
  4484. })
  4485. .Get("/person/(.*)",
  4486. [&](const Request &req, Response &res) {
  4487. string name = req.matches[1];
  4488. if (persons_.find(name) != persons_.end()) {
  4489. auto note = persons_[name];
  4490. res.set_content(note, "text/plain");
  4491. } else {
  4492. res.status = StatusCode::NotFound_404;
  4493. }
  4494. })
  4495. .Delete("/person",
  4496. [&](const Request &req, Response &res) {
  4497. if (req.has_param("name")) {
  4498. string name = req.get_param_value("name");
  4499. if (persons_.find(name) != persons_.end()) {
  4500. persons_.erase(name);
  4501. res.set_content("DELETED", "text/plain");
  4502. } else {
  4503. res.status = StatusCode::NotFound_404;
  4504. }
  4505. } else {
  4506. res.status = StatusCode::BadRequest_400;
  4507. }
  4508. })
  4509. .Post("/x-www-form-urlencoded-json",
  4510. [&](const Request &req, Response &res) {
  4511. auto json = req.get_param_value("json");
  4512. ASSERT_EQ(JSON_DATA, json);
  4513. res.set_content(json, "appliation/json");
  4514. res.status = StatusCode::OK_200;
  4515. })
  4516. .Get("/streamed-chunked",
  4517. [&](const Request & /*req*/, Response &res) {
  4518. res.set_chunked_content_provider(
  4519. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4520. sink.os << "123";
  4521. sink.os << "456";
  4522. sink.os << "789";
  4523. sink.done();
  4524. return true;
  4525. });
  4526. })
  4527. .Get("/streamed-chunked-with-prohibited-trailer",
  4528. [&](const Request & /*req*/, Response &res) {
  4529. auto i = new int(0);
  4530. // Declare both a prohibited trailer (Content-Length) and an
  4531. // allowed one
  4532. res.set_header("Trailer", "Content-Length, X-Allowed");
  4533. res.set_chunked_content_provider(
  4534. "text/plain",
  4535. [i](size_t /*offset*/, DataSink &sink) {
  4536. switch (*i) {
  4537. case 0: sink.os << "123"; break;
  4538. case 1: sink.os << "456"; break;
  4539. case 2: sink.os << "789"; break;
  4540. case 3: {
  4541. sink.done_with_trailer(
  4542. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4543. } break;
  4544. }
  4545. (*i)++;
  4546. return true;
  4547. },
  4548. [i](bool success) {
  4549. EXPECT_TRUE(success);
  4550. delete i;
  4551. });
  4552. })
  4553. .Get("/streamed-chunked2",
  4554. [&](const Request & /*req*/, Response &res) {
  4555. auto i = new int(0);
  4556. res.set_chunked_content_provider(
  4557. "text/plain",
  4558. [i](size_t /*offset*/, DataSink &sink) {
  4559. switch (*i) {
  4560. case 0: sink.os << "123"; break;
  4561. case 1: sink.os << "456"; break;
  4562. case 2: sink.os << "789"; break;
  4563. case 3: sink.done(); break;
  4564. }
  4565. (*i)++;
  4566. return true;
  4567. },
  4568. [i](bool success) {
  4569. EXPECT_TRUE(success);
  4570. delete i;
  4571. });
  4572. })
  4573. .Get("/streamed-chunked-with-trailer",
  4574. [&](const Request & /*req*/, Response &res) {
  4575. auto i = new int(0);
  4576. res.set_header("Trailer", "Dummy1, Dummy2");
  4577. res.set_chunked_content_provider(
  4578. "text/plain",
  4579. [i](size_t /*offset*/, DataSink &sink) {
  4580. switch (*i) {
  4581. case 0: sink.os << "123"; break;
  4582. case 1: sink.os << "456"; break;
  4583. case 2: sink.os << "789"; break;
  4584. case 3: {
  4585. sink.done_with_trailer(
  4586. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4587. } break;
  4588. }
  4589. (*i)++;
  4590. return true;
  4591. },
  4592. [i](bool success) {
  4593. EXPECT_TRUE(success);
  4594. delete i;
  4595. });
  4596. })
  4597. .Get("/streamed",
  4598. [&](const Request & /*req*/, Response &res) {
  4599. res.set_content_provider(
  4600. 6, "text/plain",
  4601. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4602. sink.os << (offset < 3 ? "a" : "b");
  4603. return true;
  4604. });
  4605. })
  4606. .Get("/streamed-without-length",
  4607. [&](const Request & /*req*/, Response &res) {
  4608. auto data = new std::string("abcdefg");
  4609. res.set_content_provider(
  4610. "text/plain",
  4611. [data](size_t offset, DataSink &sink) {
  4612. if (offset < data->size()) {
  4613. sink.os << data->substr(offset);
  4614. }
  4615. sink.done();
  4616. return true;
  4617. },
  4618. [data](bool success) {
  4619. EXPECT_TRUE(success);
  4620. delete data;
  4621. });
  4622. })
  4623. .Get("/streamed-with-range",
  4624. [&](const Request &req, Response &res) {
  4625. auto data = new std::string("abcdefg");
  4626. // An explicit status keeps the server from picking the 206 it
  4627. // would otherwise choose for a ranged request, so the response
  4628. // is not a partial representation.
  4629. auto status = req.get_param_value("status");
  4630. if (status == "200") {
  4631. res.status = StatusCode::OK_200;
  4632. } else if (status == "403") {
  4633. res.status = StatusCode::Forbidden_403;
  4634. }
  4635. res.set_content_provider(
  4636. data->size(), "text/plain",
  4637. [data](size_t offset, size_t length, DataSink &sink) {
  4638. size_t DATA_CHUNK_SIZE = 4;
  4639. const auto &d = *data;
  4640. auto out_len =
  4641. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4642. auto ret =
  4643. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4644. EXPECT_TRUE(ret);
  4645. return true;
  4646. },
  4647. [data, &req](bool success) {
  4648. EXPECT_EQ(success, !req.has_param("error"));
  4649. delete data;
  4650. });
  4651. })
  4652. .Get("/streamed-cancel",
  4653. [&](const Request & /*req*/, Response &res) {
  4654. res.set_content_provider(
  4655. size_t(-1), "text/plain",
  4656. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4657. sink.os << "data_chunk";
  4658. return true;
  4659. });
  4660. })
  4661. .Get("/regex-with-delimiter",
  4662. [&](const Request &req, Response & /*res*/) {
  4663. ASSERT_TRUE(req.has_param("key"));
  4664. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4665. })
  4666. .Get("/with-range",
  4667. [&](const Request & /*req*/, Response &res) {
  4668. res.set_content("abcdefg", "text/plain");
  4669. })
  4670. .Get("/test-start-time",
  4671. [&](const Request &req, Response & /*res*/) {
  4672. EXPECT_NE(req.start_time_,
  4673. std::chrono::steady_clock::time_point::min());
  4674. })
  4675. .Get("/with-range-customized-response",
  4676. [&](const Request & /*req*/, Response &res) {
  4677. res.status = StatusCode::BadRequest_400;
  4678. res.set_content(JSON_DATA, "application/json");
  4679. })
  4680. .Post("/chunked",
  4681. [&](const Request &req, Response & /*res*/) {
  4682. EXPECT_EQ(req.body, "dechunked post body");
  4683. })
  4684. .Post("/large-chunked",
  4685. [&](const Request &req, Response & /*res*/) {
  4686. std::string expected(6 * 30 * 1024u, 'a');
  4687. EXPECT_EQ(req.body, expected);
  4688. })
  4689. .Post("/multipart",
  4690. [&](const Request &req, Response & /*res*/) {
  4691. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4692. req.form.get_field_count("text2") +
  4693. req.form.get_field_count("file3") +
  4694. req.form.get_field_count("file4"));
  4695. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4696. req.form.get_file_count("file2"));
  4697. ASSERT_TRUE(!req.form.has_file("???"));
  4698. ASSERT_TRUE(!req.form.has_field("???"));
  4699. ASSERT_TRUE(req.body.empty());
  4700. {
  4701. const auto &text = req.form.get_field("text1");
  4702. EXPECT_EQ("text default", text);
  4703. }
  4704. {
  4705. const auto &text = req.form.get_field("text2");
  4706. EXPECT_EQ("aωb", text);
  4707. }
  4708. {
  4709. const auto &file = req.form.get_file("file1");
  4710. EXPECT_EQ("hello.txt", file.filename);
  4711. EXPECT_EQ("text/plain", file.content_type);
  4712. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4713. }
  4714. {
  4715. const auto &file = req.form.get_file("file2");
  4716. EXPECT_EQ("world.json", file.filename);
  4717. EXPECT_EQ("application/json", file.content_type);
  4718. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4719. }
  4720. {
  4721. const auto &text = req.form.get_field("file3");
  4722. EXPECT_EQ(0u, text.size());
  4723. }
  4724. {
  4725. const auto &text = req.form.get_field("file4");
  4726. EXPECT_EQ(0u, text.size());
  4727. }
  4728. })
  4729. .Post("/multipart/multi_file_values",
  4730. [&](const Request &req, Response & /*res*/) {
  4731. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4732. req.form.get_field_count("multi_text1"));
  4733. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4734. ASSERT_TRUE(!req.form.has_file("???"));
  4735. ASSERT_TRUE(!req.form.has_field("???"));
  4736. ASSERT_TRUE(req.body.empty());
  4737. {
  4738. const auto &text = req.form.get_field("text");
  4739. EXPECT_EQ("default text", text);
  4740. }
  4741. {
  4742. const auto &text1_values = req.form.get_fields("multi_text1");
  4743. EXPECT_EQ(2u, text1_values.size());
  4744. EXPECT_EQ("aaaaa", text1_values[0]);
  4745. EXPECT_EQ("bbbbb", text1_values[1]);
  4746. }
  4747. {
  4748. const auto &file1_values = req.form.get_files("multi_file1");
  4749. EXPECT_EQ(2u, file1_values.size());
  4750. auto file1 = file1_values[0];
  4751. EXPECT_EQ(file1.filename, "hello.txt");
  4752. EXPECT_EQ(file1.content_type, "text/plain");
  4753. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4754. auto file2 = file1_values[1];
  4755. EXPECT_EQ(file2.filename, "world.json");
  4756. EXPECT_EQ(file2.content_type, "application/json");
  4757. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4758. }
  4759. })
  4760. .Post("/empty",
  4761. [&](const Request &req, Response &res) {
  4762. EXPECT_EQ(req.body, "");
  4763. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4764. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4765. res.set_content("empty", "text/plain");
  4766. })
  4767. .Post("/empty-no-content-type",
  4768. [&](const Request &req, Response &res) {
  4769. EXPECT_EQ(req.body, "");
  4770. EXPECT_FALSE(req.has_header("Content-Type"));
  4771. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4772. res.set_content("empty-no-content-type", "text/plain");
  4773. })
  4774. .Post("/path-only",
  4775. [&](const Request &req, Response &res) {
  4776. EXPECT_EQ(req.body, "");
  4777. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4778. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4779. res.set_content("path-only", "text/plain");
  4780. })
  4781. .Post("/path-headers-only",
  4782. [&](const Request &req, Response &res) {
  4783. EXPECT_EQ(req.body, "");
  4784. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4785. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4786. EXPECT_EQ("world", req.get_header_value("hello"));
  4787. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4788. res.set_content("path-headers-only", "text/plain");
  4789. })
  4790. .Post("/post-large",
  4791. [&](const Request &req, Response &res) {
  4792. EXPECT_EQ(req.body, LARGE_DATA);
  4793. res.set_content(req.body, "text/plain");
  4794. })
  4795. .Post("/post-loopback",
  4796. [&](const Request &, Response &res,
  4797. ContentReader const &content_reader) {
  4798. std::string body;
  4799. content_reader([&](const char *data, size_t data_length) {
  4800. body.append(data, data_length);
  4801. return true;
  4802. });
  4803. res.set_content(body, "text/plain");
  4804. })
  4805. .Put("/put-loopback",
  4806. [&](const Request &, Response &res,
  4807. ContentReader const &content_reader) {
  4808. std::string body;
  4809. content_reader([&](const char *data, size_t data_length) {
  4810. body.append(data, data_length);
  4811. return true;
  4812. });
  4813. res.set_content(body, "text/plain");
  4814. })
  4815. .Patch("/patch-loopback",
  4816. [&](const Request &, Response &res,
  4817. ContentReader const &content_reader) {
  4818. std::string body;
  4819. content_reader([&](const char *data, size_t data_length) {
  4820. body.append(data, data_length);
  4821. return true;
  4822. });
  4823. res.set_content(body, "text/plain");
  4824. })
  4825. .Put("/empty-no-content-type",
  4826. [&](const Request &req, Response &res) {
  4827. EXPECT_EQ(req.body, "");
  4828. EXPECT_FALSE(req.has_header("Content-Type"));
  4829. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4830. res.set_content("empty-no-content-type", "text/plain");
  4831. })
  4832. .Put("/put",
  4833. [&](const Request &req, Response &res) {
  4834. EXPECT_EQ(req.body, "PUT");
  4835. res.set_content(req.body, "text/plain");
  4836. })
  4837. .Put("/put-large",
  4838. [&](const Request &req, Response &res) {
  4839. EXPECT_EQ(req.body, LARGE_DATA);
  4840. res.set_content(req.body, "text/plain");
  4841. })
  4842. .Patch("/patch",
  4843. [&](const Request &req, Response &res) {
  4844. EXPECT_EQ(req.body, "PATCH");
  4845. res.set_content(req.body, "text/plain");
  4846. })
  4847. .Delete("/delete",
  4848. [&](const Request & /*req*/, Response &res) {
  4849. res.set_content("DELETE", "text/plain");
  4850. })
  4851. .Delete("/delete-body",
  4852. [&](const Request &req, Response &res) {
  4853. EXPECT_EQ(req.body, "content");
  4854. res.set_content(req.body, "text/plain");
  4855. })
  4856. .Options(R"(\*)",
  4857. [&](const Request & /*req*/, Response &res) {
  4858. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4859. })
  4860. .CustomRoute("PROPFIND", "/dav/:id",
  4861. [&](const Request &req, Response &res) {
  4862. res.set_header("x-body-size",
  4863. std::to_string(req.body.size()));
  4864. res.set_header("x-matched-route", req.matched_route);
  4865. res.set_header("x-dav-id", req.path_params.at("id"));
  4866. res.status = StatusCode::MultiStatus_207;
  4867. res.set_content(req.body, "application/xml");
  4868. })
  4869. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4870. [&](const Request &req, Response &res) {
  4871. res.set_header("x-dav-match", req.matches[1]);
  4872. res.status = StatusCode::MultiStatus_207;
  4873. })
  4874. .CustomRoute("MKCOL", "/dav-mkcol",
  4875. [&](const Request &req, Response &res) {
  4876. EXPECT_TRUE(req.body.empty());
  4877. res.status = StatusCode::Created_201;
  4878. })
  4879. .CustomRoute(
  4880. "REPORT", "/dav-report",
  4881. [&](const Request & /*req*/, Response &res,
  4882. const ContentReader &content_reader) {
  4883. std::string body;
  4884. content_reader([&](const char *data, size_t data_length) {
  4885. body.append(data, data_length);
  4886. return true;
  4887. });
  4888. res.set_header("x-body-size", std::to_string(body.size()));
  4889. res.status = StatusCode::MultiStatus_207;
  4890. res.set_content(body, "application/xml");
  4891. })
  4892. .Get("/request-target",
  4893. [&](const Request &req, Response & /*res*/) {
  4894. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4895. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4896. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4897. })
  4898. .Get("/long-query-value",
  4899. [&](const Request &req, Response & /*res*/) {
  4900. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4901. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4902. })
  4903. .Get("/too-long-query-value",
  4904. [&](const Request &req, Response & /*res*/) {
  4905. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4906. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4907. })
  4908. .Get("/array-param",
  4909. [&](const Request &req, Response & /*res*/) {
  4910. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4911. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4912. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4913. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4914. })
  4915. .Get("/array-param-values",
  4916. [&](const Request &req, Response & /*res*/) {
  4917. auto values = req.get_param_values("array");
  4918. EXPECT_EQ(3u, values.size());
  4919. EXPECT_EQ("value1", values[0]);
  4920. EXPECT_EQ("value2", values[1]);
  4921. EXPECT_EQ("value3", values[2]);
  4922. auto empty = req.get_param_values("nonexistent");
  4923. EXPECT_TRUE(empty.empty());
  4924. })
  4925. .Post("/validate-no-multiple-headers",
  4926. [&](const Request &req, Response & /*res*/) {
  4927. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4928. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4929. })
  4930. .Post("/content_receiver",
  4931. [&](const Request &req, Response &res,
  4932. const ContentReader &content_reader) {
  4933. if (req.is_multipart_form_data()) {
  4934. std::vector<FormData> items;
  4935. content_reader(
  4936. [&](const FormData &file) {
  4937. items.push_back(file);
  4938. return true;
  4939. },
  4940. [&](const char *data, size_t data_length) {
  4941. items.back().content.append(data, data_length);
  4942. return true;
  4943. });
  4944. EXPECT_EQ(5u, items.size());
  4945. {
  4946. const auto &file = get_file_value(items, "text1");
  4947. EXPECT_TRUE(file.filename.empty());
  4948. EXPECT_EQ("text default", file.content);
  4949. }
  4950. {
  4951. const auto &file = get_file_value(items, "text2");
  4952. EXPECT_TRUE(file.filename.empty());
  4953. EXPECT_EQ("aωb", file.content);
  4954. }
  4955. {
  4956. const auto &file = get_file_value(items, "file1");
  4957. EXPECT_EQ("hello.txt", file.filename);
  4958. EXPECT_EQ("text/plain", file.content_type);
  4959. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4960. }
  4961. {
  4962. const auto &file = get_file_value(items, "file2");
  4963. EXPECT_EQ("world.json", file.filename);
  4964. EXPECT_EQ("application/json", file.content_type);
  4965. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4966. }
  4967. {
  4968. const auto &file = get_file_value(items, "file3");
  4969. EXPECT_TRUE(file.filename.empty());
  4970. EXPECT_EQ("application/octet-stream", file.content_type);
  4971. EXPECT_EQ(0u, file.content.size());
  4972. }
  4973. } else {
  4974. std::string body;
  4975. content_reader([&](const char *data, size_t data_length) {
  4976. EXPECT_EQ(7U, data_length);
  4977. body.append(data, data_length);
  4978. return true;
  4979. });
  4980. EXPECT_EQ(body, "content");
  4981. res.set_content(body, "text/plain");
  4982. }
  4983. })
  4984. .Put("/content_receiver",
  4985. [&](const Request & /*req*/, Response &res,
  4986. const ContentReader &content_reader) {
  4987. std::string body;
  4988. content_reader([&](const char *data, size_t data_length) {
  4989. body.append(data, data_length);
  4990. return true;
  4991. });
  4992. EXPECT_EQ(body, "content");
  4993. res.set_content(body, "text/plain");
  4994. })
  4995. .Patch("/content_receiver",
  4996. [&](const Request & /*req*/, Response &res,
  4997. const ContentReader &content_reader) {
  4998. std::string body;
  4999. content_reader([&](const char *data, size_t data_length) {
  5000. body.append(data, data_length);
  5001. return true;
  5002. });
  5003. EXPECT_EQ(body, "content");
  5004. res.set_content(body, "text/plain");
  5005. })
  5006. .Post("/query-string-and-body",
  5007. [&](const Request &req, Response & /*res*/) {
  5008. ASSERT_TRUE(req.has_param("key"));
  5009. EXPECT_EQ(req.get_param_value("key"), "value");
  5010. EXPECT_EQ(req.body, "content");
  5011. })
  5012. .Get("/last-request",
  5013. [&](const Request &req, Response & /*res*/) {
  5014. EXPECT_EQ("close", req.get_header_value("Connection"));
  5015. })
  5016. .Get(R"(/redirect/(\d+))",
  5017. [&](const Request &req, Response &res) {
  5018. auto num = std::stoi(req.matches[1]) + 1;
  5019. std::string url = "/redirect/" + std::to_string(num);
  5020. res.set_redirect(url);
  5021. })
  5022. .Post("/binary",
  5023. [&](const Request &req, Response &res) {
  5024. EXPECT_EQ(4U, req.body.size());
  5025. EXPECT_EQ("application/octet-stream",
  5026. req.get_header_value("Content-Type"));
  5027. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5028. res.set_content(req.body, "application/octet-stream");
  5029. })
  5030. .Put("/binary",
  5031. [&](const Request &req, Response &res) {
  5032. EXPECT_EQ(4U, req.body.size());
  5033. EXPECT_EQ("application/octet-stream",
  5034. req.get_header_value("Content-Type"));
  5035. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5036. res.set_content(req.body, "application/octet-stream");
  5037. })
  5038. .Patch("/binary",
  5039. [&](const Request &req, Response &res) {
  5040. EXPECT_EQ(4U, req.body.size());
  5041. EXPECT_EQ("application/octet-stream",
  5042. req.get_header_value("Content-Type"));
  5043. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5044. res.set_content(req.body, "application/octet-stream");
  5045. })
  5046. .Delete("/binary",
  5047. [&](const Request &req, Response &res) {
  5048. EXPECT_EQ(4U, req.body.size());
  5049. EXPECT_EQ("application/octet-stream",
  5050. req.get_header_value("Content-Type"));
  5051. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5052. res.set_content(req.body, "application/octet-stream");
  5053. })
  5054. .Get("/issue1772",
  5055. [&](const Request & /*req*/, Response &res) {
  5056. res.status = 401;
  5057. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5058. })
  5059. .Delete("/issue609",
  5060. [](const httplib::Request &, httplib::Response &res,
  5061. const httplib::ContentReader &) {
  5062. res.set_content("ok", "text/plain");
  5063. })
  5064. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5065. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5066. .Get("/compress",
  5067. [&](const Request & /*req*/, Response &res) {
  5068. res.set_content(
  5069. "12345678901234567890123456789012345678901234567890123456789"
  5070. "01234567890123456789012345678901234567890",
  5071. "text/plain");
  5072. })
  5073. .Get("/compress-with-charset",
  5074. [&](const Request & /*req*/, Response &res) {
  5075. res.set_content(
  5076. "12345678901234567890123456789012345678901234567890123456789"
  5077. "01234567890123456789012345678901234567890",
  5078. "application/json; charset=utf-8");
  5079. })
  5080. .Get("/nocompress",
  5081. [&](const Request & /*req*/, Response &res) {
  5082. res.set_content(
  5083. "12345678901234567890123456789012345678901234567890123456789"
  5084. "01234567890123456789012345678901234567890",
  5085. "application/octet-stream");
  5086. })
  5087. .Post("/compress-multipart",
  5088. [&](const Request &req, Response & /*res*/) {
  5089. EXPECT_EQ(2u, req.form.fields.size());
  5090. ASSERT_TRUE(!req.form.has_field("???"));
  5091. {
  5092. const auto &text = req.form.get_field("key1");
  5093. EXPECT_EQ("test", text);
  5094. }
  5095. {
  5096. const auto &text = req.form.get_field("key2");
  5097. EXPECT_EQ("--abcdefg123", text);
  5098. }
  5099. })
  5100. #endif
  5101. ;
  5102. persons_["john"] = "programmer";
  5103. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5104. svr_.wait_until_ready();
  5105. }
  5106. virtual void TearDown() {
  5107. svr_.stop();
  5108. if (!request_threads_.empty()) {
  5109. std::this_thread::sleep_for(std::chrono::seconds(1));
  5110. for (auto &t : request_threads_) {
  5111. t.join();
  5112. }
  5113. }
  5114. t_.join();
  5115. }
  5116. map<string, string> persons_;
  5117. #ifdef CPPHTTPLIB_SSL_ENABLED
  5118. SSLClient cli_;
  5119. SSLServer svr_;
  5120. #else
  5121. Client cli_;
  5122. Server svr_;
  5123. #endif
  5124. thread t_;
  5125. std::vector<thread> request_threads_;
  5126. };
  5127. TEST_F(ServerTest, GetMethod200) {
  5128. auto res = cli_.Get("/hi");
  5129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5130. EXPECT_EQ("HTTP/1.1", res->version);
  5131. EXPECT_EQ(StatusCode::OK_200, res->status);
  5132. EXPECT_EQ("OK", res->reason);
  5133. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5134. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5135. EXPECT_EQ("Hello World!", res->body);
  5136. }
  5137. TEST_F(ServerTest, GetEmptyFile) {
  5138. auto res = cli_.Get("/empty_file");
  5139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5140. EXPECT_EQ(StatusCode::OK_200, res->status);
  5141. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5142. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5143. EXPECT_EQ("", res->body);
  5144. }
  5145. TEST_F(ServerTest, GetFileContent) {
  5146. auto res = cli_.Get("/file_content");
  5147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5148. EXPECT_EQ(StatusCode::OK_200, res->status);
  5149. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5150. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5151. EXPECT_EQ("test.html", res->body);
  5152. }
  5153. TEST_F(ServerTest, GetFileContentWithRange) {
  5154. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5156. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5157. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5158. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5159. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5160. EXPECT_EQ("est", res->body);
  5161. }
  5162. TEST_F(ServerTest, GetFileContentWithContentType) {
  5163. auto res = cli_.Get("/file_content_with_content_type");
  5164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5165. EXPECT_EQ(StatusCode::OK_200, res->status);
  5166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5168. EXPECT_EQ("file\n", res->body);
  5169. }
  5170. TEST_F(ServerTest, GetInvalidFileContent) {
  5171. auto res = cli_.Get("/invalid_file_content");
  5172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5173. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5174. }
  5175. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5176. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5178. EXPECT_EQ("HTTP/1.1", res->version);
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5181. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5182. EXPECT_EQ("Hello World!", res->body);
  5183. }
  5184. TEST_F(ServerTest, GetMethod302) {
  5185. auto res = cli_.Get("/");
  5186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5187. EXPECT_EQ(StatusCode::Found_302, res->status);
  5188. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5189. }
  5190. TEST_F(ServerTest, GetMethod302Redirect) {
  5191. cli_.set_follow_location(true);
  5192. auto res = cli_.Get("/");
  5193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5194. EXPECT_EQ(StatusCode::OK_200, res->status);
  5195. EXPECT_EQ("Hello World!", res->body);
  5196. EXPECT_EQ("/hi", res->location);
  5197. }
  5198. TEST_F(ServerTest, GetMethod404) {
  5199. auto res = cli_.Get("/invalid");
  5200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5201. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5202. }
  5203. TEST_F(ServerTest, HeadMethod200) {
  5204. auto res = cli_.Head("/hi");
  5205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5206. EXPECT_EQ(StatusCode::OK_200, res->status);
  5207. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5208. EXPECT_TRUE(res->body.empty());
  5209. }
  5210. TEST_F(ServerTest, HeadMethod200Static) {
  5211. auto res = cli_.Head("/mount/dir/index.html");
  5212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5213. EXPECT_EQ(StatusCode::OK_200, res->status);
  5214. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5215. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5216. EXPECT_TRUE(res->body.empty());
  5217. }
  5218. TEST_F(ServerTest, HeadMethod404) {
  5219. auto res = cli_.Head("/invalid");
  5220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5221. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5222. EXPECT_TRUE(res->body.empty());
  5223. }
  5224. TEST_F(ServerTest, GetMethodPersonJohn) {
  5225. auto res = cli_.Get("/person/john");
  5226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5227. EXPECT_EQ(StatusCode::OK_200, res->status);
  5228. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5229. EXPECT_EQ("programmer", res->body);
  5230. }
  5231. TEST_F(ServerTest, PostMethod1) {
  5232. auto res = cli_.Get("/person/john1");
  5233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5234. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5235. res = cli_.Post("/person", "name=john1&note=coder",
  5236. "application/x-www-form-urlencoded");
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. ASSERT_EQ(StatusCode::OK_200, res->status);
  5239. res = cli_.Get("/person/john1");
  5240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5241. ASSERT_EQ(StatusCode::OK_200, res->status);
  5242. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5243. ASSERT_EQ("coder", res->body);
  5244. }
  5245. TEST_F(ServerTest, PostMethod2) {
  5246. auto res = cli_.Get("/person/john2");
  5247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5248. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5249. Params params;
  5250. params.emplace("name", "john2");
  5251. params.emplace("note", "coder");
  5252. res = cli_.Post("/person", params);
  5253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5254. ASSERT_EQ(StatusCode::OK_200, res->status);
  5255. res = cli_.Get("/person/john2");
  5256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5257. ASSERT_EQ(StatusCode::OK_200, res->status);
  5258. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5259. ASSERT_EQ("coder", res->body);
  5260. }
  5261. TEST_F(ServerTest, PutMethod3) {
  5262. auto res = cli_.Get("/person/john3");
  5263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5264. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5265. Params params;
  5266. params.emplace("name", "john3");
  5267. params.emplace("note", "coder");
  5268. res = cli_.Put("/person", params);
  5269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5270. ASSERT_EQ(StatusCode::OK_200, res->status);
  5271. res = cli_.Get("/person/john3");
  5272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5273. ASSERT_EQ(StatusCode::OK_200, res->status);
  5274. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5275. ASSERT_EQ("coder", res->body);
  5276. }
  5277. TEST_F(ServerTest, DeleteMethod1) {
  5278. auto res = cli_.Get("/person/john4");
  5279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5280. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5281. Params params;
  5282. params.emplace("name", "john4");
  5283. params.emplace("note", "coder");
  5284. res = cli_.Post("/person", params);
  5285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5286. ASSERT_EQ(StatusCode::OK_200, res->status);
  5287. res = cli_.Get("/person/john4");
  5288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5289. ASSERT_EQ(StatusCode::OK_200, res->status);
  5290. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5291. ASSERT_EQ("coder", res->body);
  5292. Params delete_params;
  5293. delete_params.emplace("name", "john4");
  5294. res = cli_.Delete("/person", delete_params);
  5295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5296. ASSERT_EQ(StatusCode::OK_200, res->status);
  5297. ASSERT_EQ("DELETED", res->body);
  5298. res = cli_.Get("/person/john4");
  5299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5300. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5301. }
  5302. TEST_F(ServerTest, DeleteMethod2) {
  5303. auto res = cli_.Get("/person/john5");
  5304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5305. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5306. Params params;
  5307. params.emplace("name", "john5");
  5308. params.emplace("note", "developer");
  5309. res = cli_.Post("/person", params);
  5310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5311. ASSERT_EQ(StatusCode::OK_200, res->status);
  5312. res = cli_.Get("/person/john5");
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. ASSERT_EQ(StatusCode::OK_200, res->status);
  5315. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5316. ASSERT_EQ("developer", res->body);
  5317. Params delete_params;
  5318. delete_params.emplace("name", "john5");
  5319. Headers headers;
  5320. headers.emplace("Custom-Header", "test-value");
  5321. res = cli_.Delete("/person", headers, delete_params);
  5322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5323. ASSERT_EQ(StatusCode::OK_200, res->status);
  5324. ASSERT_EQ("DELETED", res->body);
  5325. res = cli_.Get("/person/john5");
  5326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5327. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5328. }
  5329. TEST_F(ServerTest, DeleteMethod3) {
  5330. auto res = cli_.Get("/person/john6");
  5331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5332. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5333. Params params;
  5334. params.emplace("name", "john6");
  5335. params.emplace("note", "tester");
  5336. res = cli_.Post("/person", params);
  5337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5338. ASSERT_EQ(StatusCode::OK_200, res->status);
  5339. res = cli_.Get("/person/john6");
  5340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5341. ASSERT_EQ(StatusCode::OK_200, res->status);
  5342. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5343. ASSERT_EQ("tester", res->body);
  5344. Params delete_params;
  5345. delete_params.emplace("name", "john6");
  5346. Headers headers;
  5347. headers.emplace("Custom-Header", "test-value");
  5348. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5350. ASSERT_EQ(StatusCode::OK_200, res->status);
  5351. ASSERT_EQ("DELETED", res->body);
  5352. res = cli_.Get("/person/john6");
  5353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5354. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5355. }
  5356. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5357. Params params;
  5358. params.emplace("json", JSON_DATA);
  5359. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5361. ASSERT_EQ(StatusCode::OK_200, res->status);
  5362. ASSERT_EQ(JSON_DATA, res->body);
  5363. }
  5364. TEST_F(ServerTest, PostEmptyContent) {
  5365. auto res = cli_.Post("/empty", "", "text/plain");
  5366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5367. ASSERT_EQ(StatusCode::OK_200, res->status);
  5368. ASSERT_EQ("empty", res->body);
  5369. }
  5370. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5371. auto res = cli_.Post("/empty-no-content-type");
  5372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5373. ASSERT_EQ(StatusCode::OK_200, res->status);
  5374. ASSERT_EQ("empty-no-content-type", res->body);
  5375. }
  5376. TEST_F(ServerTest, PostPathOnly) {
  5377. auto res = cli_.Post("/path-only");
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. ASSERT_EQ(StatusCode::OK_200, res->status);
  5380. ASSERT_EQ("path-only", res->body);
  5381. }
  5382. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5383. auto res = cli_.Post("/path-headers-only",
  5384. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5386. ASSERT_EQ(StatusCode::OK_200, res->status);
  5387. ASSERT_EQ("path-headers-only", res->body);
  5388. }
  5389. TEST_F(ServerTest, PostLarge) {
  5390. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5392. ASSERT_EQ(StatusCode::OK_200, res->status);
  5393. EXPECT_EQ(LARGE_DATA, res->body);
  5394. }
  5395. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5396. auto res = cli_.Put("/empty-no-content-type");
  5397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5398. ASSERT_EQ(StatusCode::OK_200, res->status);
  5399. ASSERT_EQ("empty-no-content-type", res->body);
  5400. }
  5401. TEST_F(ServerTest, GetMethodDir) {
  5402. auto res = cli_.Get("/dir/");
  5403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5404. EXPECT_EQ(StatusCode::OK_200, res->status);
  5405. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5406. auto body = R"(<html>
  5407. <head>
  5408. </head>
  5409. <body>
  5410. <a href="/dir/test.html">Test</a>
  5411. <a href="/hi">hi</a>
  5412. </body>
  5413. </html>
  5414. )";
  5415. EXPECT_EQ(body, res->body);
  5416. }
  5417. TEST_F(ServerTest, GetMethodDirTest) {
  5418. auto res = cli_.Get("/dir/test.html");
  5419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5420. EXPECT_EQ(StatusCode::OK_200, res->status);
  5421. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5422. EXPECT_EQ("test.html", res->body);
  5423. }
  5424. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5425. auto res = cli_.Get("/dir/../dir/test.html");
  5426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5427. EXPECT_EQ(StatusCode::OK_200, res->status);
  5428. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5429. EXPECT_EQ("test.html", res->body);
  5430. }
  5431. TEST_F(ServerTest, GetMethodInvalidPath) {
  5432. auto res = cli_.Get("/dir/../test.html");
  5433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5434. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5435. }
  5436. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5437. auto res = cli_.Get("/../www/dir/test.html");
  5438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5439. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5440. }
  5441. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5442. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5444. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5445. }
  5446. TEST_F(ServerTest, GetMethodDirMountTest) {
  5447. auto res = cli_.Get("/mount/dir/test.html");
  5448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5449. EXPECT_EQ(StatusCode::OK_200, res->status);
  5450. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5451. EXPECT_EQ("test.html", res->body);
  5452. }
  5453. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5454. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5456. EXPECT_EQ(StatusCode::OK_200, res->status);
  5457. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5458. EXPECT_EQ("test.html", res->body);
  5459. }
  5460. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5461. auto res = cli_.Get("/mount/dir/../test.html");
  5462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5464. }
  5465. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5466. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5469. }
  5470. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5471. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5474. }
  5475. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5476. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5479. }
  5480. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5481. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5483. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5484. }
  5485. TEST_F(ServerTest, PostMethod303) {
  5486. auto res = cli_.Post("/1", "body", "text/plain");
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5489. EXPECT_EQ("/2", res->get_header_value("Location"));
  5490. }
  5491. TEST_F(ServerTest, PostMethod303Redirect) {
  5492. cli_.set_follow_location(true);
  5493. auto res = cli_.Post("/1", "body", "text/plain");
  5494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5495. EXPECT_EQ(StatusCode::OK_200, res->status);
  5496. EXPECT_EQ("redirected.", res->body);
  5497. EXPECT_EQ("/2", res->location);
  5498. }
  5499. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5500. auto res = cli_.Get("/dir/test.abcde");
  5501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5502. EXPECT_EQ(StatusCode::OK_200, res->status);
  5503. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5504. EXPECT_EQ("abcde", res->body);
  5505. }
  5506. TEST_F(ServerTest, StaticFileRange) {
  5507. auto res =
  5508. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5510. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5511. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5512. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5513. EXPECT_EQ(true, res->has_header("Content-Range"));
  5514. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5515. EXPECT_EQ(std::string("cd"), res->body);
  5516. }
  5517. TEST_F(ServerTest, StaticFileRanges) {
  5518. auto res = cli_.Get("/dir/test.abcde",
  5519. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5521. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5522. EXPECT_TRUE(
  5523. res->get_header_value("Content-Type")
  5524. .find(
  5525. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5526. 0);
  5527. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5528. }
  5529. TEST_F(ServerTest, StaticFileRangeHead) {
  5530. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5532. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5533. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5534. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5535. EXPECT_EQ(true, res->has_header("Content-Range"));
  5536. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5537. }
  5538. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5539. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5541. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5543. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5544. EXPECT_EQ(true, res->has_header("Content-Range"));
  5545. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5546. res->get_header_value("Content-Range"));
  5547. EXPECT_EQ("LAST\n", res->body);
  5548. }
  5549. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5550. auto res =
  5551. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5553. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5554. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5555. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5556. EXPECT_EQ(true, res->has_header("Content-Range"));
  5557. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5558. }
  5559. TEST_F(ServerTest, StaticFileBigFile) {
  5560. auto res = cli_.Get("/dir/1MB.txt");
  5561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5562. EXPECT_EQ(StatusCode::OK_200, res->status);
  5563. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5564. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5565. }
  5566. TEST_F(ServerTest, InvalidBaseDirMount) {
  5567. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5568. }
  5569. TEST_F(ServerTest, Binary) {
  5570. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5571. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5572. "application/octet-stream");
  5573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5574. ASSERT_EQ(StatusCode::OK_200, res->status);
  5575. ASSERT_EQ(4U, res->body.size());
  5576. res = cli_.Put("/binary", binary.data(), binary.size(),
  5577. "application/octet-stream");
  5578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5579. ASSERT_EQ(StatusCode::OK_200, res->status);
  5580. ASSERT_EQ(4U, res->body.size());
  5581. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5582. "application/octet-stream");
  5583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5584. ASSERT_EQ(StatusCode::OK_200, res->status);
  5585. ASSERT_EQ(4U, res->body.size());
  5586. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5587. "application/octet-stream");
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. ASSERT_EQ(StatusCode::OK_200, res->status);
  5590. ASSERT_EQ(4U, res->body.size());
  5591. }
  5592. TEST_F(ServerTest, BinaryString) {
  5593. auto binary = std::string("\x00\x01\x02\x03", 4);
  5594. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5596. ASSERT_EQ(StatusCode::OK_200, res->status);
  5597. ASSERT_EQ(4U, res->body.size());
  5598. res = cli_.Put("/binary", binary, "application/octet-stream");
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. ASSERT_EQ(StatusCode::OK_200, res->status);
  5601. ASSERT_EQ(4U, res->body.size());
  5602. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5604. ASSERT_EQ(StatusCode::OK_200, res->status);
  5605. ASSERT_EQ(4U, res->body.size());
  5606. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5608. ASSERT_EQ(StatusCode::OK_200, res->status);
  5609. ASSERT_EQ(4U, res->body.size());
  5610. }
  5611. TEST_F(ServerTest, EmptyRequest) {
  5612. auto res = cli_.Get("");
  5613. ASSERT_TRUE(!res);
  5614. EXPECT_EQ(Error::Connection, res.error());
  5615. }
  5616. TEST_F(ServerTest, LongRequest) {
  5617. std::string request;
  5618. for (size_t i = 0; i < 545; i++) {
  5619. request += "/TooLongRequest";
  5620. }
  5621. request += "OK";
  5622. auto res = cli_.Get(request.c_str());
  5623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5624. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5625. }
  5626. TEST_F(ServerTest, TooLongRequest) {
  5627. std::string request;
  5628. for (size_t i = 0; i < 546; i++) {
  5629. request += "/TooLongRequest";
  5630. }
  5631. request += "_NG";
  5632. auto start = std::chrono::high_resolution_clock::now();
  5633. cli_.set_keep_alive(true);
  5634. auto res = cli_.Get(request.c_str());
  5635. auto end = std::chrono::high_resolution_clock::now();
  5636. auto elapsed =
  5637. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5638. .count();
  5639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5640. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5641. EXPECT_LE(elapsed, 1000);
  5642. EXPECT_EQ("close", res->get_header_value("Connection"));
  5643. EXPECT_FALSE(cli_.is_socket_open());
  5644. }
  5645. TEST_F(ServerTest, AlmostTooLongRequest) {
  5646. // test for #2046 - URI length check shouldn't include other content on req
  5647. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5648. // leading /, space, HTTP/1.1)
  5649. std::string request =
  5650. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5651. auto res = cli_.Get(request.c_str());
  5652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5653. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5654. }
  5655. TEST_F(ServerTest, LongHeader) {
  5656. Request req;
  5657. req.method = "GET";
  5658. req.path = "/hi";
  5659. std::string host_and_port;
  5660. host_and_port += HOST;
  5661. host_and_port += ":";
  5662. host_and_port += std::to_string(PORT);
  5663. req.headers.emplace("Host", host_and_port.c_str());
  5664. req.headers.emplace("Accept", "*/*");
  5665. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5666. req.headers.emplace(
  5667. "Header-Name",
  5668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5692. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5696. "@@@@@@@@@@@@@@@@");
  5697. auto res = std::make_shared<Response>();
  5698. auto error = Error::Success;
  5699. auto ret = cli_.send(req, *res, error);
  5700. ASSERT_TRUE(ret);
  5701. EXPECT_EQ(StatusCode::OK_200, res->status);
  5702. }
  5703. TEST_F(ServerTest, LongQueryValue) {
  5704. auto start = std::chrono::high_resolution_clock::now();
  5705. cli_.set_keep_alive(true);
  5706. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5707. auto end = std::chrono::high_resolution_clock::now();
  5708. auto elapsed =
  5709. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5710. .count();
  5711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5712. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5713. EXPECT_LE(elapsed, 1000);
  5714. EXPECT_EQ("close", res->get_header_value("Connection"));
  5715. EXPECT_FALSE(cli_.is_socket_open());
  5716. }
  5717. TEST_F(ServerTest, TooLongQueryValue) {
  5718. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5719. ASSERT_FALSE(res);
  5720. EXPECT_EQ(Error::Read, res.error());
  5721. }
  5722. TEST_F(ServerTest, TooLongHeader) {
  5723. Request req;
  5724. req.method = "GET";
  5725. req.path = "/hi";
  5726. std::string host_and_port;
  5727. host_and_port += HOST;
  5728. host_and_port += ":";
  5729. host_and_port += std::to_string(PORT);
  5730. req.headers.emplace("Host", host_and_port.c_str());
  5731. req.headers.emplace("Accept", "*/*");
  5732. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5733. req.headers.emplace(
  5734. "Header-Name",
  5735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5757. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5763. "@@@@@@@@@@@@@@@@@");
  5764. auto res = std::make_shared<Response>();
  5765. auto error = Error::Success;
  5766. auto ret = cli_.send(req, *res, error);
  5767. ASSERT_TRUE(ret);
  5768. EXPECT_EQ(StatusCode::OK_200, res->status);
  5769. }
  5770. TEST_F(ServerTest, HeaderCountAtLimit) {
  5771. // Test with headers just under the 100 limit
  5772. httplib::Headers headers;
  5773. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5774. // This should keep us just under the 100 header limit
  5775. for (int i = 0; i < 95; i++) {
  5776. std::string name = "X-Test-Header-" + std::to_string(i);
  5777. std::string value = "value" + std::to_string(i);
  5778. headers.emplace(name, value);
  5779. }
  5780. // This should work fine as we're under the limit
  5781. auto res = cli_.Get("/hi", headers);
  5782. EXPECT_TRUE(res);
  5783. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5784. }
  5785. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5786. // Test with many headers to exceed the 100 limit
  5787. httplib::Headers headers;
  5788. // Add 150 headers to definitely exceed the 100 limit
  5789. for (int i = 0; i < 150; i++) {
  5790. std::string name = "X-Test-Header-" + std::to_string(i);
  5791. std::string value = "value" + std::to_string(i);
  5792. headers.emplace(name, value);
  5793. }
  5794. // This should fail due to exceeding header count limit
  5795. cli_.set_keep_alive(true);
  5796. auto res = cli_.Get("/hi", headers);
  5797. // The server should respond with 400 Bad Request
  5798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5799. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5800. EXPECT_EQ("close", res->get_header_value("Connection"));
  5801. EXPECT_FALSE(cli_.is_socket_open());
  5802. }
  5803. TEST_F(ServerTest, PercentEncoding) {
  5804. auto res = cli_.Get("/e%6edwith%");
  5805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5806. EXPECT_EQ(StatusCode::OK_200, res->status);
  5807. }
  5808. TEST_F(ServerTest, PercentEncodingUnicode) {
  5809. auto res = cli_.Get("/e%u006edwith%");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. EXPECT_EQ(StatusCode::OK_200, res->status);
  5812. }
  5813. TEST_F(ServerTest, InvalidPercentEncoding) {
  5814. auto res = cli_.Get("/%endwith%");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5817. }
  5818. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5819. auto res = cli_.Get("/%uendwith%");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5822. }
  5823. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5824. auto res = cli_.Get("/hello?aaa=bbb%");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5827. }
  5828. TEST_F(ServerTest, PlusSignEncoding) {
  5829. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5831. EXPECT_EQ(StatusCode::OK_200, res->status);
  5832. EXPECT_EQ("a +b", res->body);
  5833. }
  5834. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5835. // This test simulates a potential DoS attack using many headers
  5836. // to verify our security fix prevents memory exhaustion
  5837. httplib::Headers attack_headers;
  5838. // Attempt to add many headers like an attacker would (200 headers to far
  5839. // exceed limit)
  5840. for (int i = 0; i < 200; i++) {
  5841. std::string name = "X-Attack-Header-" + std::to_string(i);
  5842. std::string value = "attack_payload_" + std::to_string(i);
  5843. attack_headers.emplace(name, value);
  5844. }
  5845. // Try to POST with excessive headers
  5846. cli_.set_keep_alive(true);
  5847. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5848. // Should either fail or return 400 Bad Request due to security limit
  5849. if (res) {
  5850. // If we get a response, it should be 400 Bad Request
  5851. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5852. EXPECT_EQ("close", res->get_header_value("Connection"));
  5853. }
  5854. EXPECT_FALSE(cli_.is_socket_open());
  5855. }
  5856. TEST_F(ServerTest, MultipartFormData) {
  5857. UploadFormDataItems items = {
  5858. {"text1", "text default", "", ""},
  5859. {"text2", "aωb", "", ""},
  5860. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5861. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5862. {"file3", "", "", "application/octet-stream"},
  5863. {"file4", "", "", " application/json tmp-string "}};
  5864. auto res = cli_.Post("/multipart", items);
  5865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5866. EXPECT_EQ(StatusCode::OK_200, res->status);
  5867. }
  5868. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5869. UploadFormDataItems items = {
  5870. {"text", "default text", "", ""},
  5871. {"multi_text1", "aaaaa", "", ""},
  5872. {"multi_text1", "bbbbb", "", ""},
  5873. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5874. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5875. "application/json"},
  5876. };
  5877. auto res = cli_.Post("/multipart/multi_file_values", items);
  5878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5879. EXPECT_EQ(StatusCode::OK_200, res->status);
  5880. }
  5881. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5882. auto res = cli_.Get("/hi");
  5883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5884. EXPECT_EQ(StatusCode::OK_200, res->status);
  5885. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5886. EXPECT_EQ("Hello World!", res->body);
  5887. }
  5888. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5889. Request req;
  5890. req.method = "POST";
  5891. req.path = "/chunked";
  5892. std::string host_and_port;
  5893. host_and_port += HOST;
  5894. host_and_port += ":";
  5895. host_and_port += std::to_string(PORT);
  5896. req.headers.emplace("Host", host_and_port.c_str());
  5897. req.headers.emplace("Accept", "*/*");
  5898. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5899. req.headers.emplace("Content-Type", "text/plain");
  5900. req.headers.emplace("Content-Length", "0");
  5901. req.headers.emplace(
  5902. "Transfer-Encoding",
  5903. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5904. // Client does not chunk, so make a chunked body manually.
  5905. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5906. auto res = std::make_shared<Response>();
  5907. auto error = Error::Success;
  5908. auto ret = cli_.send(req, *res, error);
  5909. ASSERT_TRUE(ret);
  5910. EXPECT_EQ(StatusCode::OK_200, res->status);
  5911. }
  5912. template <typename ClientT>
  5913. static void expect_chunked_body_status(ClientT &cli, const char *body,
  5914. int expected_status) {
  5915. Request req;
  5916. req.method = "POST";
  5917. req.path = "/chunked";
  5918. std::string host_and_port;
  5919. host_and_port += HOST;
  5920. host_and_port += ":";
  5921. host_and_port += std::to_string(PORT);
  5922. req.headers.emplace("Host", host_and_port.c_str());
  5923. req.headers.emplace("Content-Length", "0");
  5924. req.headers.emplace("Transfer-Encoding", "chunked");
  5925. req.body = body;
  5926. auto res = std::make_shared<Response>();
  5927. auto error = Error::Success;
  5928. ASSERT_TRUE(cli.send(req, *res, error));
  5929. EXPECT_EQ(expected_status, res->status);
  5930. }
  5931. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5932. // rather than treat them as valid lengths.
  5933. template <typename ClientT>
  5934. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5935. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  5936. }
  5937. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5938. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5939. }
  5940. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5941. expect_chunked_body_rejected(
  5942. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5943. }
  5944. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  5945. // chunk-size line carries no CR, LF or other control character ahead of its
  5946. // terminator. Such a line must be refused rather than read as extension text.
  5947. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  5948. expect_chunked_body_rejected(
  5949. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5950. }
  5951. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  5952. expect_chunked_body_rejected(
  5953. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5954. }
  5955. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  5956. expect_chunked_body_rejected(
  5957. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5958. }
  5959. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  5960. // The literal stays split: a hex escape consumes every hex digit that
  5961. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  5962. expect_chunked_body_rejected(
  5963. cli_, "4;a\x01"
  5964. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5965. }
  5966. TEST_F(ServerTest, AcceptsChunkExtension) {
  5967. expect_chunked_body_status(cli_,
  5968. "4;name=value\r\ndech\r\n"
  5969. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  5970. "0;last\r\n\r\n",
  5971. StatusCode::OK_200);
  5972. }
  5973. TEST_F(ServerTest, GetStreamed2) {
  5974. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5976. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5977. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5978. EXPECT_EQ(true, res->has_header("Content-Range"));
  5979. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5980. EXPECT_EQ(std::string("ab"), res->body);
  5981. }
  5982. TEST_F(ServerTest, GetStreamed) {
  5983. auto res = cli_.Get("/streamed");
  5984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5985. EXPECT_EQ(StatusCode::OK_200, res->status);
  5986. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5987. EXPECT_EQ(std::string("aaabbb"), res->body);
  5988. }
  5989. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5990. auto res = cli_.Get("/streamed-without-length",
  5991. Headers{make_range_header({{0, -1}})});
  5992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5993. EXPECT_EQ(StatusCode::OK_200, res->status);
  5994. EXPECT_EQ(false, res->has_header("Content-Length"));
  5995. EXPECT_EQ(false, res->has_header("Content-Range"));
  5996. EXPECT_EQ(std::string("abcdefg"), res->body);
  5997. }
  5998. TEST_F(ServerTest, GetStreamedWithRange1) {
  5999. auto res =
  6000. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6003. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6004. EXPECT_EQ(true, res->has_header("Content-Range"));
  6005. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6006. EXPECT_EQ(std::string("def"), res->body);
  6007. }
  6008. TEST_F(ServerTest, GetStreamedWithRange2) {
  6009. auto res =
  6010. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6012. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6013. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6014. EXPECT_EQ(true, res->has_header("Content-Range"));
  6015. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6016. EXPECT_EQ(std::string("bcdefg"), res->body);
  6017. }
  6018. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6019. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6021. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6022. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6023. EXPECT_EQ(true, res->has_header("Content-Range"));
  6024. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6025. EXPECT_EQ(std::string("efg"), res->body);
  6026. }
  6027. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6028. auto res =
  6029. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  6030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6031. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6032. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6033. EXPECT_EQ(false, res->has_header("Content-Range"));
  6034. EXPECT_EQ(0U, res->body.size());
  6035. }
  6036. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6037. // Only a 206 is served as a partial representation. Under any other status
  6038. // `apply_ranges()` reported the full content length, so the body must match
  6039. // that header, and the content provider must never be asked for an offset
  6040. // outside the representation.
  6041. auto check = [&](int status, const char *range) {
  6042. auto path =
  6043. std::string("/streamed-with-range?status=") + std::to_string(status);
  6044. auto ctx = path + " Range: " + range;
  6045. auto res = cli_.Get(path, Headers{{"Range", range}});
  6046. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6047. EXPECT_EQ(status, res->status) << ctx;
  6048. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6049. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6050. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6051. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6052. };
  6053. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6054. check(403, "bytes=3-5");
  6055. // The offset is far past the representation.
  6056. check(403, "bytes=100000-100200");
  6057. // `first_pos` is still -1 here, and the bounds asserts in
  6058. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6059. check(403, "bytes=-3");
  6060. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6061. // multipart branch would have written one that is empty.
  6062. check(403, "bytes=1-2, 4-5");
  6063. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6064. // covers the whole representation.
  6065. check(200, "bytes=3-5");
  6066. check(200, "bytes=1-2, 4-5");
  6067. }
  6068. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6069. auto res =
  6070. cli_.Get("/streamed-with-range",
  6071. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6072. "92233720368547758079223372036854775807"}});
  6073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6074. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6075. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6076. EXPECT_EQ(false, res->has_header("Content-Range"));
  6077. EXPECT_EQ(0U, res->body.size());
  6078. }
  6079. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6080. auto res = cli_.Get(
  6081. "/with-range",
  6082. Headers{{"Range",
  6083. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6084. {"Accept-Encoding", ""}});
  6085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6086. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6087. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6088. EXPECT_EQ(true, res->has_header("Content-Range"));
  6089. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6090. EXPECT_EQ(std::string("abcdefg"), res->body);
  6091. }
  6092. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6093. auto res = cli_.Get("/with-range", Headers{
  6094. {"Range", "bytes=0-"},
  6095. {"Accept-Encoding", ""},
  6096. });
  6097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6098. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6099. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6100. EXPECT_EQ(true, res->has_header("Content-Range"));
  6101. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6102. EXPECT_EQ(std::string("abcdefg"), res->body);
  6103. }
  6104. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6105. auto res = cli_.Get("/streamed-with-range",
  6106. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6108. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6109. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6110. EXPECT_EQ(false, res->has_header("Content-Range"));
  6111. EXPECT_EQ(267U, res->body.size());
  6112. // Check that both range contents are present
  6113. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6114. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6115. // Check that Content-Range headers are present for both ranges
  6116. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6117. std::string::npos);
  6118. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6119. std::string::npos);
  6120. }
  6121. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6122. Ranges ranges;
  6123. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6124. ranges.emplace_back(0, -1);
  6125. }
  6126. auto res = cli_.Get("/streamed-with-range?error",
  6127. Headers{{make_range_header(ranges)}});
  6128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6129. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6130. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6131. EXPECT_EQ(false, res->has_header("Content-Range"));
  6132. EXPECT_EQ(0U, res->body.size());
  6133. }
  6134. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6135. auto res = cli_.Get("/streamed-with-range",
  6136. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6139. EXPECT_EQ(5U, res->body.size());
  6140. // Check that overlapping ranges are coalesced into a single range
  6141. EXPECT_EQ("bcdef", res->body);
  6142. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6143. // Should be single range, not multipart
  6144. EXPECT_TRUE(res->has_header("Content-Range"));
  6145. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6146. }
  6147. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6148. auto res = cli_.Get("/streamed-with-range",
  6149. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6151. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6152. EXPECT_EQ(268U, res->body.size());
  6153. // Check that both range contents are present
  6154. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6155. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6156. // Check that Content-Range headers are present for both ranges
  6157. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6158. std::string::npos);
  6159. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6160. std::string::npos);
  6161. }
  6162. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6163. auto res = cli_.Get("/streamed-with-range",
  6164. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6167. EXPECT_EQ(269U, res->body.size());
  6168. // Check that both duplicate range contents are present
  6169. size_t first_abc = res->body.find("abc\r\n");
  6170. EXPECT_TRUE(first_abc != std::string::npos);
  6171. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6172. EXPECT_TRUE(second_abc != std::string::npos);
  6173. // Check that Content-Range headers are present for both ranges
  6174. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6175. EXPECT_TRUE(first_range != std::string::npos);
  6176. size_t second_range =
  6177. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6178. EXPECT_TRUE(second_range != std::string::npos);
  6179. }
  6180. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6181. auto res =
  6182. cli_.Get("/streamed-with-range?error",
  6183. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6186. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6187. EXPECT_EQ(false, res->has_header("Content-Range"));
  6188. EXPECT_EQ(0U, res->body.size());
  6189. }
  6190. TEST_F(ServerTest, GetStreamedEndless) {
  6191. uint64_t offset = 0;
  6192. auto res = cli_.Get("/streamed-cancel",
  6193. [&](const char * /*data*/, uint64_t data_length) {
  6194. if (offset < 100) {
  6195. offset += data_length;
  6196. return true;
  6197. }
  6198. return false;
  6199. });
  6200. ASSERT_TRUE(!res);
  6201. EXPECT_EQ(Error::Canceled, res.error());
  6202. }
  6203. TEST_F(ServerTest, ClientStop) {
  6204. std::atomic_size_t count{4};
  6205. std::vector<std::thread> threads;
  6206. for (auto i = count.load(); i != 0; --i) {
  6207. threads.emplace_back([&]() {
  6208. auto res = cli_.Get("/streamed-cancel",
  6209. [&](const char *, uint64_t) { return true; });
  6210. --count;
  6211. ASSERT_TRUE(!res);
  6212. EXPECT_TRUE(res.error() == Error::Canceled ||
  6213. res.error() == Error::Read || res.error() == Error::Write);
  6214. });
  6215. }
  6216. std::this_thread::sleep_for(std::chrono::seconds(2));
  6217. while (count != 0) {
  6218. cli_.stop();
  6219. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6220. }
  6221. for (auto &t : threads) {
  6222. t.join();
  6223. }
  6224. }
  6225. TEST_F(ServerTest, GetWithRange1) {
  6226. auto res = cli_.Get("/with-range", Headers{
  6227. make_range_header({{3, 5}}),
  6228. {"Accept-Encoding", ""},
  6229. });
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6232. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6233. EXPECT_EQ(true, res->has_header("Content-Range"));
  6234. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6235. EXPECT_EQ(std::string("def"), res->body);
  6236. }
  6237. TEST_F(ServerTest, GetWithRange2) {
  6238. auto res = cli_.Get("/with-range", Headers{
  6239. make_range_header({{1, -1}}),
  6240. {"Accept-Encoding", ""},
  6241. });
  6242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6243. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6244. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6245. EXPECT_EQ(true, res->has_header("Content-Range"));
  6246. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6247. EXPECT_EQ(std::string("bcdefg"), res->body);
  6248. }
  6249. TEST_F(ServerTest, GetWithRange3) {
  6250. auto res = cli_.Get("/with-range", Headers{
  6251. make_range_header({{0, 0}}),
  6252. {"Accept-Encoding", ""},
  6253. });
  6254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6255. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6256. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6257. EXPECT_EQ(true, res->has_header("Content-Range"));
  6258. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6259. EXPECT_EQ(std::string("a"), res->body);
  6260. }
  6261. TEST_F(ServerTest, GetWithRange4) {
  6262. auto res = cli_.Get("/with-range", Headers{
  6263. make_range_header({{-1, 2}}),
  6264. {"Accept-Encoding", ""},
  6265. });
  6266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6267. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6268. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6269. EXPECT_EQ(true, res->has_header("Content-Range"));
  6270. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6271. EXPECT_EQ(std::string("fg"), res->body);
  6272. }
  6273. TEST_F(ServerTest, GetWithRange5) {
  6274. auto res = cli_.Get("/with-range", Headers{
  6275. make_range_header({{0, 5}}),
  6276. {"Accept-Encoding", ""},
  6277. });
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6280. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6281. EXPECT_EQ(true, res->has_header("Content-Range"));
  6282. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6283. EXPECT_EQ(std::string("abcdef"), res->body);
  6284. }
  6285. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6286. auto res =
  6287. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6289. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6290. }
  6291. TEST_F(ServerTest, GetWithRangeMultipart) {
  6292. auto res =
  6293. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6295. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6296. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6297. EXPECT_EQ(false, res->has_header("Content-Range"));
  6298. EXPECT_EQ(267U, res->body.size());
  6299. }
  6300. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6301. auto res = cli_.Get("/with-range",
  6302. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6305. }
  6306. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6307. auto res = cli_.Get("/with-range-customized-response",
  6308. Headers{{make_range_header({{1, 2}})}});
  6309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6310. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6311. EXPECT_EQ(true, res->has_header("Content-Length"));
  6312. EXPECT_EQ(false, res->has_header("Content-Range"));
  6313. EXPECT_EQ(JSON_DATA, res->body);
  6314. }
  6315. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6316. auto res = cli_.Get("/with-range-customized-response",
  6317. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6320. EXPECT_EQ(true, res->has_header("Content-Length"));
  6321. EXPECT_EQ(false, res->has_header("Content-Range"));
  6322. EXPECT_EQ(JSON_DATA, res->body);
  6323. }
  6324. TEST_F(ServerTest, Issue1772) {
  6325. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6327. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6328. }
  6329. TEST_F(ServerTest, Issue609) {
  6330. auto res = cli_.Delete("/issue609");
  6331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6332. EXPECT_EQ(StatusCode::OK_200, res->status);
  6333. EXPECT_EQ(std::string("ok"), res->body);
  6334. }
  6335. TEST_F(ServerTest, GetStreamedChunked) {
  6336. auto res = cli_.Get("/streamed-chunked");
  6337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6338. EXPECT_EQ(StatusCode::OK_200, res->status);
  6339. EXPECT_EQ(std::string("123456789"), res->body);
  6340. }
  6341. TEST_F(ServerTest, GetStreamedChunked2) {
  6342. auto res = cli_.Get("/streamed-chunked2");
  6343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6344. EXPECT_EQ(StatusCode::OK_200, res->status);
  6345. EXPECT_EQ(std::string("123456789"), res->body);
  6346. }
  6347. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6348. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. EXPECT_EQ(StatusCode::OK_200, res->status);
  6351. EXPECT_EQ(std::string("123456789"), res->body);
  6352. EXPECT_TRUE(res->has_header("Trailer"));
  6353. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6354. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6355. // Trailers are now stored separately from headers (security fix)
  6356. EXPECT_EQ(2U, res->trailers.size());
  6357. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6358. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6359. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6360. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6361. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6362. // Verify trailers are NOT in headers (security verification)
  6363. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6364. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6365. }
  6366. TEST_F(ServerTest, LargeChunkedPost) {
  6367. Request req;
  6368. req.method = "POST";
  6369. req.path = "/large-chunked";
  6370. std::string host_and_port;
  6371. host_and_port += HOST;
  6372. host_and_port += ":";
  6373. host_and_port += std::to_string(PORT);
  6374. req.headers.emplace("Host", host_and_port.c_str());
  6375. req.headers.emplace("Accept", "*/*");
  6376. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6377. req.headers.emplace("Content-Type", "text/plain");
  6378. req.headers.emplace("Content-Length", "0");
  6379. req.headers.emplace("Transfer-Encoding", "chunked");
  6380. std::string long_string(30 * 1024u, 'a');
  6381. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6382. // Attempt to make a large enough post to exceed OS buffers, to test that
  6383. // the server handles short reads if the full chunk data isn't available.
  6384. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6385. auto res = std::make_shared<Response>();
  6386. auto error = Error::Success;
  6387. auto ret = cli_.send(req, *res, error);
  6388. ASSERT_TRUE(ret);
  6389. EXPECT_EQ(StatusCode::OK_200, res->status);
  6390. }
  6391. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6392. auto res = cli_.Get("/remote_addr");
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. EXPECT_EQ(StatusCode::OK_200, res->status);
  6395. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6396. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6397. }
  6398. TEST_F(ServerTest, GetMethodLocalAddr) {
  6399. auto res = cli_.Get("/local_addr");
  6400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6401. EXPECT_EQ(StatusCode::OK_200, res->status);
  6402. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6403. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6404. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6405. }
  6406. TEST_F(ServerTest, HTTPResponseSplitting) {
  6407. auto res = cli_.Get("/http_response_splitting");
  6408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6409. EXPECT_EQ(StatusCode::OK_200, res->status);
  6410. }
  6411. TEST_F(ServerTest, SlowRequest) {
  6412. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6413. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6414. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6415. }
  6416. #if 0
  6417. TEST_F(ServerTest, SlowPost) {
  6418. char buffer[64 * 1024];
  6419. memset(buffer, 0x42, sizeof(buffer));
  6420. auto res = cli_.Post(
  6421. "/slowpost", 64 * 1024 * 1024,
  6422. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6423. auto ret = sink.write(buffer, sizeof(buffer));
  6424. EXPECT_TRUE(ret);
  6425. return true;
  6426. },
  6427. "text/plain");
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. EXPECT_EQ(StatusCode::OK_200, res->status);
  6430. }
  6431. TEST_F(ServerTest, SlowPostFail) {
  6432. char buffer[64 * 1024];
  6433. memset(buffer, 0x42, sizeof(buffer));
  6434. cli_.set_write_timeout(std::chrono::seconds(0));
  6435. auto res = cli_.Post(
  6436. "/slowpost", 64 * 1024 * 1024,
  6437. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6438. sink.write(buffer, sizeof(buffer));
  6439. return true;
  6440. },
  6441. "text/plain");
  6442. ASSERT_TRUE(!res);
  6443. EXPECT_EQ(Error::Write, res.error());
  6444. }
  6445. #endif
  6446. TEST_F(ServerTest, Put) {
  6447. auto res = cli_.Put("/put", "PUT", "text/plain");
  6448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6449. EXPECT_EQ(StatusCode::OK_200, res->status);
  6450. EXPECT_EQ("PUT", res->body);
  6451. }
  6452. TEST_F(ServerTest, PutWithContentProvider) {
  6453. auto res = cli_.Put(
  6454. "/put", 3,
  6455. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6456. sink.os << "PUT";
  6457. return true;
  6458. },
  6459. "text/plain");
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. EXPECT_EQ(StatusCode::OK_200, res->status);
  6462. EXPECT_EQ("PUT", res->body);
  6463. }
  6464. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6465. auto res = cli_.Post(
  6466. "/post", 42,
  6467. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6468. return false;
  6469. },
  6470. "text/plain");
  6471. ASSERT_TRUE(!res);
  6472. EXPECT_EQ(Error::Canceled, res.error());
  6473. }
  6474. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6475. auto res = cli_.Put(
  6476. "/put",
  6477. [](size_t /*offset*/, DataSink &sink) {
  6478. sink.os << "PUT";
  6479. sink.done();
  6480. return true;
  6481. },
  6482. "text/plain");
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. EXPECT_EQ(StatusCode::OK_200, res->status);
  6485. EXPECT_EQ("PUT", res->body);
  6486. }
  6487. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6488. auto res = cli_.Post(
  6489. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6490. "text/plain");
  6491. ASSERT_TRUE(!res);
  6492. EXPECT_EQ(Error::Canceled, res.error());
  6493. }
  6494. TEST_F(ServerTest, PostLoopBack) {
  6495. std::string body;
  6496. auto res = cli_.Post(
  6497. "/post-loopback", 9,
  6498. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6499. EXPECT_EQ(9u, length);
  6500. sink.write("123", 3);
  6501. sink.write("456", 3);
  6502. sink.write("789", 3);
  6503. return true;
  6504. },
  6505. "text/plain",
  6506. [&body](const char *data, size_t data_length) {
  6507. body.append(data, data_length);
  6508. return true;
  6509. });
  6510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6511. EXPECT_EQ(StatusCode::OK_200, res->status);
  6512. EXPECT_EQ("123456789", body);
  6513. }
  6514. TEST_F(ServerTest, PutLoopBack) {
  6515. std::string body;
  6516. auto res = cli_.Put(
  6517. "/put-loopback", 9,
  6518. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6519. EXPECT_EQ(9u, length);
  6520. sink.write("123", 3);
  6521. sink.write("456", 3);
  6522. sink.write("789", 3);
  6523. return true;
  6524. },
  6525. "text/plain",
  6526. [&body](const char *data, size_t data_length) {
  6527. body.append(data, data_length);
  6528. return true;
  6529. });
  6530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6531. EXPECT_EQ(StatusCode::OK_200, res->status);
  6532. EXPECT_EQ("123456789", body);
  6533. }
  6534. TEST_F(ServerTest, PatchLoopBack) {
  6535. std::string body;
  6536. auto res = cli_.Patch(
  6537. "/patch-loopback", 9,
  6538. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6539. EXPECT_EQ(9u, length);
  6540. sink.write("123", 3);
  6541. sink.write("456", 3);
  6542. sink.write("789", 3);
  6543. return true;
  6544. },
  6545. "text/plain",
  6546. [&body](const char *data, size_t data_length) {
  6547. body.append(data, data_length);
  6548. return true;
  6549. });
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::OK_200, res->status);
  6552. EXPECT_EQ("123456789", body);
  6553. }
  6554. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6555. std::string body;
  6556. auto res = cli_.Post(
  6557. "/post-loopback",
  6558. [](size_t /*offset*/, DataSink &sink) {
  6559. sink.write("123", 3);
  6560. sink.write("456", 3);
  6561. sink.write("789", 3);
  6562. sink.done();
  6563. return true;
  6564. },
  6565. "text/plain",
  6566. [&body](const char *data, size_t data_length) {
  6567. body.append(data, data_length);
  6568. return true;
  6569. });
  6570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6571. EXPECT_EQ(StatusCode::OK_200, res->status);
  6572. EXPECT_EQ("123456789", body);
  6573. }
  6574. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6575. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6576. cli_.set_compress(true);
  6577. auto res = cli_.Put(
  6578. "/put", 3,
  6579. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6580. sink.os << "PUT";
  6581. return true;
  6582. },
  6583. "text/plain");
  6584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6585. EXPECT_EQ(StatusCode::OK_200, res->status);
  6586. EXPECT_EQ("PUT", res->body);
  6587. }
  6588. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6589. cli_.set_compress(true);
  6590. auto res = cli_.Post(
  6591. "/post", 42,
  6592. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6593. return false;
  6594. },
  6595. "text/plain");
  6596. ASSERT_TRUE(!res);
  6597. EXPECT_EQ(Error::Canceled, res.error());
  6598. }
  6599. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6600. cli_.set_compress(true);
  6601. auto res = cli_.Put(
  6602. "/put",
  6603. [](size_t /*offset*/, DataSink &sink) {
  6604. sink.os << "PUT";
  6605. sink.done();
  6606. return true;
  6607. },
  6608. "text/plain");
  6609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6610. EXPECT_EQ(StatusCode::OK_200, res->status);
  6611. EXPECT_EQ("PUT", res->body);
  6612. }
  6613. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6614. cli_.set_compress(true);
  6615. auto res = cli_.Post(
  6616. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6617. "text/plain");
  6618. ASSERT_TRUE(!res);
  6619. EXPECT_EQ(Error::Canceled, res.error());
  6620. }
  6621. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6622. cli_.set_compress(true);
  6623. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6625. EXPECT_EQ(StatusCode::OK_200, res->status);
  6626. EXPECT_EQ(LARGE_DATA, res->body);
  6627. }
  6628. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6629. #ifdef CPPHTTPLIB_SSL_ENABLED
  6630. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6631. Client cli(s.c_str());
  6632. cli.enable_server_certificate_verification(false);
  6633. #else
  6634. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6635. Client cli(s.c_str());
  6636. #endif
  6637. cli.set_compress(true);
  6638. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6640. EXPECT_EQ(StatusCode::OK_200, res->status);
  6641. EXPECT_EQ(LARGE_DATA, res->body);
  6642. // The compressed size should be less than a 10th of the original. May vary
  6643. // depending on the zlib library.
  6644. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6645. static_cast<uint64_t>(10 * 1024 * 1024));
  6646. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6647. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6648. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6649. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6650. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6651. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6652. #endif
  6653. }
  6654. TEST_F(ServerTest, PutContentWithDeflate) {
  6655. cli_.set_compress(false);
  6656. Headers headers;
  6657. headers.emplace("Content-Encoding", "deflate");
  6658. // PUT in deflate format:
  6659. auto res = cli_.Put("/put", headers,
  6660. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6662. EXPECT_EQ(StatusCode::OK_200, res->status);
  6663. EXPECT_EQ("PUT", res->body);
  6664. }
  6665. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6666. Headers headers;
  6667. headers.emplace("Accept-Encoding", "gzip, deflate");
  6668. auto res = cli_.Get("/streamed-chunked", headers);
  6669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6670. EXPECT_EQ(StatusCode::OK_200, res->status);
  6671. EXPECT_EQ(std::string("123456789"), res->body);
  6672. }
  6673. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6674. Headers headers;
  6675. headers.emplace("Accept-Encoding", "gzip, deflate");
  6676. auto res = cli_.Get("/streamed-chunked2", headers);
  6677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6678. EXPECT_EQ(StatusCode::OK_200, res->status);
  6679. EXPECT_EQ(std::string("123456789"), res->body);
  6680. }
  6681. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6682. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6684. EXPECT_EQ(StatusCode::OK_200, res->status);
  6685. }
  6686. TEST(GzipDecompressor, ChunkedDecompression) {
  6687. std::string data;
  6688. for (size_t i = 0; i < 32 * 1024; ++i) {
  6689. data.push_back(static_cast<char>('a' + i % 26));
  6690. }
  6691. std::string compressed_data;
  6692. {
  6693. httplib::detail::gzip_compressor compressor;
  6694. bool result = compressor.compress(
  6695. data.data(), data.size(),
  6696. /*last=*/true,
  6697. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6698. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6699. compressed_data_size);
  6700. return true;
  6701. });
  6702. ASSERT_TRUE(result);
  6703. }
  6704. std::string decompressed_data;
  6705. {
  6706. httplib::detail::gzip_decompressor decompressor;
  6707. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6708. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6709. size_t chunk_size = 130;
  6710. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6711. chunk_begin += chunk_size) {
  6712. size_t current_chunk_size =
  6713. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6714. bool result = decompressor.decompress(
  6715. compressed_data.data() + chunk_begin, current_chunk_size,
  6716. [&](const char *decompressed_data_chunk,
  6717. size_t decompressed_data_chunk_size) {
  6718. decompressed_data.insert(decompressed_data.size(),
  6719. decompressed_data_chunk,
  6720. decompressed_data_chunk_size);
  6721. return true;
  6722. });
  6723. ASSERT_TRUE(result);
  6724. }
  6725. }
  6726. ASSERT_EQ(data, decompressed_data);
  6727. }
  6728. TEST(GzipDecompressor, DeflateDecompression) {
  6729. std::string original_text = "Raw deflate without gzip";
  6730. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6731. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6732. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6733. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6734. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6735. std::string decompressed_data;
  6736. {
  6737. httplib::detail::gzip_decompressor decompressor;
  6738. bool result = decompressor.decompress(
  6739. compressed_data.data(), compressed_data.size(),
  6740. [&](const char *decompressed_data_chunk,
  6741. size_t decompressed_data_chunk_size) {
  6742. decompressed_data.insert(decompressed_data.size(),
  6743. decompressed_data_chunk,
  6744. decompressed_data_chunk_size);
  6745. return true;
  6746. });
  6747. ASSERT_TRUE(result);
  6748. }
  6749. ASSERT_EQ(original_text, decompressed_data);
  6750. }
  6751. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6752. std::string original_text = "Raw deflate without gzip";
  6753. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6754. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6755. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6756. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6757. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6758. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6759. std::string decompressed_data;
  6760. {
  6761. httplib::detail::gzip_decompressor decompressor;
  6762. bool result = decompressor.decompress(
  6763. compressed_data.data(), compressed_data.size(),
  6764. [&](const char *decompressed_data_chunk,
  6765. size_t decompressed_data_chunk_size) {
  6766. decompressed_data.insert(decompressed_data.size(),
  6767. decompressed_data_chunk,
  6768. decompressed_data_chunk_size);
  6769. return true;
  6770. });
  6771. ASSERT_TRUE(result);
  6772. }
  6773. ASSERT_EQ(original_text, decompressed_data);
  6774. }
  6775. #endif
  6776. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6777. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6778. Headers headers;
  6779. headers.emplace("Accept-Encoding", "br");
  6780. auto res = cli_.Get("/streamed-chunked", headers);
  6781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6782. EXPECT_EQ(StatusCode::OK_200, res->status);
  6783. EXPECT_EQ(std::string("123456789"), res->body);
  6784. }
  6785. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6786. Headers headers;
  6787. headers.emplace("Accept-Encoding", "br");
  6788. auto res = cli_.Get("/streamed-chunked2", headers);
  6789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6790. EXPECT_EQ(StatusCode::OK_200, res->status);
  6791. EXPECT_EQ(std::string("123456789"), res->body);
  6792. }
  6793. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6794. cli_.set_compress(true);
  6795. auto res = cli_.Put(
  6796. "/put", 3,
  6797. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6798. sink.os << "PUT";
  6799. return true;
  6800. },
  6801. "text/plain");
  6802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6803. EXPECT_EQ(StatusCode::OK_200, res->status);
  6804. EXPECT_EQ("PUT", res->body);
  6805. }
  6806. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6807. cli_.set_compress(true);
  6808. auto res = cli_.Put(
  6809. "/put",
  6810. [](size_t /*offset*/, DataSink &sink) {
  6811. sink.os << "PUT";
  6812. sink.done();
  6813. return true;
  6814. },
  6815. "text/plain");
  6816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6817. EXPECT_EQ(StatusCode::OK_200, res->status);
  6818. EXPECT_EQ("PUT", res->body);
  6819. }
  6820. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6821. cli_.set_compress(true);
  6822. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6824. EXPECT_EQ(StatusCode::OK_200, res->status);
  6825. EXPECT_EQ(LARGE_DATA, res->body);
  6826. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6827. }
  6828. #endif
  6829. TEST_F(ServerTest, Patch) {
  6830. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6832. EXPECT_EQ(StatusCode::OK_200, res->status);
  6833. EXPECT_EQ("PATCH", res->body);
  6834. }
  6835. TEST_F(ServerTest, Delete) {
  6836. auto res = cli_.Delete("/delete");
  6837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6838. EXPECT_EQ(StatusCode::OK_200, res->status);
  6839. EXPECT_EQ("DELETE", res->body);
  6840. }
  6841. TEST_F(ServerTest, DeleteContentReceiver) {
  6842. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. EXPECT_EQ(StatusCode::OK_200, res->status);
  6845. EXPECT_EQ("content", res->body);
  6846. }
  6847. TEST_F(ServerTest, Options) {
  6848. auto res = cli_.Options("*");
  6849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6850. EXPECT_EQ(StatusCode::OK_200, res->status);
  6851. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6852. EXPECT_TRUE(res->body.empty());
  6853. }
  6854. TEST_F(ServerTest, URL) {
  6855. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. EXPECT_EQ(StatusCode::OK_200, res->status);
  6858. }
  6859. TEST_F(ServerTest, ArrayParam) {
  6860. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6862. EXPECT_EQ(StatusCode::OK_200, res->status);
  6863. }
  6864. TEST_F(ServerTest, ArrayParamValues) {
  6865. auto res =
  6866. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. EXPECT_EQ(StatusCode::OK_200, res->status);
  6869. }
  6870. TEST_F(ServerTest, NoMultipleHeaders) {
  6871. Headers headers = {{"Content-Length", "5"}};
  6872. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6873. "text/plain");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. }
  6877. TEST_F(ServerTest, PostContentReceiver) {
  6878. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. ASSERT_EQ(StatusCode::OK_200, res->status);
  6881. ASSERT_EQ("content", res->body);
  6882. }
  6883. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6884. UploadFormDataItems items = {
  6885. {"text1", "text default", "", ""},
  6886. {"text2", "aωb", "", ""},
  6887. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6888. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6889. {"file3", "", "", "application/octet-stream"},
  6890. };
  6891. auto res = cli_.Post("/content_receiver", items);
  6892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6893. EXPECT_EQ(StatusCode::OK_200, res->status);
  6894. }
  6895. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6896. UploadFormDataItems items = {
  6897. {"text1", "text default", "", ""},
  6898. {"text2", "aωb", "", ""},
  6899. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6900. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6901. {"file3", "", "", "application/octet-stream"},
  6902. };
  6903. auto boundary = std::string("+++++");
  6904. std::string body;
  6905. for (const auto &item : items) {
  6906. body += "--" + boundary + "\r\n";
  6907. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6908. if (!item.filename.empty()) {
  6909. body += "; filename=\"" + item.filename + "\"";
  6910. }
  6911. body += "\r\n";
  6912. if (!item.content_type.empty()) {
  6913. body += "Content-Type: " + item.content_type + "\r\n";
  6914. }
  6915. body += "\r\n";
  6916. body += item.content + "\r\n";
  6917. }
  6918. body += "--" + boundary + "--\r\n";
  6919. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6920. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6922. EXPECT_EQ(StatusCode::OK_200, res->status);
  6923. }
  6924. TEST(MultipartFormDataTest, FieldEscaping) {
  6925. Server svr;
  6926. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6927. const ContentReader &content_reader) {
  6928. ASSERT_TRUE(req.is_multipart_form_data());
  6929. std::vector<FormData> received;
  6930. content_reader(
  6931. [&](const FormData &file) {
  6932. received.push_back(file);
  6933. return true;
  6934. },
  6935. [&](const char *data, size_t data_length) {
  6936. received.back().content.append(data, data_length);
  6937. return true;
  6938. });
  6939. // '"', CR and LF in names and filenames are escaped following the
  6940. // WHATWG HTML standard, so each part still parses as a single part
  6941. // with no injected headers. Content types get CR/LF escaped too,
  6942. // while '"' (legal there, e.g. quoted charset) is preserved.
  6943. ASSERT_EQ(4U, received.size());
  6944. EXPECT_EQ("na%22me", received[0].name);
  6945. EXPECT_EQ("quoted name", received[0].content);
  6946. EXPECT_EQ("file", received[1].name);
  6947. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6948. received[1].filename);
  6949. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6950. EXPECT_EQ("injected", received[1].content);
  6951. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6952. EXPECT_EQ("my%22file.txt", received[2].filename);
  6953. EXPECT_EQ("cr lf name", received[2].content);
  6954. EXPECT_EQ("typed", received[3].name);
  6955. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6956. received[3].content_type);
  6957. EXPECT_EQ("typed content", received[3].content);
  6958. });
  6959. auto port = svr.bind_to_any_port("localhost");
  6960. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6961. auto se = detail::scope_exit([&] {
  6962. svr.stop();
  6963. t.join();
  6964. ASSERT_FALSE(svr.is_running());
  6965. });
  6966. svr.wait_until_ready();
  6967. Client cli("localhost", port);
  6968. UploadFormDataItems items = {
  6969. {"na\"me", "quoted name", "", ""},
  6970. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6971. "application/octet-stream"},
  6972. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6973. {"typed", "typed content", "",
  6974. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6975. };
  6976. auto res = cli.Post("/post", items);
  6977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6978. EXPECT_EQ(StatusCode::OK_200, res->status);
  6979. }
  6980. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6981. const UploadFormDataItems items = {
  6982. {"name1", "Content 1", "", ""},
  6983. {"name2", "Content 2", "file2.txt", "text/plain"},
  6984. };
  6985. Server svr;
  6986. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6987. const ContentReader &content_reader) {
  6988. ASSERT_TRUE(req.is_multipart_form_data());
  6989. std::vector<FormData> received;
  6990. content_reader(
  6991. [&](const FormData &file) {
  6992. received.push_back(file);
  6993. return true;
  6994. },
  6995. [&](const char *data, size_t data_length) {
  6996. received.back().content.append(data, data_length);
  6997. return true;
  6998. });
  6999. ASSERT_EQ(2U, received.size());
  7000. EXPECT_EQ("name1", received[0].name);
  7001. EXPECT_EQ("Content 1", received[0].content);
  7002. EXPECT_EQ("name2", received[1].name);
  7003. EXPECT_EQ("Content 2", received[1].content);
  7004. EXPECT_EQ("file2.txt", received[1].filename);
  7005. EXPECT_EQ("text/plain", received[1].content_type);
  7006. });
  7007. auto port = svr.bind_to_any_port("localhost");
  7008. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7009. auto se = detail::scope_exit([&] {
  7010. svr.stop();
  7011. t.join();
  7012. ASSERT_FALSE(svr.is_running());
  7013. });
  7014. svr.wait_until_ready();
  7015. Client cli("localhost", port);
  7016. // Whole-body serialization with a generated boundary
  7017. {
  7018. MultipartFormDataWriter writer;
  7019. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7020. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7021. writer.content_type());
  7022. auto body = writer.serialize(items);
  7023. EXPECT_EQ(body.size(), writer.content_length(items));
  7024. auto res = cli.Post("/post", body, writer.content_type());
  7025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7026. EXPECT_EQ(StatusCode::OK_200, res->status);
  7027. }
  7028. // Per-part framing with a custom boundary via a content provider
  7029. {
  7030. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7031. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7032. MultipartFormDataWriter writer("custom-boundary_123");
  7033. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7034. std::string body;
  7035. for (const auto &item : items) {
  7036. body += writer.item_begin(item);
  7037. body += item.content;
  7038. body += MultipartFormDataWriter::item_end();
  7039. }
  7040. body += writer.finish();
  7041. EXPECT_EQ(body.size(), writer.content_length(items));
  7042. auto res = cli.Post(
  7043. "/post", body.size(),
  7044. [&](size_t offset, size_t length, DataSink &sink) {
  7045. sink.write(body.data() + offset, length);
  7046. return true;
  7047. },
  7048. writer.content_type());
  7049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7050. EXPECT_EQ(StatusCode::OK_200, res->status);
  7051. }
  7052. }
  7053. TEST_F(ServerTest, PostContentReceiverGzip) {
  7054. cli_.set_compress(true);
  7055. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7057. ASSERT_EQ(StatusCode::OK_200, res->status);
  7058. ASSERT_EQ("content", res->body);
  7059. }
  7060. TEST_F(ServerTest, PutContentReceiver) {
  7061. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7063. ASSERT_EQ(StatusCode::OK_200, res->status);
  7064. ASSERT_EQ("content", res->body);
  7065. }
  7066. TEST_F(ServerTest, PatchContentReceiver) {
  7067. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7069. ASSERT_EQ(StatusCode::OK_200, res->status);
  7070. ASSERT_EQ("content", res->body);
  7071. }
  7072. template <typename ClientType>
  7073. void TestWithHeadersAndContentReceiver(
  7074. ClientType &cli,
  7075. std::function<Result(ClientType &, const std::string &, const Headers &,
  7076. const std::string &, const std::string &,
  7077. ContentReceiver, DownloadProgress)>
  7078. request_func) {
  7079. Headers headers;
  7080. headers.emplace("X-Custom-Header", "test-value");
  7081. std::string received_body;
  7082. auto res = request_func(
  7083. cli, "/content_receiver", headers, "content", "application/json",
  7084. [&](const char *data, size_t data_length) {
  7085. received_body.append(data, data_length);
  7086. return true;
  7087. },
  7088. nullptr);
  7089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7090. EXPECT_EQ(StatusCode::OK_200, res->status);
  7091. EXPECT_EQ("content", received_body);
  7092. }
  7093. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7094. #ifdef CPPHTTPLIB_SSL_ENABLED
  7095. using ClientT = SSLClient;
  7096. #else
  7097. using ClientT = Client;
  7098. #endif
  7099. TestWithHeadersAndContentReceiver<ClientT>(
  7100. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7101. const std::string &body, const std::string &content_type,
  7102. ContentReceiver receiver, DownloadProgress progress) {
  7103. return cli.Post(path, headers, body, content_type, receiver, progress);
  7104. });
  7105. }
  7106. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7107. #ifdef CPPHTTPLIB_SSL_ENABLED
  7108. using ClientT = SSLClient;
  7109. #else
  7110. using ClientT = Client;
  7111. #endif
  7112. TestWithHeadersAndContentReceiver<ClientT>(
  7113. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7114. const std::string &body, const std::string &content_type,
  7115. ContentReceiver receiver, DownloadProgress progress) {
  7116. return cli.Put(path, headers, body, content_type, receiver, progress);
  7117. });
  7118. }
  7119. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7120. #ifdef CPPHTTPLIB_SSL_ENABLED
  7121. using ClientT = SSLClient;
  7122. #else
  7123. using ClientT = Client;
  7124. #endif
  7125. TestWithHeadersAndContentReceiver<ClientT>(
  7126. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7127. const std::string &body, const std::string &content_type,
  7128. ContentReceiver receiver, DownloadProgress progress) {
  7129. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7130. });
  7131. }
  7132. template <typename ClientType>
  7133. void TestWithHeadersAndContentReceiverWithProgress(
  7134. ClientType &cli,
  7135. std::function<Result(ClientType &, const std::string &, const Headers &,
  7136. const std::string &, const std::string &,
  7137. ContentReceiver, DownloadProgress)>
  7138. request_func) {
  7139. Headers headers;
  7140. headers.emplace("X-Test-Header", "progress-test");
  7141. std::string received_body;
  7142. auto progress_called = false;
  7143. auto res = request_func(
  7144. cli, "/content_receiver", headers, "content", "text/plain",
  7145. [&](const char *data, size_t data_length) {
  7146. received_body.append(data, data_length);
  7147. return true;
  7148. },
  7149. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7150. progress_called = true;
  7151. return true;
  7152. });
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::OK_200, res->status);
  7155. EXPECT_EQ("content", received_body);
  7156. EXPECT_TRUE(progress_called);
  7157. }
  7158. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7159. #ifdef CPPHTTPLIB_SSL_ENABLED
  7160. using ClientT = SSLClient;
  7161. #else
  7162. using ClientT = Client;
  7163. #endif
  7164. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7165. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7166. const std::string &body, const std::string &content_type,
  7167. ContentReceiver receiver, DownloadProgress progress) {
  7168. return cli.Post(path, headers, body, content_type, receiver, progress);
  7169. });
  7170. }
  7171. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7172. #ifdef CPPHTTPLIB_SSL_ENABLED
  7173. using ClientT = SSLClient;
  7174. #else
  7175. using ClientT = Client;
  7176. #endif
  7177. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7178. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7179. const std::string &body, const std::string &content_type,
  7180. ContentReceiver receiver, DownloadProgress progress) {
  7181. return cli.Put(path, headers, body, content_type, receiver, progress);
  7182. });
  7183. }
  7184. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7185. #ifdef CPPHTTPLIB_SSL_ENABLED
  7186. using ClientT = SSLClient;
  7187. #else
  7188. using ClientT = Client;
  7189. #endif
  7190. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7191. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7192. const std::string &body, const std::string &content_type,
  7193. ContentReceiver receiver, DownloadProgress progress) {
  7194. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7195. });
  7196. }
  7197. template <typename ClientType>
  7198. void TestWithHeadersAndContentReceiverError(
  7199. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7200. const Headers &, const std::string &,
  7201. const std::string &, ContentReceiver)>
  7202. request_func) {
  7203. Headers headers;
  7204. headers.emplace("X-Error-Test", "true");
  7205. std::string received_body;
  7206. auto receiver_failed = false;
  7207. auto res =
  7208. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7209. [&](const char *data, size_t data_length) {
  7210. received_body.append(data, data_length);
  7211. receiver_failed = true;
  7212. return false;
  7213. });
  7214. ASSERT_FALSE(res);
  7215. EXPECT_TRUE(receiver_failed);
  7216. }
  7217. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7218. #ifdef CPPHTTPLIB_SSL_ENABLED
  7219. using ClientT = SSLClient;
  7220. #else
  7221. using ClientT = Client;
  7222. #endif
  7223. TestWithHeadersAndContentReceiverError<ClientT>(
  7224. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7225. const std::string &body, const std::string &content_type,
  7226. ContentReceiver receiver) {
  7227. return cli.Post(path, headers, body, content_type, receiver);
  7228. });
  7229. }
  7230. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7231. #ifdef CPPHTTPLIB_SSL_ENABLED
  7232. using ClientT = SSLClient;
  7233. #else
  7234. using ClientT = Client;
  7235. #endif
  7236. TestWithHeadersAndContentReceiverError<ClientT>(
  7237. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7238. const std::string &body, const std::string &content_type,
  7239. ContentReceiver receiver) {
  7240. return cli.Put(path, headers, body, content_type, receiver);
  7241. });
  7242. }
  7243. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7244. #ifdef CPPHTTPLIB_SSL_ENABLED
  7245. using ClientT = SSLClient;
  7246. #else
  7247. using ClientT = Client;
  7248. #endif
  7249. TestWithHeadersAndContentReceiverError<ClientT>(
  7250. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7251. const std::string &body, const std::string &content_type,
  7252. ContentReceiver receiver) {
  7253. return cli.Patch(path, headers, body, content_type, receiver);
  7254. });
  7255. }
  7256. TEST_F(ServerTest, PostQueryStringAndBody) {
  7257. auto res =
  7258. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7260. ASSERT_EQ(StatusCode::OK_200, res->status);
  7261. }
  7262. TEST_F(ServerTest, HTTP2Magic) {
  7263. Request req;
  7264. req.method = "PRI";
  7265. req.path = "*";
  7266. req.body = "SM";
  7267. auto res = std::make_shared<Response>();
  7268. auto error = Error::Success;
  7269. auto ret = cli_.send(req, *res, error);
  7270. ASSERT_TRUE(ret);
  7271. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7272. }
  7273. TEST_F(ServerTest, KeepAlive) {
  7274. auto res = cli_.Get("/hi");
  7275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7276. EXPECT_EQ(StatusCode::OK_200, res->status);
  7277. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7278. EXPECT_EQ("Hello World!", res->body);
  7279. res = cli_.Get("/hi");
  7280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7281. EXPECT_EQ(StatusCode::OK_200, res->status);
  7282. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7283. EXPECT_EQ("Hello World!", res->body);
  7284. res = cli_.Get("/hi");
  7285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7286. EXPECT_EQ(StatusCode::OK_200, res->status);
  7287. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7288. EXPECT_EQ("Hello World!", res->body);
  7289. res = cli_.Get("/not-exist");
  7290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7291. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7292. res = cli_.Post("/empty", "", "text/plain");
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ(StatusCode::OK_200, res->status);
  7295. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7296. EXPECT_EQ("empty", res->body);
  7297. EXPECT_EQ("close", res->get_header_value("Connection"));
  7298. res = cli_.Post(
  7299. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7300. "text/plain");
  7301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7302. EXPECT_EQ(StatusCode::OK_200, res->status);
  7303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7304. EXPECT_EQ("empty", res->body);
  7305. cli_.set_keep_alive(false);
  7306. res = cli_.Get("/last-request");
  7307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7308. EXPECT_EQ(StatusCode::OK_200, res->status);
  7309. EXPECT_EQ("close", res->get_header_value("Connection"));
  7310. }
  7311. TEST_F(ServerTest, TooManyRedirect) {
  7312. cli_.set_follow_location(true);
  7313. auto res = cli_.Get("/redirect/0");
  7314. ASSERT_TRUE(!res);
  7315. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7316. }
  7317. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7318. Request req;
  7319. req.method = "FOOBAR";
  7320. req.path = "/hi";
  7321. cli_.set_keep_alive(true);
  7322. auto res = cli_.send(req);
  7323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7324. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7325. EXPECT_EQ("close", res->get_header_value("Connection"));
  7326. EXPECT_FALSE(cli_.is_socket_open());
  7327. }
  7328. TEST_F(ServerTest, CustomRouteReadsBody) {
  7329. const std::string xml =
  7330. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7331. Request req;
  7332. req.method = "PROPFIND";
  7333. req.path = "/dav/dir";
  7334. req.set_header("Depth", "1");
  7335. req.body = xml;
  7336. auto res = cli_.send(req);
  7337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7338. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7339. EXPECT_EQ(xml, res->body);
  7340. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7341. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7342. }
  7343. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7344. Request req;
  7345. req.method = "PROPFIND";
  7346. req.path = "/dav/42";
  7347. auto res = cli_.send(req);
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7350. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7351. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7352. }
  7353. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7354. Request req;
  7355. req.method = "PROPFIND";
  7356. req.path = "/dav-re/123";
  7357. auto res = cli_.send(req);
  7358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7359. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7360. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7361. }
  7362. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7363. Request req;
  7364. req.method = "MKCOL";
  7365. req.path = "/dav-mkcol";
  7366. auto res = cli_.send(req);
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::Created_201, res->status);
  7369. }
  7370. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7371. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7372. Request req;
  7373. req.method = "REPORT";
  7374. req.path = "/dav-report";
  7375. req.body = xml;
  7376. auto res = cli_.send(req);
  7377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7378. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7379. EXPECT_EQ(xml, res->body);
  7380. }
  7381. // A content reader route must fire even when the request carries no body,
  7382. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7383. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7384. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7385. Request req;
  7386. req.method = "REPORT";
  7387. req.path = "/dav-report";
  7388. auto res = cli_.send(req);
  7389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7390. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7391. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7392. }
  7393. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7394. Request req;
  7395. req.method = "PROPFIND";
  7396. req.path = "/not-dav";
  7397. auto res = cli_.send(req);
  7398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7399. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7400. }
  7401. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7402. Request req;
  7403. req.method = "UNLOCK";
  7404. req.path = "/dav/dir";
  7405. cli_.set_keep_alive(true);
  7406. auto res = cli_.send(req);
  7407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7408. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7409. EXPECT_EQ("close", res->get_header_value("Connection"));
  7410. EXPECT_FALSE(cli_.is_socket_open());
  7411. }
  7412. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7413. // The mount point serves this path, but only for GET and HEAD.
  7414. auto get_res = cli_.Get("/dir/index.html");
  7415. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7416. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7417. Request req;
  7418. req.method = "PROPFIND";
  7419. req.path = "/dir/index.html";
  7420. auto res = cli_.send(req);
  7421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7422. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7423. }
  7424. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7425. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7426. cli_.set_keep_alive(true);
  7427. for (auto i = 0; i < 2; i++) {
  7428. Request req;
  7429. req.method = "PROPFIND";
  7430. req.path = "/dav/dir";
  7431. req.body = xml;
  7432. auto res = cli_.send(req);
  7433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7434. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7435. EXPECT_EQ(xml, res->body);
  7436. EXPECT_TRUE(cli_.is_socket_open());
  7437. }
  7438. // A built-in method must still be served on the same connection.
  7439. cli_.set_keep_alive(false);
  7440. auto res = cli_.Get("/hi");
  7441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7442. EXPECT_EQ(StatusCode::OK_200, res->status);
  7443. EXPECT_EQ("close", res->get_header_value("Connection"));
  7444. }
  7445. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7446. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7447. Request req;
  7448. req.method = "PROPFIND";
  7449. req.path = "/dav/dir";
  7450. req.set_header("Expect", "100-continue");
  7451. req.body = xml;
  7452. auto res = cli_.send(req);
  7453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7454. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7455. EXPECT_EQ(xml, res->body);
  7456. }
  7457. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7458. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7459. TEST_F(ServerTest, Gzip) {
  7460. Headers headers;
  7461. headers.emplace("Accept-Encoding", "gzip, deflate");
  7462. auto res = cli_.Get("/compress", headers);
  7463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7464. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7465. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7466. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7467. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7468. "7890123456789012345678901234567890",
  7469. res->body);
  7470. EXPECT_EQ(StatusCode::OK_200, res->status);
  7471. }
  7472. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7473. Headers headers;
  7474. headers.emplace("Accept-Encoding", "gzip, deflate");
  7475. auto res = cli_.Get("/compress-with-charset", headers);
  7476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7477. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7478. EXPECT_EQ("application/json; charset=utf-8",
  7479. res->get_header_value("Content-Type"));
  7480. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7481. "7890123456789012345678901234567890",
  7482. res->body);
  7483. EXPECT_EQ(StatusCode::OK_200, res->status);
  7484. }
  7485. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7486. Headers headers;
  7487. headers.emplace("Accept-Encoding", "");
  7488. auto res = cli_.Get("/compress", headers);
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7491. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7492. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7493. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7494. "7890123456789012345678901234567890",
  7495. res->body);
  7496. EXPECT_EQ(StatusCode::OK_200, res->status);
  7497. }
  7498. TEST_F(ServerTest, GzipWithContentReceiver) {
  7499. Headers headers;
  7500. headers.emplace("Accept-Encoding", "gzip, deflate");
  7501. std::string body;
  7502. auto res = cli_.Get("/compress", headers,
  7503. [&](const char *data, uint64_t data_length) {
  7504. EXPECT_EQ(100U, data_length);
  7505. body.append(data, data_length);
  7506. return true;
  7507. });
  7508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7509. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7510. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7511. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7512. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7513. "7890123456789012345678901234567890",
  7514. body);
  7515. EXPECT_EQ(StatusCode::OK_200, res->status);
  7516. }
  7517. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7518. Headers headers;
  7519. headers.emplace("Accept-Encoding", "gzip, deflate");
  7520. cli_.set_decompress(false);
  7521. auto res = cli_.Get("/compress", headers);
  7522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7523. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7524. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7525. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7526. EXPECT_EQ(33U, res->body.size());
  7527. EXPECT_EQ(StatusCode::OK_200, res->status);
  7528. }
  7529. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7530. Headers headers;
  7531. headers.emplace("Accept-Encoding", "");
  7532. std::string body;
  7533. auto res = cli_.Get("/compress", headers,
  7534. [&](const char *data, uint64_t data_length) {
  7535. EXPECT_EQ(100U, data_length);
  7536. body.append(data, data_length);
  7537. return true;
  7538. });
  7539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7540. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7541. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7542. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7543. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7544. "7890123456789012345678901234567890",
  7545. body);
  7546. EXPECT_EQ(StatusCode::OK_200, res->status);
  7547. }
  7548. TEST_F(ServerTest, NoGzip) {
  7549. Headers headers;
  7550. headers.emplace("Accept-Encoding", "gzip, deflate");
  7551. auto res = cli_.Get("/nocompress", headers);
  7552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7553. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7554. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7555. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7556. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7557. "7890123456789012345678901234567890",
  7558. res->body);
  7559. EXPECT_EQ(StatusCode::OK_200, res->status);
  7560. }
  7561. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7562. Headers headers;
  7563. headers.emplace("Accept-Encoding", "gzip, deflate");
  7564. std::string body;
  7565. auto res = cli_.Get("/nocompress", headers,
  7566. [&](const char *data, uint64_t data_length) {
  7567. EXPECT_EQ(100U, data_length);
  7568. body.append(data, data_length);
  7569. return true;
  7570. });
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7573. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7574. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7575. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7576. "7890123456789012345678901234567890",
  7577. body);
  7578. EXPECT_EQ(StatusCode::OK_200, res->status);
  7579. }
  7580. TEST_F(ServerTest, MultipartFormDataGzip) {
  7581. UploadFormDataItems items = {
  7582. {"key1", "test", "", ""},
  7583. {"key2", "--abcdefg123", "", ""},
  7584. };
  7585. cli_.set_compress(true);
  7586. auto res = cli_.Post("/compress-multipart", items);
  7587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7588. EXPECT_EQ(StatusCode::OK_200, res->status);
  7589. }
  7590. #endif
  7591. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7592. // Static file compression is opt-in, so these run their own server rather than
  7593. // flipping it on for the shared ServerTest fixture, which would silently
  7594. // rewrite what every other static file test is asserting.
  7595. class StaticFileCompressionTest : public ::testing::Test {
  7596. protected:
  7597. void TearDown() override {
  7598. if (t_.joinable()) {
  7599. svr_.stop();
  7600. t_.join();
  7601. }
  7602. }
  7603. int start(const std::function<void(Server &)> &configure = nullptr) {
  7604. // Serves the same tree as a directory of build-time compressed assets
  7605. // would be served: the mount point names the coding the files are already
  7606. // stored in. Registered before "/" so it is the one that matches.
  7607. svr_.set_mount_point("/pre-encoded", "./www",
  7608. {{"Content-Encoding", "gzip"}});
  7609. svr_.set_mount_point("/", "./www");
  7610. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7611. res.set_file_content("./www/dir/index.html", "text/html");
  7612. });
  7613. svr_.Get("/pre-encoded-file-content",
  7614. [](const Request & /*req*/, Response &res) {
  7615. res.set_header("Content-Encoding", "gzip");
  7616. res.set_file_content("./www/dir/index.html", "text/html");
  7617. });
  7618. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7619. res.set_content_provider(
  7620. 6, "text/plain",
  7621. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7622. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7623. return true;
  7624. });
  7625. });
  7626. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7627. res.set_content_provider(
  7628. 1000, "text/plain",
  7629. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7630. if (offset < 100) {
  7631. std::string data(100, 'A');
  7632. sink.write(data.data(), data.size());
  7633. return true;
  7634. }
  7635. std::this_thread::sleep_for(std::chrono::seconds(2));
  7636. std::string data(900, 'B');
  7637. sink.write(data.data(), data.size());
  7638. return true;
  7639. });
  7640. });
  7641. if (configure) { configure(svr_); }
  7642. auto port = svr_.bind_to_any_port(HOST);
  7643. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7644. svr_.wait_until_ready();
  7645. return port;
  7646. }
  7647. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7648. // Every file under ./www except 1MB.txt is smaller than the default
  7649. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7650. // it out of the way.
  7651. static void enable_without_floor(Server &svr) {
  7652. svr.set_static_file_compression(true);
  7653. svr.set_static_file_compression_min_length(0);
  7654. }
  7655. Server svr_;
  7656. std::thread t_;
  7657. };
  7658. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7659. auto port = start();
  7660. Client cli(HOST, port);
  7661. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7663. EXPECT_EQ(StatusCode::OK_200, res->status);
  7664. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7665. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7666. EXPECT_EQ(1048576U, res->body.size());
  7667. }
  7668. TEST_F(StaticFileCompressionTest, MountPoint) {
  7669. auto port = start(enable);
  7670. Client cli(HOST, port);
  7671. cli.set_decompress(false);
  7672. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7676. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7677. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7678. // The response stays self-delimiting: a length, not a chunked body.
  7679. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7680. EXPECT_EQ(std::to_string(res->body.size()),
  7681. res->get_header_value("Content-Length"));
  7682. EXPECT_LT(res->body.size(), 1048576U);
  7683. EXPECT_FALSE(res->body.empty());
  7684. }
  7685. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7686. auto port = start(enable);
  7687. Client cli(HOST, port);
  7688. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7690. EXPECT_EQ(StatusCode::OK_200, res->status);
  7691. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7692. EXPECT_EQ(1048576U, res->body.size());
  7693. }
  7694. TEST_F(StaticFileCompressionTest, FileContent) {
  7695. auto port = start(enable_without_floor);
  7696. Client cli(HOST, port);
  7697. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7699. EXPECT_EQ(StatusCode::OK_200, res->status);
  7700. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7701. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7702. EXPECT_EQ(104U, res->body.size());
  7703. }
  7704. // A handler that serves an already-encoded file names the coding itself. The
  7705. // file-backed path decided its coding from Accept-Encoding and the content
  7706. // type alone, so it compressed the stored bytes a second time and appended a
  7707. // second Content-Encoding field line.
  7708. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7709. auto port = start(enable_without_floor);
  7710. Client cli(HOST, port);
  7711. cli.set_decompress(false);
  7712. auto res = cli.Get("/pre-encoded-file-content",
  7713. Headers{{"Accept-Encoding", "gzip"}});
  7714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7715. EXPECT_EQ(StatusCode::OK_200, res->status);
  7716. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7717. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7718. // Vary belongs to a coding the server chose, and it chose none here.
  7719. EXPECT_FALSE(res->has_header("Vary"));
  7720. // The file travels exactly as it is stored on disk.
  7721. EXPECT_EQ(104U, res->body.size());
  7722. }
  7723. // The 1MB file clears the default floor, so this one runs the configuration a
  7724. // deployment would actually have.
  7725. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7726. auto port = start(enable);
  7727. Client cli(HOST, port);
  7728. cli.set_decompress(false);
  7729. auto res =
  7730. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7732. EXPECT_EQ(StatusCode::OK_200, res->status);
  7733. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7734. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7735. EXPECT_FALSE(res->has_header("Vary"));
  7736. EXPECT_EQ(1048576U, res->body.size());
  7737. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7738. }
  7739. TEST_F(StaticFileCompressionTest, Head) {
  7740. auto port = start(enable);
  7741. Client cli(HOST, port);
  7742. cli.set_decompress(false);
  7743. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7744. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7745. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7747. EXPECT_EQ(StatusCode::OK_200, res->status);
  7748. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7749. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7750. // HEAD still reports the size a GET would return.
  7751. EXPECT_EQ(get->get_header_value("Content-Length"),
  7752. res->get_header_value("Content-Length"));
  7753. EXPECT_TRUE(res->body.empty());
  7754. }
  7755. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7756. auto port = start(enable);
  7757. Client cli(HOST, port);
  7758. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7759. {"Accept-Encoding", "gzip"}});
  7760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7761. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7762. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7763. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7764. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7765. EXPECT_EQ("cd", res->body);
  7766. }
  7767. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7768. auto port = start(enable);
  7769. Client cli(HOST, port);
  7770. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::OK_200, res->status);
  7773. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7774. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7775. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7776. }
  7777. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7778. auto port = start(enable);
  7779. Client cli(HOST, port);
  7780. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7782. EXPECT_EQ(StatusCode::OK_200, res->status);
  7783. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7784. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7785. EXPECT_TRUE(res->body.empty());
  7786. }
  7787. TEST_F(StaticFileCompressionTest, MinLength) {
  7788. auto port = start(enable);
  7789. Client cli(HOST, port);
  7790. // 104 bytes, well under the default floor. Compressing it would add the
  7791. // gzip header and trailer to a body that already fits in one packet.
  7792. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7794. EXPECT_EQ(StatusCode::OK_200, res->status);
  7795. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7796. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7797. }
  7798. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7799. auto port = start([](Server &svr) {
  7800. svr.set_static_file_compression(true);
  7801. svr.set_static_file_compression_min_length(1);
  7802. });
  7803. Client cli(HOST, port);
  7804. cli.set_decompress(false);
  7805. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7807. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7808. // A 9-byte file comes back larger than it went in, because gzip's header and
  7809. // trailer outweigh anything deflate can save. That is the end of the range
  7810. // the floor exists to keep out.
  7811. EXPECT_GT(res->body.size(), 9U);
  7812. }
  7813. TEST_F(StaticFileCompressionTest, MaxLength) {
  7814. auto port = start([](Server &svr) {
  7815. svr.set_static_file_compression(true);
  7816. svr.set_static_file_compression_min_length(0);
  7817. svr.set_static_file_compression_max_length(1024);
  7818. });
  7819. Client cli(HOST, port);
  7820. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7821. // defines `small` as a macro on Windows.
  7822. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7823. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7824. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7825. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7826. // Under it: compressed.
  7827. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7828. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7829. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7830. }
  7831. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7832. auto port = start(enable_without_floor);
  7833. Client cli(HOST, port);
  7834. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7835. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7836. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7837. auto identity_etag = identity->get_header_value("ETag");
  7838. ASSERT_FALSE(identity_etag.empty());
  7839. auto gzipped =
  7840. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7841. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7842. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7843. auto gzip_etag = gzipped->get_header_value("ETag");
  7844. ASSERT_FALSE(gzip_etag.empty());
  7845. // Two representations, two validators.
  7846. EXPECT_NE(identity_etag, gzip_etag);
  7847. // Each one revalidates against the request that would produce it...
  7848. auto fresh =
  7849. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7850. {"If-None-Match", gzip_etag}});
  7851. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7852. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7853. auto fresh_identity =
  7854. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7855. {"If-None-Match", identity_etag}});
  7856. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7857. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7858. // ...and not against the other representation.
  7859. auto crossed =
  7860. cli.Get("/dir/index.html",
  7861. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7862. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7863. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7864. }
  7865. // The opt-in covers responses the server reads off disk itself. A caller's own
  7866. // known-length provider keeps its Content-Length and, more importantly, keeps
  7867. // delivering incrementally: routing it through a compressor would hold every
  7868. // write back until zlib's window filled.
  7869. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7870. auto port = start(enable);
  7871. Client cli(HOST, port);
  7872. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7874. EXPECT_EQ(StatusCode::OK_200, res->status);
  7875. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7876. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7877. EXPECT_EQ("aaabbb", res->body);
  7878. }
  7879. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7880. auto port = start(enable);
  7881. Client cli(HOST, port);
  7882. cli.set_read_timeout(1, 0);
  7883. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7884. Headers{{"Accept-Encoding", "gzip"}});
  7885. ASSERT_TRUE(handle.is_valid());
  7886. // The provider writes 100 bytes and then stalls for longer than the read
  7887. // timeout. Those first bytes have to arrive anyway: run the response through
  7888. // a compressor and zlib holds them until its window fills, so the read would
  7889. // come back empty instead.
  7890. char buf[256];
  7891. auto n = handle.read(buf, sizeof(buf));
  7892. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7893. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7894. }
  7895. #endif
  7896. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7897. TEST_F(ServerTest, Brotli) {
  7898. Headers headers;
  7899. headers.emplace("Accept-Encoding", "br");
  7900. auto res = cli_.Get("/compress", headers);
  7901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7902. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7903. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7904. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7905. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7906. "7890123456789012345678901234567890",
  7907. res->body);
  7908. EXPECT_EQ(StatusCode::OK_200, res->status);
  7909. }
  7910. #endif
  7911. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7912. TEST_F(ServerTest, Zstd) {
  7913. Headers headers;
  7914. headers.emplace("Accept-Encoding", "zstd");
  7915. auto res = cli_.Get("/compress", headers);
  7916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7917. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7919. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7920. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7921. "7890123456789012345678901234567890",
  7922. res->body);
  7923. EXPECT_EQ(StatusCode::OK_200, res->status);
  7924. }
  7925. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7926. Headers headers;
  7927. headers.emplace("Accept-Encoding", "");
  7928. auto res = cli_.Get("/compress", headers);
  7929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7930. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7931. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7932. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7933. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7934. "7890123456789012345678901234567890",
  7935. res->body);
  7936. EXPECT_EQ(StatusCode::OK_200, res->status);
  7937. }
  7938. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7939. Headers headers;
  7940. headers.emplace("Accept-Encoding", "zstd");
  7941. std::string body;
  7942. auto res = cli_.Get("/compress", headers,
  7943. [&](const char *data, uint64_t data_length) {
  7944. EXPECT_EQ(100U, data_length);
  7945. body.append(data, data_length);
  7946. return true;
  7947. });
  7948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7949. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7950. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7951. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7952. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7953. "7890123456789012345678901234567890",
  7954. body);
  7955. EXPECT_EQ(StatusCode::OK_200, res->status);
  7956. }
  7957. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7958. Headers headers;
  7959. headers.emplace("Accept-Encoding", "zstd");
  7960. cli_.set_decompress(false);
  7961. auto res = cli_.Get("/compress", headers);
  7962. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7963. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7964. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7965. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7967. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7968. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7969. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7970. EXPECT_EQ(StatusCode::OK_200, res->status);
  7971. ASSERT_EQ(26U, res->body.size());
  7972. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7973. 0);
  7974. }
  7975. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7976. Headers headers;
  7977. headers.emplace("Accept-Encoding", "");
  7978. std::string body;
  7979. auto res = cli_.Get("/compress", headers,
  7980. [&](const char *data, uint64_t data_length) {
  7981. EXPECT_EQ(100U, data_length);
  7982. body.append(data, data_length);
  7983. return true;
  7984. });
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7987. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7988. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7989. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7990. "7890123456789012345678901234567890",
  7991. body);
  7992. EXPECT_EQ(StatusCode::OK_200, res->status);
  7993. }
  7994. TEST_F(ServerTest, NoZstd) {
  7995. Headers headers;
  7996. headers.emplace("Accept-Encoding", "zstd");
  7997. auto res = cli_.Get("/nocompress", headers);
  7998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7999. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8000. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8001. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8002. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8003. "7890123456789012345678901234567890",
  8004. res->body);
  8005. EXPECT_EQ(StatusCode::OK_200, res->status);
  8006. }
  8007. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8008. Headers headers;
  8009. headers.emplace("Accept-Encoding", "zstd");
  8010. std::string body;
  8011. auto res = cli_.Get("/nocompress", headers,
  8012. [&](const char *data, uint64_t data_length) {
  8013. EXPECT_EQ(100U, data_length);
  8014. body.append(data, data_length);
  8015. return true;
  8016. });
  8017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8018. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8019. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8020. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8021. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8022. "7890123456789012345678901234567890",
  8023. body);
  8024. EXPECT_EQ(StatusCode::OK_200, res->status);
  8025. }
  8026. // TODO: How to enable zstd ??
  8027. TEST_F(ServerTest, MultipartFormDataZstd) {
  8028. UploadFormDataItems items = {
  8029. {"key1", "test", "", ""},
  8030. {"key2", "--abcdefg123", "", ""},
  8031. };
  8032. Headers headers;
  8033. headers.emplace("Accept-Encoding", "zstd");
  8034. cli_.set_compress(true);
  8035. auto res = cli_.Post("/compress-multipart", headers, items);
  8036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8037. EXPECT_EQ(StatusCode::OK_200, res->status);
  8038. }
  8039. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8040. Headers headers;
  8041. headers.emplace("Accept-Encoding", "zstd");
  8042. cli_.set_compress(true);
  8043. auto res = cli_.Put(
  8044. "/put", headers, 3,
  8045. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8046. sink.os << "PUT";
  8047. return true;
  8048. },
  8049. "text/plain");
  8050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8051. EXPECT_EQ(StatusCode::OK_200, res->status);
  8052. EXPECT_EQ("PUT", res->body);
  8053. }
  8054. // Pre-compression logging tests
  8055. TEST_F(ServerTest, PreCompressionLogging) {
  8056. // Test data for compression (matches the actual /compress endpoint content)
  8057. const std::string test_content =
  8058. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8059. "3456789012345678901234567890";
  8060. // Variables to capture logging data
  8061. std::string pre_compression_body;
  8062. std::string pre_compression_content_type;
  8063. std::string pre_compression_content_encoding;
  8064. std::string post_compression_body;
  8065. std::string post_compression_content_type;
  8066. std::string post_compression_content_encoding;
  8067. // Set up pre-compression logger
  8068. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8069. const Response &res) {
  8070. pre_compression_body = res.body;
  8071. pre_compression_content_type = res.get_header_value("Content-Type");
  8072. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8073. });
  8074. // Set up post-compression logger
  8075. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8076. post_compression_body = res.body;
  8077. post_compression_content_type = res.get_header_value("Content-Type");
  8078. post_compression_content_encoding =
  8079. res.get_header_value("Content-Encoding");
  8080. });
  8081. // Test with gzip compression
  8082. Headers headers;
  8083. headers.emplace("Accept-Encoding", "gzip");
  8084. auto res = cli_.Get("/compress", headers);
  8085. // Verify response was compressed
  8086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8087. EXPECT_EQ(StatusCode::OK_200, res->status);
  8088. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8089. // Verify pre-compression logger captured uncompressed content
  8090. EXPECT_EQ(test_content, pre_compression_body);
  8091. EXPECT_EQ("text/plain", pre_compression_content_type);
  8092. EXPECT_TRUE(pre_compression_content_encoding
  8093. .empty()); // No encoding header before compression
  8094. // Verify post-compression logger captured compressed content
  8095. EXPECT_NE(test_content,
  8096. post_compression_body); // Should be different after compression
  8097. EXPECT_EQ("text/plain", post_compression_content_type);
  8098. EXPECT_EQ("gzip", post_compression_content_encoding);
  8099. // Verify compressed content is smaller
  8100. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8101. }
  8102. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8103. const std::string test_content =
  8104. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8105. "3456789012345678901234567890";
  8106. std::string pre_compression_body;
  8107. std::string post_compression_body;
  8108. svr_.set_pre_compression_logger(
  8109. [&](const Request & /*req*/, const Response &res) {
  8110. pre_compression_body = res.body;
  8111. });
  8112. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8113. post_compression_body = res.body;
  8114. });
  8115. Headers headers;
  8116. headers.emplace("Accept-Encoding", "br");
  8117. auto res = cli_.Get("/compress", headers);
  8118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8119. EXPECT_EQ(StatusCode::OK_200, res->status);
  8120. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8121. // Verify pre-compression content is uncompressed
  8122. EXPECT_EQ(test_content, pre_compression_body);
  8123. // Verify post-compression content is compressed
  8124. EXPECT_NE(test_content, post_compression_body);
  8125. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8126. }
  8127. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8128. const std::string test_content =
  8129. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8130. "3456789012345678901234567890";
  8131. std::string pre_compression_body;
  8132. std::string post_compression_body;
  8133. svr_.set_pre_compression_logger(
  8134. [&](const Request & /*req*/, const Response &res) {
  8135. pre_compression_body = res.body;
  8136. });
  8137. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8138. post_compression_body = res.body;
  8139. });
  8140. // Request without compression (use /nocompress endpoint)
  8141. Headers headers;
  8142. auto res = cli_.Get("/nocompress", headers);
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8146. // Pre-compression logger should not be called when no compression is applied
  8147. EXPECT_TRUE(
  8148. pre_compression_body.empty()); // Pre-compression logger not called
  8149. EXPECT_EQ(
  8150. test_content,
  8151. post_compression_body); // Post-compression logger captures final content
  8152. }
  8153. TEST_F(ServerTest, LoggerSeesContentLength) {
  8154. size_t logged_content_length = 0;
  8155. std::string logged_content_length_header;
  8156. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8157. logged_content_length = res.content_length_;
  8158. logged_content_length_header = res.get_header_value("Content-Length");
  8159. });
  8160. auto res = cli_.Get("/nocompress");
  8161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8162. EXPECT_EQ(StatusCode::OK_200, res->status);
  8163. EXPECT_EQ(res->body.size(), logged_content_length);
  8164. EXPECT_EQ(std::to_string(logged_content_length),
  8165. logged_content_length_header);
  8166. }
  8167. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8168. const std::string test_content =
  8169. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8170. "3456789012345678901234567890";
  8171. std::string pre_compression_body;
  8172. bool pre_logger_called = false;
  8173. // Set only pre-compression logger
  8174. svr_.set_pre_compression_logger(
  8175. [&](const Request & /*req*/, const Response &res) {
  8176. pre_compression_body = res.body;
  8177. pre_logger_called = true;
  8178. });
  8179. Headers headers;
  8180. headers.emplace("Accept-Encoding", "gzip");
  8181. auto res = cli_.Get("/compress", headers);
  8182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8183. EXPECT_EQ(StatusCode::OK_200, res->status);
  8184. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8185. // Verify pre-compression logger was called
  8186. EXPECT_TRUE(pre_logger_called);
  8187. EXPECT_EQ(test_content, pre_compression_body);
  8188. }
  8189. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8190. {
  8191. // Test with Expect: 100-continue header - success case
  8192. // Server returns 100 Continue, client sends body, server returns 200 OK
  8193. Request req;
  8194. req.method = "POST";
  8195. req.path = "/post-large";
  8196. req.set_header("Expect", "100-continue");
  8197. req.body = LARGE_DATA;
  8198. Response res;
  8199. auto error = Error::Success;
  8200. cli_.set_keep_alive(true);
  8201. auto ret = cli_.send(req, res, error);
  8202. EXPECT_TRUE(ret);
  8203. EXPECT_EQ(StatusCode::OK_200, res.status);
  8204. EXPECT_EQ(LARGE_DATA, res.body);
  8205. }
  8206. {
  8207. // Test with Expect: 100-continue header - error case
  8208. // Client should not send the body when server returns an error
  8209. Request req;
  8210. req.method = "POST";
  8211. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8212. req.set_header("Expect", "100-continue");
  8213. req.body = LARGE_DATA;
  8214. Response res;
  8215. auto error = Error::Success;
  8216. auto start = std::chrono::high_resolution_clock::now();
  8217. cli_.set_keep_alive(true);
  8218. auto ret = cli_.send(req, res, error);
  8219. auto end = std::chrono::high_resolution_clock::now();
  8220. auto elapsed =
  8221. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8222. .count();
  8223. // With Expect: 100-continue, request completes successfully but with error
  8224. EXPECT_TRUE(ret);
  8225. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8226. EXPECT_EQ("close", res.get_header_value("Connection"));
  8227. EXPECT_FALSE(cli_.is_socket_open());
  8228. EXPECT_LE(elapsed, 2000);
  8229. }
  8230. {
  8231. // Send an extra GET request to ensure error recovery without hanging
  8232. Request req;
  8233. req.method = "GET";
  8234. req.path = "/hi";
  8235. auto start = std::chrono::high_resolution_clock::now();
  8236. auto res = cli_.send(req);
  8237. auto end = std::chrono::high_resolution_clock::now();
  8238. auto elapsed =
  8239. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8240. .count();
  8241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8242. EXPECT_EQ(StatusCode::OK_200, res->status);
  8243. EXPECT_EQ("Hello World!", res->body);
  8244. EXPECT_LE(elapsed, 500);
  8245. }
  8246. }
  8247. TEST(ZstdDecompressor, ChunkedDecompression) {
  8248. std::string data;
  8249. for (size_t i = 0; i < 32 * 1024; ++i) {
  8250. data.push_back(static_cast<char>('a' + i % 26));
  8251. }
  8252. std::string compressed_data;
  8253. {
  8254. httplib::detail::zstd_compressor compressor;
  8255. bool result = compressor.compress(
  8256. data.data(), data.size(),
  8257. /*last=*/true,
  8258. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8259. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8260. compressed_data_size);
  8261. return true;
  8262. });
  8263. ASSERT_TRUE(result);
  8264. }
  8265. std::string decompressed_data;
  8266. {
  8267. httplib::detail::zstd_decompressor decompressor;
  8268. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8269. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8270. size_t chunk_size = 130;
  8271. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8272. chunk_begin += chunk_size) {
  8273. size_t current_chunk_size =
  8274. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8275. bool result = decompressor.decompress(
  8276. compressed_data.data() + chunk_begin, current_chunk_size,
  8277. [&](const char *decompressed_data_chunk,
  8278. size_t decompressed_data_chunk_size) {
  8279. decompressed_data.insert(decompressed_data.size(),
  8280. decompressed_data_chunk,
  8281. decompressed_data_chunk_size);
  8282. return true;
  8283. });
  8284. ASSERT_TRUE(result);
  8285. }
  8286. }
  8287. ASSERT_EQ(data, decompressed_data);
  8288. }
  8289. TEST(ZstdDecompressor, Decompress) {
  8290. std::string original_text = "Compressed with ZSTD";
  8291. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8292. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8293. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8294. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8295. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8296. std::string decompressed_data;
  8297. {
  8298. httplib::detail::zstd_decompressor decompressor;
  8299. bool result = decompressor.decompress(
  8300. compressed_data.data(), compressed_data.size(),
  8301. [&](const char *decompressed_data_chunk,
  8302. size_t decompressed_data_chunk_size) {
  8303. decompressed_data.insert(decompressed_data.size(),
  8304. decompressed_data_chunk,
  8305. decompressed_data_chunk_size);
  8306. return true;
  8307. });
  8308. ASSERT_TRUE(result);
  8309. }
  8310. ASSERT_EQ(original_text, decompressed_data);
  8311. }
  8312. #endif
  8313. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8314. // separate chunks so that the server sees each part in its own read(). Used to
  8315. // place a read boundary at a specific offset of a request body.
  8316. static bool send_request_in_parts(time_t read_timeout_sec,
  8317. const std::vector<std::string> &parts,
  8318. std::string *resp = nullptr,
  8319. int port = PORT) {
  8320. auto error = Error::Success;
  8321. auto client_sock = detail::create_client_socket(
  8322. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8323. /*connection_timeout_sec=*/5, 0,
  8324. /*read_timeout_sec=*/5, 0,
  8325. /*write_timeout_sec=*/5, 0, std::string(), error);
  8326. if (client_sock == INVALID_SOCKET) { return false; }
  8327. auto ret = detail::process_client_socket(
  8328. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8329. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8330. for (size_t i = 0; i < parts.size(); i++) {
  8331. const auto &part = parts[i];
  8332. if (part.size() !=
  8333. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8334. return false;
  8335. }
  8336. if (i + 1 < parts.size()) {
  8337. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8338. }
  8339. }
  8340. char buf[512];
  8341. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8342. while (line_reader.getline()) {
  8343. if (resp) { *resp += line_reader.ptr(); }
  8344. }
  8345. return true;
  8346. });
  8347. detail::close_socket(client_sock);
  8348. return ret;
  8349. }
  8350. // Sends a raw request to a server listening at HOST:PORT.
  8351. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8352. std::string *resp = nullptr, int port = PORT) {
  8353. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8354. }
  8355. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8356. Server svr;
  8357. std::string header_value;
  8358. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8359. header_value = req.get_header_value("foo");
  8360. res.set_content("ok", "text/plain");
  8361. });
  8362. thread t = thread([&] { svr.listen(HOST, PORT); });
  8363. auto se = detail::scope_exit([&] {
  8364. svr.stop();
  8365. t.join();
  8366. ASSERT_FALSE(svr.is_running());
  8367. });
  8368. svr.wait_until_ready();
  8369. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8370. // like characters are not treated the same - use vertical tab and escape.
  8371. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8372. "foo: \t \v bar \x1B\t \r\n"
  8373. "Connection: close\r\n"
  8374. "\r\n";
  8375. std::string res;
  8376. ASSERT_TRUE(send_request(5, req, &res));
  8377. EXPECT_EQ(header_value, "");
  8378. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8379. }
  8380. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8381. Server svr;
  8382. std::string received;
  8383. svr.Get("/order", [&](const Request &req, Response &res) {
  8384. received = entries_to_string(req.headers);
  8385. res.set_content("ok", "text/plain");
  8386. });
  8387. auto port = svr.bind_to_any_port(HOST);
  8388. thread t = thread([&] { svr.listen_after_bind(); });
  8389. auto se = detail::scope_exit([&] {
  8390. svr.stop();
  8391. t.join();
  8392. ASSERT_FALSE(svr.is_running());
  8393. });
  8394. svr.wait_until_ready();
  8395. const std::string req = "GET /order HTTP/1.1\r\n"
  8396. "X-First: 1\r\n"
  8397. "X-Dup: a\r\n"
  8398. "X-Second: 2\r\n"
  8399. "X-Dup: b\r\n"
  8400. "Connection: close\r\n"
  8401. "\r\n";
  8402. std::string res;
  8403. ASSERT_TRUE(send_request(5, req, &res, port));
  8404. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8405. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8406. }
  8407. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8408. Server svr;
  8409. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8410. res.set_header("Set-Cookie", "first=1");
  8411. res.set_header("X-Between", "y");
  8412. res.set_header("Set-Cookie", "second=2");
  8413. res.set_content("ok", "text/plain");
  8414. });
  8415. auto port = svr.bind_to_any_port(HOST);
  8416. thread t = thread([&] { svr.listen_after_bind(); });
  8417. auto se = detail::scope_exit([&] {
  8418. svr.stop();
  8419. t.join();
  8420. ASSERT_FALSE(svr.is_running());
  8421. });
  8422. svr.wait_until_ready();
  8423. Client cli(HOST, port);
  8424. auto res = cli.Get("/cookies");
  8425. ASSERT_TRUE(res);
  8426. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8427. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8428. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8429. }
  8430. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8431. Server svr;
  8432. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8433. auto i = new int(0);
  8434. res.set_header("Trailer", "X-Safe, X-Reflected");
  8435. res.set_chunked_content_provider(
  8436. "text/plain",
  8437. [i](size_t /*offset*/, DataSink &sink) {
  8438. if (*i == 0) {
  8439. sink.os << "body";
  8440. } else {
  8441. Headers trailer;
  8442. // A valid trailer that must survive.
  8443. trailer.emplace("X-Safe", "safe");
  8444. // Attacker-controlled value carrying CR/LF (response splitting).
  8445. trailer.emplace("X-Reflected",
  8446. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8447. // Attacker-controlled name carrying CR/LF.
  8448. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8449. sink.done_with_trailer(trailer);
  8450. }
  8451. (*i)++;
  8452. return true;
  8453. },
  8454. [i](bool /*success*/) { delete i; });
  8455. });
  8456. thread t = thread([&] { svr.listen(HOST, PORT); });
  8457. auto se = detail::scope_exit([&] {
  8458. svr.stop();
  8459. t.join();
  8460. ASSERT_FALSE(svr.is_running());
  8461. });
  8462. svr.wait_until_ready();
  8463. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8464. "Host: " + HOST +
  8465. "\r\n"
  8466. "Connection: close\r\n"
  8467. "\r\n";
  8468. std::string res;
  8469. ASSERT_TRUE(send_request(5, req, &res));
  8470. // The injected fields must not appear anywhere in the raw response.
  8471. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8472. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8473. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8474. // Invalid trailers are dropped entirely, matching set_header().
  8475. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8476. // The valid trailer still passes through.
  8477. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8478. }
  8479. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8480. Server svr;
  8481. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8482. // res.headers is a public field an application can populate directly,
  8483. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8484. // A valid header that must survive.
  8485. res.headers.emplace("X-Safe", "safe");
  8486. // Attacker-controlled value carrying CR/LF (response splitting).
  8487. res.headers.emplace("X-Reflected",
  8488. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8489. // Attacker-controlled name carrying CR/LF.
  8490. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8491. res.set_content("body", "text/plain");
  8492. });
  8493. thread t = thread([&] { svr.listen(HOST, PORT); });
  8494. auto se = detail::scope_exit([&] {
  8495. svr.stop();
  8496. t.join();
  8497. ASSERT_FALSE(svr.is_running());
  8498. });
  8499. svr.wait_until_ready();
  8500. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8501. "Host: " + HOST +
  8502. "\r\n"
  8503. "Connection: close\r\n"
  8504. "\r\n";
  8505. std::string res;
  8506. ASSERT_TRUE(send_request(5, req, &res));
  8507. // The injected fields must not appear anywhere in the raw response.
  8508. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8509. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8510. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8511. // Invalid headers are dropped entirely, matching set_header().
  8512. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8513. // The valid header still passes through.
  8514. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8515. }
  8516. // Forward declaration: in split builds split.py strips `inline` and moves the
  8517. // definition into httplib.cc, so detail::write_request_line is not visible from
  8518. // the public httplib.h. Re-declaring it here lets the tests link against the
  8519. // symbol in both header-only and split builds.
  8520. namespace httplib {
  8521. namespace detail {
  8522. ssize_t write_request_line(Stream &strm, const std::string &method,
  8523. const std::string &path);
  8524. } // namespace detail
  8525. } // namespace httplib
  8526. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  8527. // A well-formed target is written verbatim.
  8528. {
  8529. detail::BufferStream strm;
  8530. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8531. EXPECT_GT(n, 0);
  8532. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8533. }
  8534. // A target carrying CR/LF must be rejected before anything reaches the wire,
  8535. // otherwise it splits the request line and injects a header or a whole
  8536. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  8537. // when path encoding is disabled.
  8538. const std::string evil_targets[] = {
  8539. "/a\r\nInjected: pwned",
  8540. "/a\rInjected",
  8541. "/a\nInjected",
  8542. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8543. };
  8544. for (const auto &evil : evil_targets) {
  8545. detail::BufferStream strm;
  8546. auto n = detail::write_request_line(strm, "GET", evil);
  8547. EXPECT_LT(n, 0);
  8548. EXPECT_TRUE(strm.get_buffer().empty());
  8549. }
  8550. }
  8551. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8552. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  8553. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  8554. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  8555. // client must fail cleanly with Error::Write instead of putting a
  8556. // request-line-less, header-injecting request on the wire.
  8557. Server svr;
  8558. svr.Get("/a", [](const Request &, Response &res) {
  8559. res.set_content("ok", "text/plain");
  8560. });
  8561. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8562. auto se = detail::scope_exit([&] {
  8563. svr.stop();
  8564. thread.join();
  8565. ASSERT_FALSE(svr.is_running());
  8566. });
  8567. svr.wait_until_ready();
  8568. {
  8569. Client cli(HOST, PORT);
  8570. cli.set_path_encode(false);
  8571. // The request is rejected before anything is written, so the connection
  8572. // stays silent and the subsequent response read would otherwise block for
  8573. // the full default read timeout. Shorten it -- the assertion is on the
  8574. // error, not the timeout.
  8575. cli.set_read_timeout(1, 0);
  8576. auto res = cli.Get("/a\r\nInjected: pwned");
  8577. EXPECT_FALSE(res);
  8578. EXPECT_EQ(Error::Write, res.error());
  8579. }
  8580. }
  8581. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8582. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8583. // including extension methods.
  8584. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8585. for (const auto &method : good_methods) {
  8586. detail::BufferStream strm;
  8587. auto n = detail::write_request_line(strm, method, "/");
  8588. EXPECT_GT(n, 0);
  8589. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8590. }
  8591. // A method carrying CR/LF would split the request line and smuggle a whole
  8592. // request ahead of the real one. A space or an empty method corrupts the
  8593. // request line. All must be rejected before anything reaches the wire.
  8594. const std::string evil_methods[] = {
  8595. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8596. "GET\r\nInjected: pwned",
  8597. "GET\r",
  8598. "GET\n",
  8599. "GE T",
  8600. "",
  8601. };
  8602. for (const auto &evil : evil_methods) {
  8603. detail::BufferStream strm;
  8604. auto n = detail::write_request_line(strm, evil, "/");
  8605. EXPECT_LT(n, 0);
  8606. EXPECT_TRUE(strm.get_buffer().empty());
  8607. }
  8608. }
  8609. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8610. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8611. // through Client::send must fail with Error::Write and no request, neither
  8612. // the smuggled one nor the real one, may reach the server.
  8613. Server svr;
  8614. std::atomic<int> request_count(0);
  8615. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8616. request_count++;
  8617. res.status = StatusCode::OK_200;
  8618. return Server::HandlerResponse::Handled;
  8619. });
  8620. auto port = svr.bind_to_any_port(HOST);
  8621. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8622. auto se = detail::scope_exit([&] {
  8623. svr.stop();
  8624. thread.join();
  8625. ASSERT_FALSE(svr.is_running());
  8626. });
  8627. svr.wait_until_ready();
  8628. {
  8629. Client cli(HOST, port);
  8630. const std::string evil_methods[] = {
  8631. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8632. "GE T",
  8633. "",
  8634. };
  8635. for (const auto &evil : evil_methods) {
  8636. Request req;
  8637. req.method = evil;
  8638. req.path = "/";
  8639. auto res = cli.send(req);
  8640. EXPECT_FALSE(res);
  8641. EXPECT_EQ(Error::Write, res.error());
  8642. }
  8643. auto handle =
  8644. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8645. EXPECT_FALSE(handle.is_valid());
  8646. EXPECT_EQ(Error::Write, handle.error);
  8647. // A valid request on the same client still goes through.
  8648. auto res = cli.Get("/");
  8649. ASSERT_TRUE(res);
  8650. EXPECT_EQ(StatusCode::OK_200, res->status);
  8651. }
  8652. EXPECT_EQ(1, request_count.load());
  8653. }
  8654. // Sends a raw request and verifies that there isn't a crash or exception.
  8655. static void test_raw_request(const std::string &req,
  8656. std::string *out = nullptr) {
  8657. Server svr;
  8658. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8659. res.set_content("ok", "text/plain");
  8660. });
  8661. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8662. res.set_content("ok", "text/plain");
  8663. });
  8664. svr.Get("/header_field_value_check",
  8665. [&](const Request & /*req*/, Response &res) {
  8666. res.set_content("ok", "text/plain");
  8667. });
  8668. svr.CustomRoute("PROPFIND", "/dav",
  8669. [&](const Request & /*req*/, Response &res) {
  8670. res.status = StatusCode::MultiStatus_207;
  8671. });
  8672. // Server read timeout must be longer than the client read timeout for the
  8673. // bug to reproduce, probably to force the server to process a request
  8674. // without a trailing blank line.
  8675. const time_t client_read_timeout_sec = 1;
  8676. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8677. bool listen_thread_ok = false;
  8678. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8679. auto se = detail::scope_exit([&] {
  8680. svr.stop();
  8681. t.join();
  8682. ASSERT_FALSE(svr.is_running());
  8683. EXPECT_TRUE(listen_thread_ok);
  8684. });
  8685. svr.wait_until_ready();
  8686. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8687. }
  8688. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8689. // A certain header line causes an exception if the header property is parsed
  8690. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8691. test_raw_request(
  8692. "GET /hi HTTP/1.1\r\n"
  8693. " : "
  8694. " "
  8695. " ");
  8696. }
  8697. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8698. // A certain header line causes an exception if the header property *name* is
  8699. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8700. // greedy matcher and requires backtracking when there are a lot of ":"
  8701. // characters.
  8702. // This occurs with libc++ but not libstdc++.
  8703. test_raw_request(
  8704. "GET /hi HTTP/1.1\r\n"
  8705. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8706. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8707. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8708. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8709. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8710. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8711. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8712. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8713. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8714. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8715. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8716. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8717. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8718. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8719. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8720. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8721. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8722. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8723. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8724. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8725. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8726. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8727. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8728. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8729. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8730. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8731. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8732. "&&&%%%");
  8733. }
  8734. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8735. // Make sure this doesn't crash the server.
  8736. // In a previous version of the header line regex, the "\r" rendered the line
  8737. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8738. // a new position where the leading white space ended and the field value
  8739. // began.
  8740. // The crash occurs with libc++ but not libstdc++.
  8741. test_raw_request("GET /hi HTTP/1.1\r\n"
  8742. "a:" +
  8743. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8744. "\r\n"
  8745. "\r\n");
  8746. }
  8747. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8748. std::string out;
  8749. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8750. "Content-Type: text/plain\r\n"
  8751. "Transfer-Encoding: chunked\r\n"
  8752. "\r\n"
  8753. "nothex\r\n",
  8754. &out);
  8755. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8756. }
  8757. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8758. std::string out;
  8759. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8760. "Content-Type: text/plain\r\n"
  8761. "Transfer-Encoding: chunked\r\n"
  8762. "\r\n"
  8763. "3\r\n"
  8764. "xyz\r\n"
  8765. "NaN\r\n",
  8766. &out);
  8767. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8768. }
  8769. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8770. std::string out;
  8771. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8772. "Content-Type: text/plain\r\n"
  8773. "Transfer-Encoding: chunked\r\n"
  8774. "\r\n"
  8775. // Length is too large for 64 bits.
  8776. "1ffffffffffffffff\r\n"
  8777. "xyz\r\n",
  8778. &out);
  8779. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8780. }
  8781. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8782. test_raw_request("GET /hi HTTP/1.1\r\n"
  8783. "Content-Type: text/plain\r\n\r");
  8784. }
  8785. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8786. std::string out;
  8787. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8788. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8789. }
  8790. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8791. Server svr;
  8792. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8793. EXPECT_TRUE(!req.remote_addr.empty());
  8794. });
  8795. thread t = thread([&] { svr.listen(HOST, PORT); });
  8796. auto se = detail::scope_exit([&] {
  8797. svr.stop();
  8798. t.join();
  8799. ASSERT_FALSE(svr.is_running());
  8800. });
  8801. svr.wait_until_ready();
  8802. // Send an invalid request line to trigger Bad Request
  8803. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8804. std::string out;
  8805. ASSERT_TRUE(send_request(5, bad_req, &out));
  8806. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8807. }
  8808. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8809. // answered right away rather than blocking on a read that waits for EOF.
  8810. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8811. std::string out;
  8812. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8813. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8814. }
  8815. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8816. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8817. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8818. for (const auto *method : methods) {
  8819. Server svr;
  8820. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8821. EXPECT_FALSE(svr.is_valid()) << method;
  8822. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8823. }
  8824. }
  8825. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8826. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8827. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8828. for (const auto *method : methods) {
  8829. Server svr;
  8830. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8831. EXPECT_FALSE(svr.is_valid()) << method;
  8832. }
  8833. }
  8834. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8835. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8836. "COPY", "MOVE", "LOCK",
  8837. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8838. Server svr;
  8839. for (const auto *method : methods) {
  8840. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8841. }
  8842. EXPECT_TRUE(svr.is_valid());
  8843. }
  8844. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8845. Server svr;
  8846. svr.CustomRoute("POST", "/x",
  8847. [](const Request &, Response &, const ContentReader &) {});
  8848. EXPECT_FALSE(svr.is_valid());
  8849. }
  8850. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8851. Server svr;
  8852. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8853. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8854. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8855. EXPECT_FALSE(svr.is_valid());
  8856. }
  8857. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8858. Server svr;
  8859. auto captured = Error::Success;
  8860. svr.set_error_logger(
  8861. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8862. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8863. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8864. }
  8865. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8866. std::string out;
  8867. std::string request(
  8868. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8869. test_raw_request(request, &out);
  8870. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8871. }
  8872. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8873. std::string out;
  8874. std::string request(
  8875. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8876. test_raw_request(request, &out);
  8877. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8878. }
  8879. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8880. std::string out;
  8881. std::string request(
  8882. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8883. test_raw_request(request, &out);
  8884. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8885. }
  8886. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8887. std::string out;
  8888. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8889. "Test: \r\n\r\n",
  8890. &out);
  8891. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8892. }
  8893. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8894. Server svr;
  8895. std::string x_custom;
  8896. std::string cookie;
  8897. std::string xff;
  8898. std::string x_unicode;
  8899. std::string x_iis;
  8900. svr.Get("/check", [&](const Request &req, Response &res) {
  8901. x_custom = req.get_header_value("X-Custom");
  8902. cookie = req.get_header_value("Cookie");
  8903. xff = req.get_header_value("X-Forwarded-For");
  8904. x_unicode = req.get_header_value("X-Unicode");
  8905. x_iis = req.get_header_value("X-IIS");
  8906. res.set_content("ok", "text/plain");
  8907. });
  8908. thread t = thread([&] { svr.listen(HOST, PORT); });
  8909. auto se = detail::scope_exit([&] {
  8910. svr.stop();
  8911. t.join();
  8912. ASSERT_FALSE(svr.is_running());
  8913. });
  8914. svr.wait_until_ready();
  8915. const std::string req = "GET /check HTTP/1.1\r\n"
  8916. "Host: localhost\r\n"
  8917. "X-Custom: a%0D%0AInjected: b\r\n"
  8918. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8919. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8920. "X-Unicode: %E3%81%82\r\n"
  8921. "X-IIS: %u00E9\r\n"
  8922. "Connection: close\r\n"
  8923. "\r\n";
  8924. std::string res;
  8925. ASSERT_TRUE(send_request(5, req, &res));
  8926. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8927. // Every value must be returned verbatim (wire form), with no decoding.
  8928. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8929. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8930. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8931. EXPECT_EQ("%E3%81%82", x_unicode);
  8932. EXPECT_EQ("%u00E9", x_iis);
  8933. }
  8934. // Applications that previously relied on automatic percent-decoding can
  8935. // reproduce the old behavior by explicitly calling decode_path_component()
  8936. // or, for RFC 3986 conformance, decode_uri_component().
  8937. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8938. Server svr;
  8939. std::string decoded;
  8940. svr.Get("/check", [&](const Request &req, Response &res) {
  8941. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8942. res.set_content("ok", "text/plain");
  8943. });
  8944. thread t = thread([&] { svr.listen(HOST, PORT); });
  8945. auto se = detail::scope_exit([&] {
  8946. svr.stop();
  8947. t.join();
  8948. ASSERT_FALSE(svr.is_running());
  8949. });
  8950. svr.wait_until_ready();
  8951. const std::string req = "GET /check HTTP/1.1\r\n"
  8952. "Host: localhost\r\n"
  8953. "X-Custom: hello%20world\r\n"
  8954. "Connection: close\r\n"
  8955. "\r\n";
  8956. std::string res;
  8957. ASSERT_TRUE(send_request(5, req, &res));
  8958. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8959. EXPECT_EQ("hello world", decoded);
  8960. }
  8961. // Regression test for #2033. Browsers send Referer values that include
  8962. // percent-encoded characters such as %0A inside the URL. Decoding the
  8963. // header value would either trip the post-decode CR/LF/NUL guard (the
  8964. // original bug, returning 400) or, after that guard was relaxed, silently
  8965. // store a literal LF — both unacceptable. The wire form must round-trip.
  8966. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8967. Server svr;
  8968. std::string referer;
  8969. svr.Get("/check", [&](const Request &req, Response &res) {
  8970. referer = req.get_header_value("Referer");
  8971. res.set_content("ok", "text/plain");
  8972. });
  8973. thread t = thread([&] { svr.listen(HOST, PORT); });
  8974. auto se = detail::scope_exit([&] {
  8975. svr.stop();
  8976. t.join();
  8977. ASSERT_FALSE(svr.is_running());
  8978. });
  8979. svr.wait_until_ready();
  8980. const std::string req = "GET /check HTTP/1.1\r\n"
  8981. "Host: localhost\r\n"
  8982. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8983. "Connection: close\r\n"
  8984. "\r\n";
  8985. std::string res;
  8986. ASSERT_TRUE(send_request(5, req, &res));
  8987. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8988. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8989. }
  8990. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8991. Server svr;
  8992. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8993. res.set_header("Cache-Control", "no-cache");
  8994. res.set_chunked_content_provider(
  8995. "text/event-stream", [](size_t offset, DataSink &sink) {
  8996. std::string s = "data:";
  8997. s += std::to_string(offset);
  8998. s += "\n\n";
  8999. auto ret = sink.write(s.data(), s.size());
  9000. EXPECT_TRUE(ret);
  9001. std::this_thread::sleep_for(std::chrono::seconds(1));
  9002. return true;
  9003. });
  9004. });
  9005. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9006. svr.wait_until_ready();
  9007. Client client(HOST, PORT);
  9008. const Headers headers = {{"Accept", "text/event-stream"}};
  9009. auto get_thread = std::thread([&client, &headers]() {
  9010. auto res = client.Get(
  9011. "/events", headers,
  9012. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9013. });
  9014. auto se = detail::scope_exit([&] {
  9015. svr.stop();
  9016. get_thread.join();
  9017. listen_thread.join();
  9018. ASSERT_FALSE(svr.is_running());
  9019. });
  9020. // Give GET time to get a few messages.
  9021. std::this_thread::sleep_for(std::chrono::seconds(2));
  9022. }
  9023. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9024. httplib::Server svr;
  9025. svr.Post("/hi",
  9026. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9027. res.status = StatusCode::OK_200;
  9028. });
  9029. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9030. svr.wait_until_ready();
  9031. Client cli(HOST, PORT);
  9032. auto res = cli.Post("/hi", "data", "text/plain");
  9033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9034. EXPECT_EQ(StatusCode::OK_200, res->status);
  9035. svr.stop();
  9036. thread.join();
  9037. ASSERT_FALSE(svr.is_running());
  9038. res = cli.Post("/hi", "data", "text/plain");
  9039. ASSERT_FALSE(res);
  9040. }
  9041. TEST(ServerStopTest, ListenFailure) {
  9042. Server svr;
  9043. auto t = thread([&]() {
  9044. auto ret = svr.listen("????", PORT);
  9045. EXPECT_FALSE(ret);
  9046. });
  9047. svr.wait_until_ready();
  9048. svr.stop();
  9049. t.join();
  9050. }
  9051. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9052. TEST(ServerStopTest, Decommision) {
  9053. Server svr;
  9054. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9055. for (int i = 0; i < 4; i++) {
  9056. auto is_even = !(i % 2);
  9057. std::thread t{[&] {
  9058. try {
  9059. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9060. if (is_even) {
  9061. throw std::runtime_error("Some thing that happens to go wrong.");
  9062. }
  9063. svr.listen(HOST, PORT);
  9064. } catch (...) { svr.decommission(); }
  9065. }};
  9066. svr.wait_until_ready();
  9067. // Server is up
  9068. {
  9069. Client cli(HOST, PORT);
  9070. auto res = cli.Get("/hi");
  9071. if (is_even) {
  9072. EXPECT_FALSE(res);
  9073. } else {
  9074. EXPECT_TRUE(res);
  9075. EXPECT_EQ("hi...", res->body);
  9076. }
  9077. }
  9078. svr.stop();
  9079. t.join();
  9080. // Server is down...
  9081. {
  9082. Client cli(HOST, PORT);
  9083. auto res = cli.Get("/hi");
  9084. EXPECT_FALSE(res);
  9085. }
  9086. }
  9087. }
  9088. #endif
  9089. // Helper function for string body upload progress tests
  9090. template <typename SetupHandler, typename ClientCall>
  9091. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9092. ClientCall &&client_call,
  9093. const string &body) {
  9094. Server svr;
  9095. setup_handler(svr);
  9096. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9097. auto se = detail::scope_exit([&] {
  9098. svr.stop();
  9099. t.join();
  9100. });
  9101. svr.wait_until_ready();
  9102. Client cli(HOST, PORT);
  9103. vector<uint64_t> progress_values;
  9104. bool progress_called = false;
  9105. auto res =
  9106. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9107. progress_values.push_back(current);
  9108. progress_called = true;
  9109. return true;
  9110. });
  9111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9112. EXPECT_EQ(200, res->status);
  9113. EXPECT_TRUE(progress_called);
  9114. }
  9115. TEST(UploadProgressTest, PostStringBodyBasic) {
  9116. TestStringBodyUploadProgress(
  9117. [](Server &svr) {
  9118. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9119. res.set_content("received", "text/plain");
  9120. });
  9121. },
  9122. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9123. return cli.Post("/test", body, "text/plain", progress_callback);
  9124. },
  9125. "test data for upload progress");
  9126. }
  9127. TEST(UploadProgressTest, PutStringBodyBasic) {
  9128. TestStringBodyUploadProgress(
  9129. [](Server &svr) {
  9130. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9131. res.set_content("put received", "text/plain");
  9132. });
  9133. },
  9134. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9135. return cli.Put("/test", body, "text/plain", progress_callback);
  9136. },
  9137. "put test data for upload progress");
  9138. }
  9139. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9140. TestStringBodyUploadProgress(
  9141. [](Server &svr) {
  9142. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9143. res.set_content("patch received", "text/plain");
  9144. });
  9145. },
  9146. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9147. return cli.Patch("/test", body, "text/plain", progress_callback);
  9148. },
  9149. "patch test data for upload progress");
  9150. }
  9151. // Helper function for content provider upload progress tests
  9152. template <typename SetupHandler, typename ClientCall>
  9153. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9154. ClientCall &&client_call) {
  9155. Server svr;
  9156. setup_handler(svr);
  9157. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9158. auto se = detail::scope_exit([&] {
  9159. svr.stop();
  9160. t.join();
  9161. });
  9162. svr.wait_until_ready();
  9163. Client cli(HOST, PORT);
  9164. vector<uint64_t> progress_values;
  9165. auto res =
  9166. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9167. progress_values.push_back(current);
  9168. return true;
  9169. });
  9170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9171. EXPECT_EQ(200, res->status);
  9172. EXPECT_FALSE(progress_values.empty());
  9173. }
  9174. TEST(UploadProgressTest, PostContentProviderProgress) {
  9175. TestContentProviderUploadProgress(
  9176. [](Server &svr) {
  9177. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9178. res.set_content("provider received", "text/plain");
  9179. });
  9180. },
  9181. [](Client &cli, UploadProgress progress_callback) {
  9182. return cli.Post(
  9183. "/test", 10,
  9184. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9185. sink.os << "test data";
  9186. return true;
  9187. },
  9188. "text/plain", progress_callback);
  9189. });
  9190. }
  9191. // Helper function for multipart upload progress tests
  9192. template <typename SetupHandler, typename ClientCall>
  9193. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9194. ClientCall &&client_call,
  9195. const string &endpoint) {
  9196. Server svr;
  9197. setup_handler(svr);
  9198. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9199. auto se = detail::scope_exit([&] {
  9200. svr.stop();
  9201. t.join();
  9202. });
  9203. svr.wait_until_ready();
  9204. Client cli(HOST, PORT);
  9205. vector<uint64_t> progress_values;
  9206. UploadFormDataItems items = {
  9207. {"field1", "value1", "", ""},
  9208. {"field2", "longer value for progress tracking test", "", ""},
  9209. {"file1", "file content data for upload progress", "test.txt",
  9210. "text/plain"}};
  9211. auto res = client_call(cli, endpoint, items,
  9212. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9213. progress_values.push_back(current);
  9214. return true;
  9215. });
  9216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9217. EXPECT_EQ(200, res->status);
  9218. EXPECT_FALSE(progress_values.empty());
  9219. }
  9220. TEST(UploadProgressTest, PostMultipartProgress) {
  9221. TestMultipartUploadProgress(
  9222. [](Server &svr) {
  9223. svr.Post("/multipart", [](const Request &req, Response &res) {
  9224. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9225. res.set_content("multipart received", "text/plain");
  9226. });
  9227. },
  9228. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9229. UploadProgress progress_callback) {
  9230. return cli.Post(endpoint, items, progress_callback);
  9231. },
  9232. "/multipart");
  9233. }
  9234. // Helper function for basic download progress tests
  9235. template <typename SetupHandler, typename ClientCall>
  9236. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9237. ClientCall &&client_call, const string &endpoint,
  9238. size_t expected_content_size) {
  9239. Server svr;
  9240. setup_handler(svr);
  9241. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9242. auto se = detail::scope_exit([&] {
  9243. svr.stop();
  9244. t.join();
  9245. });
  9246. svr.wait_until_ready();
  9247. Client cli(HOST, PORT);
  9248. vector<uint64_t> progress_values;
  9249. auto res = client_call(cli, endpoint,
  9250. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9251. progress_values.push_back(current);
  9252. return true;
  9253. });
  9254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9255. EXPECT_EQ(200, res->status);
  9256. EXPECT_FALSE(progress_values.empty());
  9257. EXPECT_EQ(expected_content_size, res->body.size());
  9258. }
  9259. TEST(DownloadProgressTest, GetBasic) {
  9260. TestBasicDownloadProgress(
  9261. [](Server &svr) {
  9262. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9263. string content(1000, 'D');
  9264. res.set_content(content, "text/plain");
  9265. });
  9266. },
  9267. [](Client &cli, const string &endpoint,
  9268. DownloadProgress progress_callback) {
  9269. return cli.Get(endpoint, progress_callback);
  9270. },
  9271. "/download", 1000u);
  9272. }
  9273. // Helper function for content receiver download progress tests
  9274. template <typename SetupHandler, typename ClientCall>
  9275. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9276. ClientCall &&client_call,
  9277. const string &endpoint,
  9278. size_t expected_content_size) {
  9279. Server svr;
  9280. setup_handler(svr);
  9281. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9282. auto se = detail::scope_exit([&] {
  9283. svr.stop();
  9284. t.join();
  9285. });
  9286. svr.wait_until_ready();
  9287. Client cli(HOST, PORT);
  9288. vector<uint64_t> progress_values;
  9289. string received_body;
  9290. auto res = client_call(
  9291. cli, endpoint,
  9292. [&](const char *data, size_t data_length) -> bool {
  9293. received_body.append(data, data_length);
  9294. return true;
  9295. },
  9296. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9297. progress_values.push_back(current);
  9298. return true;
  9299. });
  9300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9301. EXPECT_EQ(200, res->status);
  9302. EXPECT_FALSE(progress_values.empty());
  9303. EXPECT_EQ(expected_content_size, received_body.size());
  9304. EXPECT_TRUE(res->body.empty());
  9305. }
  9306. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9307. TestContentReceiverDownloadProgress(
  9308. [](Server &svr) {
  9309. svr.Get("/download-receiver",
  9310. [](const Request & /*req*/, Response &res) {
  9311. string content(2000, 'R');
  9312. res.set_content(content, "text/plain");
  9313. });
  9314. },
  9315. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9316. DownloadProgress progress_callback) {
  9317. return cli.Get(endpoint, content_receiver, progress_callback);
  9318. },
  9319. "/download-receiver", 2000u);
  9320. }
  9321. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9322. // A provider reaching a pass with nothing to hand over - an empty buffer
  9323. // popped off a queue, say - must not be taken to mean the body is finished.
  9324. // It used to end the loop with the terminating chunk unwritten while the
  9325. // server still considered the response complete, so the peer waited for an
  9326. // end that never arrived.
  9327. Server svr;
  9328. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9329. auto step = std::make_shared<int>(0);
  9330. res.set_chunked_content_provider("text/plain",
  9331. [step](size_t /*offset*/, DataSink &sink) {
  9332. switch ((*step)++) {
  9333. case 0: sink.write("", 0); break;
  9334. case 1: sink.write("hello", 5); break;
  9335. default: sink.done(); break;
  9336. }
  9337. return true;
  9338. });
  9339. });
  9340. auto port = svr.bind_to_any_port(HOST);
  9341. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9342. auto listen_se = detail::scope_exit([&] {
  9343. svr.stop();
  9344. listen_thread.join();
  9345. ASSERT_FALSE(svr.is_running());
  9346. });
  9347. svr.wait_until_ready();
  9348. Client cli(HOST, port);
  9349. // Without the fix the body is never terminated, so bound the wait rather
  9350. // than letting the test hang on the default read timeout.
  9351. cli.set_read_timeout(5, 0);
  9352. auto res = cli.Get("/stream");
  9353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9354. EXPECT_EQ(StatusCode::OK_200, res->status);
  9355. EXPECT_EQ("hello", res->body);
  9356. }
  9357. TEST(StreamingTest, NoContentLengthStreaming) {
  9358. Server svr;
  9359. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9360. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9361. if (offset < 6) {
  9362. sink.os << (offset < 3 ? "a" : "b");
  9363. } else {
  9364. sink.done();
  9365. }
  9366. return true;
  9367. });
  9368. });
  9369. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9370. auto listen_se = detail::scope_exit([&] {
  9371. svr.stop();
  9372. listen_thread.join();
  9373. ASSERT_FALSE(svr.is_running());
  9374. });
  9375. svr.wait_until_ready();
  9376. Client client(HOST, PORT);
  9377. auto get_thread = std::thread([&client]() {
  9378. std::string s;
  9379. auto res =
  9380. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9381. s += std::string(data, len);
  9382. return true;
  9383. });
  9384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9385. EXPECT_EQ(StatusCode::OK_200, res->status);
  9386. EXPECT_EQ("aaabbb", s);
  9387. });
  9388. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9389. // Give GET time to get a few messages.
  9390. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9391. }
  9392. TEST(MountTest, Unmount) {
  9393. Server svr;
  9394. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9395. auto se = detail::scope_exit([&] {
  9396. svr.stop();
  9397. listen_thread.join();
  9398. ASSERT_FALSE(svr.is_running());
  9399. });
  9400. svr.wait_until_ready();
  9401. Client cli("localhost", PORT);
  9402. svr.set_mount_point("/mount2", "./www2");
  9403. auto res = cli.Get("/");
  9404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9405. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9406. res = cli.Get("/mount2/dir/test.html");
  9407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9408. EXPECT_EQ(StatusCode::OK_200, res->status);
  9409. svr.set_mount_point("/", "./www");
  9410. res = cli.Get("/dir/");
  9411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9412. EXPECT_EQ(StatusCode::OK_200, res->status);
  9413. svr.remove_mount_point("/");
  9414. res = cli.Get("/dir/");
  9415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9416. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9417. svr.remove_mount_point("/mount2");
  9418. res = cli.Get("/mount2/dir/test.html");
  9419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9420. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9421. }
  9422. TEST(MountTest, PathSegmentBoundary) {
  9423. Server svr;
  9424. svr.set_mount_point("/mount2", "./www2");
  9425. svr.set_mount_point("/", "./www");
  9426. auto port = svr.bind_to_any_port(HOST);
  9427. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9428. auto se = detail::scope_exit([&] {
  9429. svr.stop();
  9430. listen_thread.join();
  9431. ASSERT_FALSE(svr.is_running());
  9432. });
  9433. svr.wait_until_ready();
  9434. Client cli(HOST, port);
  9435. auto res = cli.Get("/mount2/dir/test.html");
  9436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9437. EXPECT_EQ(StatusCode::OK_200, res->status);
  9438. // "/mount2" must not match part-way through a path segment.
  9439. res = cli.Get("/mount2dir/test.html");
  9440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9441. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9442. // A mount point ending in '/' keeps matching every path below it.
  9443. res = cli.Get("/dir/test.html");
  9444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9445. EXPECT_EQ(StatusCode::OK_200, res->status);
  9446. }
  9447. TEST(MountTest, Redicect) {
  9448. Server svr;
  9449. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9450. auto se = detail::scope_exit([&] {
  9451. svr.stop();
  9452. listen_thread.join();
  9453. ASSERT_FALSE(svr.is_running());
  9454. });
  9455. svr.set_mount_point("/", "./www");
  9456. svr.wait_until_ready();
  9457. Client cli("localhost", PORT);
  9458. auto res = cli.Get("/dir/");
  9459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9460. EXPECT_EQ(StatusCode::OK_200, res->status);
  9461. res = cli.Get("/dir");
  9462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9463. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9464. res = cli.Get("/file");
  9465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9466. EXPECT_EQ(StatusCode::OK_200, res->status);
  9467. res = cli.Get("/file/");
  9468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9470. cli.set_follow_location(true);
  9471. res = cli.Get("/dir");
  9472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9473. EXPECT_EQ(StatusCode::OK_200, res->status);
  9474. }
  9475. TEST(MountTest, MultibytesPathName) {
  9476. Server svr;
  9477. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9478. auto se = detail::scope_exit([&] {
  9479. svr.stop();
  9480. listen_thread.join();
  9481. ASSERT_FALSE(svr.is_running());
  9482. });
  9483. svr.set_mount_point("/", "./www");
  9484. svr.wait_until_ready();
  9485. Client cli("localhost", PORT);
  9486. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9488. EXPECT_EQ(StatusCode::OK_200, res->status);
  9489. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9490. }
  9491. #ifdef _WIN32
  9492. // Issue #2435: mmap::open() must succeed even when another handle holds
  9493. // the file open for writing (e.g. an active log file).
  9494. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9495. const char *path = "mmap_concurrent_writer_test.txt";
  9496. const char *content = "hello";
  9497. {
  9498. std::ofstream f(path, std::ios::binary);
  9499. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9500. }
  9501. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9502. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9503. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9504. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9505. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9506. detail::mmap m(path);
  9507. ASSERT_TRUE(m.is_open());
  9508. EXPECT_EQ(strlen(content), m.size());
  9509. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9510. }
  9511. #endif
  9512. #ifndef _WIN32
  9513. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9514. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9515. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9516. TEST(MmapTest, FailedMappingIsNotOpen) {
  9517. const char *path = "./mmap_failed_mapping_test_dir";
  9518. ASSERT_EQ(0, ::mkdir(path, 0755));
  9519. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9520. detail::mmap m(path);
  9521. EXPECT_FALSE(m.is_open());
  9522. EXPECT_EQ(0U, m.size());
  9523. EXPECT_NE(static_cast<const void *>(m.data()),
  9524. static_cast<const void *>(MAP_FAILED));
  9525. }
  9526. #endif
  9527. TEST(KeepAliveTest, ReadTimeout) {
  9528. Server svr;
  9529. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9530. std::this_thread::sleep_for(std::chrono::seconds(2));
  9531. res.set_content("a", "text/plain");
  9532. });
  9533. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9534. res.set_content("b", "text/plain");
  9535. });
  9536. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9537. auto se = detail::scope_exit([&] {
  9538. svr.stop();
  9539. listen_thread.join();
  9540. ASSERT_FALSE(svr.is_running());
  9541. });
  9542. svr.wait_until_ready();
  9543. Client cli("localhost", PORT);
  9544. cli.set_keep_alive(true);
  9545. cli.set_read_timeout(std::chrono::seconds(1));
  9546. auto resa = cli.Get("/a");
  9547. ASSERT_FALSE(resa);
  9548. EXPECT_EQ(Error::Read, resa.error());
  9549. auto resb = cli.Get("/b");
  9550. ASSERT_TRUE(resb);
  9551. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9552. EXPECT_EQ("b", resb->body);
  9553. }
  9554. TEST(KeepAliveTest, MaxCount) {
  9555. size_t keep_alive_max_count = 3;
  9556. Server svr;
  9557. svr.set_keep_alive_max_count(keep_alive_max_count);
  9558. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9559. res.set_content("Hello World!", "text/plain");
  9560. });
  9561. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9562. auto se = detail::scope_exit([&] {
  9563. svr.stop();
  9564. listen_thread.join();
  9565. ASSERT_FALSE(svr.is_running());
  9566. });
  9567. svr.wait_until_ready();
  9568. Client cli(HOST, PORT);
  9569. cli.set_keep_alive(true);
  9570. for (size_t i = 0; i < 5; i++) {
  9571. auto result = cli.Get("/hi");
  9572. ASSERT_TRUE(result);
  9573. EXPECT_EQ(StatusCode::OK_200, result->status);
  9574. if (i == keep_alive_max_count - 1) {
  9575. EXPECT_EQ("close", result->get_header_value("Connection"));
  9576. } else {
  9577. EXPECT_FALSE(result->has_header("Connection"));
  9578. }
  9579. }
  9580. }
  9581. TEST(KeepAliveTest, Issue1041) {
  9582. Server svr;
  9583. svr.set_keep_alive_timeout(3);
  9584. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9585. res.set_content("Hello World!", "text/plain");
  9586. });
  9587. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9588. auto se = detail::scope_exit([&] {
  9589. svr.stop();
  9590. listen_thread.join();
  9591. ASSERT_FALSE(svr.is_running());
  9592. });
  9593. svr.wait_until_ready();
  9594. Client cli(HOST, PORT);
  9595. cli.set_keep_alive(true);
  9596. auto result = cli.Get("/hi");
  9597. ASSERT_TRUE(result);
  9598. EXPECT_EQ(StatusCode::OK_200, result->status);
  9599. std::this_thread::sleep_for(std::chrono::seconds(5));
  9600. result = cli.Get("/hi");
  9601. ASSERT_TRUE(result);
  9602. EXPECT_EQ(StatusCode::OK_200, result->status);
  9603. }
  9604. TEST(KeepAliveTest, Issue1959) {
  9605. Server svr;
  9606. svr.set_keep_alive_timeout(5);
  9607. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9608. res.set_content("a", "text/plain");
  9609. });
  9610. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9611. auto se = detail::scope_exit([&] {
  9612. if (!svr.is_running()) return;
  9613. svr.stop();
  9614. listen_thread.join();
  9615. ASSERT_FALSE(svr.is_running());
  9616. });
  9617. svr.wait_until_ready();
  9618. Client cli("localhost", PORT);
  9619. cli.set_keep_alive(true);
  9620. using namespace std::chrono;
  9621. auto start = steady_clock::now();
  9622. cli.Get("/a");
  9623. svr.stop();
  9624. listen_thread.join();
  9625. auto end = steady_clock::now();
  9626. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9627. EXPECT_LT(elapsed, 5000);
  9628. }
  9629. #ifdef CPPHTTPLIB_SSL_ENABLED
  9630. TEST(KeepAliveTest, SSLClientReconnection) {
  9631. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9632. ASSERT_TRUE(svr.is_valid());
  9633. svr.set_keep_alive_timeout(1);
  9634. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9635. res.set_content("Hello World!", "text/plain");
  9636. });
  9637. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9638. auto se = detail::scope_exit([&] {
  9639. svr.stop();
  9640. listen_thread.join();
  9641. ASSERT_FALSE(svr.is_running());
  9642. });
  9643. svr.wait_until_ready();
  9644. SSLClient cli(HOST, PORT);
  9645. cli.enable_server_certificate_verification(false);
  9646. cli.set_keep_alive(true);
  9647. auto result = cli.Get("/hi");
  9648. ASSERT_TRUE(result);
  9649. EXPECT_EQ(StatusCode::OK_200, result->status);
  9650. result = cli.Get("/hi");
  9651. ASSERT_TRUE(result);
  9652. EXPECT_EQ(StatusCode::OK_200, result->status);
  9653. std::this_thread::sleep_for(std::chrono::seconds(2));
  9654. // Recoonect
  9655. result = cli.Get("/hi");
  9656. ASSERT_TRUE(result);
  9657. EXPECT_EQ(StatusCode::OK_200, result->status);
  9658. result = cli.Get("/hi");
  9659. ASSERT_TRUE(result);
  9660. EXPECT_EQ(StatusCode::OK_200, result->status);
  9661. }
  9662. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9663. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9664. ASSERT_TRUE(svr.is_valid());
  9665. svr.set_keep_alive_timeout(1);
  9666. std::string content = "reconnect";
  9667. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9668. res.set_content("Hello World!", "text/plain");
  9669. });
  9670. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9671. auto se = detail::scope_exit([&] {
  9672. svr.stop();
  9673. listen_thread.join();
  9674. ASSERT_FALSE(svr.is_running());
  9675. });
  9676. svr.wait_until_ready();
  9677. SSLClient cli(HOST, PORT);
  9678. cli.enable_server_certificate_verification(false);
  9679. cli.set_keep_alive(true);
  9680. auto result = cli.Post(
  9681. "/hi", content.size(),
  9682. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9683. sink.write(content.c_str(), content.size());
  9684. return true;
  9685. },
  9686. "text/plain");
  9687. ASSERT_TRUE(result);
  9688. EXPECT_EQ(200, result->status);
  9689. std::this_thread::sleep_for(std::chrono::seconds(2));
  9690. // Recoonect
  9691. result = cli.Post(
  9692. "/hi", content.size(),
  9693. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9694. sink.write(content.c_str(), content.size());
  9695. return true;
  9696. },
  9697. "text/plain");
  9698. ASSERT_TRUE(result);
  9699. EXPECT_EQ(200, result->status);
  9700. result = cli.Post(
  9701. "/hi", content.size(),
  9702. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9703. sink.write(content.c_str(), content.size());
  9704. return true;
  9705. },
  9706. "text/plain");
  9707. ASSERT_TRUE(result);
  9708. EXPECT_EQ(200, result->status);
  9709. }
  9710. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9711. using namespace httplib::tls;
  9712. {
  9713. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9714. ASSERT_TRUE(svr.is_valid());
  9715. svr.Get("/sni", [&](const Request &req, Response &res) {
  9716. std::string expected = req.sni();
  9717. EXPECT_EQ(expected, req.get_param_value("expected"));
  9718. res.set_content("ok", "text/plain");
  9719. });
  9720. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9721. auto se = detail::scope_exit([&] {
  9722. svr.stop();
  9723. listen_thread.join();
  9724. ASSERT_FALSE(svr.is_running());
  9725. });
  9726. svr.wait_until_ready();
  9727. {
  9728. SSLClient cli("localhost", PORT);
  9729. cli.enable_server_certificate_verification(false);
  9730. auto res = cli.Get("/sni?expected=localhost");
  9731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9732. }
  9733. {
  9734. SSLClient cli("::1", PORT);
  9735. cli.enable_server_certificate_verification(false);
  9736. auto res = cli.Get("/sni?expected=");
  9737. // NOTE: This may fail if the server is listening on IPv4 only
  9738. // (e.g., when localhost resolves to 127.0.0.1 only)
  9739. if (res) {
  9740. EXPECT_EQ(StatusCode::OK_200, res->status);
  9741. } else {
  9742. EXPECT_EQ(Error::Connection, res.error());
  9743. }
  9744. }
  9745. }
  9746. }
  9747. #endif
  9748. TEST(ClientProblemDetectionTest, ContentProvider) {
  9749. Server svr;
  9750. size_t content_length = 1024 * 1024;
  9751. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9752. res.set_content_provider(
  9753. content_length, "text/plain",
  9754. [&](size_t offset, size_t length, DataSink &sink) {
  9755. auto out_len = std::min(length, static_cast<size_t>(1024));
  9756. std::string out(out_len, '@');
  9757. sink.write(out.data(), out_len);
  9758. return offset < 4096;
  9759. },
  9760. [](bool success) { ASSERT_FALSE(success); });
  9761. });
  9762. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9763. res.set_content_provider(
  9764. 0, "text/plain",
  9765. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9766. EXPECT_TRUE(false);
  9767. return true;
  9768. },
  9769. [](bool success) { ASSERT_FALSE(success); });
  9770. });
  9771. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9772. auto se = detail::scope_exit([&] {
  9773. svr.stop();
  9774. listen_thread.join();
  9775. ASSERT_FALSE(svr.is_running());
  9776. });
  9777. svr.wait_until_ready();
  9778. Client cli("localhost", PORT);
  9779. {
  9780. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9781. size_t /*data_length*/) { return false; });
  9782. ASSERT_FALSE(res);
  9783. }
  9784. {
  9785. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9786. size_t /*data_length*/) { return false; });
  9787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9788. }
  9789. }
  9790. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9791. // A provider that reports success without writing anything and without
  9792. // calling done() used to be handed the same offset and length again on every
  9793. // pass, so it spun for as long as the peer stayed connected.
  9794. Server svr;
  9795. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9796. res.set_content("ok", "text/plain");
  9797. });
  9798. auto port = svr.bind_to_any_port(HOST);
  9799. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  9800. auto se = detail::scope_exit([&] {
  9801. svr.stop();
  9802. listen_thread.join();
  9803. ASSERT_FALSE(svr.is_running());
  9804. });
  9805. svr.wait_until_ready();
  9806. std::atomic<int> call_count{0};
  9807. Client cli(HOST, port);
  9808. auto res = cli.Post(
  9809. "/", 1024,
  9810. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9811. // Give up after enough passes to show the spin, so that losing the
  9812. // check below fails this test instead of hanging it.
  9813. return ++call_count < 100;
  9814. },
  9815. "text/plain");
  9816. ASSERT_FALSE(res);
  9817. EXPECT_EQ(Error::Write, res.error());
  9818. EXPECT_EQ(1, call_count.load());
  9819. }
  9820. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9821. // A writer only has to assign `write`. The other three used to be left as
  9822. // empty std::functions, so a provider calling one threw
  9823. // std::bad_function_call out of the thread running it and took the whole
  9824. // process down.
  9825. DataSink sink;
  9826. std::string written;
  9827. sink.write = [&](const char *data, size_t data_len) {
  9828. written.append(data, data_len);
  9829. return true;
  9830. };
  9831. EXPECT_TRUE(sink.is_writable());
  9832. sink.done();
  9833. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9834. EXPECT_TRUE(written.empty());
  9835. }
  9836. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9837. // A sink that cannot carry trailers still has to finish.
  9838. DataSink sink;
  9839. auto done_count = 0;
  9840. sink.done = [&]() { done_count++; };
  9841. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9842. EXPECT_EQ(1, done_count);
  9843. }
  9844. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9845. Server svr;
  9846. const std::string body(4096, 'x');
  9847. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9848. res.set_content_provider(body.size(), "text/plain",
  9849. [&](size_t offset, size_t length, DataSink &sink) {
  9850. sink.write(body.data() + offset, length);
  9851. sink.done();
  9852. return true;
  9853. });
  9854. });
  9855. auto port = svr.bind_to_any_port(HOST);
  9856. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9857. auto se = detail::scope_exit([&] {
  9858. svr.stop();
  9859. listen_thread.join();
  9860. ASSERT_FALSE(svr.is_running());
  9861. });
  9862. svr.wait_until_ready();
  9863. Client cli(HOST, port);
  9864. auto res = cli.Get("/");
  9865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9866. EXPECT_EQ(StatusCode::OK_200, res->status);
  9867. EXPECT_EQ(body, res->body);
  9868. }
  9869. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9870. Server svr;
  9871. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9872. res.set_content_provider(
  9873. 1024, "text/plain",
  9874. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9875. sink.write("hello", 5);
  9876. sink.done(); // short of the 1024 bytes the response promised
  9877. return true;
  9878. });
  9879. });
  9880. auto port = svr.bind_to_any_port(HOST);
  9881. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9882. auto se = detail::scope_exit([&] {
  9883. svr.stop();
  9884. listen_thread.join();
  9885. ASSERT_FALSE(svr.is_running());
  9886. });
  9887. svr.wait_until_ready();
  9888. Client cli(HOST, port);
  9889. cli.set_read_timeout(5, 0);
  9890. // The response is short of its Content-Length, so the client cannot read a
  9891. // complete body. What matters is that this returns at all: a no-op done()
  9892. // would leave the writer looping over a provider that never makes progress.
  9893. auto res = cli.Get("/");
  9894. EXPECT_FALSE(res);
  9895. }
  9896. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9897. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9898. // The compressed path builds the whole body before connecting, so this
  9899. // fails client-side and never reaches a server.
  9900. Client cli(HOST, PORT);
  9901. cli.set_compress(true);
  9902. auto res = cli.Post(
  9903. "/", 1024,
  9904. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9905. sink.write("hello", 5);
  9906. sink.done(); // short of the 1024 bytes the request announced
  9907. return true;
  9908. },
  9909. "text/plain");
  9910. ASSERT_FALSE(res);
  9911. EXPECT_EQ(Error::Write, res.error());
  9912. }
  9913. #endif
  9914. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9915. Server svr;
  9916. svr.set_error_handler([](Request const &, Response &res) -> void {
  9917. res.set_chunked_content_provider(
  9918. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9919. sink.os << "hello";
  9920. sink.os << "world";
  9921. sink.done();
  9922. return true;
  9923. });
  9924. });
  9925. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9926. auto se = detail::scope_exit([&] {
  9927. svr.stop();
  9928. listen_thread.join();
  9929. ASSERT_FALSE(svr.is_running());
  9930. });
  9931. svr.wait_until_ready();
  9932. Client cli("localhost", PORT);
  9933. auto res = cli.Get("/");
  9934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9935. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9936. EXPECT_EQ("helloworld", res->body);
  9937. }
  9938. TEST(LongPollingTest, ClientCloseDetection) {
  9939. Server svr;
  9940. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9941. res.set_chunked_content_provider(
  9942. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9943. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9944. sink.os << "hello";
  9945. auto count = 10;
  9946. while (count > 0 && sink.is_writable()) {
  9947. this_thread::sleep_for(chrono::milliseconds(10));
  9948. count--;
  9949. }
  9950. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9951. return true;
  9952. });
  9953. });
  9954. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9955. auto se = detail::scope_exit([&] {
  9956. svr.stop();
  9957. listen_thread.join();
  9958. ASSERT_FALSE(svr.is_running());
  9959. });
  9960. svr.wait_until_ready();
  9961. Client cli("localhost", PORT);
  9962. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9963. EXPECT_EQ("hello", string(data, data_length));
  9964. return false; // close the socket immediately.
  9965. });
  9966. ASSERT_FALSE(res);
  9967. }
  9968. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9969. Server svr;
  9970. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9971. res.set_chunked_content_provider(
  9972. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9973. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9974. sink.os << "hello";
  9975. EXPECT_TRUE(sink.os.good());
  9976. // Wait for the client to close the connection
  9977. auto count = 10;
  9978. while (count > 0 && sink.is_writable()) {
  9979. this_thread::sleep_for(chrono::milliseconds(10));
  9980. count--;
  9981. }
  9982. // After client disconnect, write repeatedly until the socket
  9983. // write actually fails (small writes may be absorbed by the
  9984. // kernel buffer)
  9985. std::string chunk(1024, 'x');
  9986. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9987. sink.os << chunk;
  9988. }
  9989. EXPECT_TRUE(sink.os.fail());
  9990. return true;
  9991. });
  9992. });
  9993. auto port = svr.bind_to_any_port("localhost");
  9994. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9995. auto se = detail::scope_exit([&] {
  9996. svr.stop();
  9997. listen_thread.join();
  9998. ASSERT_FALSE(svr.is_running());
  9999. });
  10000. svr.wait_until_ready();
  10001. Client cli("localhost", port);
  10002. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10003. EXPECT_EQ("hello", string(data, data_length));
  10004. return false; // close the socket immediately.
  10005. });
  10006. ASSERT_FALSE(res);
  10007. }
  10008. TEST(GetWithParametersTest, GetWithParameters) {
  10009. Server svr;
  10010. svr.Get("/", [&](const Request &req, Response &) {
  10011. EXPECT_EQ("world", req.get_param_value("hello"));
  10012. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10013. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10014. });
  10015. svr.Get("/params", [&](const Request &req, Response &) {
  10016. EXPECT_EQ("world", req.get_param_value("hello"));
  10017. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10018. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10019. });
  10020. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10021. EXPECT_EQ("resource-id", req.matches[1]);
  10022. EXPECT_EQ("foo", req.get_param_value("param1"));
  10023. EXPECT_EQ("bar", req.get_param_value("param2"));
  10024. });
  10025. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10026. EXPECT_EQ("user-id", req.path_params.at("id"));
  10027. EXPECT_EQ("foo", req.get_param_value("param1"));
  10028. EXPECT_EQ("bar", req.get_param_value("param2"));
  10029. });
  10030. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10031. auto se = detail::scope_exit([&] {
  10032. svr.stop();
  10033. listen_thread.join();
  10034. ASSERT_FALSE(svr.is_running());
  10035. });
  10036. svr.wait_until_ready();
  10037. {
  10038. Client cli(HOST, PORT);
  10039. Params params;
  10040. params.emplace("hello", "world");
  10041. params.emplace("hello2", "world2");
  10042. params.emplace("hello3", "world3");
  10043. auto res = cli.Get("/", params, Headers{});
  10044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10045. EXPECT_EQ(StatusCode::OK_200, res->status);
  10046. }
  10047. {
  10048. Client cli(HOST, PORT);
  10049. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10051. EXPECT_EQ(StatusCode::OK_200, res->status);
  10052. }
  10053. {
  10054. Client cli(HOST, PORT);
  10055. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10057. EXPECT_EQ(StatusCode::OK_200, res->status);
  10058. }
  10059. {
  10060. Client cli(HOST, PORT);
  10061. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10063. EXPECT_EQ(StatusCode::OK_200, res->status);
  10064. }
  10065. }
  10066. TEST(GetWithParametersTest, GetWithParameters2) {
  10067. Server svr;
  10068. svr.Get("/", [&](const Request &req, Response &res) {
  10069. auto text = req.get_param_value("hello");
  10070. res.set_content(text, "text/plain");
  10071. });
  10072. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10073. auto se = detail::scope_exit([&] {
  10074. svr.stop();
  10075. listen_thread.join();
  10076. ASSERT_FALSE(svr.is_running());
  10077. });
  10078. svr.wait_until_ready();
  10079. Client cli("localhost", PORT);
  10080. Params params;
  10081. params.emplace("hello", "world");
  10082. std::string body;
  10083. auto res = cli.Get("/", params, Headers{},
  10084. [&](const char *data, size_t data_length) {
  10085. body.append(data, data_length);
  10086. return true;
  10087. });
  10088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10089. EXPECT_EQ(StatusCode::OK_200, res->status);
  10090. EXPECT_EQ("world", body);
  10091. }
  10092. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10093. Server svr;
  10094. svr.Get("/search", [&](const Request &req, Response &res) {
  10095. auto q = req.get_param_value("q");
  10096. res.set_content(q, "text/plain");
  10097. });
  10098. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10099. auto se = detail::scope_exit([&] {
  10100. svr.stop();
  10101. listen_thread.join();
  10102. ASSERT_FALSE(svr.is_running());
  10103. });
  10104. svr.wait_until_ready();
  10105. Client cli("localhost", PORT);
  10106. // Verify that Get(path, params) works without requiring Headers argument
  10107. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10109. EXPECT_EQ(StatusCode::OK_200, res->status);
  10110. EXPECT_EQ("cpp-httplib", res->body);
  10111. }
  10112. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10113. auto host = "httpbingo.org";
  10114. auto path = std::string{"/range/32"};
  10115. #ifdef CPPHTTPLIB_SSL_ENABLED
  10116. SSLClient cli(host);
  10117. #else
  10118. Client cli(host);
  10119. #endif
  10120. cli.set_default_headers({make_range_header({{1, 10}})});
  10121. cli.set_connection_timeout(5);
  10122. {
  10123. auto res = cli.Get(path);
  10124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10125. EXPECT_EQ("bcdefghijk", res->body);
  10126. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10127. }
  10128. {
  10129. auto res = cli.Get(path);
  10130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10131. EXPECT_EQ("bcdefghijk", res->body);
  10132. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10133. }
  10134. }
  10135. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10136. Server svr;
  10137. svr.set_default_headers({{"Hello", "World"}});
  10138. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10139. res.set_content("ok", "text/plain");
  10140. });
  10141. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10142. auto se = detail::scope_exit([&] {
  10143. svr.stop();
  10144. listen_thread.join();
  10145. ASSERT_FALSE(svr.is_running());
  10146. });
  10147. svr.wait_until_ready();
  10148. Client cli("localhost", PORT);
  10149. auto res = cli.Get("/");
  10150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10151. EXPECT_EQ(StatusCode::OK_200, res->status);
  10152. EXPECT_EQ("ok", res->body);
  10153. EXPECT_EQ("World", res->get_header_value("Hello"));
  10154. }
  10155. #ifdef CPPHTTPLIB_SSL_ENABLED
  10156. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10158. ASSERT_TRUE(svr.is_valid());
  10159. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10160. std::this_thread::sleep_for(std::chrono::seconds(2));
  10161. res.set_content("a", "text/plain");
  10162. });
  10163. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10164. res.set_content("b", "text/plain");
  10165. });
  10166. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10167. auto se = detail::scope_exit([&] {
  10168. svr.stop();
  10169. listen_thread.join();
  10170. ASSERT_FALSE(svr.is_running());
  10171. });
  10172. svr.wait_until_ready();
  10173. SSLClient cli("localhost", PORT);
  10174. cli.enable_server_certificate_verification(false);
  10175. cli.set_keep_alive(true);
  10176. cli.set_read_timeout(std::chrono::seconds(1));
  10177. auto resa = cli.Get("/a");
  10178. ASSERT_TRUE(!resa);
  10179. EXPECT_EQ(Error::Read, resa.error());
  10180. auto resb = cli.Get("/b");
  10181. ASSERT_TRUE(resb);
  10182. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10183. EXPECT_EQ("b", resb->body);
  10184. }
  10185. // Closing an idle keep-alive connection sends close_notify and returns. The
  10186. // server must not wait for the client's close_notify: an idle client never
  10187. // sends one, so the worker would be held until the read timeout expires, and
  10188. // stop() would wait for it.
  10189. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10190. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10191. ASSERT_TRUE(svr.is_valid());
  10192. svr.set_keep_alive_timeout(1);
  10193. svr.set_read_timeout(10, 0);
  10194. svr.Get("/", [](const Request &, Response &res) {
  10195. res.set_content("ok", "text/plain");
  10196. });
  10197. auto port = svr.bind_to_any_port(HOST);
  10198. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10199. auto se = detail::scope_exit([&] {
  10200. if (listen_thread.joinable()) {
  10201. svr.stop();
  10202. listen_thread.join();
  10203. }
  10204. });
  10205. svr.wait_until_ready();
  10206. SSLClient cli(HOST, port);
  10207. cli.enable_server_certificate_verification(false);
  10208. cli.set_keep_alive(true);
  10209. auto res = cli.Get("/");
  10210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10211. EXPECT_EQ(StatusCode::OK_200, res->status);
  10212. // Stay idle past the keep-alive timeout so the server closes the connection.
  10213. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10214. auto start = std::chrono::steady_clock::now();
  10215. svr.stop();
  10216. listen_thread.join();
  10217. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10218. std::chrono::steady_clock::now() - start)
  10219. .count();
  10220. EXPECT_LT(elapsed, 3000);
  10221. }
  10222. #endif
  10223. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10224. protected:
  10225. ServerTestWithAI_PASSIVE()
  10226. : cli_(HOST, PORT)
  10227. #ifdef CPPHTTPLIB_SSL_ENABLED
  10228. ,
  10229. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10230. #endif
  10231. {
  10232. #ifdef CPPHTTPLIB_SSL_ENABLED
  10233. cli_.enable_server_certificate_verification(false);
  10234. #endif
  10235. }
  10236. virtual void SetUp() {
  10237. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10238. res.set_content("Hello World!", "text/plain");
  10239. });
  10240. t_ = thread(
  10241. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10242. svr_.wait_until_ready();
  10243. }
  10244. virtual void TearDown() {
  10245. svr_.stop();
  10246. t_.join();
  10247. }
  10248. #ifdef CPPHTTPLIB_SSL_ENABLED
  10249. SSLClient cli_;
  10250. SSLServer svr_;
  10251. #else
  10252. Client cli_;
  10253. Server svr_;
  10254. #endif
  10255. thread t_;
  10256. };
  10257. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10258. auto res = cli_.Get("/hi");
  10259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10260. EXPECT_EQ(StatusCode::OK_200, res->status);
  10261. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10262. EXPECT_EQ("Hello World!", res->body);
  10263. }
  10264. class ServerUpDownTest : public ::testing::Test {
  10265. protected:
  10266. ServerUpDownTest() : cli_(HOST, PORT) {}
  10267. virtual void SetUp() {
  10268. t_ = thread([&]() {
  10269. svr_.bind_to_any_port(HOST);
  10270. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10271. ASSERT_TRUE(svr_.listen_after_bind());
  10272. });
  10273. svr_.wait_until_ready();
  10274. }
  10275. virtual void TearDown() {
  10276. svr_.stop();
  10277. t_.join();
  10278. }
  10279. Client cli_;
  10280. Server svr_;
  10281. thread t_;
  10282. };
  10283. TEST_F(ServerUpDownTest, QuickStartStop) {
  10284. // Should not crash, especially when run with
  10285. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10286. }
  10287. class PayloadMaxLengthTest : public ::testing::Test {
  10288. protected:
  10289. PayloadMaxLengthTest()
  10290. : cli_(HOST, PORT)
  10291. #ifdef CPPHTTPLIB_SSL_ENABLED
  10292. ,
  10293. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10294. #endif
  10295. {
  10296. #ifdef CPPHTTPLIB_SSL_ENABLED
  10297. cli_.enable_server_certificate_verification(false);
  10298. #endif
  10299. }
  10300. virtual void SetUp() {
  10301. svr_.set_payload_max_length(8);
  10302. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10303. res.set_content("test", "text/plain");
  10304. });
  10305. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10306. svr_.wait_until_ready();
  10307. }
  10308. virtual void TearDown() {
  10309. svr_.stop();
  10310. t_.join();
  10311. }
  10312. #ifdef CPPHTTPLIB_SSL_ENABLED
  10313. SSLClient cli_;
  10314. SSLServer svr_;
  10315. #else
  10316. Client cli_;
  10317. Server svr_;
  10318. #endif
  10319. thread t_;
  10320. };
  10321. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10322. auto res = cli_.Post("/test", "123456789", "text/plain");
  10323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10324. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10325. res = cli_.Post("/test", "12345678", "text/plain");
  10326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10327. EXPECT_EQ(StatusCode::OK_200, res->status);
  10328. }
  10329. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10330. // Test chunked encoding with payload exceeding the 8-byte limit
  10331. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10332. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10334. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10335. }
  10336. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10337. // Test chunked encoding with payload within the 8-byte limit
  10338. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10339. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10341. EXPECT_EQ(StatusCode::OK_200, res->status);
  10342. }
  10343. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10344. // Test using send_request to send chunked data exceeding payload limit
  10345. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10346. "Host: " +
  10347. std::string(HOST) + ":" + std::to_string(PORT) +
  10348. "\r\n"
  10349. "Transfer-Encoding: chunked\r\n"
  10350. "Connection: close\r\n"
  10351. "\r\n"
  10352. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10353. "0123456789\r\n"
  10354. "0\r\n" // End chunk
  10355. "\r\n";
  10356. std::string response;
  10357. bool result = send_request(1, chunked_request, &response);
  10358. if (!result) {
  10359. // If send_request fails, it might be because the server closed the
  10360. // connection due to payload limit enforcement, which is acceptable
  10361. SUCCEED()
  10362. << "Server rejected oversized chunked request (connection closed)";
  10363. } else {
  10364. // If we got a response, check if it's an error response or connection was
  10365. // closed early Short response length indicates connection was closed due to
  10366. // payload limit
  10367. if (response.length() <= 10) {
  10368. SUCCEED() << "Server closed connection for oversized chunked request";
  10369. } else {
  10370. // Check for error status codes
  10371. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10372. response.find("Payload Too Large") != std::string::npos ||
  10373. response.find("400") != std::string::npos);
  10374. }
  10375. }
  10376. }
  10377. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10378. // Test request without Content-Length header exceeding payload limit
  10379. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10380. "Host: " +
  10381. std::string(HOST) + ":" +
  10382. std::to_string(PORT) +
  10383. "\r\n"
  10384. "Connection: close\r\n"
  10385. "\r\n";
  10386. // Add payload exceeding the 8-byte limit
  10387. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10388. request_without_content_length += large_payload;
  10389. std::string response;
  10390. bool result = send_request(1, request_without_content_length, &response);
  10391. if (!result) {
  10392. // If send_request fails, server likely closed connection due to payload
  10393. // limit
  10394. SUCCEED() << "Server rejected oversized request without Content-Length "
  10395. "(connection closed)";
  10396. } else {
  10397. // Check if server responded with error or closed connection early
  10398. if (response.length() <= 10) {
  10399. SUCCEED() << "Server closed connection for oversized request without "
  10400. "Content-Length";
  10401. } else {
  10402. // Check for error status codes
  10403. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10404. response.find("Payload Too Large") != std::string::npos ||
  10405. response.find("400") != std::string::npos);
  10406. }
  10407. }
  10408. }
  10409. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10410. // Test request without Content-Length header within payload limit
  10411. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10412. "Host: " +
  10413. std::string(HOST) + ":" +
  10414. std::to_string(PORT) +
  10415. "\r\n"
  10416. "Connection: close\r\n"
  10417. "\r\n";
  10418. // Add payload within the 8-byte limit
  10419. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10420. request_without_content_length += small_payload;
  10421. std::string response;
  10422. bool result = send_request(1, request_without_content_length, &response);
  10423. // For requests without Content-Length, the server may have different behavior
  10424. // The key is that it should not reject due to payload limit for small
  10425. // payloads
  10426. if (result) {
  10427. // Check for any HTTP response (success or error, but not connection closed)
  10428. if (response.length() > 10) {
  10429. SUCCEED()
  10430. << "Server processed request without Content-Length within limit";
  10431. } else {
  10432. // Short response might indicate connection closed, which is acceptable
  10433. SUCCEED() << "Server closed connection for request without "
  10434. "Content-Length (acceptable behavior)";
  10435. }
  10436. } else {
  10437. // Connection failure might be due to protocol requirements
  10438. SUCCEED() << "Connection issue with request without Content-Length "
  10439. "(environment-specific)";
  10440. }
  10441. }
  10442. class LargePayloadMaxLengthTest : public ::testing::Test {
  10443. protected:
  10444. LargePayloadMaxLengthTest()
  10445. : cli_(HOST, PORT)
  10446. #ifdef CPPHTTPLIB_SSL_ENABLED
  10447. ,
  10448. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10449. #endif
  10450. {
  10451. #ifdef CPPHTTPLIB_SSL_ENABLED
  10452. cli_.enable_server_certificate_verification(false);
  10453. #endif
  10454. }
  10455. virtual void SetUp() {
  10456. // Set 10MB payload limit
  10457. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10458. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10459. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10460. res.set_content("Large payload test", "text/plain");
  10461. });
  10462. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10463. svr_.wait_until_ready();
  10464. }
  10465. virtual void TearDown() {
  10466. svr_.stop();
  10467. t_.join();
  10468. }
  10469. #ifdef CPPHTTPLIB_SSL_ENABLED
  10470. SSLClient cli_;
  10471. SSLServer svr_;
  10472. #else
  10473. Client cli_;
  10474. Server svr_;
  10475. #endif
  10476. thread t_;
  10477. };
  10478. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10479. // Test chunked encoding with payload within 10MB limit
  10480. std::string medium_payload(5 * 1024 * 1024,
  10481. 'A'); // 5MB payload, within 10MB limit
  10482. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10484. EXPECT_EQ(StatusCode::OK_200, res->status);
  10485. }
  10486. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10487. // Test chunked encoding with payload exceeding 10MB limit
  10488. std::string large_payload(12 * 1024 * 1024,
  10489. 'B'); // 12MB payload, exceeds 10MB limit
  10490. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10491. // Server may either return 413 or close the connection
  10492. if (res) {
  10493. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10494. } else {
  10495. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10496. }
  10497. }
  10498. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10499. // Test request without Content-Length header within 10MB limit
  10500. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10501. "Host: " +
  10502. std::string(HOST) + ":" +
  10503. std::to_string(PORT) +
  10504. "\r\n"
  10505. "Connection: close\r\n"
  10506. "\r\n";
  10507. // Add 1MB payload (within 10MB limit)
  10508. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10509. request_without_content_length += medium_payload;
  10510. std::string response;
  10511. bool result = send_request(5, request_without_content_length, &response);
  10512. if (result) {
  10513. // Should get a proper HTTP response for payloads within limit
  10514. if (response.length() > 10) {
  10515. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10516. "10MB limit";
  10517. } else {
  10518. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10519. "Content-Length)";
  10520. }
  10521. } else {
  10522. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10523. }
  10524. }
  10525. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10526. // Test request without Content-Length header exceeding 10MB limit
  10527. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10528. "Host: " +
  10529. std::string(HOST) + ":" +
  10530. std::to_string(PORT) +
  10531. "\r\n"
  10532. "Connection: close\r\n"
  10533. "\r\n";
  10534. // Add 12MB payload (exceeds 10MB limit)
  10535. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10536. request_without_content_length += large_payload;
  10537. std::string response;
  10538. bool result = send_request(10, request_without_content_length, &response);
  10539. if (!result) {
  10540. // Server should close connection due to payload limit
  10541. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10542. "(connection closed)";
  10543. } else {
  10544. // Check for error response
  10545. if (response.length() <= 10) {
  10546. SUCCEED()
  10547. << "Server closed connection for 12MB request exceeding 10MB limit";
  10548. } else {
  10549. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10550. response.find("Payload Too Large") != std::string::npos ||
  10551. response.find("400") != std::string::npos);
  10552. }
  10553. }
  10554. }
  10555. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10556. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10557. // path.
  10558. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10559. Server svr;
  10560. const size_t LIMIT = 64 * 1024; // 64KB
  10561. svr.set_payload_max_length(LIMIT);
  10562. size_t total = 0;
  10563. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10564. const ContentReader &content_reader) {
  10565. content_reader([&](const char * /*data*/, size_t len) {
  10566. total += len;
  10567. return true;
  10568. });
  10569. res.status = 200;
  10570. res.set_content("stream_ok", "text/plain");
  10571. });
  10572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10573. auto se = detail::scope_exit([&] {
  10574. svr.stop();
  10575. thread.join();
  10576. ASSERT_FALSE(svr.is_running());
  10577. });
  10578. svr.wait_until_ready();
  10579. // Prepare 256KB raw data and gzip-compress it
  10580. std::string raw(256 * 1024, 'A');
  10581. std::string gz;
  10582. {
  10583. z_stream zs{};
  10584. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10585. Z_DEFAULT_STRATEGY);
  10586. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10587. zs.avail_in = static_cast<uInt>(raw.size());
  10588. char outbuf[4096];
  10589. int ret;
  10590. do {
  10591. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10592. zs.avail_out = sizeof(outbuf);
  10593. ret = deflate(&zs, Z_FINISH);
  10594. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10595. } while (ret != Z_STREAM_END);
  10596. deflateEnd(&zs);
  10597. }
  10598. Client cli(HOST, PORT);
  10599. cli.set_connection_timeout(std::chrono::seconds(5));
  10600. Headers headers = {{"Content-Encoding", "gzip"}};
  10601. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10602. "application/octet-stream");
  10603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10604. // Server must reject oversized decompressed payloads with 413.
  10605. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10606. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10607. EXPECT_LE(total, LIMIT);
  10608. }
  10609. #ifndef CPPHTTPLIB_SSL_ENABLED
  10610. // For a request with neither Content-Length nor Transfer-Encoding, the
  10611. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10612. // compressed wire bytes straight to the ContentReader without ever routing
  10613. // them through the decompressor, so payload_max_length_ only bounded the
  10614. // compressed size on the wire, not the decompressed size.
  10615. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10616. Server svr;
  10617. const size_t LIMIT = 64 * 1024; // 64KB
  10618. svr.set_payload_max_length(LIMIT);
  10619. size_t total = 0;
  10620. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10621. const ContentReader &content_reader) {
  10622. content_reader([&](const char * /*data*/, size_t len) {
  10623. total += len;
  10624. return true;
  10625. });
  10626. res.status = 200;
  10627. res.set_content("stream_ok", "text/plain");
  10628. });
  10629. auto port = svr.bind_to_any_port(HOST);
  10630. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10631. auto se = detail::scope_exit([&] {
  10632. svr.stop();
  10633. thread.join();
  10634. ASSERT_FALSE(svr.is_running());
  10635. });
  10636. svr.wait_until_ready();
  10637. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10638. // StreamingGzipDecompression test above.
  10639. std::string raw(256 * 1024, 'A');
  10640. std::string gz;
  10641. {
  10642. httplib::detail::gzip_compressor compressor;
  10643. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10644. [&](const char *chunk, size_t len) {
  10645. gz.append(chunk, len);
  10646. return true;
  10647. });
  10648. ASSERT_TRUE(result);
  10649. }
  10650. // Send the gzip body over raw TCP with neither Content-Length nor
  10651. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10652. // kicks in.
  10653. std::string req = "POST /stream HTTP/1.1\r\n"
  10654. "Host: " +
  10655. std::string(HOST) + ":" + std::to_string(port) +
  10656. "\r\n"
  10657. "Content-Encoding: gzip\r\n"
  10658. "Connection: close\r\n"
  10659. "\r\n" +
  10660. gz;
  10661. std::string response;
  10662. ASSERT_TRUE(send_request(5, req, &response, port));
  10663. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10664. EXPECT_LE(total, LIMIT);
  10665. }
  10666. #endif
  10667. #endif
  10668. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10669. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10670. // the payload must be passed through untouched instead of being rejected.
  10671. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10672. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10673. Server svr;
  10674. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10675. res.set_content(body, "image/jpeg");
  10676. res.set_header("Content-Encoding", "UTF-8");
  10677. });
  10678. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10679. res.set_content(body, "image/jpeg");
  10680. res.set_header("Content-Encoding", "identity");
  10681. });
  10682. svr.Post("/echo", [](const Request &req, Response &res) {
  10683. res.set_content(req.body, "image/jpeg");
  10684. });
  10685. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10686. auto se = detail::scope_exit([&] {
  10687. svr.stop();
  10688. t.join();
  10689. ASSERT_FALSE(svr.is_running());
  10690. });
  10691. svr.wait_until_ready();
  10692. Client cli(HOST, PORT);
  10693. {
  10694. auto res = cli.Get("/image");
  10695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10696. EXPECT_EQ(StatusCode::OK_200, res->status);
  10697. EXPECT_EQ(body, res->body);
  10698. }
  10699. {
  10700. auto res = cli.Get("/identity");
  10701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10702. EXPECT_EQ(StatusCode::OK_200, res->status);
  10703. EXPECT_EQ(body, res->body);
  10704. }
  10705. {
  10706. // The same applies to a request body reaching the server.
  10707. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10708. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10710. EXPECT_EQ(StatusCode::OK_200, res->status);
  10711. EXPECT_EQ(body, res->body);
  10712. }
  10713. }
  10714. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10715. // gzip-encoded response even when the build has no zlib support.
  10716. static const char GZIPPED_HELLO_WORLD[] = {
  10717. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10718. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10719. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10720. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10721. // A content coding is a whole token, not something the field value merely
  10722. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10723. // as "fibre" look like Brotli, and turned a multi-coding value like
  10724. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10725. // it was never meant to see.
  10726. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10727. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10728. Server svr;
  10729. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10730. res.set_content(body, "image/jpeg");
  10731. res.set_header("Content-Encoding", "fibre");
  10732. });
  10733. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10734. res.set_content(body, "image/jpeg");
  10735. res.set_header("Content-Encoding", "gzip, br");
  10736. });
  10737. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10738. res.set_content(body, "image/jpeg");
  10739. res.set_header("Content-Encoding", "x-zstd-ish");
  10740. });
  10741. auto port = svr.bind_to_any_port(HOST);
  10742. thread t = thread([&]() { svr.listen_after_bind(); });
  10743. auto se = detail::scope_exit([&] {
  10744. svr.stop();
  10745. t.join();
  10746. ASSERT_FALSE(svr.is_running());
  10747. });
  10748. svr.wait_until_ready();
  10749. Client cli(HOST, port);
  10750. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10751. auto res = cli.Get(path);
  10752. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10753. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10754. // Not a coding we recognize, so the payload comes back untouched
  10755. EXPECT_EQ(body, res->body) << path;
  10756. }
  10757. }
  10758. // A content coding cpp-httplib recognizes but was not built with must be
  10759. // reported as such. Handing the still-compressed payload back to the caller
  10760. // would silently corrupt it.
  10761. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10762. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10763. Server svr;
  10764. // "image/jpeg" keeps the server from applying a content coding of its own,
  10765. // so the hand-crafted Content-Encoding below survives.
  10766. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10767. res.set_content(gzipped, "image/jpeg");
  10768. res.set_header("Content-Encoding", "gzip");
  10769. });
  10770. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10771. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10772. res.set_content(gzipped, "image/jpeg");
  10773. res.set_header("Content-Encoding", "GZIP");
  10774. });
  10775. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10776. auto se = detail::scope_exit([&] {
  10777. svr.stop();
  10778. t.join();
  10779. ASSERT_FALSE(svr.is_running());
  10780. });
  10781. svr.wait_until_ready();
  10782. Client cli(HOST, PORT);
  10783. {
  10784. auto res = cli.Get("/gzipped");
  10785. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10787. EXPECT_EQ("Hello World!", res->body);
  10788. #else
  10789. ASSERT_FALSE(res);
  10790. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10791. #endif
  10792. }
  10793. {
  10794. // open_stream() must behave the same way.
  10795. auto handle = cli.open_stream("GET", "/gzipped");
  10796. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10797. ASSERT_TRUE(handle.is_valid());
  10798. std::string received;
  10799. char buf[256];
  10800. ssize_t n;
  10801. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10802. received.append(buf, static_cast<size_t>(n));
  10803. }
  10804. EXPECT_EQ("Hello World!", received);
  10805. #else
  10806. EXPECT_FALSE(handle.is_valid());
  10807. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10808. #endif
  10809. }
  10810. {
  10811. // A differently-cased coding must not be mistaken for an unknown one, or
  10812. // the body would be handed back still compressed.
  10813. auto res = cli.Get("/gzipped-uppercase");
  10814. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10816. EXPECT_EQ("Hello World!", res->body);
  10817. #else
  10818. ASSERT_FALSE(res);
  10819. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10820. #endif
  10821. }
  10822. }
  10823. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10824. // A handler serving pre-compressed content (e.g. build-time gzipped static
  10825. // assets) sets Content-Encoding itself. The server used to pick a coding from
  10826. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  10827. // body a second time and appending a second Content-Encoding field line, so
  10828. // clients that decode one coding per listed value handed back raw gzip bytes.
  10829. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  10830. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10831. Server svr;
  10832. // text/plain is a compressible type, so only the pre-set Content-Encoding
  10833. // keeps the server from applying a coding of its own.
  10834. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10835. res.set_content(gzipped, "text/plain");
  10836. res.set_header("Content-Encoding", "gzip");
  10837. });
  10838. auto port = svr.bind_to_any_port(HOST);
  10839. thread t = thread([&]() { svr.listen_after_bind(); });
  10840. auto se = detail::scope_exit([&] {
  10841. svr.stop();
  10842. t.join();
  10843. ASSERT_FALSE(svr.is_running());
  10844. });
  10845. svr.wait_until_ready();
  10846. Client cli(HOST, port);
  10847. Headers headers = {{"Accept-Encoding", "gzip"}};
  10848. auto res = cli.Get("/pre-gzipped", headers);
  10849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10850. EXPECT_EQ(StatusCode::OK_200, res->status);
  10851. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10852. EXPECT_EQ("Hello World!", res->body);
  10853. }
  10854. // A chunked provider settles its coding where the headers are written and
  10855. // reuses it at write time. Both ends of that have to hold: a handler's own
  10856. // Content-Encoding suppresses the coding, and a response without one is still
  10857. // compressed as it always was.
  10858. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  10859. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10860. const std::string plain = "Hello World! Hello World! Hello World!";
  10861. Server svr;
  10862. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10863. res.set_header("Content-Encoding", "gzip");
  10864. res.set_chunked_content_provider(
  10865. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  10866. sink.write(gzipped.data(), gzipped.size());
  10867. sink.done();
  10868. return true;
  10869. });
  10870. });
  10871. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  10872. res.set_chunked_content_provider(
  10873. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  10874. sink.write(plain.data(), plain.size());
  10875. sink.done();
  10876. return true;
  10877. });
  10878. });
  10879. auto port = svr.bind_to_any_port(HOST);
  10880. thread t = thread([&]() { svr.listen_after_bind(); });
  10881. auto se = detail::scope_exit([&] {
  10882. svr.stop();
  10883. t.join();
  10884. ASSERT_FALSE(svr.is_running());
  10885. });
  10886. svr.wait_until_ready();
  10887. Client cli(HOST, port);
  10888. Headers headers = {{"Accept-Encoding", "gzip"}};
  10889. {
  10890. auto res = cli.Get("/pre-gzipped", headers);
  10891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10892. EXPECT_EQ(StatusCode::OK_200, res->status);
  10893. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10894. EXPECT_EQ("Hello World!", res->body);
  10895. }
  10896. {
  10897. auto res = cli.Get("/negotiated", headers);
  10898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10899. EXPECT_EQ(StatusCode::OK_200, res->status);
  10900. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  10901. EXPECT_EQ(plain, res->body);
  10902. }
  10903. }
  10904. #endif
  10905. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10906. // the same message as the comma-joined one, so both have to be read the same
  10907. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10908. // single gzip coding, and a body the sender says was encoded twice was handed
  10909. // back after one pass, still compressed but presented as decoded.
  10910. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10911. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10912. Server svr;
  10913. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10914. res.set_content(body, "image/jpeg");
  10915. res.headers.emplace("Content-Encoding", "gzip");
  10916. res.headers.emplace("Content-Encoding", "gzip");
  10917. });
  10918. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10919. res.set_content(body, "image/jpeg");
  10920. res.set_header("Content-Encoding", "gzip, gzip");
  10921. });
  10922. auto port = svr.bind_to_any_port(HOST);
  10923. thread t = thread([&]() { svr.listen_after_bind(); });
  10924. auto se = detail::scope_exit([&] {
  10925. svr.stop();
  10926. t.join();
  10927. ASSERT_FALSE(svr.is_running());
  10928. });
  10929. svr.wait_until_ready();
  10930. Client cli(HOST, port);
  10931. // Two codings is not something cpp-httplib decodes, so both representations
  10932. // take the pass-through path rather than one of them being gunzipped once.
  10933. for (const char *path : {"/split", "/joined"}) {
  10934. auto res = cli.Get(path);
  10935. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10936. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10937. EXPECT_EQ(body, res->body) << path;
  10938. }
  10939. }
  10940. // Regression test for DoS vulnerability: a malicious server sending a response
  10941. // without Content-Length header must not cause unbounded memory consumption on
  10942. // the client side. The client should stop reading after a reasonable limit,
  10943. // similar to the server-side set_payload_max_length protection.
  10944. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10945. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10946. #ifndef _WIN32
  10947. signal(SIGPIPE, SIG_IGN);
  10948. #endif
  10949. auto server_thread = std::thread([] {
  10950. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10951. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10952. default_socket_options(srv);
  10953. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10954. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10955. sockaddr_in addr{};
  10956. addr.sin_family = AF_INET;
  10957. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10958. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10959. int opt = 1;
  10960. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10961. #ifdef _WIN32
  10962. reinterpret_cast<const char *>(&opt),
  10963. #else
  10964. &opt,
  10965. #endif
  10966. sizeof(opt));
  10967. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10968. ::listen(srv, 1);
  10969. sockaddr_in cli_addr{};
  10970. socklen_t cli_len = sizeof(cli_addr);
  10971. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10972. if (cli != INVALID_SOCKET) {
  10973. char buf[4096];
  10974. ::recv(cli, buf, sizeof(buf), 0);
  10975. // Malicious response: no Content-Length, no chunked encoding
  10976. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10977. "Connection: close\r\n"
  10978. "\r\n";
  10979. ::send(cli,
  10980. #ifdef _WIN32
  10981. static_cast<const char *>(response_header.c_str()),
  10982. static_cast<int>(response_header.size()),
  10983. #else
  10984. response_header.c_str(), response_header.size(),
  10985. #endif
  10986. 0);
  10987. // Send 10MB of data
  10988. std::string chunk(64 * 1024, 'A');
  10989. size_t total_sent = 0;
  10990. while (total_sent < MALICIOUS_DATA_SIZE) {
  10991. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  10992. auto sent = ::send(cli,
  10993. #ifdef _WIN32
  10994. static_cast<const char *>(chunk.c_str()),
  10995. static_cast<int>(to_send),
  10996. #else
  10997. chunk.c_str(), to_send,
  10998. #endif
  10999. 0);
  11000. if (sent <= 0) break;
  11001. total_sent += static_cast<size_t>(sent);
  11002. }
  11003. detail::close_socket(cli);
  11004. }
  11005. detail::close_socket(srv);
  11006. });
  11007. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11008. size_t total_read = 0;
  11009. {
  11010. Client cli("127.0.0.1", PORT + 2);
  11011. cli.set_read_timeout(5, 0);
  11012. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11013. auto stream = cli.open_stream("GET", "/malicious");
  11014. ASSERT_TRUE(stream.is_valid());
  11015. char buffer[64 * 1024];
  11016. ssize_t n;
  11017. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11018. total_read += static_cast<size_t>(n);
  11019. }
  11020. } // StreamHandle and Client destroyed here, closing the socket
  11021. server_thread.join();
  11022. // With set_payload_max_length, the client must stop reading before consuming
  11023. // all 10MB. The read loop should be cut off at or near the configured limit.
  11024. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11025. << "Client read " << total_read << " bytes, exceeding the configured "
  11026. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11027. }
  11028. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11029. // the entire response body without truncation.
  11030. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11031. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11032. #ifndef _WIN32
  11033. signal(SIGPIPE, SIG_IGN);
  11034. #endif
  11035. auto server_thread = std::thread([] {
  11036. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11037. default_socket_options(srv);
  11038. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11039. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11040. sockaddr_in addr{};
  11041. addr.sin_family = AF_INET;
  11042. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11043. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11044. int opt = 1;
  11045. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11046. #ifdef _WIN32
  11047. reinterpret_cast<const char *>(&opt),
  11048. #else
  11049. &opt,
  11050. #endif
  11051. sizeof(opt));
  11052. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11053. ::listen(srv, 1);
  11054. sockaddr_in cli_addr{};
  11055. socklen_t cli_len = sizeof(cli_addr);
  11056. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11057. if (cli != INVALID_SOCKET) {
  11058. char buf[4096];
  11059. ::recv(cli, buf, sizeof(buf), 0);
  11060. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11061. "Connection: close\r\n"
  11062. "\r\n";
  11063. ::send(cli,
  11064. #ifdef _WIN32
  11065. static_cast<const char *>(response_header.c_str()),
  11066. static_cast<int>(response_header.size()),
  11067. #else
  11068. response_header.c_str(), response_header.size(),
  11069. #endif
  11070. 0);
  11071. std::string chunk(64 * 1024, 'A');
  11072. size_t total_sent = 0;
  11073. while (total_sent < DATA_SIZE) {
  11074. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11075. auto sent = ::send(cli,
  11076. #ifdef _WIN32
  11077. static_cast<const char *>(chunk.c_str()),
  11078. static_cast<int>(to_send),
  11079. #else
  11080. chunk.c_str(), to_send,
  11081. #endif
  11082. 0);
  11083. if (sent <= 0) break;
  11084. total_sent += static_cast<size_t>(sent);
  11085. }
  11086. #ifdef _WIN32
  11087. ::shutdown(cli, SD_SEND);
  11088. #else
  11089. ::shutdown(cli, SHUT_WR);
  11090. #endif
  11091. // Drain until the client closes its end, ensuring all data is delivered
  11092. char drain[1024];
  11093. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11094. detail::close_socket(cli);
  11095. }
  11096. detail::close_socket(srv);
  11097. });
  11098. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11099. size_t total_read = 0;
  11100. {
  11101. Client cli("127.0.0.1", PORT + 2);
  11102. cli.set_read_timeout(5, 0);
  11103. cli.set_payload_max_length(0); // 0 means no limit
  11104. auto stream = cli.open_stream("GET", "/data");
  11105. ASSERT_TRUE(stream.is_valid());
  11106. char buffer[64 * 1024];
  11107. ssize_t n;
  11108. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11109. total_read += static_cast<size_t>(n);
  11110. }
  11111. }
  11112. server_thread.join();
  11113. EXPECT_EQ(total_read, DATA_SIZE)
  11114. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11115. << " bytes without truncation, but only read " << total_read << " bytes.";
  11116. }
  11117. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11118. // enormous Content-Length must not cause the client to pre-allocate a huge
  11119. // response body buffer. The reservation is capped at payload_max_length_, and
  11120. // the read itself fails when the body exceeds the limit.
  11121. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11122. #ifndef _WIN32
  11123. signal(SIGPIPE, SIG_IGN);
  11124. #endif
  11125. auto server_thread = std::thread([] {
  11126. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11127. default_socket_options(srv);
  11128. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11129. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11130. sockaddr_in addr{};
  11131. addr.sin_family = AF_INET;
  11132. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11133. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11134. int opt = 1;
  11135. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11136. #ifdef _WIN32
  11137. reinterpret_cast<const char *>(&opt),
  11138. #else
  11139. &opt,
  11140. #endif
  11141. sizeof(opt));
  11142. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11143. ::listen(srv, 1);
  11144. sockaddr_in cli_addr{};
  11145. socklen_t cli_len = sizeof(cli_addr);
  11146. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11147. if (cli != INVALID_SOCKET) {
  11148. char buf[4096];
  11149. ::recv(cli, buf, sizeof(buf), 0);
  11150. // Malicious response: claim a 20GB body but send only a tiny payload.
  11151. std::string response = "HTTP/1.1 200 OK\r\n"
  11152. "Content-Length: 20000000000\r\n"
  11153. "\r\n"
  11154. "abc";
  11155. ::send(cli,
  11156. #ifdef _WIN32
  11157. static_cast<const char *>(response.c_str()),
  11158. static_cast<int>(response.size()),
  11159. #else
  11160. response.c_str(), response.size(),
  11161. #endif
  11162. 0);
  11163. detail::close_socket(cli);
  11164. }
  11165. detail::close_socket(srv);
  11166. });
  11167. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11168. {
  11169. Client cli("127.0.0.1", PORT + 2);
  11170. cli.set_read_timeout(5, 0);
  11171. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11172. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11173. // (server claims more bytes than payload_max_length permits), but it must
  11174. // not exhaust memory before getting there.
  11175. auto res = cli.Get("/malicious");
  11176. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11177. }
  11178. server_thread.join();
  11179. }
  11180. // Verify that content_receiver bypasses the default payload_max_length,
  11181. // allowing streaming downloads larger than 100MB without requiring an explicit
  11182. // set_payload_max_length call.
  11183. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11184. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11185. #ifndef _WIN32
  11186. signal(SIGPIPE, SIG_IGN);
  11187. #endif
  11188. auto server_thread = std::thread([] {
  11189. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11190. default_socket_options(srv);
  11191. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11192. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11193. sockaddr_in addr{};
  11194. addr.sin_family = AF_INET;
  11195. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11196. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11197. int opt = 1;
  11198. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11199. #ifdef _WIN32
  11200. reinterpret_cast<const char *>(&opt),
  11201. #else
  11202. &opt,
  11203. #endif
  11204. sizeof(opt));
  11205. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11206. ::listen(srv, 1);
  11207. sockaddr_in cli_addr{};
  11208. socklen_t cli_len = sizeof(cli_addr);
  11209. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11210. if (cli != INVALID_SOCKET) {
  11211. char buf[4096];
  11212. ::recv(cli, buf, sizeof(buf), 0);
  11213. // Response with Content-Length larger than default 100MB limit
  11214. auto content_length = std::to_string(DATA_SIZE);
  11215. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11216. "Content-Length: " +
  11217. content_length +
  11218. "\r\n"
  11219. "Connection: close\r\n"
  11220. "\r\n";
  11221. ::send(cli,
  11222. #ifdef _WIN32
  11223. static_cast<const char *>(response_header.c_str()),
  11224. static_cast<int>(response_header.size()),
  11225. #else
  11226. response_header.c_str(), response_header.size(),
  11227. #endif
  11228. 0);
  11229. std::string chunk(64 * 1024, 'A');
  11230. size_t total_sent = 0;
  11231. while (total_sent < DATA_SIZE) {
  11232. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11233. auto sent = ::send(cli,
  11234. #ifdef _WIN32
  11235. static_cast<const char *>(chunk.c_str()),
  11236. static_cast<int>(to_send),
  11237. #else
  11238. chunk.c_str(), to_send,
  11239. #endif
  11240. 0);
  11241. if (sent <= 0) break;
  11242. total_sent += static_cast<size_t>(sent);
  11243. }
  11244. detail::close_socket(cli);
  11245. }
  11246. detail::close_socket(srv);
  11247. });
  11248. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11249. size_t total_received = 0;
  11250. {
  11251. Client cli("127.0.0.1", PORT + 2);
  11252. cli.set_read_timeout(10, 0);
  11253. // Do NOT call set_payload_max_length — use the default 100MB limit
  11254. auto res =
  11255. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11256. total_received += data_length;
  11257. return true;
  11258. });
  11259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11260. EXPECT_EQ(StatusCode::OK_200, res->status);
  11261. }
  11262. server_thread.join();
  11263. EXPECT_EQ(total_received, DATA_SIZE)
  11264. << "With content_receiver, the client should read all " << DATA_SIZE
  11265. << " bytes despite the default 100MB payload_max_length, but only read "
  11266. << total_received << " bytes.";
  11267. }
  11268. // Verify that an explicit set_payload_max_length smaller than the response is
  11269. // enforced even when a content_receiver is used.
  11270. TEST(ClientVulnerabilityTest,
  11271. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11272. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11273. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11274. #ifndef _WIN32
  11275. signal(SIGPIPE, SIG_IGN);
  11276. #endif
  11277. auto server_thread = std::thread([] {
  11278. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11279. default_socket_options(srv);
  11280. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11281. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11282. sockaddr_in addr{};
  11283. addr.sin_family = AF_INET;
  11284. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11285. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11286. int opt = 1;
  11287. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11288. #ifdef _WIN32
  11289. reinterpret_cast<const char *>(&opt),
  11290. #else
  11291. &opt,
  11292. #endif
  11293. sizeof(opt));
  11294. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11295. ::listen(srv, 1);
  11296. sockaddr_in cli_addr{};
  11297. socklen_t cli_len = sizeof(cli_addr);
  11298. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11299. if (cli != INVALID_SOCKET) {
  11300. char buf[4096];
  11301. ::recv(cli, buf, sizeof(buf), 0);
  11302. auto content_length = std::to_string(DATA_SIZE);
  11303. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11304. "Content-Length: " +
  11305. content_length +
  11306. "\r\n"
  11307. "Connection: close\r\n"
  11308. "\r\n";
  11309. ::send(cli,
  11310. #ifdef _WIN32
  11311. static_cast<const char *>(response_header.c_str()),
  11312. static_cast<int>(response_header.size()),
  11313. #else
  11314. response_header.c_str(), response_header.size(),
  11315. #endif
  11316. 0);
  11317. std::string chunk(64 * 1024, 'A');
  11318. size_t total_sent = 0;
  11319. while (total_sent < DATA_SIZE) {
  11320. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11321. auto sent = ::send(cli,
  11322. #ifdef _WIN32
  11323. static_cast<const char *>(chunk.c_str()),
  11324. static_cast<int>(to_send),
  11325. #else
  11326. chunk.c_str(), to_send,
  11327. #endif
  11328. 0);
  11329. if (sent <= 0) break;
  11330. total_sent += static_cast<size_t>(sent);
  11331. }
  11332. detail::close_socket(cli);
  11333. }
  11334. detail::close_socket(srv);
  11335. });
  11336. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11337. size_t total_received = 0;
  11338. {
  11339. Client cli("127.0.0.1", PORT + 2);
  11340. cli.set_read_timeout(10, 0);
  11341. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11342. auto res =
  11343. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11344. total_received += data_length;
  11345. return true;
  11346. });
  11347. // Should fail because 200MB exceeds the explicit 150MB limit
  11348. EXPECT_FALSE(res);
  11349. }
  11350. server_thread.join();
  11351. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11352. << "Client with content_receiver should respect the explicit "
  11353. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11354. << total_received << " bytes.";
  11355. }
  11356. // Verify that an explicit set_payload_max_length larger than the response
  11357. // allows the content_receiver to read all data successfully.
  11358. TEST(ClientVulnerabilityTest,
  11359. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11360. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11361. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11362. #ifndef _WIN32
  11363. signal(SIGPIPE, SIG_IGN);
  11364. #endif
  11365. auto server_thread = std::thread([] {
  11366. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11367. default_socket_options(srv);
  11368. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11369. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11370. sockaddr_in addr{};
  11371. addr.sin_family = AF_INET;
  11372. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11373. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11374. int opt = 1;
  11375. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11376. #ifdef _WIN32
  11377. reinterpret_cast<const char *>(&opt),
  11378. #else
  11379. &opt,
  11380. #endif
  11381. sizeof(opt));
  11382. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11383. ::listen(srv, 1);
  11384. sockaddr_in cli_addr{};
  11385. socklen_t cli_len = sizeof(cli_addr);
  11386. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11387. if (cli != INVALID_SOCKET) {
  11388. char buf[4096];
  11389. ::recv(cli, buf, sizeof(buf), 0);
  11390. auto content_length = std::to_string(DATA_SIZE);
  11391. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11392. "Content-Length: " +
  11393. content_length +
  11394. "\r\n"
  11395. "Connection: close\r\n"
  11396. "\r\n";
  11397. ::send(cli,
  11398. #ifdef _WIN32
  11399. static_cast<const char *>(response_header.c_str()),
  11400. static_cast<int>(response_header.size()),
  11401. #else
  11402. response_header.c_str(), response_header.size(),
  11403. #endif
  11404. 0);
  11405. std::string chunk(64 * 1024, 'A');
  11406. size_t total_sent = 0;
  11407. while (total_sent < DATA_SIZE) {
  11408. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11409. auto sent = ::send(cli,
  11410. #ifdef _WIN32
  11411. static_cast<const char *>(chunk.c_str()),
  11412. static_cast<int>(to_send),
  11413. #else
  11414. chunk.c_str(), to_send,
  11415. #endif
  11416. 0);
  11417. if (sent <= 0) break;
  11418. total_sent += static_cast<size_t>(sent);
  11419. }
  11420. #ifdef _WIN32
  11421. ::shutdown(cli, SD_SEND);
  11422. #else
  11423. ::shutdown(cli, SHUT_WR);
  11424. #endif
  11425. char drain[1024];
  11426. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11427. detail::close_socket(cli);
  11428. }
  11429. detail::close_socket(srv);
  11430. });
  11431. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11432. size_t total_received = 0;
  11433. {
  11434. Client cli("127.0.0.1", PORT + 2);
  11435. cli.set_read_timeout(10, 0);
  11436. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11437. auto res =
  11438. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11439. total_received += data_length;
  11440. return true;
  11441. });
  11442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11443. EXPECT_EQ(StatusCode::OK_200, res->status);
  11444. }
  11445. server_thread.join();
  11446. EXPECT_EQ(total_received, DATA_SIZE)
  11447. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11448. << " bytes (larger than " << DATA_SIZE
  11449. << " bytes response), content_receiver should read all data, but only "
  11450. "read "
  11451. << total_received << " bytes.";
  11452. }
  11453. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11454. // Regression test for "zip bomb" attack on the client side: a malicious server
  11455. // sends a small gzip-compressed response that decompresses to a huge payload.
  11456. // The client must enforce payload_max_length on the decompressed size.
  11457. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11458. constexpr size_t DECOMPRESSED_SIZE =
  11459. 10 * 1024 * 1024; // 10MB after decompression
  11460. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11461. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11462. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11463. std::string compressed;
  11464. {
  11465. httplib::detail::gzip_compressor compressor;
  11466. bool ok =
  11467. compressor.compress(uncompressed.data(), uncompressed.size(),
  11468. /*last=*/true, [&](const char *buf, size_t len) {
  11469. compressed.append(buf, len);
  11470. return true;
  11471. });
  11472. ASSERT_TRUE(ok);
  11473. }
  11474. // Sanity: compressed data should be much smaller than the decompressed size
  11475. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11476. #ifndef _WIN32
  11477. signal(SIGPIPE, SIG_IGN);
  11478. #endif
  11479. // Set up the listening socket in the main thread so the server is guaranteed
  11480. // to be ready before the client connects (eliminates race condition).
  11481. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11482. default_socket_options(srv);
  11483. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11484. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11485. sockaddr_in addr{};
  11486. addr.sin_family = AF_INET;
  11487. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11488. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11489. int opt = 1;
  11490. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11491. #ifdef _WIN32
  11492. reinterpret_cast<const char *>(&opt),
  11493. #else
  11494. &opt,
  11495. #endif
  11496. sizeof(opt));
  11497. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11498. ASSERT_EQ(0, ::listen(srv, 1));
  11499. auto server_thread = std::thread([&compressed, srv] {
  11500. sockaddr_in cli_addr{};
  11501. socklen_t cli_len = sizeof(cli_addr);
  11502. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11503. if (cli != INVALID_SOCKET) {
  11504. // Read the full HTTP request (until \r\n\r\n)
  11505. char buf[4096];
  11506. size_t total = 0;
  11507. while (total < sizeof(buf)) {
  11508. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11509. if (n <= 0) break;
  11510. total += static_cast<size_t>(n);
  11511. // Check for end of headers
  11512. if (total >= 4) {
  11513. std::string req(buf, total);
  11514. if (req.find("\r\n\r\n") != std::string::npos) break;
  11515. }
  11516. }
  11517. // Malicious response: gzip-compressed body, no Content-Length
  11518. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11519. "Content-Encoding: gzip\r\n"
  11520. "Connection: close\r\n"
  11521. "\r\n";
  11522. ::send(cli,
  11523. #ifdef _WIN32
  11524. static_cast<const char *>(response_header.c_str()),
  11525. static_cast<int>(response_header.size()),
  11526. #else
  11527. response_header.c_str(), response_header.size(),
  11528. #endif
  11529. 0);
  11530. // Send the compressed payload (small on the wire, huge when decompressed)
  11531. size_t total_sent = 0;
  11532. while (total_sent < compressed.size()) {
  11533. auto to_send = std::min(compressed.size() - total_sent,
  11534. static_cast<size_t>(64 * 1024));
  11535. auto sent =
  11536. ::send(cli,
  11537. #ifdef _WIN32
  11538. static_cast<const char *>(compressed.c_str() + total_sent),
  11539. static_cast<int>(to_send),
  11540. #else
  11541. compressed.c_str() + total_sent, to_send,
  11542. #endif
  11543. 0);
  11544. if (sent <= 0) break;
  11545. total_sent += static_cast<size_t>(sent);
  11546. }
  11547. detail::close_socket(cli);
  11548. }
  11549. });
  11550. auto se = detail::scope_exit([&] {
  11551. detail::close_socket(srv);
  11552. server_thread.join();
  11553. });
  11554. size_t total_decompressed = 0;
  11555. {
  11556. Client cli("127.0.0.1", PORT + 3);
  11557. cli.set_read_timeout(5, 0);
  11558. cli.set_decompress(true);
  11559. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11560. auto stream = cli.open_stream("GET", "/zipbomb");
  11561. ASSERT_TRUE(stream.is_valid());
  11562. char buffer[64 * 1024];
  11563. ssize_t n;
  11564. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11565. total_decompressed += static_cast<size_t>(n);
  11566. }
  11567. }
  11568. // The decompressed size must be capped by payload_max_length. Without
  11569. // protection, the client would decompress the full 10MB from a tiny
  11570. // compressed payload, enabling a zip bomb DoS attack.
  11571. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11572. << "Client decompressed " << total_decompressed
  11573. << " bytes from a gzip response. The decompressed size should be "
  11574. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11575. }
  11576. #endif
  11577. TEST(HostAndPortPropertiesTest, NoSSL) {
  11578. httplib::Client cli("www.google.com", 1234);
  11579. ASSERT_EQ("www.google.com", cli.host());
  11580. ASSERT_EQ(1234, cli.port());
  11581. }
  11582. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11583. httplib::Client cli("www.google.com:1234");
  11584. ASSERT_EQ("www.google.com", cli.host());
  11585. ASSERT_EQ(1234, cli.port());
  11586. }
  11587. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11588. // Port number that overflows int — should not crash, client becomes invalid
  11589. httplib::Client cli("http://www.google.com:99999999999999999999");
  11590. ASSERT_FALSE(cli.is_valid());
  11591. }
  11592. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11593. // Port 99999 exceeds valid range (1-65535) — should not crash
  11594. httplib::Client cli("http://www.google.com:99999");
  11595. ASSERT_FALSE(cli.is_valid());
  11596. }
  11597. #ifdef CPPHTTPLIB_SSL_ENABLED
  11598. TEST(HostAndPortPropertiesTest, SSL) {
  11599. httplib::SSLClient cli("www.google.com");
  11600. ASSERT_EQ("www.google.com", cli.host());
  11601. ASSERT_EQ(443, cli.port());
  11602. }
  11603. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11604. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11605. std::string cert;
  11606. read_file(CA_CERT_FILE, cert);
  11607. httplib::SSLClient httplib_client("www.google.com");
  11608. // Load CA store first time
  11609. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11610. // Load CA store second time (update)
  11611. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11612. // Verify client is still valid and can make connections
  11613. httplib_client.enable_server_certificate_verification(true);
  11614. auto res = httplib_client.Get("/");
  11615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11616. // Google may return 200 or 301 depending on various factors
  11617. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11618. res->status == StatusCode::MovedPermanently_301);
  11619. }
  11620. TEST(SSLClientTest, ServerNameIndication_Online) {
  11621. auto host = "httpbingo.org";
  11622. auto path = std::string{"/get"};
  11623. SSLClient cli(host, 443);
  11624. auto res = cli.Get(path);
  11625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11626. ASSERT_EQ(StatusCode::OK_200, res->status);
  11627. }
  11628. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11629. // Use a site that will cause SSL verification failure due to self-signed cert
  11630. SSLClient cli("self-signed.badssl.com", 443);
  11631. cli.enable_server_certificate_verification(true);
  11632. auto res = cli.Get("/");
  11633. ASSERT_TRUE(!res);
  11634. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11635. // Verify backend error is captured for SSLServerVerification
  11636. // This occurs when certificate verification fails
  11637. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11638. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11639. EXPECT_NE(0UL, res.ssl_backend_error());
  11640. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11641. // For OpenSSL, ssl_error is 0 for verification errors
  11642. EXPECT_EQ(0, res.ssl_error());
  11643. #if !defined(_WIN32) || \
  11644. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11645. // On non-Windows or when Windows Schannel is disabled, the error comes
  11646. // from OpenSSL's verification
  11647. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11648. res.ssl_backend_error());
  11649. #endif
  11650. #endif
  11651. }
  11652. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11653. // Use a site where hostname doesn't match the certificate
  11654. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11655. SSLClient cli("wrong.host.badssl.com", 443);
  11656. cli.enable_server_certificate_verification(true);
  11657. cli.enable_server_hostname_verification(true);
  11658. auto res = cli.Get("/");
  11659. ASSERT_TRUE(!res);
  11660. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11661. // Verify backend error is captured for hostname verification failure
  11662. EXPECT_NE(0UL, res.ssl_backend_error());
  11663. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11664. // For OpenSSL, ssl_error is 0 for verification errors
  11665. EXPECT_EQ(0, res.ssl_error());
  11666. #if !defined(_WIN32) || \
  11667. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11668. // On non-Windows or when Windows Schannel is disabled, the error comes
  11669. // from OpenSSL's hostname verification
  11670. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11671. res.ssl_backend_error());
  11672. #endif
  11673. #endif
  11674. }
  11675. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11676. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11677. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11678. SSLClient cli("www.google.com", 443);
  11679. cli.enable_server_certificate_verification(true);
  11680. auto res = cli.Get("/");
  11681. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11682. }
  11683. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11684. SSLClient cli("www.google.com", 443);
  11685. cli.enable_server_certificate_verification(true);
  11686. cli.enable_windows_certificate_verification(false);
  11687. auto res = cli.Get("/");
  11688. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11689. }
  11690. #endif
  11691. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11692. Client cli("https://google.com");
  11693. auto res = cli.Get("/");
  11694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11695. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11696. }
  11697. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11698. SSLClient cli("google.com");
  11699. cli.set_ca_cert_path(CA_CERT_FILE);
  11700. auto res = cli.Get("/");
  11701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11702. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11703. }
  11704. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11705. SSLClient cli("google.com");
  11706. cli.enable_server_certificate_verification(true);
  11707. cli.set_ca_cert_path("hello");
  11708. auto res = cli.Get("/");
  11709. ASSERT_TRUE(!res);
  11710. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11711. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11712. // should be set
  11713. EXPECT_EQ(0, res.ssl_error());
  11714. // Verify backend error is captured for SSLLoadingCerts
  11715. // This error occurs when loading CA certificates fails
  11716. EXPECT_NE(0UL, res.ssl_backend_error());
  11717. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11718. // OpenSSL specific error codes:
  11719. // > openssl errstr 0x80000002
  11720. // error:80000002:system library::No such file or directory
  11721. // > openssl errstr 0xA000126
  11722. // error:0A000126:SSL routines::unexpected eof while reading
  11723. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11724. res.ssl_backend_error() == 0xA000126);
  11725. #endif
  11726. }
  11727. TEST(SSLClientTest, ServerCertificateVerification4) {
  11728. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11729. ASSERT_TRUE(svr.is_valid());
  11730. svr.Get("/test", [&](const Request &, Response &res) {
  11731. res.set_content("test", "text/plain");
  11732. svr.stop();
  11733. ASSERT_TRUE(true);
  11734. });
  11735. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11736. auto se = detail::scope_exit([&] {
  11737. t.join();
  11738. ASSERT_FALSE(svr.is_running());
  11739. });
  11740. svr.wait_until_ready();
  11741. SSLClient cli("127.0.0.1", PORT);
  11742. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11743. cli.enable_server_certificate_verification(true);
  11744. cli.set_connection_timeout(30);
  11745. auto res = cli.Get("/test");
  11746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11747. ASSERT_EQ(StatusCode::OK_200, res->status);
  11748. }
  11749. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11750. std::string cert;
  11751. read_file(CA_CERT_FILE, cert);
  11752. SSLClient cli("google.com");
  11753. cli.load_ca_cert_store(cert.data(), cert.size());
  11754. const auto res = cli.Get("/");
  11755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11756. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11757. }
  11758. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11759. // clang-format off
  11760. static constexpr char cert[] =
  11761. "GlobalSign Root CA\n"
  11762. "==================\n"
  11763. "-----BEGIN CERTIFICATE-----\n"
  11764. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11765. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11766. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11767. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11768. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11769. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11770. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11771. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11772. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11773. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11774. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11775. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11776. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11777. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11778. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11779. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11780. "-----END CERTIFICATE-----\n";
  11781. // clang-format on
  11782. SSLClient cli("google.com");
  11783. cli.load_ca_cert_store(cert, sizeof(cert));
  11784. const auto res = cli.Get("/");
  11785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11786. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11787. }
  11788. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11789. SSLClient cli("www.youtube.com");
  11790. cli.set_ca_cert_path(CA_CERT_FILE);
  11791. cli.enable_server_certificate_verification(true);
  11792. cli.set_follow_location(true);
  11793. auto res = cli.Get("/");
  11794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11795. ASSERT_EQ(StatusCode::OK_200, res->status);
  11796. }
  11797. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11798. SSLClient cli("wWw.YouTube.Com");
  11799. cli.set_ca_cert_path(CA_CERT_FILE);
  11800. cli.enable_server_certificate_verification(true);
  11801. cli.enable_server_hostname_verification(true);
  11802. cli.set_follow_location(true);
  11803. auto res = cli.Get("/");
  11804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11805. ASSERT_EQ(StatusCode::OK_200, res->status);
  11806. }
  11807. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11808. SSLClient cli("gOoGlE.COm");
  11809. cli.enable_server_certificate_verification(true);
  11810. cli.enable_server_hostname_verification(true);
  11811. cli.set_follow_location(true);
  11812. auto res = cli.Get("/");
  11813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11814. ASSERT_EQ(StatusCode::OK_200, res->status);
  11815. }
  11816. TEST(SSLClientTest, Issue2004_Online) {
  11817. Client client("https://google.com");
  11818. client.set_follow_location(true);
  11819. auto res = client.Get("/");
  11820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11821. ASSERT_EQ(StatusCode::OK_200, res->status);
  11822. auto body = res->body;
  11823. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11824. }
  11825. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11826. // Create SSLClient with invalid cert/key to make is_valid() return false
  11827. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11828. "nonexistent_key.pem");
  11829. // is_valid() should be false due to cert loading failure
  11830. ASSERT_FALSE(cli.is_valid());
  11831. auto res = cli.Get("/");
  11832. ASSERT_FALSE(res);
  11833. EXPECT_EQ(Error::SSLConnection, res.error());
  11834. }
  11835. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11836. // Test for Issue #2251: SSL error not properly reported when client cert
  11837. // and key paths are swapped or mismatched
  11838. // This simulates the scenario where user accidentally swaps the cert and key
  11839. // files
  11840. // Using client cert file as private key and vice versa (completely wrong)
  11841. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11842. // Should fail validation due to cert/key mismatch
  11843. ASSERT_FALSE(cli.is_valid());
  11844. // Attempt to make a request should fail with proper error
  11845. auto res = cli.Get("/");
  11846. ASSERT_FALSE(res);
  11847. EXPECT_EQ(Error::SSLConnection, res.error());
  11848. // SSL error should be recorded in the Result object (this is the key fix for
  11849. // Issue #2251)
  11850. auto backend_error = res.ssl_backend_error();
  11851. EXPECT_NE(0u, backend_error);
  11852. }
  11853. // Tests cert/key mismatch detection at the TLS context level
  11854. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11855. // Test that using mismatched cert/key causes connection failure.
  11856. // We verify this at the SSLClient level rather than through internal
  11857. // TLS API functions.
  11858. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11859. cli.enable_server_certificate_verification(false);
  11860. cli.set_connection_timeout(2);
  11861. // The mismatch should cause a connection or handshake error
  11862. auto res = cli.Get("/test");
  11863. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11864. // Either way, the request should fail
  11865. EXPECT_FALSE(res);
  11866. }
  11867. #endif
  11868. #if 0
  11869. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11870. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11871. ASSERT_TRUE(cli != nullptr);
  11872. cli->set_address_family(AF_INET6);
  11873. cli->set_interface("en0");
  11874. auto res = cli->Get("/get");
  11875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11876. ASSERT_EQ(StatusCode::OK_200, res->status);
  11877. }
  11878. #endif
  11879. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11880. #ifdef CPPHTTPLIB_SSL_ENABLED
  11881. void ClientCertPresent(
  11882. const std::string &client_cert_file,
  11883. const std::string &client_private_key_file,
  11884. const std::string &client_encrypted_private_key_pass = std::string()) {
  11885. using namespace httplib::tls;
  11886. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11887. CLIENT_CA_CERT_DIR);
  11888. ASSERT_TRUE(svr.is_valid());
  11889. svr.Get("/test", [&](const Request &req, Response &res) {
  11890. res.set_content("test", "text/plain");
  11891. auto cert = req.peer_cert();
  11892. ASSERT_TRUE(static_cast<bool>(cert));
  11893. std::string common_name = cert.subject_cn();
  11894. EXPECT_EQ("Common Name", common_name);
  11895. });
  11896. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11897. auto se = detail::scope_exit([&] {
  11898. svr.stop();
  11899. t.join();
  11900. ASSERT_FALSE(svr.is_running());
  11901. });
  11902. svr.wait_until_ready();
  11903. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11904. client_encrypted_private_key_pass);
  11905. cli.enable_server_certificate_verification(false);
  11906. cli.set_connection_timeout(30);
  11907. auto res = cli.Get("/test");
  11908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11909. ASSERT_EQ(StatusCode::OK_200, res->status);
  11910. }
  11911. TEST(SSLClientServerTest, ClientCertPresent) {
  11912. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11913. }
  11914. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11915. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11916. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11917. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11918. }
  11919. // PEM memory-based constructor tests (works with all TLS backends)
  11920. void PemMemoryClientCertPresent(
  11921. const std::string &client_cert_file,
  11922. const std::string &client_private_key_file,
  11923. const std::string &client_encrypted_private_key_pass = std::string()) {
  11924. // Read PEM files into memory
  11925. std::string server_cert_pem, server_key_pem;
  11926. std::string client_ca_pem;
  11927. std::string client_cert_pem, client_key_pem;
  11928. read_file(SERVER_CERT_FILE, server_cert_pem);
  11929. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11930. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11931. read_file(client_cert_file, client_cert_pem);
  11932. read_file(client_private_key_file, client_key_pem);
  11933. // Create server with PEM memory
  11934. SSLServer::PemMemory server_pem = {
  11935. server_cert_pem.c_str(),
  11936. server_cert_pem.size(),
  11937. server_key_pem.c_str(),
  11938. server_key_pem.size(),
  11939. client_ca_pem.c_str(),
  11940. client_ca_pem.size(),
  11941. nullptr // no password for server key
  11942. };
  11943. SSLServer svr(server_pem);
  11944. ASSERT_TRUE(svr.is_valid());
  11945. svr.Get("/test", [&](const Request &, Response &res) {
  11946. res.set_content("test", "text/plain");
  11947. });
  11948. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11949. auto se = detail::scope_exit([&] {
  11950. svr.stop();
  11951. t.join();
  11952. ASSERT_FALSE(svr.is_running());
  11953. });
  11954. svr.wait_until_ready();
  11955. // Create client with PEM memory
  11956. const char *password = client_encrypted_private_key_pass.empty()
  11957. ? nullptr
  11958. : client_encrypted_private_key_pass.c_str();
  11959. SSLClient::PemMemory client_pem = {
  11960. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  11961. client_key_pem.size(), password};
  11962. SSLClient cli(HOST, PORT, client_pem);
  11963. cli.enable_server_certificate_verification(false);
  11964. cli.set_connection_timeout(30);
  11965. auto res = cli.Get("/test");
  11966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11967. ASSERT_EQ(StatusCode::OK_200, res->status);
  11968. }
  11969. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  11970. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11971. }
  11972. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  11973. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11974. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11975. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11976. }
  11977. TEST(SSLClientServerTest, ClientCertMissing) {
  11978. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11979. CLIENT_CA_CERT_DIR);
  11980. ASSERT_TRUE(svr.is_valid());
  11981. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  11982. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11983. auto se = detail::scope_exit([&] {
  11984. svr.stop();
  11985. t.join();
  11986. ASSERT_FALSE(svr.is_running());
  11987. });
  11988. svr.wait_until_ready();
  11989. SSLClient cli(HOST, PORT);
  11990. cli.set_connection_timeout(30);
  11991. auto res = cli.Get("/test");
  11992. ASSERT_TRUE(!res);
  11993. // When client cert is missing and server requires it, connection fails
  11994. // Error type depends on backend implementation
  11995. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11996. res.error() == Error::SSLConnection);
  11997. // Verify backend error is captured
  11998. // Note: This test may have different error codes depending on the exact
  11999. // verification failure
  12000. EXPECT_NE(0UL, res.ssl_backend_error());
  12001. }
  12002. TEST(SSLClientServerTest, TrustDirOptional) {
  12003. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12004. ASSERT_TRUE(svr.is_valid());
  12005. svr.Get("/test", [&](const Request &, Response &res) {
  12006. res.set_content("test", "text/plain");
  12007. });
  12008. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12009. auto se = detail::scope_exit([&] {
  12010. svr.stop();
  12011. t.join();
  12012. ASSERT_FALSE(svr.is_running());
  12013. });
  12014. svr.wait_until_ready();
  12015. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12016. cli.enable_server_certificate_verification(false);
  12017. cli.set_connection_timeout(30);
  12018. auto res = cli.Get("/test");
  12019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12020. ASSERT_EQ(StatusCode::OK_200, res->status);
  12021. }
  12022. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12023. class NoListenSSLServer : public SSLServer {
  12024. public:
  12025. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12026. const char *client_ca_cert_file_path,
  12027. const char *client_ca_cert_dir_path = nullptr)
  12028. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12029. client_ca_cert_dir_path),
  12030. stop_(false) {}
  12031. std::atomic_bool stop_;
  12032. private:
  12033. bool process_and_close_socket(socket_t /*sock*/) override {
  12034. // Don't create SSL context
  12035. while (!stop_.load()) {
  12036. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12037. }
  12038. return true;
  12039. }
  12040. };
  12041. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12042. CLIENT_CA_CERT_FILE);
  12043. ASSERT_TRUE(svr.is_valid());
  12044. svr.Get("/test", [&](const Request &, Response &res) {
  12045. res.set_content("test", "text/plain");
  12046. });
  12047. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12048. auto se = detail::scope_exit([&] {
  12049. svr.stop_ = true;
  12050. svr.stop();
  12051. t.join();
  12052. ASSERT_FALSE(svr.is_running());
  12053. });
  12054. svr.wait_until_ready();
  12055. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12056. cli.enable_server_certificate_verification(false);
  12057. cli.set_connection_timeout(1);
  12058. auto res = cli.Get("/test");
  12059. ASSERT_TRUE(!res);
  12060. EXPECT_EQ(Error::SSLConnection, res.error());
  12061. // Timeout results in WantRead error code (maps to backend-specific value)
  12062. EXPECT_NE(0, res.ssl_error());
  12063. }
  12064. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12065. // Test SSLServer with client certificate verification using the standard
  12066. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12067. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12068. CLIENT_CA_CERT_DIR);
  12069. ASSERT_TRUE(svr.is_valid());
  12070. svr.Get("/test", [&](const Request &req, Response &res) {
  12071. res.set_content("test", "text/plain");
  12072. auto cert = req.peer_cert();
  12073. ASSERT_TRUE(static_cast<bool>(cert));
  12074. auto common_name = cert.subject_cn();
  12075. EXPECT_EQ("Common Name", common_name);
  12076. });
  12077. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12078. auto se = detail::scope_exit([&] {
  12079. svr.stop();
  12080. t.join();
  12081. ASSERT_FALSE(svr.is_running());
  12082. });
  12083. svr.wait_until_ready();
  12084. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12085. cli.enable_server_certificate_verification(false);
  12086. cli.set_connection_timeout(30);
  12087. auto res = cli.Get("/test");
  12088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12089. ASSERT_EQ(StatusCode::OK_200, res->status);
  12090. }
  12091. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12092. // Verifies that wildcard matching and exact matching work consistently
  12093. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12094. using namespace httplib::tls;
  12095. // We need a running server to test against
  12096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12097. ASSERT_TRUE(svr.is_valid());
  12098. svr.Get("/test", [](const Request &, Response &res) {
  12099. res.set_content("ok", "text/plain");
  12100. });
  12101. thread t([&]() { svr.listen(HOST, PORT); });
  12102. auto se = detail::scope_exit([&] {
  12103. svr.stop();
  12104. t.join();
  12105. });
  12106. svr.wait_until_ready();
  12107. bool verify_callback_called = false;
  12108. bool verify_result_wrong = false;
  12109. SSLClient cli(HOST, PORT);
  12110. cli.enable_server_certificate_verification(true);
  12111. cli.set_ca_cert_path(CA_CERT_FILE);
  12112. cli.set_connection_timeout(5);
  12113. // Note: Test certificate has CN="Common Name", not "localhost"
  12114. bool verify_result_cn = false;
  12115. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12116. verify_callback_called = true;
  12117. if (!ctx.cert) return false;
  12118. // Test 1: "Common Name" should match (our test server cert CN)
  12119. verify_result_cn = ctx.check_hostname("Common Name");
  12120. // Test 2: wrong hostname should not match
  12121. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12122. return true; // Accept for the purpose of this test
  12123. });
  12124. auto res = cli.Get("/test");
  12125. // The request may succeed or fail depending on cert configuration
  12126. // but the callback should have been called
  12127. ASSERT_TRUE(verify_callback_called)
  12128. << "Verify callback should have been called";
  12129. // CN="Common Name" should match our test certificate
  12130. //
  12131. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12132. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12133. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12134. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12135. // <openssl/base.h>, which is included transitively when
  12136. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12137. #if defined(OPENSSL_IS_BORINGSSL)
  12138. EXPECT_FALSE(verify_result_cn)
  12139. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12140. #else
  12141. EXPECT_TRUE(verify_result_cn)
  12142. << "verify_hostname should match 'Common Name' (certificate CN)";
  12143. #endif
  12144. // Wrong hostname should not match
  12145. EXPECT_FALSE(verify_result_wrong)
  12146. << "verify_hostname should not match 'wronghost.example.com'";
  12147. }
  12148. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12149. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12150. // X509_check_ip behavior and must hold for every backend.
  12151. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12152. using namespace httplib::tls;
  12153. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12154. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12155. ASSERT_TRUE(svr.is_valid());
  12156. svr.Get("/test", [](const Request &, Response &res) {
  12157. res.set_content("ok", "text/plain");
  12158. });
  12159. thread t([&]() { svr.listen(HOST, PORT); });
  12160. auto se = detail::scope_exit([&] {
  12161. svr.stop();
  12162. t.join();
  12163. });
  12164. svr.wait_until_ready();
  12165. bool verify_callback_called = false;
  12166. bool ip_matched_via_cn = true;
  12167. SSLClient cli(HOST, PORT);
  12168. cli.enable_server_certificate_verification(true);
  12169. cli.set_ca_cert_path(CA_CERT_FILE);
  12170. cli.set_connection_timeout(5);
  12171. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12172. verify_callback_called = true;
  12173. if (!ctx.cert) return false;
  12174. // The IP appears only in the CN, so it must NOT be accepted.
  12175. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12176. return true; // Accept for the purpose of this test
  12177. });
  12178. cli.Get("/test");
  12179. ASSERT_TRUE(verify_callback_called)
  12180. << "Verify callback should have been called";
  12181. EXPECT_FALSE(ip_matched_via_cn)
  12182. << "An IP host must not be authenticated via the certificate CN";
  12183. }
  12184. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12185. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12186. using namespace httplib::tls;
  12187. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12188. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12189. ASSERT_TRUE(svr.is_valid());
  12190. svr.Get("/test", [](const Request &, Response &res) {
  12191. res.set_content("ok", "text/plain");
  12192. });
  12193. thread t([&]() { svr.listen(HOST, PORT); });
  12194. auto se = detail::scope_exit([&] {
  12195. svr.stop();
  12196. t.join();
  12197. });
  12198. svr.wait_until_ready();
  12199. bool verify_callback_called = false;
  12200. bool san_matched = false;
  12201. bool wrong_ipv6_matched = true;
  12202. bool cn_ipv6_matched = true;
  12203. SSLClient cli(HOST, PORT);
  12204. cli.enable_server_certificate_verification(true);
  12205. cli.set_ca_cert_path(CA_CERT_FILE);
  12206. cli.set_connection_timeout(5);
  12207. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12208. verify_callback_called = true;
  12209. if (!ctx.cert) return false;
  12210. // Matches the IPv6 iPAddress SAN.
  12211. san_matched = ctx.check_hostname("2001:db8::1");
  12212. // A different IPv6 address must not match.
  12213. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12214. // "::1" lives only in the CN, so it must not be accepted.
  12215. cn_ipv6_matched = ctx.check_hostname("::1");
  12216. return true; // Accept for the purpose of this test
  12217. });
  12218. cli.Get("/test");
  12219. ASSERT_TRUE(verify_callback_called)
  12220. << "Verify callback should have been called";
  12221. EXPECT_TRUE(san_matched)
  12222. << "verify_hostname should match an IPv6 iPAddress SAN";
  12223. EXPECT_FALSE(wrong_ipv6_matched)
  12224. << "verify_hostname should not match a non-matching IPv6 address";
  12225. EXPECT_FALSE(cn_ipv6_matched)
  12226. << "An IPv6 host must not be authenticated via the certificate CN";
  12227. }
  12228. #endif
  12229. // mbedTLS-specific callback constructor test
  12230. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12231. #ifdef CPPHTTPLIB_SSL_ENABLED
  12232. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12233. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12234. ASSERT_TRUE(svr.is_valid());
  12235. // Set up a handler to verify client certificate is present
  12236. bool client_cert_verified = false;
  12237. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12238. // Verify that client certificate was provided
  12239. client_cert_verified = true;
  12240. res.set_content("success", "text/plain");
  12241. });
  12242. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12243. auto se = detail::scope_exit([&] {
  12244. svr.stop();
  12245. t.join();
  12246. ASSERT_FALSE(svr.is_running());
  12247. });
  12248. svr.wait_until_ready();
  12249. // Client with certificate
  12250. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12251. cli.enable_server_certificate_verification(false);
  12252. cli.set_connection_timeout(30);
  12253. auto res = cli.Get("/test");
  12254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12255. ASSERT_EQ(StatusCode::OK_200, res->status);
  12256. ASSERT_TRUE(client_cert_verified);
  12257. EXPECT_EQ("success", res->body);
  12258. }
  12259. #endif
  12260. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12261. // backends
  12262. #ifdef CPPHTTPLIB_SSL_ENABLED
  12263. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12264. using namespace httplib::tls;
  12265. // Test that when client CA cert file is provided,
  12266. // the server properly requests and validates client certificates
  12267. // Create a server with client authentication
  12268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12269. ASSERT_TRUE(svr.is_valid());
  12270. bool handler_called = false;
  12271. svr.Get("/test", [&](const Request &req, Response &res) {
  12272. handler_called = true;
  12273. // Verify that a client certificate was provided
  12274. auto cert = req.peer_cert();
  12275. ASSERT_TRUE(static_cast<bool>(cert));
  12276. // Get the issuer name
  12277. std::string issuer_str = cert.issuer_name();
  12278. ASSERT_FALSE(issuer_str.empty());
  12279. // The client certificate should be issued by our test CA
  12280. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12281. res.set_content("authenticated", "text/plain");
  12282. });
  12283. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12284. auto se = detail::scope_exit([&] {
  12285. svr.stop();
  12286. t.join();
  12287. ASSERT_FALSE(svr.is_running());
  12288. });
  12289. svr.wait_until_ready();
  12290. // Connect with a client certificate issued by the CA
  12291. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12292. cli.enable_server_certificate_verification(false);
  12293. cli.set_connection_timeout(30);
  12294. auto res = cli.Get("/test");
  12295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12296. ASSERT_EQ(StatusCode::OK_200, res->status);
  12297. ASSERT_TRUE(handler_called);
  12298. EXPECT_EQ("authenticated", res->body);
  12299. }
  12300. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12301. using namespace httplib::tls;
  12302. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12303. ASSERT_TRUE(svr.is_valid());
  12304. svr.Get("/test", [](const Request &, Response &res) {
  12305. res.set_content("ok", "text/plain");
  12306. });
  12307. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12308. auto se = detail::scope_exit([&] {
  12309. svr.stop();
  12310. t.join();
  12311. });
  12312. svr.wait_until_ready();
  12313. SSLClient cli(HOST, PORT);
  12314. cli.enable_server_certificate_verification(false);
  12315. cli.set_connection_timeout(30);
  12316. bool cert_checked = false;
  12317. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12318. if (ctx.cert) {
  12319. auto sans = ctx.sans();
  12320. // Test certificate may or may not have SANs - just verify the API
  12321. // works If SANs exist, verify the types are valid
  12322. for (const auto &san : sans) {
  12323. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12324. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12325. san.type == SanType::OTHER);
  12326. EXPECT_FALSE(san.value.empty());
  12327. }
  12328. cert_checked = true;
  12329. }
  12330. return true;
  12331. });
  12332. auto res = cli.Get("/test");
  12333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12334. EXPECT_TRUE(cert_checked);
  12335. }
  12336. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12337. using namespace httplib::tls;
  12338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12339. ASSERT_TRUE(svr.is_valid());
  12340. svr.Get("/test", [](const Request &, Response &res) {
  12341. res.set_content("ok", "text/plain");
  12342. });
  12343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12344. auto se = detail::scope_exit([&] {
  12345. svr.stop();
  12346. t.join();
  12347. });
  12348. svr.wait_until_ready();
  12349. SSLClient cli(HOST, PORT);
  12350. cli.enable_server_certificate_verification(false);
  12351. cli.set_connection_timeout(30);
  12352. bool validity_checked = false;
  12353. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12354. if (ctx.cert) {
  12355. time_t not_before = 0, not_after = 0;
  12356. bool result = ctx.validity(not_before, not_after);
  12357. EXPECT_TRUE(result);
  12358. // Verify that not_before < now < not_after for a valid cert
  12359. time_t now = time(nullptr);
  12360. EXPECT_LT(not_before, now);
  12361. EXPECT_GT(not_after, now);
  12362. validity_checked = true;
  12363. }
  12364. return true;
  12365. });
  12366. auto res = cli.Get("/test");
  12367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12368. EXPECT_TRUE(validity_checked);
  12369. }
  12370. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12371. using namespace httplib::tls;
  12372. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12373. ASSERT_TRUE(svr.is_valid());
  12374. svr.Get("/test", [](const Request &, Response &res) {
  12375. res.set_content("ok", "text/plain");
  12376. });
  12377. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12378. auto se = detail::scope_exit([&] {
  12379. svr.stop();
  12380. t.join();
  12381. });
  12382. svr.wait_until_ready();
  12383. SSLClient cli(HOST, PORT);
  12384. cli.enable_server_certificate_verification(false);
  12385. cli.set_connection_timeout(30);
  12386. bool serial_checked = false;
  12387. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12388. if (ctx.cert) {
  12389. std::string serial = ctx.serial();
  12390. EXPECT_FALSE(serial.empty());
  12391. // Serial should be a hex string
  12392. for (char c : serial) {
  12393. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12394. (c >= 'a' && c <= 'f'));
  12395. }
  12396. serial_checked = true;
  12397. }
  12398. return true;
  12399. });
  12400. auto res = cli.Get("/test");
  12401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12402. EXPECT_TRUE(serial_checked);
  12403. }
  12404. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12405. // Test 1: Valid CA file - no error should be recorded
  12406. {
  12407. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12408. CLIENT_CA_CERT_FILE);
  12409. ASSERT_TRUE(svr.is_valid());
  12410. // With valid setup, last_ssl_error should be 0
  12411. EXPECT_EQ(0, svr.ssl_last_error());
  12412. }
  12413. // Test 2: Invalid CA file content
  12414. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12415. {
  12416. // Create a temporary file with completely invalid content
  12417. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12418. {
  12419. std::ofstream ofs(temp_invalid_ca);
  12420. ofs << "This is not a certificate file at all\n";
  12421. ofs << "Just plain text content\n";
  12422. }
  12423. // Create server with invalid CA file
  12424. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12425. // Clean up temporary file
  12426. std::remove(temp_invalid_ca);
  12427. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12428. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12429. // Note: SSL_CTX_load_verify_locations typically fails first,
  12430. // but our error handling code path is still exercised
  12431. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12432. }
  12433. }
  12434. TEST(VerifyCallbackTest, VerifyContextFields) {
  12435. using namespace httplib::tls;
  12436. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12437. ASSERT_TRUE(svr.is_valid());
  12438. svr.Get("/test", [](const Request &, Response &res) {
  12439. res.set_content("ok", "text/plain");
  12440. });
  12441. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12442. auto se = detail::scope_exit([&] {
  12443. svr.stop();
  12444. t.join();
  12445. });
  12446. svr.wait_until_ready();
  12447. SSLClient cli(HOST, PORT);
  12448. cli.enable_server_certificate_verification(false);
  12449. cli.set_connection_timeout(30);
  12450. int callback_count = 0;
  12451. bool saw_leaf_cert = false;
  12452. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12453. if (ctx.cert) {
  12454. callback_count++;
  12455. // We should see at least one certificate (the leaf)
  12456. std::string cn = ctx.subject_cn();
  12457. if (!cn.empty()) { saw_leaf_cert = true; }
  12458. // Verify context fields are populated
  12459. EXPECT_NE(ctx.session, nullptr);
  12460. EXPECT_GE(ctx.depth, 0);
  12461. }
  12462. return true;
  12463. });
  12464. auto res = cli.Get("/test");
  12465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12466. EXPECT_GT(callback_count, 0);
  12467. EXPECT_TRUE(saw_leaf_cert);
  12468. }
  12469. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12470. using httplib::tls::TlsError;
  12471. // Test that verify_error_to_string returns empty for success
  12472. std::string success_str = TlsError::verify_error_to_string(0);
  12473. EXPECT_TRUE(success_str.empty());
  12474. // Test that verify_error_to_string returns non-empty for error codes
  12475. // Using a common error code (certificate expired)
  12476. std::string error_str =
  12477. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12478. EXPECT_FALSE(error_str.empty());
  12479. }
  12480. TEST(SessionVerifierTest, CertificateAccepted) {
  12481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12482. ASSERT_TRUE(svr.is_valid());
  12483. svr.Get("/test", [](const Request &, Response &res) {
  12484. res.set_content("ok", "text/plain");
  12485. });
  12486. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12487. auto se = detail::scope_exit([&] {
  12488. svr.stop();
  12489. t.join();
  12490. });
  12491. svr.wait_until_ready();
  12492. SSLClient cli(HOST, PORT);
  12493. cli.enable_server_certificate_verification(false);
  12494. cli.set_connection_timeout(30);
  12495. bool callback_called = false;
  12496. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12497. EXPECT_NE(session, nullptr);
  12498. callback_called = true;
  12499. return SSLVerifierResponse::CertificateAccepted;
  12500. });
  12501. auto res = cli.Get("/test");
  12502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12503. EXPECT_EQ(200, res->status);
  12504. EXPECT_TRUE(callback_called);
  12505. }
  12506. TEST(SessionVerifierTest, CertificateRejected) {
  12507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12508. ASSERT_TRUE(svr.is_valid());
  12509. svr.Get("/test", [](const Request &, Response &res) {
  12510. res.set_content("ok", "text/plain");
  12511. });
  12512. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12513. auto se = detail::scope_exit([&] {
  12514. svr.stop();
  12515. t.join();
  12516. });
  12517. svr.wait_until_ready();
  12518. SSLClient cli(HOST, PORT);
  12519. cli.enable_server_certificate_verification(false);
  12520. cli.set_connection_timeout(30);
  12521. bool callback_called = false;
  12522. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12523. EXPECT_NE(session, nullptr);
  12524. callback_called = true;
  12525. return SSLVerifierResponse::CertificateRejected;
  12526. });
  12527. auto res = cli.Get("/test");
  12528. EXPECT_FALSE(res);
  12529. EXPECT_TRUE(callback_called);
  12530. }
  12531. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12533. ASSERT_TRUE(svr.is_valid());
  12534. svr.Get("/test", [](const Request &, Response &res) {
  12535. res.set_content("ok", "text/plain");
  12536. });
  12537. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12538. auto se = detail::scope_exit([&] {
  12539. svr.stop();
  12540. t.join();
  12541. });
  12542. svr.wait_until_ready();
  12543. // NoDecisionMade with verification disabled should succeed (no default check)
  12544. SSLClient cli(HOST, PORT);
  12545. cli.enable_server_certificate_verification(false);
  12546. cli.set_connection_timeout(30);
  12547. bool callback_called = false;
  12548. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12549. EXPECT_NE(session, nullptr);
  12550. callback_called = true;
  12551. return SSLVerifierResponse::NoDecisionMade;
  12552. });
  12553. auto res = cli.Get("/test");
  12554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12555. EXPECT_EQ(200, res->status);
  12556. EXPECT_TRUE(callback_called);
  12557. }
  12558. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12559. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12560. ASSERT_TRUE(svr.is_valid());
  12561. svr.Get("/test", [](const Request &, Response &res) {
  12562. res.set_content("ok", "text/plain");
  12563. });
  12564. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12565. auto se = detail::scope_exit([&] {
  12566. svr.stop();
  12567. t.join();
  12568. });
  12569. svr.wait_until_ready();
  12570. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12571. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12572. // so we only check that the request fails, not whether the callback was
  12573. // called.
  12574. SSLClient cli(HOST, PORT);
  12575. cli.enable_server_certificate_verification(true);
  12576. cli.set_connection_timeout(30);
  12577. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12578. EXPECT_NE(session, nullptr);
  12579. return SSLVerifierResponse::NoDecisionMade;
  12580. });
  12581. auto res = cli.Get("/test");
  12582. EXPECT_FALSE(res);
  12583. }
  12584. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12585. // Test SSL server using PemMemory constructor with client CA certificates
  12586. // Read PEM files
  12587. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12588. read_file(SERVER_CERT_FILE, server_cert_pem);
  12589. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12590. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12591. // Create SSLServer with PemMemory constructor including client CA
  12592. SSLServer::PemMemory server_pem = {
  12593. server_cert_pem.c_str(),
  12594. server_cert_pem.size(),
  12595. server_key_pem.c_str(),
  12596. server_key_pem.size(),
  12597. client_ca_pem.c_str(),
  12598. client_ca_pem.size(),
  12599. nullptr // no password for server key
  12600. };
  12601. SSLServer svr(server_pem);
  12602. ASSERT_TRUE(svr.is_valid());
  12603. // No SSL error should be recorded for valid setup
  12604. EXPECT_EQ(0, svr.ssl_last_error());
  12605. // Set up server endpoints
  12606. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12607. res.set_content("ok", "text/plain");
  12608. });
  12609. // Start server in a thread
  12610. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12611. svr.wait_until_ready();
  12612. // Connect with client certificate (using constructor with paths)
  12613. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12614. cli.enable_server_certificate_verification(false);
  12615. auto res = cli.Get("/test-pem-ca");
  12616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12617. EXPECT_EQ(200, res->status);
  12618. EXPECT_EQ("ok", res->body);
  12619. svr.stop();
  12620. server_thread.join();
  12621. }
  12622. #endif
  12623. #ifdef _WIN32
  12624. TEST(CleanupTest, WSACleanup) {
  12625. int ret = WSACleanup();
  12626. ASSERT_EQ(0, ret);
  12627. }
  12628. #endif
  12629. #ifndef CPPHTTPLIB_SSL_ENABLED
  12630. TEST(NoSSLSupport, SimpleInterface) {
  12631. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12632. }
  12633. #endif
  12634. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12635. TEST(InvalidScheme, SimpleInterface) {
  12636. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12637. }
  12638. #endif
  12639. TEST(NoScheme, SimpleInterface) {
  12640. Client cli("yahoo.com:80");
  12641. ASSERT_TRUE(cli.is_valid());
  12642. }
  12643. TEST(SendAPI, SimpleInterface_Online) {
  12644. Client cli("http://yahoo.com");
  12645. Request req;
  12646. req.method = "GET";
  12647. req.path = "/";
  12648. auto res = cli.send(req);
  12649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12650. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12651. }
  12652. TEST(SendAPI, WithParamsInRequest) {
  12653. Server svr;
  12654. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12655. EXPECT_TRUE(req.has_param("test"));
  12656. EXPECT_EQ("test_value", req.get_param_value("test"));
  12657. });
  12658. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12659. auto se = detail::scope_exit([&] {
  12660. svr.stop();
  12661. t.join();
  12662. ASSERT_FALSE(svr.is_running());
  12663. });
  12664. svr.wait_until_ready();
  12665. Client cli(HOST, PORT);
  12666. {
  12667. Request req;
  12668. req.method = "GET";
  12669. req.path = "/";
  12670. req.params.emplace("test", "test_value");
  12671. auto res = cli.send(req);
  12672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12673. }
  12674. {
  12675. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12677. }
  12678. }
  12679. TEST(ClientImplMethods, GetSocketTest) {
  12680. httplib::Server svr;
  12681. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12682. res.status = StatusCode::OK_200;
  12683. });
  12684. auto port = svr.bind_to_any_port("127.0.0.1");
  12685. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12686. auto se = detail::scope_exit([&] {
  12687. svr.stop();
  12688. thread.join();
  12689. ASSERT_FALSE(svr.is_running());
  12690. });
  12691. svr.wait_until_ready();
  12692. {
  12693. httplib::Client cli("127.0.0.1", port);
  12694. cli.set_keep_alive(true);
  12695. // Use the behavior of cpp-httplib of opening the connection
  12696. // only when the first request happens. If that changes,
  12697. // this test would be obsolete.
  12698. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12699. // This also implicitly tests the server. But other tests would fail much
  12700. // earlier than this one to be considered.
  12701. auto res = cli.Get("/");
  12702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12703. EXPECT_EQ(StatusCode::OK_200, res->status);
  12704. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12705. }
  12706. }
  12707. #ifdef CPPHTTPLIB_SSL_ENABLED
  12708. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12709. Client cli("http://yahoo.com");
  12710. auto res = cli.Get("/");
  12711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12712. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12713. cli.set_follow_location(true);
  12714. res = cli.Get("/");
  12715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12716. EXPECT_EQ(StatusCode::OK_200, res->status);
  12717. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12718. }
  12719. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12720. Client cli("https://yahoo.com");
  12721. auto res = cli.Get("/");
  12722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12723. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12724. cli.set_follow_location(true);
  12725. res = cli.Get("/");
  12726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12727. EXPECT_EQ(StatusCode::OK_200, res->status);
  12728. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12729. }
  12730. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12731. Client cli("https://yahoo.com");
  12732. auto res = cli.Get("/");
  12733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12734. ASSERT_FALSE(!res);
  12735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12736. ASSERT_FALSE(res == nullptr);
  12737. ASSERT_TRUE(res != nullptr);
  12738. EXPECT_EQ(Error::Success, res.error());
  12739. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12740. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12741. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12742. cli.set_follow_location(true);
  12743. res = cli.Get("/");
  12744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12745. EXPECT_EQ(Error::Success, res.error());
  12746. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12747. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12748. EXPECT_EQ(StatusCode::OK_200, res->status);
  12749. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12750. }
  12751. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12752. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12753. Client cli("https://cdnjs.cloudflare.com");
  12754. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12755. Headers{{"Accept-Encoding", "br"}});
  12756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12757. EXPECT_EQ(StatusCode::OK_200, res->status);
  12758. EXPECT_EQ(287630U, res->body.size());
  12759. EXPECT_EQ("application/javascript; charset=utf-8",
  12760. res->get_header_value("Content-Type"));
  12761. }
  12762. #endif
  12763. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12764. #undef REDIR_HOST // Silence compiler warning
  12765. #define REDIR_HOST "https://httpbingo.org"
  12766. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12767. Client cli(REDIR_HOST);
  12768. cli.set_follow_location(true);
  12769. auto res =
  12770. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12772. EXPECT_EQ(StatusCode::OK_200, res->status);
  12773. }
  12774. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12775. Client cli(REDIR_HOST);
  12776. cli.set_follow_location(true);
  12777. Params params;
  12778. params.emplace("url", "http://example.com");
  12779. params.emplace("status_code", "302");
  12780. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12782. EXPECT_EQ(StatusCode::OK_200, res->status);
  12783. }
  12784. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12785. Client cli(REDIR_HOST);
  12786. cli.set_follow_location(true);
  12787. Params params;
  12788. params.emplace("url", "http://example.com");
  12789. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12791. EXPECT_EQ(StatusCode::OK_200, res->status);
  12792. }
  12793. TEST(HttpToHttpsRedirectTest, CertFile) {
  12794. auto ssl_port = PORT + 1;
  12795. Server svr;
  12796. ASSERT_TRUE(svr.is_valid());
  12797. svr.Get("/index", [&](const Request &, Response &res) {
  12798. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12799. "/index");
  12800. svr.stop();
  12801. });
  12802. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12803. ASSERT_TRUE(ssl_svr.is_valid());
  12804. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12805. res.set_content("test", "text/plain");
  12806. ssl_svr.stop();
  12807. });
  12808. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12809. thread t2 =
  12810. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12811. auto se = detail::scope_exit([&] {
  12812. t2.join();
  12813. t.join();
  12814. ASSERT_FALSE(svr.is_running());
  12815. });
  12816. svr.wait_until_ready();
  12817. ssl_svr.wait_until_ready();
  12818. Client cli("127.0.0.1", PORT);
  12819. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12820. cli.enable_server_certificate_verification(true);
  12821. cli.set_follow_location(true);
  12822. cli.set_connection_timeout(30);
  12823. auto res = cli.Get("/index");
  12824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12825. ASSERT_EQ(StatusCode::OK_200, res->status);
  12826. }
  12827. TEST(SSLClientRedirectTest, CertFile) {
  12828. auto ssl_port = PORT + 1;
  12829. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12830. ASSERT_TRUE(ssl_svr1.is_valid());
  12831. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12832. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12833. "/index");
  12834. ssl_svr1.stop();
  12835. });
  12836. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12837. ASSERT_TRUE(ssl_svr2.is_valid());
  12838. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12839. res.set_content("test", "text/plain");
  12840. ssl_svr2.stop();
  12841. });
  12842. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12843. thread t2 =
  12844. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12845. auto se = detail::scope_exit([&] {
  12846. t2.join();
  12847. t.join();
  12848. ASSERT_FALSE(ssl_svr1.is_running());
  12849. });
  12850. ssl_svr1.wait_until_ready();
  12851. ssl_svr2.wait_until_ready();
  12852. SSLClient cli("127.0.0.1", PORT);
  12853. std::string cert;
  12854. read_file(SERVER_CERT2_FILE, cert);
  12855. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12856. cli.enable_server_certificate_verification(true);
  12857. cli.set_follow_location(true);
  12858. cli.set_connection_timeout(30);
  12859. auto res = cli.Get("/index");
  12860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12861. ASSERT_EQ(StatusCode::OK_200, res->status);
  12862. }
  12863. #endif
  12864. #ifdef CPPHTTPLIB_SSL_ENABLED
  12865. // Test that set_ca_cert_store() skips system certs (consistent with
  12866. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12867. // should be trusted - system certs should NOT be loaded.
  12868. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12869. // Load a specific cert that is NOT a system CA cert
  12870. std::string cert;
  12871. read_file(SERVER_CERT2_FILE, cert);
  12872. SSLClient cli("google.com");
  12873. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12874. cli.enable_server_certificate_verification(true);
  12875. // This should FAIL because:
  12876. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12877. // 2. System certs should NOT be loaded when custom store is set
  12878. // If system certs WERE loaded, this would succeed
  12879. auto res = cli.Get("/");
  12880. ASSERT_FALSE(res);
  12881. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12882. }
  12883. // Same as above, but through the native store handle path. Regression test:
  12884. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12885. // merged system certs into the user-provided store.
  12886. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12887. std::string cert;
  12888. read_file(SERVER_CERT2_FILE, cert);
  12889. SSLClient cli("google.com");
  12890. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12891. cli.enable_server_certificate_verification(true);
  12892. auto res = cli.Get("/");
  12893. ASSERT_FALSE(res);
  12894. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12895. }
  12896. // A custom store set via the native handle must still verify a server whose
  12897. // cert it does contain.
  12898. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12899. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12900. ASSERT_TRUE(svr.is_valid());
  12901. svr.Get("/test", [&](const Request &, Response &res) {
  12902. res.set_content("test", "text/plain");
  12903. });
  12904. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12905. auto se = detail::scope_exit([&] {
  12906. svr.stop();
  12907. t.join();
  12908. ASSERT_FALSE(svr.is_running());
  12909. });
  12910. svr.wait_until_ready();
  12911. SSLClient cli("127.0.0.1", PORT);
  12912. std::string cert;
  12913. read_file(SERVER_CERT2_FILE, cert);
  12914. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12915. cli.enable_server_certificate_verification(true);
  12916. cli.set_connection_timeout(30);
  12917. auto res = cli.Get("/test");
  12918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12919. ASSERT_EQ(StatusCode::OK_200, res->status);
  12920. }
  12921. // CA certs loaded through the universal Client must be transferred to the
  12922. // client created internally for following an HTTPS redirect. Regression test:
  12923. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12924. // the CA data for redirect transfer.
  12925. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12926. auto ssl_port = PORT + 1;
  12927. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12928. ASSERT_TRUE(ssl_svr1.is_valid());
  12929. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12930. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12931. "/index");
  12932. });
  12933. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12934. ASSERT_TRUE(ssl_svr2.is_valid());
  12935. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12936. res.set_content("test", "text/plain");
  12937. });
  12938. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12939. thread t2 =
  12940. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12941. auto se = detail::scope_exit([&] {
  12942. ssl_svr2.stop();
  12943. ssl_svr1.stop();
  12944. t2.join();
  12945. t.join();
  12946. ASSERT_FALSE(ssl_svr1.is_running());
  12947. });
  12948. ssl_svr1.wait_until_ready();
  12949. ssl_svr2.wait_until_ready();
  12950. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12951. std::string cert;
  12952. read_file(SERVER_CERT2_FILE, cert);
  12953. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12954. cli.enable_server_certificate_verification(true);
  12955. cli.set_follow_location(true);
  12956. cli.set_connection_timeout(30);
  12957. auto res = cli.Get("/index");
  12958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12959. ASSERT_EQ(StatusCode::OK_200, res->status);
  12960. }
  12961. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  12962. // so a host signed by a system CA verifies even though a custom CA is set
  12963. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  12964. std::string cert;
  12965. read_file(SERVER_CERT2_FILE, cert);
  12966. SSLClient cli("google.com");
  12967. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12968. cli.enable_system_ca(true);
  12969. cli.enable_server_certificate_verification(true);
  12970. auto res = cli.Get("/");
  12971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12972. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12973. }
  12974. // The custom CA remains effective when combined with the system CA
  12975. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  12976. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12977. ASSERT_TRUE(svr.is_valid());
  12978. svr.Get("/test", [&](const Request &, Response &res) {
  12979. res.set_content("test", "text/plain");
  12980. });
  12981. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12982. auto se = detail::scope_exit([&] {
  12983. svr.stop();
  12984. t.join();
  12985. ASSERT_FALSE(svr.is_running());
  12986. });
  12987. svr.wait_until_ready();
  12988. SSLClient cli("127.0.0.1", PORT);
  12989. std::string cert;
  12990. read_file(SERVER_CERT2_FILE, cert);
  12991. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12992. cli.enable_system_ca(true);
  12993. cli.enable_server_certificate_verification(true);
  12994. cli.set_connection_timeout(30);
  12995. auto res = cli.Get("/test");
  12996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12997. ASSERT_EQ(StatusCode::OK_200, res->status);
  12998. }
  12999. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13000. // skip chain verification entirely (only the certificate identity was
  13001. // checked), so a server presenting an untrusted certificate with a matching
  13002. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13003. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13004. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13005. ASSERT_TRUE(svr.is_valid());
  13006. svr.Get("/test", [&](const Request &, Response &res) {
  13007. res.set_content("test", "text/plain");
  13008. });
  13009. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13010. auto se = detail::scope_exit([&] {
  13011. svr.stop();
  13012. t.join();
  13013. ASSERT_FALSE(svr.is_running());
  13014. });
  13015. svr.wait_until_ready();
  13016. SSLClient cli("127.0.0.1", PORT);
  13017. std::string cert;
  13018. // A trusted CA that did not sign the server certificate. The server cert
  13019. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13020. // this connection.
  13021. read_file(CLIENT_CA_CERT_FILE, cert);
  13022. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13023. cli.enable_server_certificate_verification(true);
  13024. cli.set_connection_timeout(30);
  13025. auto res = cli.Get("/test");
  13026. ASSERT_FALSE(res);
  13027. }
  13028. // enable_system_ca(false) prevents system CA loading entirely
  13029. TEST(SSLClientTest, DisableSystemCa_Online) {
  13030. SSLClient cli("google.com");
  13031. cli.enable_system_ca(false);
  13032. cli.enable_server_certificate_verification(true);
  13033. auto res = cli.Get("/");
  13034. ASSERT_FALSE(res);
  13035. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13036. // itself when the CA chain is empty
  13037. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13038. res.error() == Error::SSLConnection);
  13039. }
  13040. // The universal Client forwards enable_system_ca()
  13041. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13042. std::string cert;
  13043. read_file(SERVER_CERT2_FILE, cert);
  13044. Client cli("https://google.com");
  13045. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13046. cli.enable_system_ca(true);
  13047. cli.enable_server_certificate_verification(true);
  13048. auto res = cli.Get("/");
  13049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13050. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13051. }
  13052. // The system CA policy must carry over to the client created internally for
  13053. // following a cross-host HTTPS redirect
  13054. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13055. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13056. ASSERT_TRUE(svr.is_valid());
  13057. svr.Get("/index", [&](const Request &, Response &res) {
  13058. res.set_redirect("https://www.google.com/");
  13059. });
  13060. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13061. auto se = detail::scope_exit([&] {
  13062. svr.stop();
  13063. t.join();
  13064. ASSERT_FALSE(svr.is_running());
  13065. });
  13066. svr.wait_until_ready();
  13067. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13068. std::string cert;
  13069. read_file(SERVER_CERT2_FILE, cert);
  13070. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13071. cli.enable_system_ca(true);
  13072. cli.enable_server_certificate_verification(true);
  13073. cli.set_follow_location(true);
  13074. cli.set_connection_timeout(30);
  13075. // Receiving any response proves the redirect client completed the TLS
  13076. // handshake with a system-CA-signed host
  13077. auto res = cli.Get("/index");
  13078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13079. }
  13080. TEST(MultipartFormDataTest, LargeData) {
  13081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13082. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13083. const ContentReader &content_reader) {
  13084. if (req.is_multipart_form_data()) {
  13085. std::vector<FormData> items;
  13086. content_reader(
  13087. [&](const FormData &file) {
  13088. items.push_back(file);
  13089. return true;
  13090. },
  13091. [&](const char *data, size_t data_length) {
  13092. items.back().content.append(data, data_length);
  13093. return true;
  13094. });
  13095. EXPECT_TRUE(std::string(items[0].name) == "document");
  13096. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13097. EXPECT_TRUE(items[0].filename == "2MB_data");
  13098. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13099. EXPECT_TRUE(items[1].name == "hello");
  13100. EXPECT_TRUE(items[1].content == "world");
  13101. EXPECT_TRUE(items[1].filename == "");
  13102. EXPECT_TRUE(items[1].content_type == "");
  13103. } else {
  13104. std::string body;
  13105. content_reader([&](const char *data, size_t data_length) {
  13106. body.append(data, data_length);
  13107. return true;
  13108. });
  13109. }
  13110. });
  13111. auto port = svr.bind_to_any_port(HOST);
  13112. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13113. auto se = detail::scope_exit([&] {
  13114. svr.stop();
  13115. t.join();
  13116. ASSERT_FALSE(svr.is_running());
  13117. });
  13118. svr.wait_until_ready();
  13119. {
  13120. std::string data(1024 * 1024 * 2, '.');
  13121. std::stringstream buffer;
  13122. buffer << data;
  13123. SSLClient cli(HOST, port);
  13124. cli.enable_server_certificate_verification(false);
  13125. UploadFormDataItems items{
  13126. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13127. {"hello", "world", "", ""},
  13128. };
  13129. auto res = cli.Post("/post", items);
  13130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13131. ASSERT_EQ(StatusCode::OK_200, res->status);
  13132. }
  13133. }
  13134. TEST(MultipartFormDataTest, DataProviderItems) {
  13135. std::random_device seed_gen;
  13136. std::mt19937 random(seed_gen());
  13137. std::string rand1;
  13138. rand1.resize(1000);
  13139. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13140. std::string rand2;
  13141. rand2.resize(3000);
  13142. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13143. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13144. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13145. const ContentReader &content_reader) {
  13146. ASSERT_FALSE(req.is_multipart_form_data());
  13147. std::string body;
  13148. content_reader([&](const char *data, size_t data_length) {
  13149. body.append(data, data_length);
  13150. return true;
  13151. });
  13152. EXPECT_EQ(body, "");
  13153. });
  13154. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13155. const ContentReader &content_reader) {
  13156. ASSERT_TRUE(req.is_multipart_form_data());
  13157. std::vector<FormData> items;
  13158. content_reader(
  13159. [&](const FormData &file) {
  13160. items.push_back(file);
  13161. return true;
  13162. },
  13163. [&](const char *data, size_t data_length) {
  13164. items.back().content.append(data, data_length);
  13165. return true;
  13166. });
  13167. ASSERT_TRUE(items.size() == 2);
  13168. EXPECT_EQ(std::string(items[0].name), "name1");
  13169. EXPECT_EQ(items[0].content, "Testing123");
  13170. EXPECT_EQ(items[0].filename, "filename1");
  13171. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13172. EXPECT_EQ(items[1].name, "name2");
  13173. EXPECT_EQ(items[1].content, "Testing456");
  13174. EXPECT_EQ(items[1].filename, "");
  13175. EXPECT_EQ(items[1].content_type, "");
  13176. });
  13177. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13178. const ContentReader &content_reader) {
  13179. ASSERT_TRUE(req.is_multipart_form_data());
  13180. std::vector<FormData> items;
  13181. content_reader(
  13182. [&](const FormData &file) {
  13183. items.push_back(file);
  13184. return true;
  13185. },
  13186. [&](const char *data, size_t data_length) {
  13187. items.back().content.append(data, data_length);
  13188. return true;
  13189. });
  13190. ASSERT_TRUE(items.size() == 2);
  13191. EXPECT_EQ(items[0].name, "name3");
  13192. EXPECT_EQ(items[0].content, rand1);
  13193. EXPECT_EQ(items[0].filename, "filename3");
  13194. EXPECT_EQ(items[0].content_type, "");
  13195. EXPECT_EQ(items[1].name, "name4");
  13196. EXPECT_EQ(items[1].content, rand2);
  13197. EXPECT_EQ(items[1].filename, "filename4");
  13198. EXPECT_EQ(items[1].content_type, "");
  13199. });
  13200. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13201. const ContentReader &content_reader) {
  13202. ASSERT_TRUE(req.is_multipart_form_data());
  13203. std::vector<FormData> items;
  13204. content_reader(
  13205. [&](const FormData &file) {
  13206. items.push_back(file);
  13207. return true;
  13208. },
  13209. [&](const char *data, size_t data_length) {
  13210. items.back().content.append(data, data_length);
  13211. return true;
  13212. });
  13213. ASSERT_TRUE(items.size() == 4);
  13214. EXPECT_EQ(std::string(items[0].name), "name1");
  13215. EXPECT_EQ(items[0].content, "Testing123");
  13216. EXPECT_EQ(items[0].filename, "filename1");
  13217. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13218. EXPECT_EQ(items[1].name, "name2");
  13219. EXPECT_EQ(items[1].content, "Testing456");
  13220. EXPECT_EQ(items[1].filename, "");
  13221. EXPECT_EQ(items[1].content_type, "");
  13222. EXPECT_EQ(items[2].name, "name3");
  13223. EXPECT_EQ(items[2].content, rand1);
  13224. EXPECT_EQ(items[2].filename, "filename3");
  13225. EXPECT_EQ(items[2].content_type, "");
  13226. EXPECT_EQ(items[3].name, "name4");
  13227. EXPECT_EQ(items[3].content, rand2);
  13228. EXPECT_EQ(items[3].filename, "filename4");
  13229. EXPECT_EQ(items[3].content_type, "");
  13230. });
  13231. auto port = svr.bind_to_any_port("localhost");
  13232. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13233. auto se = detail::scope_exit([&] {
  13234. svr.stop();
  13235. t.join();
  13236. ASSERT_FALSE(svr.is_running());
  13237. });
  13238. svr.wait_until_ready();
  13239. {
  13240. SSLClient cli("localhost", port);
  13241. cli.enable_server_certificate_verification(false);
  13242. UploadFormDataItems items{
  13243. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13244. {"name2", "Testing456", "", ""}, // not a file
  13245. };
  13246. {
  13247. auto res = cli.Post("/post-none", {}, {}, {});
  13248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13249. ASSERT_EQ(StatusCode::OK_200, res->status);
  13250. }
  13251. FormDataProviderItems providers;
  13252. {
  13253. auto res =
  13254. cli.Post("/post-items", {}, items, providers); // empty providers
  13255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13256. ASSERT_EQ(StatusCode::OK_200, res->status);
  13257. }
  13258. providers.push_back({"name3",
  13259. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13260. // test the offset is given correctly at each step
  13261. if (!offset)
  13262. sink.os.write(rand1.data(), 30);
  13263. else if (offset == 30)
  13264. sink.os.write(rand1.data() + 30, 300);
  13265. else if (offset == 330)
  13266. sink.os.write(rand1.data() + 330, 670);
  13267. else if (offset == rand1.size())
  13268. sink.done();
  13269. return true;
  13270. },
  13271. "filename3",
  13272. {}});
  13273. providers.push_back({"name4",
  13274. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13275. // test the offset is given correctly at each step
  13276. if (!offset)
  13277. sink.os.write(rand2.data(), 2000);
  13278. else if (offset == 2000)
  13279. sink.os.write(rand2.data() + 2000, 1);
  13280. else if (offset == 2001)
  13281. sink.os.write(rand2.data() + 2001, 999);
  13282. else if (offset == rand2.size())
  13283. sink.done();
  13284. return true;
  13285. },
  13286. "filename4",
  13287. {}});
  13288. {
  13289. auto res = cli.Post("/post-providers", {}, {}, providers);
  13290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13291. ASSERT_EQ(StatusCode::OK_200, res->status);
  13292. }
  13293. {
  13294. auto res = cli.Post("/post-both", {}, items, providers);
  13295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13296. ASSERT_EQ(StatusCode::OK_200, res->status);
  13297. }
  13298. }
  13299. }
  13300. TEST(MultipartFormDataTest, BadHeader) {
  13301. Server svr;
  13302. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13303. res.set_content("ok", "text/plain");
  13304. });
  13305. thread t = thread([&] { svr.listen(HOST, PORT); });
  13306. auto se = detail::scope_exit([&] {
  13307. svr.stop();
  13308. t.join();
  13309. ASSERT_FALSE(svr.is_running());
  13310. });
  13311. svr.wait_until_ready();
  13312. const std::string body =
  13313. "This is the preamble. It is to be ignored, though it\r\n"
  13314. "is a handy place for composition agents to include an\r\n"
  13315. "explanatory note to non-MIME conformant readers.\r\n"
  13316. "\r\n"
  13317. "\r\n"
  13318. "--simple boundary\r\n"
  13319. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13320. ": BAD...\r\n"
  13321. "\r\n"
  13322. "value1\r\n"
  13323. "--simple boundary\r\n"
  13324. "Content-Disposition: form-data; name=\"field2\"; "
  13325. "filename=\"example.txt\"\r\n"
  13326. "\r\n"
  13327. "value2\r\n"
  13328. "--simple boundary--\r\n"
  13329. "This is the epilogue. It is also to be ignored.\r\n";
  13330. std::string content_type =
  13331. R"(multipart/form-data; boundary="simple boundary")";
  13332. Client cli(HOST, PORT);
  13333. auto res = cli.Post("/post", body, content_type.c_str());
  13334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13335. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13336. }
  13337. TEST(MultipartFormDataTest, WithPreamble) {
  13338. Server svr;
  13339. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13340. res.set_content("ok", "text/plain");
  13341. });
  13342. thread t = thread([&] { svr.listen(HOST, PORT); });
  13343. auto se = detail::scope_exit([&] {
  13344. svr.stop();
  13345. t.join();
  13346. ASSERT_FALSE(svr.is_running());
  13347. });
  13348. svr.wait_until_ready();
  13349. const std::string body =
  13350. "This is the preamble. It is to be ignored, though it\r\n"
  13351. "is a handy place for composition agents to include an\r\n"
  13352. "explanatory note to non-MIME conformant readers.\r\n"
  13353. "\r\n"
  13354. "\r\n"
  13355. "--simple boundary\r\n"
  13356. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13357. "\r\n"
  13358. "value1\r\n"
  13359. "--simple boundary\r\n"
  13360. "Content-Disposition: form-data; name=\"field2\"; "
  13361. "filename=\"example.txt\"\r\n"
  13362. "\r\n"
  13363. "value2\r\n"
  13364. "--simple boundary--\r\n"
  13365. "This is the epilogue. It is also to be ignored.\r\n";
  13366. std::string content_type =
  13367. R"(multipart/form-data; boundary="simple boundary")";
  13368. Client cli(HOST, PORT);
  13369. auto res = cli.Post("/post", body, content_type.c_str());
  13370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13371. EXPECT_EQ(StatusCode::OK_200, res->status);
  13372. }
  13373. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13374. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13375. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13376. const ContentReader &content_reader) {
  13377. if (req.is_multipart_form_data()) {
  13378. std::vector<FormData> items;
  13379. content_reader(
  13380. [&](const FormData &file) {
  13381. items.push_back(file);
  13382. return true;
  13383. },
  13384. [&](const char *data, size_t data_length) {
  13385. items.back().content.append(data, data_length);
  13386. return true;
  13387. });
  13388. EXPECT_TRUE(std::string(items[0].name) == "document");
  13389. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13390. EXPECT_TRUE(items[0].filename == "2MB_data");
  13391. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13392. EXPECT_TRUE(items[1].name == "hello");
  13393. EXPECT_TRUE(items[1].content == "world");
  13394. EXPECT_TRUE(items[1].filename == "");
  13395. EXPECT_TRUE(items[1].content_type == "");
  13396. } else {
  13397. std::string body;
  13398. content_reader([&](const char *data, size_t data_length) {
  13399. body.append(data, data_length);
  13400. return true;
  13401. });
  13402. }
  13403. });
  13404. auto port = svr.bind_to_any_port("localhost");
  13405. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13406. auto se = detail::scope_exit([&] {
  13407. svr.stop();
  13408. t.join();
  13409. ASSERT_FALSE(svr.is_running());
  13410. });
  13411. svr.wait_until_ready();
  13412. {
  13413. std::string data(1024 * 1024 * 2, '.');
  13414. std::stringstream buffer;
  13415. buffer << data;
  13416. SSLClient cli("localhost", port);
  13417. cli.enable_server_certificate_verification(false);
  13418. UploadFormDataItems items{
  13419. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13420. {"hello", "world", "", ""},
  13421. };
  13422. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13424. ASSERT_EQ(StatusCode::OK_200, res->status);
  13425. }
  13426. }
  13427. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13428. std::string data(1024 * 1024 * 2, '&');
  13429. std::stringstream buffer;
  13430. buffer << data;
  13431. Client cli("https://localhost:8080");
  13432. UploadFormDataItems items{
  13433. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13434. {"hello", "world", "", ""},
  13435. };
  13436. for (const char &c : " \t\r\n") {
  13437. auto res =
  13438. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13439. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13440. ASSERT_FALSE(res);
  13441. }
  13442. }
  13443. TEST(MultipartFormDataTest, PutFormData) {
  13444. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13445. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13446. const ContentReader &content_reader) {
  13447. if (req.is_multipart_form_data()) {
  13448. std::vector<FormData> items;
  13449. content_reader(
  13450. [&](const FormData &file) {
  13451. items.push_back(file);
  13452. return true;
  13453. },
  13454. [&](const char *data, size_t data_length) {
  13455. items.back().content.append(data, data_length);
  13456. return true;
  13457. });
  13458. EXPECT_TRUE(std::string(items[0].name) == "document");
  13459. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13460. EXPECT_TRUE(items[0].filename == "2MB_data");
  13461. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13462. EXPECT_TRUE(items[1].name == "hello");
  13463. EXPECT_TRUE(items[1].content == "world");
  13464. EXPECT_TRUE(items[1].filename == "");
  13465. EXPECT_TRUE(items[1].content_type == "");
  13466. } else {
  13467. std::string body;
  13468. content_reader([&](const char *data, size_t data_length) {
  13469. body.append(data, data_length);
  13470. return true;
  13471. });
  13472. }
  13473. });
  13474. auto port = svr.bind_to_any_port("localhost");
  13475. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13476. auto se = detail::scope_exit([&] {
  13477. svr.stop();
  13478. t.join();
  13479. ASSERT_FALSE(svr.is_running());
  13480. });
  13481. svr.wait_until_ready();
  13482. {
  13483. std::string data(1024 * 1024 * 2, '&');
  13484. std::stringstream buffer;
  13485. buffer << data;
  13486. SSLClient cli("localhost", port);
  13487. cli.enable_server_certificate_verification(false);
  13488. UploadFormDataItems items{
  13489. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13490. {"hello", "world", "", ""},
  13491. };
  13492. auto res = cli.Put("/put", items);
  13493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13494. ASSERT_EQ(StatusCode::OK_200, res->status);
  13495. }
  13496. }
  13497. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13498. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13499. svr.Put("/put_customboundary",
  13500. [&](const Request &req, const Response & /*res*/,
  13501. const ContentReader &content_reader) {
  13502. if (req.is_multipart_form_data()) {
  13503. std::vector<FormData> items;
  13504. content_reader(
  13505. [&](const FormData &file) {
  13506. items.push_back(file);
  13507. return true;
  13508. },
  13509. [&](const char *data, size_t data_length) {
  13510. items.back().content.append(data, data_length);
  13511. return true;
  13512. });
  13513. EXPECT_TRUE(std::string(items[0].name) == "document");
  13514. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13515. EXPECT_TRUE(items[0].filename == "2MB_data");
  13516. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13517. EXPECT_TRUE(items[1].name == "hello");
  13518. EXPECT_TRUE(items[1].content == "world");
  13519. EXPECT_TRUE(items[1].filename == "");
  13520. EXPECT_TRUE(items[1].content_type == "");
  13521. } else {
  13522. std::string body;
  13523. content_reader([&](const char *data, size_t data_length) {
  13524. body.append(data, data_length);
  13525. return true;
  13526. });
  13527. }
  13528. });
  13529. auto port = svr.bind_to_any_port("localhost");
  13530. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13531. auto se = detail::scope_exit([&] {
  13532. svr.stop();
  13533. t.join();
  13534. ASSERT_FALSE(svr.is_running());
  13535. });
  13536. svr.wait_until_ready();
  13537. {
  13538. std::string data(1024 * 1024 * 2, '&');
  13539. std::stringstream buffer;
  13540. buffer << data;
  13541. SSLClient cli("localhost", port);
  13542. cli.enable_server_certificate_verification(false);
  13543. UploadFormDataItems items{
  13544. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13545. {"hello", "world", "", ""},
  13546. };
  13547. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13549. ASSERT_EQ(StatusCode::OK_200, res->status);
  13550. }
  13551. }
  13552. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13553. std::string data(1024 * 1024 * 2, '&');
  13554. std::stringstream buffer;
  13555. buffer << data;
  13556. Client cli("https://localhost:8080");
  13557. cli.enable_server_certificate_verification(false);
  13558. UploadFormDataItems items{
  13559. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13560. {"hello", "world", "", ""},
  13561. };
  13562. for (const char &c : " \t\r\n") {
  13563. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13564. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13565. ASSERT_FALSE(res);
  13566. }
  13567. }
  13568. TEST(MultipartFormDataTest, AlternateFilename) {
  13569. auto handled = false;
  13570. Server svr;
  13571. svr.Post("/test", [&](const Request &req, Response &res) {
  13572. ASSERT_EQ(2u, req.form.files.size());
  13573. ASSERT_EQ(1u, req.form.fields.size());
  13574. // Test files
  13575. const auto &file1 = req.form.get_file("file1");
  13576. ASSERT_EQ("file1", file1.name);
  13577. ASSERT_EQ("A.txt", file1.filename);
  13578. ASSERT_EQ("text/plain", file1.content_type);
  13579. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13580. const auto &file2 = req.form.get_file("file2");
  13581. ASSERT_EQ("file2", file2.name);
  13582. ASSERT_EQ("a.html", file2.filename);
  13583. ASSERT_EQ("text/html", file2.content_type);
  13584. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13585. file2.content);
  13586. // Test text field
  13587. const auto &text = req.form.get_field("text");
  13588. ASSERT_EQ("text default", text);
  13589. res.set_content("ok", "text/plain");
  13590. handled = true;
  13591. });
  13592. thread t = thread([&] { svr.listen(HOST, PORT); });
  13593. auto se = detail::scope_exit([&] {
  13594. svr.stop();
  13595. t.join();
  13596. ASSERT_FALSE(svr.is_running());
  13597. ASSERT_TRUE(handled);
  13598. });
  13599. svr.wait_until_ready();
  13600. auto req = "POST /test HTTP/1.1\r\n"
  13601. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13602. "Content-Length: 399\r\n"
  13603. "\r\n"
  13604. "----------\r\n"
  13605. "Content-Disposition: form-data; name=\"text\"\r\n"
  13606. "\r\n"
  13607. "text default\r\n"
  13608. "----------\r\n"
  13609. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13610. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13611. "Content-Type: text/plain\r\n"
  13612. "\r\n"
  13613. "Content of a.txt.\r\n"
  13614. "\r\n"
  13615. "----------\r\n"
  13616. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13617. "\"a.html\"\r\n"
  13618. "Content-Type: text/html\r\n"
  13619. "\r\n"
  13620. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13621. "\r\n"
  13622. "------------\r\n";
  13623. ASSERT_TRUE(send_request(1, req));
  13624. }
  13625. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13626. auto handled = false;
  13627. Server svr;
  13628. svr.Post("/test", [&](const Request &req, Response &res) {
  13629. // Case-insensitive "utf-8''" prefix with a long value
  13630. const auto &file = req.form.get_file("file1");
  13631. ASSERT_EQ("file1", file.name);
  13632. // 8000 chars exercises both the Content-Disposition parser and the
  13633. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13634. // Prior to the fix, std::regex_match on this header would cause O(N)
  13635. // stack recursion in libstdc++, leading to SIGSEGV.
  13636. std::string expected_filename(8000, 'A');
  13637. ASSERT_EQ(expected_filename, file.filename);
  13638. res.set_content("ok", "text/plain");
  13639. handled = true;
  13640. });
  13641. thread t = thread([&] { svr.listen(HOST, PORT); });
  13642. auto se = detail::scope_exit([&] {
  13643. svr.stop();
  13644. t.join();
  13645. ASSERT_FALSE(svr.is_running());
  13646. ASSERT_TRUE(handled);
  13647. });
  13648. svr.wait_until_ready();
  13649. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13650. // Regression test for GHSA-qq6v-r583-3h69
  13651. std::string long_filename(8000, 'A');
  13652. std::string body = "----------\r\n"
  13653. "Content-Disposition: form-data; name=\"file1\"; "
  13654. "filename*=\"Utf-8''" +
  13655. long_filename +
  13656. "\"\r\n"
  13657. "\r\n"
  13658. "hello\r\n"
  13659. "------------\r\n";
  13660. auto req = "POST /test HTTP/1.1\r\n"
  13661. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13662. "Content-Length: " +
  13663. std::to_string(body.size()) + "\r\n\r\n" + body;
  13664. ASSERT_TRUE(send_request(1, req));
  13665. }
  13666. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13667. auto handled = false;
  13668. Server svr;
  13669. svr.Post("/test", [&](const Request &req, Response &) {
  13670. ASSERT_EQ(2u, req.form.fields.size());
  13671. const auto &text1 = req.form.get_field("text1");
  13672. ASSERT_EQ("text1", text1);
  13673. const auto &text2 = req.form.get_field("text2");
  13674. ASSERT_EQ("text2", text2);
  13675. handled = true;
  13676. });
  13677. thread t = thread([&] { svr.listen(HOST, PORT); });
  13678. auto se = detail::scope_exit([&] {
  13679. svr.stop();
  13680. t.join();
  13681. ASSERT_FALSE(svr.is_running());
  13682. ASSERT_TRUE(handled);
  13683. });
  13684. svr.wait_until_ready();
  13685. auto req = "POST /test HTTP/1.1\r\n"
  13686. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13687. "Content-Length: 146\r\n"
  13688. "\r\n----------\r\n"
  13689. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13690. "\r\n"
  13691. "text1"
  13692. "\r\n----------\r\n"
  13693. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13694. "\r\n"
  13695. "text2"
  13696. "\r\n------------";
  13697. std::string response;
  13698. ASSERT_TRUE(send_request(1, req, &response));
  13699. ASSERT_EQ("200", response.substr(9, 3));
  13700. }
  13701. TEST(MultipartFormDataTest, ContentLength) {
  13702. auto handled = false;
  13703. Server svr;
  13704. svr.Post("/test", [&](const Request &req, Response &) {
  13705. ASSERT_EQ(2u, req.form.fields.size());
  13706. const auto &text1 = req.form.get_field("text1");
  13707. ASSERT_EQ("text1", text1);
  13708. const auto &text2 = req.form.get_field("text2");
  13709. ASSERT_EQ("text2", text2);
  13710. handled = true;
  13711. });
  13712. thread t = thread([&] { svr.listen(HOST, PORT); });
  13713. auto se = detail::scope_exit([&] {
  13714. svr.stop();
  13715. t.join();
  13716. ASSERT_FALSE(svr.is_running());
  13717. ASSERT_TRUE(handled);
  13718. });
  13719. svr.wait_until_ready();
  13720. auto req = "POST /test HTTP/1.1\r\n"
  13721. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13722. "Content-Length: 167\r\n"
  13723. "\r\n----------\r\n"
  13724. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13725. "Content-Length: 5\r\n"
  13726. "\r\n"
  13727. "text1"
  13728. "\r\n----------\r\n"
  13729. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13730. "\r\n"
  13731. "text2"
  13732. "\r\n------------\r\n";
  13733. std::string response;
  13734. ASSERT_TRUE(send_request(1, req, &response));
  13735. ASSERT_EQ("200", response.substr(9, 3));
  13736. }
  13737. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13738. auto handled = false;
  13739. Server svr;
  13740. svr.Post("/test", [&](const Request &req, Response &) {
  13741. ASSERT_EQ(2u, req.form.fields.size());
  13742. const auto &text1 = req.form.get_field("text1");
  13743. ASSERT_EQ("text1", text1);
  13744. // TODO: Add header access for text fields if needed
  13745. const auto &text2 = req.form.get_field("text2");
  13746. ASSERT_EQ("text2", text2);
  13747. // TODO: Header access for text fields needs to be implemented
  13748. // auto &headers = it->second.headers;
  13749. // ASSERT_EQ(3U, headers.size());
  13750. // auto custom_header = headers.find("x-whatever");
  13751. // ASSERT_TRUE(custom_header != headers.end());
  13752. // ASSERT_NE("customvalue", custom_header->second);
  13753. // ASSERT_EQ("CustomValue", custom_header->second);
  13754. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13755. handled = true;
  13756. });
  13757. thread t = thread([&] { svr.listen(HOST, PORT); });
  13758. auto se = detail::scope_exit([&] {
  13759. svr.stop();
  13760. t.join();
  13761. ASSERT_FALSE(svr.is_running());
  13762. ASSERT_TRUE(handled);
  13763. });
  13764. svr.wait_until_ready();
  13765. auto req = "POST /test HTTP/1.1\r\n"
  13766. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13767. "Content-Length: 232\r\n"
  13768. "\r\n----------\r\n"
  13769. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13770. "Content-Length: 5\r\n"
  13771. "X-Test: 1\r\n"
  13772. "\r\n"
  13773. "text1"
  13774. "\r\n----------\r\n"
  13775. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13776. "Content-Type: text/plain\r\n"
  13777. "X-Whatever: CustomValue\r\n"
  13778. "\r\n"
  13779. "text2"
  13780. "\r\n------------\r\n"
  13781. "That should be disregarded. Not even read";
  13782. std::string response;
  13783. ASSERT_TRUE(send_request(1, req, &response));
  13784. ASSERT_EQ("200", response.substr(9, 3));
  13785. }
  13786. TEST(MultipartFormDataTest, LargeHeader) {
  13787. auto handled = false;
  13788. Server svr;
  13789. svr.Post("/test", [&](const Request &req, Response &) {
  13790. ASSERT_EQ(1u, req.form.fields.size());
  13791. const auto &text = req.form.get_field("name1");
  13792. ASSERT_EQ("text1", text);
  13793. handled = true;
  13794. });
  13795. thread t = thread([&] { svr.listen(HOST, PORT); });
  13796. auto se = detail::scope_exit([&] {
  13797. svr.stop();
  13798. t.join();
  13799. ASSERT_FALSE(svr.is_running());
  13800. ASSERT_TRUE(handled);
  13801. });
  13802. svr.wait_until_ready();
  13803. auto boundary = std::string("cpp-httplib-multipart-data");
  13804. std::string content = "--" + boundary +
  13805. "\r\n"
  13806. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13807. "\r\n"
  13808. "text1\r\n"
  13809. "--" +
  13810. boundary + "--\r\n";
  13811. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13812. "Content-Type: multipart/form-data;boundary=" +
  13813. boundary +
  13814. "\r\n"
  13815. "Content-Length: " +
  13816. std::to_string(content.size()) +
  13817. "\r\n"
  13818. "Dummy-Header: ";
  13819. std::string header_suffix = "\r\n"
  13820. "\r\n";
  13821. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13822. size_t header_dummy_size =
  13823. read_buff_size -
  13824. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13825. auto header_dummy = std::string(header_dummy_size, '@');
  13826. auto req = header_prefix + header_dummy + header_suffix + content;
  13827. std::string response;
  13828. ASSERT_TRUE(send_request(1, req, &response));
  13829. ASSERT_EQ("200", response.substr(9, 3));
  13830. }
  13831. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13832. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13833. // (not chunked Transfer-Encoding) after the streaming refactor.
  13834. auto handled = false;
  13835. Server svr;
  13836. svr.Post("/upload", [&](const Request &req, Response &res) {
  13837. auto cl_it = req.headers.find("Content-Length");
  13838. EXPECT_TRUE(cl_it != req.headers.end());
  13839. auto te_it = req.headers.find("Transfer-Encoding");
  13840. EXPECT_TRUE(te_it == req.headers.end());
  13841. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13842. res.set_content("ok", "text/plain");
  13843. handled = true;
  13844. });
  13845. auto port = svr.bind_to_any_port(HOST);
  13846. auto t = thread([&] { svr.listen_after_bind(); });
  13847. auto se = detail::scope_exit([&] {
  13848. svr.stop();
  13849. t.join();
  13850. ASSERT_FALSE(svr.is_running());
  13851. ASSERT_TRUE(handled);
  13852. });
  13853. svr.wait_until_ready();
  13854. UploadFormDataItems items = {
  13855. {"field1", "hello", "", "text/plain"},
  13856. {"file1", "world", "test.txt", "application/octet-stream"},
  13857. };
  13858. Client cli(HOST, port);
  13859. auto res = cli.Post("/upload", {}, items);
  13860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13861. EXPECT_EQ(StatusCode::OK_200, res->status);
  13862. }
  13863. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13864. // Verify that make_multipart_content_provider coalesces many small segments
  13865. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13866. constexpr size_t kItemCount = 1000;
  13867. UploadFormDataItems items;
  13868. items.reserve(kItemCount);
  13869. for (size_t i = 0; i < kItemCount; i++) {
  13870. items.push_back(
  13871. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13872. }
  13873. const std::string boundary = "----test-boundary";
  13874. auto content_length = detail::get_multipart_content_length(items, boundary);
  13875. auto provider = detail::make_multipart_content_provider(items, boundary);
  13876. // Drive the provider the same way write_content_with_progress does
  13877. size_t write_count = 0;
  13878. size_t total_bytes = 0;
  13879. DataSink sink;
  13880. size_t offset = 0;
  13881. sink.write = [&](const char *d, size_t l) -> bool {
  13882. (void)d;
  13883. write_count++;
  13884. total_bytes += l;
  13885. offset += l;
  13886. return true;
  13887. };
  13888. sink.is_writable = []() -> bool { return true; };
  13889. while (offset < content_length) {
  13890. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13891. }
  13892. EXPECT_EQ(content_length, total_bytes);
  13893. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13894. // With buffering into 64KB blocks, write_count should be much smaller.
  13895. auto segment_count = 3 * kItemCount + 1;
  13896. EXPECT_LT(write_count, segment_count / 10);
  13897. }
  13898. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13899. // Integration test: send many UploadFormDataItems and verify the server
  13900. // receives all of them correctly (#2410).
  13901. constexpr size_t kItemCount = 500;
  13902. auto handled = false;
  13903. Server svr;
  13904. svr.Post("/upload", [&](const Request &req, Response &res) {
  13905. EXPECT_EQ(kItemCount, req.form.fields.size());
  13906. for (size_t i = 0; i < kItemCount; i++) {
  13907. auto key = "field" + std::to_string(i);
  13908. auto val = "value" + std::to_string(i);
  13909. auto it = req.form.fields.find(key);
  13910. if (it != req.form.fields.end()) {
  13911. EXPECT_EQ(val, it->second.content);
  13912. } else {
  13913. ADD_FAILURE() << "Missing field: " << key;
  13914. }
  13915. }
  13916. res.set_content("ok", "text/plain");
  13917. handled = true;
  13918. });
  13919. auto port = svr.bind_to_any_port(HOST);
  13920. auto t = thread([&] { svr.listen_after_bind(); });
  13921. auto se = detail::scope_exit([&] {
  13922. svr.stop();
  13923. t.join();
  13924. ASSERT_FALSE(svr.is_running());
  13925. ASSERT_TRUE(handled);
  13926. });
  13927. svr.wait_until_ready();
  13928. UploadFormDataItems items;
  13929. items.reserve(kItemCount);
  13930. for (size_t i = 0; i < kItemCount; i++) {
  13931. items.push_back(
  13932. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13933. }
  13934. Client cli(HOST, port);
  13935. auto res = cli.Post("/upload", items);
  13936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13937. EXPECT_EQ(StatusCode::OK_200, res->status);
  13938. }
  13939. TEST(MultipartFormDataTest, MakeFileProvider) {
  13940. // Verify make_file_provider sends a file's contents correctly.
  13941. const std::string file_content(4096, 'Z');
  13942. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13943. {
  13944. std::ofstream ofs(tmp_path, std::ios::binary);
  13945. ofs.write(file_content.data(),
  13946. static_cast<std::streamsize>(file_content.size()));
  13947. }
  13948. auto handled = false;
  13949. Server svr;
  13950. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13951. const ContentReader &content_reader) {
  13952. ASSERT_TRUE(req.is_multipart_form_data());
  13953. std::vector<FormData> items;
  13954. content_reader(
  13955. [&](const FormData &file) {
  13956. items.push_back(file);
  13957. return true;
  13958. },
  13959. [&](const char *data, size_t data_length) {
  13960. items.back().content.append(data, data_length);
  13961. return true;
  13962. });
  13963. ASSERT_EQ(1u, items.size());
  13964. EXPECT_EQ("myfile", items[0].name);
  13965. EXPECT_EQ("data.bin", items[0].filename);
  13966. EXPECT_EQ("application/octet-stream", items[0].content_type);
  13967. EXPECT_EQ(file_content, items[0].content);
  13968. handled = true;
  13969. });
  13970. auto port = svr.bind_to_any_port(HOST);
  13971. auto t = thread([&] { svr.listen_after_bind(); });
  13972. auto se = detail::scope_exit([&] {
  13973. svr.stop();
  13974. t.join();
  13975. ASSERT_FALSE(svr.is_running());
  13976. ASSERT_TRUE(handled);
  13977. std::remove(tmp_path.c_str());
  13978. });
  13979. svr.wait_until_ready();
  13980. FormDataProviderItems providers;
  13981. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  13982. "application/octet-stream"));
  13983. Client cli(HOST, port);
  13984. auto res = cli.Post("/upload", {}, {}, providers);
  13985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13986. EXPECT_EQ(StatusCode::OK_200, res->status);
  13987. }
  13988. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  13989. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  13990. // (100) headers is rejected with a 400 Bad Request response.
  13991. Server svr;
  13992. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13993. res.set_content("ok", "text/plain");
  13994. });
  13995. thread t = thread([&] { svr.listen(HOST, PORT); });
  13996. auto se = detail::scope_exit([&] {
  13997. svr.stop();
  13998. t.join();
  13999. ASSERT_FALSE(svr.is_running());
  14000. });
  14001. svr.wait_until_ready();
  14002. // Build a multipart part with 101 custom headers (exceeding
  14003. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14004. std::stringstream body;
  14005. body << "--simpleboundary\r\n"
  14006. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14007. for (int i = 0; i < 101; i++) {
  14008. body << "X-Custom-Header-" << i << ": value\r\n";
  14009. }
  14010. body << "\r\n"
  14011. << "value1\r\n"
  14012. << "--simpleboundary--\r\n";
  14013. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14014. Client cli(HOST, PORT);
  14015. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14017. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14018. }
  14019. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14020. // A body that never contains the declared boundary must not be accumulated
  14021. // while the parser waits for it. Buffering it would also make every read
  14022. // rescan everything seen so far, which is quadratic in the body size.
  14023. Server svr;
  14024. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14025. res.set_content("ok", "text/plain");
  14026. });
  14027. auto port = svr.bind_to_any_port(HOST);
  14028. thread t = thread([&] { svr.listen_after_bind(); });
  14029. auto se = detail::scope_exit([&] {
  14030. svr.stop();
  14031. t.join();
  14032. ASSERT_FALSE(svr.is_running());
  14033. });
  14034. svr.wait_until_ready();
  14035. Client cli(HOST, port);
  14036. cli.set_read_timeout(60, 0);
  14037. cli.set_write_timeout(60, 0);
  14038. // '-' is the worst case: it matches the first character of the boundary, so
  14039. // every position has to be checked against it.
  14040. auto post_dashes = [&](size_t size) {
  14041. const std::string body(size, '-');
  14042. auto start = std::chrono::steady_clock::now();
  14043. auto res =
  14044. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14045. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14046. std::chrono::steady_clock::now() - start)
  14047. .count();
  14048. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14049. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14050. return ms;
  14051. };
  14052. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14053. // Windows.
  14054. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14055. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14056. // Comparing the two sizes rather than checking an absolute duration keeps
  14057. // this meaningful across build types and CI load, both of which move the
  14058. // absolute numbers by more than an order of magnitude. Four times the bytes
  14059. // costs about four times the time when parsing is linear, and about sixteen
  14060. // times when the body is buffered and rescanned.
  14061. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14062. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14063. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14064. << "ms, which suggests the body is being buffered and rescanned";
  14065. }
  14066. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14067. // A boundary can only be followed by CRLF or by "--", so anything else is
  14068. // malformed no matter what comes next. The parser must say so right away
  14069. // instead of buffering the rest of the declared body.
  14070. Server svr;
  14071. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14072. res.set_content("ok", "text/plain");
  14073. });
  14074. auto port = svr.bind_to_any_port(HOST);
  14075. thread t = thread([&] { svr.listen_after_bind(); });
  14076. auto se = detail::scope_exit([&] {
  14077. svr.stop();
  14078. t.join();
  14079. ASSERT_FALSE(svr.is_running());
  14080. });
  14081. svr.wait_until_ready();
  14082. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14083. // buffers instead of failing would still be waiting for the remaining bytes.
  14084. const std::string body = "--zzzz\r\n"
  14085. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14086. "\r\n"
  14087. "text1"
  14088. "\r\n--zzzzXX";
  14089. const std::string req = "POST /post HTTP/1.1\r\n"
  14090. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14091. "Content-Length: 1048576\r\n"
  14092. "\r\n" +
  14093. body;
  14094. std::string response;
  14095. ASSERT_TRUE(send_request(3, req, &response, port));
  14096. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14097. EXPECT_EQ("400", response.substr(9, 3));
  14098. }
  14099. // Posts a multipart body split into two writes, so that the server sees the
  14100. // split at whatever offset the caller chose, and expects the single "text1"
  14101. // field to come through.
  14102. static void expect_split_multipart_ok(const std::string &body1,
  14103. const std::string &body2) {
  14104. auto handled = false;
  14105. Server svr;
  14106. svr.Post("/post", [&](const Request &req, Response &) {
  14107. EXPECT_EQ(1u, req.form.fields.size());
  14108. EXPECT_EQ("text1", req.form.get_field("text1"));
  14109. handled = true;
  14110. });
  14111. auto port = svr.bind_to_any_port(HOST);
  14112. thread t = thread([&] { svr.listen_after_bind(); });
  14113. auto se = detail::scope_exit([&] {
  14114. svr.stop();
  14115. t.join();
  14116. ASSERT_FALSE(svr.is_running());
  14117. ASSERT_TRUE(handled);
  14118. });
  14119. svr.wait_until_ready();
  14120. // "Connection: close" makes the server close once it has answered, so the
  14121. // response drain ends immediately instead of idling until the read timeout.
  14122. const std::string head =
  14123. "POST /post HTTP/1.1\r\n"
  14124. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14125. "Connection: close\r\n"
  14126. "Content-Length: " +
  14127. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14128. std::string response;
  14129. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14130. ASSERT_GE(response.size(), 12u) << "no response";
  14131. EXPECT_EQ("200", response.substr(9, 3));
  14132. }
  14133. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14134. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14135. // ignored, including when it does not arrive in the same read as the
  14136. // close-delimiter itself.
  14137. expect_split_multipart_ok("--zzzz\r\n"
  14138. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14139. "\r\n"
  14140. "text1"
  14141. "\r\n--zzzz--",
  14142. "\r\nthis epilogue must be ignored\r\n");
  14143. }
  14144. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14145. // The initial boundary may be preceded by a preamble of any length and may
  14146. // straddle a read boundary. Discarding data while waiting for it must not
  14147. // throw away a partial boundary sitting at the end of the buffer.
  14148. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14149. "zz\r\n"
  14150. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14151. "\r\n"
  14152. "text1"
  14153. "\r\n--zzzz--\r\n");
  14154. }
  14155. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14156. // The received boundary was only checked for being non-empty, so it could be
  14157. // as long as a header is allowed to be. The parser scans the body for
  14158. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14159. // costs a nearly full comparison at nearly every position, making the
  14160. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14161. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14162. Server svr;
  14163. svr.Post("/post", [](const Request &req, Response &res) {
  14164. EXPECT_EQ(1u, req.form.fields.size());
  14165. EXPECT_EQ("text1", req.form.get_field("text1"));
  14166. res.set_content("ok", "text/plain");
  14167. });
  14168. auto port = svr.bind_to_any_port(HOST);
  14169. thread t = thread([&] { svr.listen_after_bind(); });
  14170. auto se = detail::scope_exit([&] {
  14171. svr.stop();
  14172. t.join();
  14173. ASSERT_FALSE(svr.is_running());
  14174. });
  14175. svr.wait_until_ready();
  14176. Client cli(HOST, port);
  14177. auto post_with_boundary_of_length = [&](size_t len) {
  14178. const std::string boundary(len, 'a');
  14179. const std::string body =
  14180. "--" + boundary +
  14181. "\r\n"
  14182. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14183. "\r\n"
  14184. "text1"
  14185. "\r\n--" +
  14186. boundary + "--\r\n";
  14187. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14188. };
  14189. auto res = post_with_boundary_of_length(70);
  14190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14191. EXPECT_EQ(StatusCode::OK_200, res->status);
  14192. res = post_with_boundary_of_length(71);
  14193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14194. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14195. }
  14196. TEST(MakeFileBodyTest, Basic) {
  14197. const std::string file_content(4096, 'Z');
  14198. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14199. {
  14200. std::ofstream ofs(tmp_path, std::ios::binary);
  14201. ofs.write(file_content.data(),
  14202. static_cast<std::streamsize>(file_content.size()));
  14203. }
  14204. auto handled = false;
  14205. Server svr;
  14206. svr.Post("/upload", [&](const Request &req, Response &res) {
  14207. EXPECT_EQ(file_content, req.body);
  14208. handled = true;
  14209. res.status = StatusCode::OK_200;
  14210. });
  14211. auto port = svr.bind_to_any_port(HOST);
  14212. auto t = thread([&] { svr.listen_after_bind(); });
  14213. auto se = detail::scope_exit([&] {
  14214. svr.stop();
  14215. t.join();
  14216. ASSERT_FALSE(svr.is_running());
  14217. ASSERT_TRUE(handled);
  14218. std::remove(tmp_path.c_str());
  14219. });
  14220. svr.wait_until_ready();
  14221. auto fb = make_file_body(tmp_path);
  14222. ASSERT_GT(fb.first, 0u);
  14223. Client cli(HOST, port);
  14224. auto res =
  14225. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14227. EXPECT_EQ(StatusCode::OK_200, res->status);
  14228. }
  14229. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14230. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14231. {
  14232. std::ofstream ofs(path, std::ios::binary);
  14233. const std::string content(100, 'A');
  14234. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14235. }
  14236. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14237. auto body = make_file_body(path);
  14238. ASSERT_EQ(100u, body.first);
  14239. ASSERT_TRUE(static_cast<bool>(body.second));
  14240. // Rewritten shorter after its length was measured - and, on a server, after
  14241. // that length has already gone out as Content-Length.
  14242. {
  14243. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14244. const std::string content(10, 'A');
  14245. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14246. }
  14247. std::string written;
  14248. DataSink sink;
  14249. sink.write = [&](const char *d, size_t l) {
  14250. written.append(d, l);
  14251. return true;
  14252. };
  14253. // The provider has to report failure. write_content_with_progress() advances
  14254. // its offset only by what was written, so a provider that returns true
  14255. // without completing the length it promised is called again straight away,
  14256. // and again.
  14257. EXPECT_FALSE(body.second(0, body.first, sink));
  14258. EXPECT_EQ(std::string(10, 'A'), written);
  14259. }
  14260. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14261. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14262. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14263. {
  14264. std::ofstream ofs(path, std::ios::binary);
  14265. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14266. }
  14267. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14268. auto body = make_file_body(path);
  14269. ASSERT_EQ(content.size(), body.first);
  14270. ASSERT_TRUE(static_cast<bool>(body.second));
  14271. std::string written;
  14272. DataSink sink;
  14273. sink.write = [&](const char *d, size_t l) {
  14274. written.append(d, l);
  14275. return true;
  14276. };
  14277. EXPECT_TRUE(body.second(0, body.first, sink));
  14278. EXPECT_EQ(content, written);
  14279. }
  14280. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14281. static constexpr unsigned int number_of_tasks{1000000};
  14282. std::atomic_uint count{0};
  14283. std::unique_ptr<TaskQueue> task_queue{
  14284. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14285. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14286. auto queued = task_queue->enqueue(
  14287. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14288. EXPECT_TRUE(queued);
  14289. }
  14290. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14291. task_queue->shutdown();
  14292. #else
  14293. EXPECT_NO_THROW(task_queue->shutdown());
  14294. #endif
  14295. EXPECT_EQ(number_of_tasks, count.load());
  14296. }
  14297. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14298. static constexpr unsigned int number_of_tasks{1000000};
  14299. static constexpr unsigned int qlimit{2};
  14300. unsigned int queued_count{0};
  14301. std::atomic_uint count{0};
  14302. std::unique_ptr<TaskQueue> task_queue{
  14303. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14304. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14305. if (task_queue->enqueue(
  14306. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14307. queued_count++;
  14308. }
  14309. }
  14310. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14311. task_queue->shutdown();
  14312. #else
  14313. EXPECT_NO_THROW(task_queue->shutdown());
  14314. #endif
  14315. EXPECT_EQ(queued_count, count.load());
  14316. EXPECT_TRUE(queued_count <= number_of_tasks);
  14317. EXPECT_TRUE(queued_count >= qlimit);
  14318. }
  14319. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14320. // Use a short idle timeout so a dynamic thread spawns, times out and
  14321. // exits during the test, and the pool keeps working afterwards.
  14322. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14323. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14324. /*idle_timeout_sec=*/1}};
  14325. std::atomic_uint count{0};
  14326. std::condition_variable cv;
  14327. std::mutex mtx;
  14328. bool release = false;
  14329. // Block the base thread so the second task spawns a dynamic thread.
  14330. EXPECT_TRUE(task_queue->enqueue([&] {
  14331. std::unique_lock<std::mutex> lock(mtx);
  14332. while (!release) {
  14333. cv.wait(lock);
  14334. }
  14335. count++;
  14336. }));
  14337. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14338. // Let the dynamic thread finish its task and exceed the idle timeout.
  14339. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14340. {
  14341. std::unique_lock<std::mutex> lock(mtx);
  14342. release = true;
  14343. }
  14344. cv.notify_all();
  14345. // The pool must still accept and run tasks after the dynamic thread exited.
  14346. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14347. task_queue->shutdown();
  14348. EXPECT_EQ(3u, count.load());
  14349. }
  14350. TEST(TaskQueueTest, MaxQueuedRequests) {
  14351. static constexpr unsigned int qlimit{3};
  14352. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14353. std::condition_variable sem_cv;
  14354. std::mutex sem_mtx;
  14355. int credits = 0;
  14356. bool queued;
  14357. /* Fill up the queue with tasks that will block until we give them credits to
  14358. * complete. */
  14359. for (unsigned int n = 0; n <= qlimit;) {
  14360. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14361. std::unique_lock<std::mutex> lock(sem_mtx);
  14362. while (credits <= 0) {
  14363. sem_cv.wait(lock);
  14364. }
  14365. /* Consume the credit and signal the test code if they are all gone. */
  14366. if (--credits == 0) { sem_cv.notify_one(); }
  14367. });
  14368. if (n < qlimit) {
  14369. /* The first qlimit enqueues must succeed. */
  14370. EXPECT_TRUE(queued);
  14371. } else {
  14372. /* The last one will succeed only when the worker thread
  14373. * starts and dequeues the first blocking task. Although
  14374. * not necessary for the correctness of this test, we sleep for
  14375. * a short while to avoid busy waiting. */
  14376. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14377. }
  14378. if (queued) { n++; }
  14379. }
  14380. /* Further enqueues must fail since the queue is full. */
  14381. for (auto i = 0; i < 4; i++) {
  14382. queued = task_queue->enqueue([] {});
  14383. EXPECT_FALSE(queued);
  14384. }
  14385. /* Give the credits to allow the previous tasks to complete. */
  14386. {
  14387. std::unique_lock<std::mutex> lock(sem_mtx);
  14388. credits += qlimit + 1;
  14389. }
  14390. sem_cv.notify_all();
  14391. /* Wait for all the credits to be consumed. */
  14392. {
  14393. std::unique_lock<std::mutex> lock(sem_mtx);
  14394. while (credits > 0) {
  14395. sem_cv.wait(lock);
  14396. }
  14397. }
  14398. /* Check that we are able again to enqueue at least qlimit tasks. */
  14399. for (unsigned int i = 0; i < qlimit; i++) {
  14400. queued = task_queue->enqueue([] {});
  14401. EXPECT_TRUE(queued);
  14402. }
  14403. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14404. task_queue->shutdown();
  14405. #else
  14406. EXPECT_NO_THROW(task_queue->shutdown());
  14407. #endif
  14408. }
  14409. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14410. Server svr;
  14411. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14412. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14413. });
  14414. svr.Get("/hello", [](const Request &req, Response &res) {
  14415. res.set_content(req.get_param_value("key"), "text/plain");
  14416. });
  14417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14418. auto se = detail::scope_exit([&] {
  14419. svr.stop();
  14420. thread.join();
  14421. ASSERT_FALSE(svr.is_running());
  14422. });
  14423. svr.wait_until_ready();
  14424. {
  14425. Client cli(HOST, PORT);
  14426. cli.set_follow_location(true);
  14427. auto res = cli.Get("/");
  14428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14429. EXPECT_EQ(StatusCode::OK_200, res->status);
  14430. EXPECT_EQ("val&key2=val2", res->body);
  14431. }
  14432. }
  14433. #endif
  14434. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14435. Server svr;
  14436. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14437. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14438. });
  14439. svr.Get("/hello", [](const Request &req, Response &res) {
  14440. res.set_content(req.get_param_value("key"), "text/plain");
  14441. });
  14442. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14443. auto se = detail::scope_exit([&] {
  14444. svr.stop();
  14445. thread.join();
  14446. ASSERT_FALSE(svr.is_running());
  14447. });
  14448. svr.wait_until_ready();
  14449. {
  14450. Client cli(HOST, PORT);
  14451. cli.set_follow_location(true);
  14452. auto res = cli.Get("/");
  14453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14454. EXPECT_EQ(StatusCode::OK_200, res->status);
  14455. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14456. }
  14457. }
  14458. TEST(RedirectTest, RedirectWithPlusInPath) {
  14459. Server svr;
  14460. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14461. res.set_redirect("/a+b");
  14462. });
  14463. // Route pattern uses regex; escape + as \\+
  14464. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14465. res.set_content(req.path, "text/plain");
  14466. });
  14467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14468. auto se = detail::scope_exit([&] {
  14469. svr.stop();
  14470. thread.join();
  14471. ASSERT_FALSE(svr.is_running());
  14472. });
  14473. svr.wait_until_ready();
  14474. {
  14475. Client cli(HOST, PORT);
  14476. cli.set_follow_location(true);
  14477. auto res = cli.Get("/");
  14478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14479. EXPECT_EQ(StatusCode::OK_200, res->status);
  14480. EXPECT_EQ("/a+b", res->body);
  14481. }
  14482. }
  14483. TEST(RedirectTest, ResolveRelativeLocation) {
  14484. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14485. const std::vector<std::pair<std::string, std::string>> cases = {
  14486. {"g", "/b/c/g"},
  14487. {"./g", "/b/c/g"},
  14488. {"g/", "/b/c/g/"},
  14489. {"?y", "/b/c/d;p?y"},
  14490. {"g?y", "/b/c/g?y"},
  14491. {"#s", "/b/c/d;p?q#s"},
  14492. {"g#s", "/b/c/g#s"},
  14493. {"g?y#s", "/b/c/g?y#s"},
  14494. {";x", "/b/c/;x"},
  14495. {"g;x", "/b/c/g;x"},
  14496. {".", "/b/c/"},
  14497. {"./", "/b/c/"},
  14498. {"..", "/b/"},
  14499. {"../", "/b/"},
  14500. {"../g", "/b/g"},
  14501. {"../..", "/"},
  14502. {"../../", "/"},
  14503. {"../../g", "/g"},
  14504. {"../../../g", "/g"},
  14505. {"g.", "/b/c/g."},
  14506. {".g", "/b/c/.g"},
  14507. {"g..", "/b/c/g.."},
  14508. {"..g", "/b/c/..g"},
  14509. {"./../g", "/b/g"},
  14510. {"./g/.", "/b/c/g/"},
  14511. {"g/./h", "/b/c/g/h"},
  14512. {"g/../h", "/b/c/h"},
  14513. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14514. {"g;x=1/../y", "/b/c/y"},
  14515. {"g?y/./x", "/b/c/g?y/./x"},
  14516. {"g#s/../x", "/b/c/g#s/../x"},
  14517. // Not relative-path references, so left for parse_url.
  14518. {"/g", "/g"},
  14519. {"//g", "//g"},
  14520. {"http://g/x", "http://g/x"},
  14521. {"g:h", "g:h"},
  14522. };
  14523. for (const auto &c : cases) {
  14524. EXPECT_EQ(c.second,
  14525. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  14526. << c.first;
  14527. }
  14528. }
  14529. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  14530. Server svr;
  14531. svr.Get("/dir/page", [](const Request &req, Response &res) {
  14532. res.set_redirect(req.get_param_value("to"));
  14533. });
  14534. svr.Get("/dir/next", [](const Request &req, Response &res) {
  14535. res.set_content(req.target, "text/plain");
  14536. });
  14537. svr.Get("/other", [](const Request &req, Response &res) {
  14538. res.set_content(req.target, "text/plain");
  14539. });
  14540. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14541. auto se = detail::scope_exit([&] {
  14542. svr.stop();
  14543. thread.join();
  14544. ASSERT_FALSE(svr.is_running());
  14545. });
  14546. svr.wait_until_ready();
  14547. const std::vector<std::pair<std::string, std::string>> cases = {
  14548. {"next", "/dir/next"},
  14549. {"./next?x=1", "/dir/next?x=1"},
  14550. {"../other", "/other"},
  14551. };
  14552. for (const auto &c : cases) {
  14553. Client cli(HOST, PORT);
  14554. cli.set_follow_location(true);
  14555. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  14556. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  14557. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  14558. EXPECT_EQ(c.second, res->body) << c.first;
  14559. }
  14560. }
  14561. #ifdef CPPHTTPLIB_SSL_ENABLED
  14562. TEST(RedirectTest, Issue2185_Online) {
  14563. SSLClient client("github.com");
  14564. client.set_follow_location(true);
  14565. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14566. "Coollab-Windows.zip");
  14567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14568. EXPECT_EQ(StatusCode::OK_200, res->status);
  14569. EXPECT_EQ(9920427U, res->body.size());
  14570. }
  14571. #endif
  14572. TEST(VulnerabilityTest, CRLFInjection) {
  14573. Server svr;
  14574. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14575. res.set_content("Hello 1", "text/plain");
  14576. });
  14577. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14578. res.set_content("Hello 2", "text/plain");
  14579. });
  14580. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14581. res.set_content("Hello 3", "text/plain");
  14582. });
  14583. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14584. res.set_content("Hello 4", "text/plain");
  14585. });
  14586. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14587. for (const auto &x : req.headers) {
  14588. auto key = x.first;
  14589. EXPECT_STRNE("evil", key.c_str());
  14590. }
  14591. });
  14592. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14593. auto se = detail::scope_exit([&] {
  14594. svr.stop();
  14595. thread.join();
  14596. ASSERT_FALSE(svr.is_running());
  14597. });
  14598. svr.wait_until_ready();
  14599. {
  14600. Client cli(HOST, PORT);
  14601. cli.Post("/test1", "A=B",
  14602. "application/x-www-form-urlencoded\r\nevil: hello1");
  14603. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14604. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14605. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14606. }
  14607. }
  14608. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14609. auto server_thread = std::thread([] {
  14610. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14611. default_socket_options(srv);
  14612. sockaddr_in addr{};
  14613. addr.sin_family = AF_INET;
  14614. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14615. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14616. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14617. ::listen(srv, 1);
  14618. sockaddr_in cli_addr{};
  14619. socklen_t cli_len = sizeof(cli_addr);
  14620. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14621. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14622. std::string buf_all;
  14623. char buf[2048];
  14624. ssize_t n;
  14625. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14626. buf_all.append(buf, static_cast<size_t>(n));
  14627. size_t pos;
  14628. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14629. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14630. auto e = request_block.find("\r\n");
  14631. if (e != std::string::npos) {
  14632. auto request_line = request_block.substr(0, e);
  14633. std::string msg =
  14634. "CRLF injection detected in request line: '" + request_line + "'";
  14635. EXPECT_FALSE(true) << msg;
  14636. }
  14637. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14638. ::send(cli,
  14639. #ifdef _WIN32
  14640. static_cast<const char *>(resp.c_str()),
  14641. static_cast<int>(resp.size()),
  14642. #else
  14643. resp.c_str(), resp.size(),
  14644. #endif
  14645. 0);
  14646. buf_all.erase(0, pos + 4);
  14647. }
  14648. }
  14649. detail::close_socket(cli);
  14650. detail::close_socket(srv);
  14651. });
  14652. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14653. auto cli = Client("127.0.0.1", PORT + 1);
  14654. auto headers = Headers{
  14655. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14656. {"Connection", "keep-alive"}};
  14657. auto res = cli.Get("/hi", headers);
  14658. EXPECT_FALSE(res);
  14659. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14660. server_thread.join();
  14661. }
  14662. // A request rejected before any byte reaches the socket must fail right away
  14663. // instead of waiting for a response the server will never send.
  14664. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  14665. // The kernel completes the TCP handshake from the listen backlog, so the
  14666. // client connects, but nothing ever reads, responds or closes.
  14667. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14668. default_socket_options(srv);
  14669. sockaddr_in addr{};
  14670. addr.sin_family = AF_INET;
  14671. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14672. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14673. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14674. ASSERT_EQ(0, ::listen(srv, 8));
  14675. auto cli = Client("127.0.0.1", PORT + 1);
  14676. cli.set_read_timeout(10, 0);
  14677. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  14678. return std::chrono::duration_cast<std::chrono::milliseconds>(
  14679. std::chrono::steady_clock::now() - start)
  14680. .count();
  14681. };
  14682. {
  14683. Request req;
  14684. req.method = "GE T";
  14685. req.path = "/";
  14686. auto start = std::chrono::steady_clock::now();
  14687. auto res = cli.send(req);
  14688. EXPECT_FALSE(res);
  14689. EXPECT_EQ(Error::Write, res.error());
  14690. EXPECT_LT(elapsed_ms(start), 1000);
  14691. }
  14692. {
  14693. auto start = std::chrono::steady_clock::now();
  14694. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  14695. EXPECT_FALSE(res);
  14696. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14697. EXPECT_LT(elapsed_ms(start), 1000);
  14698. }
  14699. EXPECT_FALSE(cli.is_socket_open());
  14700. detail::close_socket(srv);
  14701. }
  14702. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  14703. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14704. default_socket_options(srv);
  14705. sockaddr_in addr{};
  14706. addr.sin_family = AF_INET;
  14707. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14708. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14709. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14710. ASSERT_EQ(0, ::listen(srv, 1));
  14711. std::string received;
  14712. auto server_thread = std::thread([&] {
  14713. auto sock = ::accept(srv, nullptr, nullptr);
  14714. if (sock == INVALID_SOCKET) { return; }
  14715. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  14716. char buf[2048];
  14717. ssize_t n;
  14718. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  14719. received.append(buf, static_cast<size_t>(n));
  14720. }
  14721. detail::close_socket(sock);
  14722. });
  14723. {
  14724. auto cli = Client("127.0.0.1", PORT + 1);
  14725. // "Z" sorts after the default headers, so writing straight to the socket
  14726. // would have sent the request line and those headers before the rejection.
  14727. auto handle =
  14728. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  14729. EXPECT_FALSE(handle.is_valid());
  14730. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  14731. }
  14732. server_thread.join();
  14733. detail::close_socket(srv);
  14734. EXPECT_TRUE(received.empty()) << received;
  14735. }
  14736. TEST(PathParamsTest, StaticMatch) {
  14737. const auto pattern = "/users/all";
  14738. detail::PathParamsMatcher matcher(pattern);
  14739. Request request;
  14740. request.path = "/users/all";
  14741. ASSERT_TRUE(matcher.match(request));
  14742. std::unordered_map<std::string, std::string> expected_params = {};
  14743. EXPECT_EQ(request.path_params, expected_params);
  14744. }
  14745. TEST(PathParamsTest, StaticMismatch) {
  14746. const auto pattern = "/users/all";
  14747. detail::PathParamsMatcher matcher(pattern);
  14748. Request request;
  14749. request.path = "/users/1";
  14750. ASSERT_FALSE(matcher.match(request));
  14751. }
  14752. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14753. const auto pattern = "/users/:id/subscriptions";
  14754. detail::PathParamsMatcher matcher(pattern);
  14755. Request request;
  14756. request.path = "/users/42/subscriptions";
  14757. ASSERT_TRUE(matcher.match(request));
  14758. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14759. EXPECT_EQ(request.path_params, expected_params);
  14760. }
  14761. TEST(PathParamsTest, SingleParamInTheEnd) {
  14762. const auto pattern = "/users/:id";
  14763. detail::PathParamsMatcher matcher(pattern);
  14764. Request request;
  14765. request.path = "/users/24";
  14766. ASSERT_TRUE(matcher.match(request));
  14767. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14768. EXPECT_EQ(request.path_params, expected_params);
  14769. }
  14770. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14771. const auto pattern = "/users/:id/";
  14772. detail::PathParamsMatcher matcher(pattern);
  14773. Request request;
  14774. request.path = "/users/42/";
  14775. ASSERT_TRUE(matcher.match(request));
  14776. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14777. EXPECT_EQ(request.path_params, expected_params);
  14778. }
  14779. TEST(PathParamsTest, EmptyParam) {
  14780. const auto pattern = "/users/:id/";
  14781. detail::PathParamsMatcher matcher(pattern);
  14782. Request request;
  14783. request.path = "/users//";
  14784. ASSERT_TRUE(matcher.match(request));
  14785. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14786. EXPECT_EQ(request.path_params, expected_params);
  14787. }
  14788. TEST(PathParamsTest, FragmentMismatch) {
  14789. const auto pattern = "/users/:id/";
  14790. detail::PathParamsMatcher matcher(pattern);
  14791. Request request;
  14792. request.path = "/admins/24/";
  14793. ASSERT_FALSE(matcher.match(request));
  14794. }
  14795. TEST(PathParamsTest, ExtraFragments) {
  14796. const auto pattern = "/users/:id";
  14797. detail::PathParamsMatcher matcher(pattern);
  14798. Request request;
  14799. request.path = "/users/42/subscriptions";
  14800. ASSERT_FALSE(matcher.match(request));
  14801. }
  14802. TEST(PathParamsTest, MissingTrailingParam) {
  14803. const auto pattern = "/users/:id";
  14804. detail::PathParamsMatcher matcher(pattern);
  14805. Request request;
  14806. request.path = "/users";
  14807. ASSERT_FALSE(matcher.match(request));
  14808. }
  14809. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14810. const auto pattern = "/users/:id/subscriptions";
  14811. detail::PathParamsMatcher matcher(pattern);
  14812. Request request;
  14813. request.path = "/users/subscriptions";
  14814. ASSERT_FALSE(matcher.match(request));
  14815. }
  14816. TEST(PathParamsTest, MultipleParams) {
  14817. const auto pattern = "/users/:userid/subscriptions/:subid";
  14818. detail::PathParamsMatcher matcher(pattern);
  14819. Request request;
  14820. request.path = "/users/42/subscriptions/2";
  14821. ASSERT_TRUE(matcher.match(request));
  14822. std::unordered_map<std::string, std::string> expected_params = {
  14823. {"userid", "42"}, {"subid", "2"}};
  14824. EXPECT_EQ(request.path_params, expected_params);
  14825. }
  14826. TEST(PathParamsTest, SequenceOfParams) {
  14827. const auto pattern = "/values/:x/:y/:z";
  14828. detail::PathParamsMatcher matcher(pattern);
  14829. Request request;
  14830. request.path = "/values/1/2/3";
  14831. ASSERT_TRUE(matcher.match(request));
  14832. std::unordered_map<std::string, std::string> expected_params = {
  14833. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14834. EXPECT_EQ(request.path_params, expected_params);
  14835. }
  14836. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14837. const auto pattern = "/prefix:suffix";
  14838. detail::PathParamsMatcher matcher(pattern);
  14839. Request request;
  14840. request.path = "/prefix:suffix";
  14841. ASSERT_TRUE(matcher.match(request));
  14842. const std::unordered_map<std::string, std::string> expected_params = {};
  14843. EXPECT_EQ(request.path_params, expected_params);
  14844. }
  14845. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14846. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14847. // calling thread's stack on a long enough path for a quantified pattern;
  14848. // RegexMatcher must refuse to run regex matching on paths beyond
  14849. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14850. detail::RegexMatcher matcher("/files/(.*)");
  14851. Request within_limit;
  14852. within_limit.path = "/files/" + std::string(10, 'A');
  14853. EXPECT_TRUE(matcher.match(within_limit));
  14854. Request over_limit;
  14855. over_limit.path =
  14856. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14857. EXPECT_FALSE(matcher.match(over_limit));
  14858. }
  14859. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14860. Server svr;
  14861. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14862. res.set_content("ok", "text/plain");
  14863. });
  14864. auto port = svr.bind_to_any_port(HOST);
  14865. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14866. auto se = detail::scope_exit([&] {
  14867. svr.stop();
  14868. thread.join();
  14869. ASSERT_FALSE(svr.is_running());
  14870. });
  14871. svr.wait_until_ready();
  14872. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14873. // request URI limit; this used to be able to crash the process.
  14874. std::string path =
  14875. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14876. std::string req = "GET " + path +
  14877. " HTTP/1.1\r\n"
  14878. "Host: " +
  14879. std::string(HOST) + ":" + std::to_string(port) +
  14880. "\r\n"
  14881. "Connection: close\r\n"
  14882. "\r\n";
  14883. std::string response;
  14884. ASSERT_TRUE(send_request(5, req, &response, port));
  14885. EXPECT_NE(std::string::npos, response.find("404"));
  14886. }
  14887. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14888. Server svr;
  14889. auto handler = [](const Request & /*req*/, Response &res) {
  14890. res.set_content("hit", "text/plain");
  14891. };
  14892. // No regex metacharacter, so this one is compared literally
  14893. svr.Get("/literal/route", handler);
  14894. // '.' is a regex metacharacter, so this one must keep regex semantics
  14895. svr.Get("/a.c", handler);
  14896. auto port = svr.bind_to_any_port(HOST);
  14897. std::thread t([&]() { svr.listen_after_bind(); });
  14898. auto se = detail::scope_exit([&] {
  14899. svr.stop();
  14900. t.join();
  14901. ASSERT_FALSE(svr.is_running());
  14902. });
  14903. svr.wait_until_ready();
  14904. Client cli(HOST, port);
  14905. struct {
  14906. const char *path;
  14907. int status;
  14908. } cases[] = {
  14909. {"/literal/route", StatusCode::OK_200},
  14910. {"/literal/routes", StatusCode::NotFound_404},
  14911. {"/literal/rout", StatusCode::NotFound_404},
  14912. {"/abc", StatusCode::OK_200},
  14913. {"/a.c", StatusCode::OK_200},
  14914. };
  14915. for (const auto &x : cases) {
  14916. auto res = cli.Get(x.path);
  14917. ASSERT_TRUE(res) << x.path;
  14918. EXPECT_EQ(x.status, res->status) << x.path;
  14919. }
  14920. }
  14921. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14922. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14923. // from exhausting the stack, so it must only constrain routes that actually
  14924. // run a regular expression. A literal route is matched by comparison and
  14925. // stays usable at any length.
  14926. Server svr;
  14927. const std::string pattern =
  14928. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14929. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14930. res.set_content("hit", "text/plain");
  14931. });
  14932. auto port = svr.bind_to_any_port(HOST);
  14933. std::thread t([&]() { svr.listen_after_bind(); });
  14934. auto se = detail::scope_exit([&] {
  14935. svr.stop();
  14936. t.join();
  14937. ASSERT_FALSE(svr.is_running());
  14938. });
  14939. svr.wait_until_ready();
  14940. Client cli(HOST, port);
  14941. auto res = cli.Get(pattern);
  14942. ASSERT_TRUE(res);
  14943. EXPECT_EQ(StatusCode::OK_200, res->status);
  14944. }
  14945. TEST(ParseUrlTest, VariousPatterns) {
  14946. {
  14947. detail::UrlComponents uc;
  14948. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14949. EXPECT_EQ("http", uc.scheme);
  14950. EXPECT_EQ("example.com", uc.host);
  14951. EXPECT_EQ("8080", uc.port);
  14952. EXPECT_EQ("/path", uc.path);
  14953. EXPECT_EQ("?q=1", uc.query);
  14954. }
  14955. {
  14956. detail::UrlComponents uc;
  14957. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  14958. EXPECT_EQ("https", uc.scheme);
  14959. EXPECT_EQ("example.com", uc.host);
  14960. EXPECT_TRUE(uc.port.empty());
  14961. EXPECT_EQ("/path", uc.path);
  14962. }
  14963. {
  14964. detail::UrlComponents uc;
  14965. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  14966. EXPECT_EQ("::1", uc.host);
  14967. EXPECT_EQ("8080", uc.port);
  14968. EXPECT_EQ("/path", uc.path);
  14969. }
  14970. {
  14971. detail::UrlComponents uc;
  14972. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  14973. }
  14974. {
  14975. // Bytes after the IPv6 literal must be a delimiter, not folded into
  14976. // the path while the connection still targets the bracketed host.
  14977. detail::UrlComponents uc;
  14978. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  14979. }
  14980. {
  14981. detail::UrlComponents uc;
  14982. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  14983. }
  14984. {
  14985. detail::UrlComponents uc;
  14986. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  14987. EXPECT_EQ("::1", uc.host);
  14988. EXPECT_TRUE(uc.port.empty());
  14989. EXPECT_EQ("/path", uc.path);
  14990. }
  14991. {
  14992. detail::UrlComponents uc;
  14993. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  14994. EXPECT_TRUE(uc.scheme.empty());
  14995. EXPECT_EQ("example.com", uc.host);
  14996. EXPECT_EQ("/path", uc.path);
  14997. EXPECT_EQ("?q=1", uc.query);
  14998. }
  14999. {
  15000. detail::UrlComponents uc;
  15001. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15002. EXPECT_TRUE(uc.host.empty());
  15003. EXPECT_EQ("/path", uc.path);
  15004. EXPECT_EQ("?q=1", uc.query);
  15005. }
  15006. {
  15007. detail::UrlComponents uc;
  15008. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15009. EXPECT_EQ("example.com", uc.host);
  15010. EXPECT_EQ("8080", uc.port);
  15011. }
  15012. {
  15013. // Unix socket path — must not be parsed as host
  15014. detail::UrlComponents uc;
  15015. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15016. EXPECT_TRUE(uc.host.empty());
  15017. }
  15018. {
  15019. detail::UrlComponents uc;
  15020. ASSERT_TRUE(detail::parse_url("", uc));
  15021. EXPECT_TRUE(uc.host.empty());
  15022. EXPECT_TRUE(uc.path.empty());
  15023. }
  15024. {
  15025. detail::UrlComponents uc;
  15026. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15027. }
  15028. {
  15029. detail::UrlComponents uc;
  15030. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15031. }
  15032. {
  15033. // Accepted by parse_url; callers restrict to http/https
  15034. detail::UrlComponents uc;
  15035. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15036. EXPECT_EQ("ftp", uc.scheme);
  15037. }
  15038. {
  15039. detail::UrlComponents uc;
  15040. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15041. }
  15042. {
  15043. detail::UrlComponents uc;
  15044. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15045. }
  15046. }
  15047. TEST(ParseUrlTest, FragmentHandling) {
  15048. {
  15049. detail::UrlComponents uc;
  15050. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15051. EXPECT_EQ("/path", uc.path);
  15052. EXPECT_TRUE(uc.query.empty());
  15053. }
  15054. {
  15055. detail::UrlComponents uc;
  15056. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15057. EXPECT_TRUE(uc.path.empty());
  15058. EXPECT_TRUE(uc.query.empty());
  15059. }
  15060. }
  15061. TEST(ParseUrlTest, UserinfoHandling) {
  15062. // Userinfo with @ but no colon — host includes @
  15063. detail::UrlComponents uc;
  15064. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15065. EXPECT_EQ("user@host.com", uc.host);
  15066. EXPECT_EQ("/path", uc.path);
  15067. }
  15068. TEST(ParseUrlTest, IPv6EdgeCases) {
  15069. {
  15070. detail::UrlComponents uc;
  15071. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15072. EXPECT_TRUE(uc.scheme.empty());
  15073. EXPECT_EQ("::1", uc.host);
  15074. EXPECT_EQ("8080", uc.port);
  15075. }
  15076. {
  15077. // Zone ID '%25' is not in [a-fA-F0-9:]
  15078. detail::UrlComponents uc;
  15079. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15080. }
  15081. }
  15082. TEST(ParseUrlTest, SchemeEdgeCases) {
  15083. {
  15084. detail::UrlComponents uc;
  15085. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15086. }
  15087. {
  15088. detail::UrlComponents uc;
  15089. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15090. }
  15091. {
  15092. detail::UrlComponents uc;
  15093. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15094. }
  15095. }
  15096. TEST(ParseUrlTest, PortEdgeCases) {
  15097. {
  15098. detail::UrlComponents uc;
  15099. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15100. EXPECT_TRUE(uc.port.empty());
  15101. EXPECT_EQ("/path", uc.path);
  15102. }
  15103. {
  15104. // parse_url accepts any port string; validation is done by parse_port
  15105. detail::UrlComponents uc;
  15106. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15107. EXPECT_EQ("abc", uc.port);
  15108. }
  15109. }
  15110. TEST(ParseUrlTest, WebSocketPatterns) {
  15111. {
  15112. detail::UrlComponents uc;
  15113. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15114. EXPECT_EQ("ws", uc.scheme);
  15115. EXPECT_EQ("echo.example.com", uc.host);
  15116. EXPECT_EQ("8080", uc.port);
  15117. EXPECT_EQ("/ws", uc.path);
  15118. }
  15119. {
  15120. detail::UrlComponents uc;
  15121. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15122. EXPECT_EQ("wss", uc.scheme);
  15123. EXPECT_EQ("echo.example.com", uc.host);
  15124. EXPECT_TRUE(uc.port.empty());
  15125. EXPECT_EQ("/ws", uc.path);
  15126. }
  15127. }
  15128. TEST(ParseUrlTest, QueryOnly) {
  15129. detail::UrlComponents uc;
  15130. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15131. EXPECT_TRUE(uc.host.empty());
  15132. EXPECT_TRUE(uc.path.empty());
  15133. EXPECT_EQ("?q=1&r=2", uc.query);
  15134. }
  15135. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15136. detail::UrlComponents uc;
  15137. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15138. EXPECT_TRUE(uc.scheme.empty());
  15139. EXPECT_EQ("example.com", uc.host);
  15140. EXPECT_EQ("443", uc.port);
  15141. EXPECT_EQ("/path", uc.path);
  15142. }
  15143. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15144. // If ipv6 regex working, regex match codepath is taken.
  15145. // else port will default to 80 in Client impl
  15146. int clientImplMagicPort = 80;
  15147. int port = 4321;
  15148. // above ports must be different to avoid false negative
  15149. EXPECT_NE(clientImplMagicPort, port);
  15150. std::string ipV6TestURL = "http://[ff06::c3]";
  15151. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15152. CLIENT_PRIVATE_KEY_FILE);
  15153. EXPECT_EQ(cli.port(), port);
  15154. }
  15155. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15156. auto file_path = "./www/dir/index.html";
  15157. auto dir_path = "./www/dir";
  15158. detail::FileStat stat_file(file_path);
  15159. EXPECT_TRUE(stat_file.is_file());
  15160. EXPECT_FALSE(stat_file.is_dir());
  15161. detail::FileStat stat_dir(dir_path);
  15162. EXPECT_FALSE(stat_dir.is_file());
  15163. EXPECT_TRUE(stat_dir.is_dir());
  15164. }
  15165. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15166. // IPv4 with default HTTP port (80)
  15167. EXPECT_EQ("example.com",
  15168. detail::make_host_and_port_string("example.com", 80, false));
  15169. // IPv4 with default HTTPS port (443)
  15170. EXPECT_EQ("example.com",
  15171. detail::make_host_and_port_string("example.com", 443, true));
  15172. // IPv4 with non-default HTTP port
  15173. EXPECT_EQ("example.com:8080",
  15174. detail::make_host_and_port_string("example.com", 8080, false));
  15175. // IPv4 with non-default HTTPS port
  15176. EXPECT_EQ("example.com:8443",
  15177. detail::make_host_and_port_string("example.com", 8443, true));
  15178. // IPv6 with default HTTP port (80)
  15179. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15180. // IPv6 with default HTTPS port (443)
  15181. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15182. // IPv6 with non-default HTTP port
  15183. EXPECT_EQ("[::1]:8080",
  15184. detail::make_host_and_port_string("::1", 8080, false));
  15185. // IPv6 with non-default HTTPS port
  15186. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15187. // IPv6 full address with default port
  15188. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15189. detail::make_host_and_port_string(
  15190. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15191. // IPv6 full address with non-default port
  15192. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15193. detail::make_host_and_port_string(
  15194. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15195. // IPv6 localhost with non-default port
  15196. EXPECT_EQ("[::1]:3000",
  15197. detail::make_host_and_port_string("::1", 3000, false));
  15198. // IPv6 with zone ID (link-local address) with default port
  15199. EXPECT_EQ("[fe80::1%eth0]",
  15200. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15201. // IPv6 with zone ID (link-local address) with non-default port
  15202. EXPECT_EQ("[fe80::1%eth0]:8080",
  15203. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15204. // Edge case: Port 443 with is_ssl=false (should add port)
  15205. EXPECT_EQ("example.com:443",
  15206. detail::make_host_and_port_string("example.com", 443, false));
  15207. // Edge case: Port 80 with is_ssl=true (should add port)
  15208. EXPECT_EQ("example.com:80",
  15209. detail::make_host_and_port_string("example.com", 80, true));
  15210. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15211. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15212. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15213. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15214. // Security fix: Already bracketed IPv6 should not get double brackets
  15215. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15216. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15217. EXPECT_EQ("[::1]:8080",
  15218. detail::make_host_and_port_string("[::1]", 8080, false));
  15219. EXPECT_EQ("[2001:db8::1]:8080",
  15220. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15221. EXPECT_EQ("[fe80::1%eth0]",
  15222. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15223. EXPECT_EQ("[fe80::1%eth0]:8080",
  15224. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15225. // Edge case: Empty host (should return as-is)
  15226. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15227. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15228. // This is a known limitation but shouldn't crash
  15229. EXPECT_EQ("[host:name]",
  15230. detail::make_host_and_port_string("host:name", 80, false));
  15231. // Port number edge cases (no validation, but should not crash)
  15232. EXPECT_EQ("example.com:0",
  15233. detail::make_host_and_port_string("example.com", 0, false));
  15234. EXPECT_EQ("example.com:-1",
  15235. detail::make_host_and_port_string("example.com", -1, false));
  15236. EXPECT_EQ("example.com:65535",
  15237. detail::make_host_and_port_string("example.com", 65535, false));
  15238. EXPECT_EQ("example.com:65536",
  15239. detail::make_host_and_port_string("example.com", 65536, false));
  15240. }
  15241. #ifdef CPPHTTPLIB_SSL_ENABLED
  15242. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15243. httplib::SSLClient cli("roblox.com", 443);
  15244. cli.set_follow_location(true);
  15245. auto res = cli.Get("/");
  15246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15247. EXPECT_EQ(StatusCode::OK_200, res->status);
  15248. }
  15249. #endif
  15250. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15251. Server svr;
  15252. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15253. EXPECT_EQ(res.status, 400);
  15254. });
  15255. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15256. auto se = detail::scope_exit([&] {
  15257. svr.stop();
  15258. thread.join();
  15259. ASSERT_FALSE(svr.is_running());
  15260. });
  15261. svr.wait_until_ready();
  15262. Client cli(HOST, PORT);
  15263. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15264. }
  15265. TEST(InvalidHeaderCharsTest, is_field_name) {
  15266. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15267. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15268. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15269. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15270. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15271. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15272. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15273. EXPECT_FALSE(detail::fields::is_field_name(""));
  15274. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15275. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15276. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15277. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15278. }
  15279. TEST(InvalidHeaderCharsTest, is_field_value) {
  15280. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15281. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15282. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15283. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15284. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15285. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15286. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15287. EXPECT_TRUE(detail::fields::is_field_value(""));
  15288. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15289. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15290. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15291. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15292. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15293. }
  15294. TEST(InvalidHeaderCharsTest, OnServer) {
  15295. Server svr;
  15296. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15297. std::string header = "Not Set";
  15298. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15299. res.set_header(header, "value");
  15300. res.set_content("Page Content Page Content", "text/plain");
  15301. });
  15302. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15303. std::string header = "Not Set";
  15304. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15305. res.set_header("X-Test", header);
  15306. res.set_content("Page Content Page Content", "text/plain");
  15307. });
  15308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15309. auto se = detail::scope_exit([&] {
  15310. svr.stop();
  15311. thread.join();
  15312. ASSERT_FALSE(svr.is_running());
  15313. });
  15314. svr.wait_until_ready();
  15315. Client cli(HOST, PORT);
  15316. {
  15317. auto res = cli.Get(
  15318. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15320. EXPECT_EQ("Page Content Page Content", res->body);
  15321. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15322. }
  15323. {
  15324. auto res = cli.Get(
  15325. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15327. EXPECT_EQ("Page Content Page Content", res->body);
  15328. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15329. }
  15330. }
  15331. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15332. auto handled = false;
  15333. Server svr;
  15334. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15335. thread t = thread([&] { svr.listen(HOST, PORT); });
  15336. auto se = detail::scope_exit([&] {
  15337. svr.stop();
  15338. t.join();
  15339. ASSERT_FALSE(svr.is_running());
  15340. ASSERT_FALSE(handled);
  15341. });
  15342. svr.wait_until_ready();
  15343. auto req = "POST /test HTTP/1.1\r\n"
  15344. "Content-Length: x\r\n"
  15345. "\r\n";
  15346. std::string response;
  15347. ASSERT_TRUE(send_request(1, req, &response));
  15348. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15349. response.substr(0, response.find("\r\n")));
  15350. }
  15351. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15352. // case-insensitive, and a server that receives a 100-continue expectation in
  15353. // an HTTP/1.0 request MUST ignore it.
  15354. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15355. std::string response;
  15356. ASSERT_TRUE(send_request(1, req, &response, port));
  15357. *got_100 = response.find("100 Continue") != std::string::npos;
  15358. }
  15359. class ExpectTokenTest : public ::testing::Test {
  15360. protected:
  15361. void SetUp() override {
  15362. svr_.Post("/p", [](const Request &, Response &res) {
  15363. res.set_content("ok", "text/plain");
  15364. });
  15365. port_ = svr_.bind_to_any_port(HOST);
  15366. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15367. svr_.wait_until_ready();
  15368. }
  15369. void TearDown() override {
  15370. svr_.stop();
  15371. if (thread_.joinable()) { thread_.join(); }
  15372. }
  15373. std::string request(const char *version, const char *expect_value) const {
  15374. return std::string("POST /p ") + version +
  15375. "\r\n"
  15376. "Host: localhost\r\n"
  15377. "Content-Length: 2\r\n"
  15378. "Connection: close\r\n"
  15379. "Expect: " +
  15380. expect_value +
  15381. "\r\n"
  15382. "\r\n"
  15383. "hi";
  15384. }
  15385. Server svr_;
  15386. int port_ = 0;
  15387. thread thread_;
  15388. };
  15389. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15390. bool got_100 = false;
  15391. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15392. EXPECT_TRUE(got_100);
  15393. }
  15394. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15395. bool got_100 = true;
  15396. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15397. EXPECT_FALSE(got_100);
  15398. }
  15399. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15400. bool got_100 = false;
  15401. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15402. EXPECT_TRUE(got_100);
  15403. }
  15404. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15405. bool got_100 = false;
  15406. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15407. EXPECT_TRUE(got_100);
  15408. }
  15409. // `100 Continue` is sent only when the server starts reading the body, so a
  15410. // request rejected before that never invites the client to send it. The
  15411. // requests below carry the expectation but withhold the body, as a client
  15412. // waiting for `100 Continue` would.
  15413. // A POST that expects `100 Continue` and withholds its two-byte body.
  15414. static std::string expect_headers_only(const std::string &path) {
  15415. return "POST " + path +
  15416. " HTTP/1.1\r\n"
  15417. "Host: localhost\r\n"
  15418. "Content-Length: 2\r\n"
  15419. "Expect: 100-continue\r\n"
  15420. "\r\n";
  15421. }
  15422. class ExpectLazyContinueTest : public ::testing::Test {
  15423. protected:
  15424. void SetUp() override {
  15425. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15426. if (req.path == "/pre-routing") {
  15427. res.status = StatusCode::Unauthorized_401;
  15428. return Server::HandlerResponse::Handled;
  15429. }
  15430. return Server::HandlerResponse::Unhandled;
  15431. });
  15432. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15433. if (req.matched_route == "/pre-request") {
  15434. res.status = StatusCode::Forbidden_403;
  15435. return Server::HandlerResponse::Handled;
  15436. }
  15437. return Server::HandlerResponse::Unhandled;
  15438. });
  15439. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15440. res.set_content("ok", "text/plain");
  15441. });
  15442. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15443. res.set_content("ok", "text/plain");
  15444. });
  15445. svr_.Post("/reader-used", [](const Request &, Response &res,
  15446. const ContentReader &content_reader) {
  15447. std::string body;
  15448. content_reader([&](const char *data, size_t len) {
  15449. body.append(data, len);
  15450. return true;
  15451. });
  15452. res.set_content(body, "text/plain");
  15453. });
  15454. svr_.Post("/reader-unused",
  15455. [](const Request &, Response &res, const ContentReader &) {
  15456. res.set_content("ignored", "text/plain");
  15457. });
  15458. port_ = svr_.bind_to_any_port(HOST);
  15459. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15460. svr_.wait_until_ready();
  15461. }
  15462. void TearDown() override {
  15463. svr_.stop();
  15464. if (thread_.joinable()) { thread_.join(); }
  15465. }
  15466. // Sends `req` and reads until the server closes the connection. Returns
  15467. // false if the read had to wait for the client-side timeout instead.
  15468. bool send_until_closed(const std::string &req, std::string *resp) const {
  15469. auto start = std::chrono::steady_clock::now();
  15470. if (!send_request(3, req, resp, port_)) { return false; }
  15471. auto elapsed = std::chrono::steady_clock::now() - start;
  15472. return elapsed < std::chrono::seconds(2);
  15473. }
  15474. // The final response comes without `100 Continue`, and the server closes
  15475. // the connection since the body may or may not follow.
  15476. void expect_final_without_interim(const std::string &path,
  15477. const char *status_line) const {
  15478. std::string resp;
  15479. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15480. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15481. EXPECT_EQ(0u, resp.find(status_line));
  15482. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15483. }
  15484. Server svr_;
  15485. int port_ = 0;
  15486. thread thread_;
  15487. };
  15488. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15489. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15490. }
  15491. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15492. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15493. }
  15494. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15495. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15496. }
  15497. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15498. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15499. }
  15500. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15501. // The body follows once `100 Continue` has had time to arrive.
  15502. auto req = expect_headers_only("/reader-used");
  15503. req.insert(req.size() - 2, "Connection: close\r\n");
  15504. std::string resp;
  15505. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15506. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15507. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15508. EXPECT_NE(std::string::npos, resp.find("hi"));
  15509. }
  15510. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15511. // Large enough for the client to add `Expect: 100-continue` itself.
  15512. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15513. std::atomic<bool> body_sent{false};
  15514. Client cli(HOST, port_);
  15515. auto res = cli.Post(
  15516. "/pre-request", length,
  15517. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15518. body_sent = true;
  15519. std::string chunk(len, 'x');
  15520. sink.write(chunk.data(), chunk.size());
  15521. return true;
  15522. },
  15523. "application/octet-stream");
  15524. ASSERT_TRUE(res);
  15525. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15526. EXPECT_FALSE(body_sent);
  15527. }
  15528. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15529. Server svr;
  15530. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15531. return StatusCode::ExpectationFailed_417;
  15532. });
  15533. svr.Post("/p", [](const Request &, Response &res) {
  15534. res.set_content("ok", "text/plain");
  15535. });
  15536. auto port = svr.bind_to_any_port(HOST);
  15537. thread t = thread([&] { svr.listen_after_bind(); });
  15538. auto se = detail::scope_exit([&] {
  15539. svr.stop();
  15540. t.join();
  15541. });
  15542. svr.wait_until_ready();
  15543. std::string resp;
  15544. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15545. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15546. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15547. // Exactly one response: the route handler must not run after the 417.
  15548. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15549. }
  15550. #ifndef _WIN32
  15551. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15552. static constexpr char reject[] = "Unauthorized";
  15553. static constexpr char accept[] = "Upload accepted";
  15554. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15555. Server svr;
  15556. svr.set_expect_100_continue_handler(
  15557. [](const Request & /*req*/, Response &res) {
  15558. res.status = StatusCode::Unauthorized_401;
  15559. res.set_content(reject, "text/plain");
  15560. return res.status;
  15561. });
  15562. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15563. res.set_content(accept, "text/plain");
  15564. });
  15565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15566. auto se = detail::scope_exit([&] {
  15567. svr.stop();
  15568. thread.join();
  15569. ASSERT_FALSE(svr.is_running());
  15570. });
  15571. svr.wait_until_ready();
  15572. {
  15573. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15574. curl_easy_init(), &curl_easy_cleanup};
  15575. ASSERT_NE(curl, nullptr);
  15576. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15577. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15578. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15579. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15580. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15581. &curl_slist_free_all};
  15582. ASSERT_NE(list, nullptr);
  15583. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15584. struct read_data {
  15585. size_t read_size;
  15586. size_t total_size;
  15587. } data = {0, total_size};
  15588. using read_callback_t =
  15589. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15590. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15591. void *userdata) -> size_t {
  15592. read_data *d = (read_data *)userdata;
  15593. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15594. std::fill_n(ptr, size * nmemb, 'A');
  15595. d->read_size += size * nmemb;
  15596. return size * nmemb;
  15597. };
  15598. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15599. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15600. std::vector<char> buffer;
  15601. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15602. using write_callback_t =
  15603. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15604. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15605. void *userdata) -> size_t {
  15606. std::vector<char> *buf = (std::vector<char> *)userdata;
  15607. buf->reserve(buf->size() + size * nmemb + 1);
  15608. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15609. return size * nmemb;
  15610. };
  15611. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15612. {
  15613. const auto res = curl_easy_perform(curl.get());
  15614. ASSERT_EQ(res, CURLE_OK);
  15615. }
  15616. {
  15617. auto response_code = long{};
  15618. const auto res =
  15619. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15620. ASSERT_EQ(res, CURLE_OK);
  15621. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15622. }
  15623. {
  15624. auto dl = curl_off_t{};
  15625. const auto res =
  15626. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15627. ASSERT_EQ(res, CURLE_OK);
  15628. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15629. }
  15630. {
  15631. buffer.push_back('\0');
  15632. ASSERT_STRCASEEQ(buffer.data(), reject);
  15633. }
  15634. }
  15635. }
  15636. #endif
  15637. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15638. // Regression test for #2458.
  15639. //
  15640. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15641. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15642. // ticket can make the client socket spuriously readable during the
  15643. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15644. // the client withholds the body and then blocks reading a response that never
  15645. // comes, failing with `Failed to read connection`.
  15646. //
  15647. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15648. // within the timeout. This raw OpenSSL server deliberately never sends
  15649. // `100 Continue`; the client must still deliver the body and receive 200.
  15650. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15651. signal(SIGPIPE, SIG_IGN);
  15652. const auto port = PORT + 4;
  15653. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15654. ASSERT_NE(srv, INVALID_SOCKET);
  15655. int opt = 1;
  15656. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15657. sockaddr_in addr{};
  15658. addr.sin_family = AF_INET;
  15659. addr.sin_port = htons(static_cast<uint16_t>(port));
  15660. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15661. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15662. ASSERT_EQ(0, ::listen(srv, 1));
  15663. std::atomic<size_t> server_body_bytes{0};
  15664. auto server_thread = std::thread([&] {
  15665. sockaddr_in cli_addr{};
  15666. socklen_t cli_len = sizeof(cli_addr);
  15667. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15668. if (cli == INVALID_SOCKET) { return; }
  15669. // Bound the lifetime of the server side so a buggy client (which never
  15670. // sends the body) cannot make this thread block forever on join.
  15671. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15672. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15673. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15674. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15675. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15676. SSL *ssl = SSL_new(ctx);
  15677. SSL_set_fd(ssl, static_cast<int>(cli));
  15678. if (SSL_accept(ssl) > 0) {
  15679. // Read the request headers. Reading here also flushes the TLS 1.3
  15680. // session tickets to the client. Deliberately do NOT send
  15681. // `100 Continue`.
  15682. std::string buf;
  15683. char tmp[1024];
  15684. while (buf.find("\r\n\r\n") == std::string::npos) {
  15685. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15686. if (n <= 0) { break; }
  15687. buf.append(tmp, static_cast<size_t>(n));
  15688. }
  15689. // A correct client sends the body now; count what arrives.
  15690. auto pos = buf.find("\r\n\r\n");
  15691. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15692. while (body < 4096) {
  15693. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15694. if (n <= 0) { break; }
  15695. body += static_cast<size_t>(n);
  15696. }
  15697. server_body_bytes = body;
  15698. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15699. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15700. SSL_shutdown(ssl);
  15701. }
  15702. SSL_free(ssl);
  15703. detail::close_socket(cli);
  15704. SSL_CTX_free(ctx);
  15705. });
  15706. auto se = detail::scope_exit([&] {
  15707. server_thread.join();
  15708. detail::close_socket(srv);
  15709. });
  15710. SSLClient cli("127.0.0.1", port);
  15711. cli.enable_server_certificate_verification(false);
  15712. cli.set_connection_timeout(5, 0);
  15713. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15714. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15715. std::string body(4096, 'A');
  15716. auto res = cli.Put("/api/test", body, "application/json");
  15717. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15718. EXPECT_EQ(StatusCode::OK_200, res->status);
  15719. EXPECT_EQ(body.size(), server_body_bytes.load());
  15720. }
  15721. #endif
  15722. template <typename S, typename C>
  15723. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15724. svr.Get("/stream", [&](const Request &, Response &res) {
  15725. auto data = new std::string("01234567890123456789");
  15726. res.set_content_provider(
  15727. data->size(), "text/plain",
  15728. [&, data](size_t offset, size_t length, DataSink &sink) {
  15729. const size_t DATA_CHUNK_SIZE = 4;
  15730. const auto &d = *data;
  15731. std::this_thread::sleep_for(std::chrono::seconds(1));
  15732. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15733. return true;
  15734. },
  15735. [data](bool success) {
  15736. EXPECT_FALSE(success);
  15737. delete data;
  15738. });
  15739. });
  15740. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15741. auto i = new size_t(0);
  15742. res.set_content_provider(
  15743. "text/plain",
  15744. [i](size_t, DataSink &sink) {
  15745. if (*i < 5) {
  15746. std::this_thread::sleep_for(std::chrono::seconds(1));
  15747. sink.write("abcd", 4);
  15748. (*i)++;
  15749. } else {
  15750. sink.done();
  15751. }
  15752. return true;
  15753. },
  15754. [i](bool success) {
  15755. EXPECT_FALSE(success);
  15756. delete i;
  15757. });
  15758. });
  15759. svr.Get("/chunked", [&](const Request &, Response &res) {
  15760. auto i = new size_t(0);
  15761. res.set_chunked_content_provider(
  15762. "text/plain",
  15763. [i](size_t, DataSink &sink) {
  15764. if (*i < 5) {
  15765. std::this_thread::sleep_for(std::chrono::seconds(1));
  15766. sink.os << "abcd";
  15767. (*i)++;
  15768. } else {
  15769. sink.done();
  15770. }
  15771. return true;
  15772. },
  15773. [i](bool success) {
  15774. EXPECT_FALSE(success);
  15775. delete i;
  15776. });
  15777. });
  15778. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15779. auto se = detail::scope_exit([&] {
  15780. svr.stop();
  15781. listen_thread.join();
  15782. ASSERT_FALSE(svr.is_running());
  15783. });
  15784. svr.wait_until_ready();
  15785. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15786. {
  15787. auto start = std::chrono::steady_clock::now();
  15788. auto res = cli.Get("/stream");
  15789. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15790. std::chrono::steady_clock::now() - start)
  15791. .count();
  15792. ASSERT_FALSE(res);
  15793. EXPECT_EQ(Error::Read, res.error());
  15794. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15795. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15796. }
  15797. {
  15798. auto start = std::chrono::steady_clock::now();
  15799. auto res = cli.Get("/stream_without_length");
  15800. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15801. std::chrono::steady_clock::now() - start)
  15802. .count();
  15803. ASSERT_FALSE(res);
  15804. EXPECT_EQ(Error::Read, res.error());
  15805. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15806. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15807. }
  15808. {
  15809. auto start = std::chrono::steady_clock::now();
  15810. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15811. EXPECT_EQ("abcd", string(data, data_length));
  15812. return true;
  15813. });
  15814. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15815. std::chrono::steady_clock::now() - start)
  15816. .count();
  15817. ASSERT_FALSE(res);
  15818. EXPECT_EQ(Error::Read, res.error());
  15819. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15820. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15821. }
  15822. }
  15823. TEST(MaxTimeoutTest, ContentStream) {
  15824. time_t timeout = 2000;
  15825. time_t threshold = 200;
  15826. Server svr;
  15827. Client cli("localhost", PORT);
  15828. max_timeout_test(svr, cli, timeout, threshold);
  15829. }
  15830. #ifdef CPPHTTPLIB_SSL_ENABLED
  15831. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15832. time_t timeout = 2000;
  15833. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15834. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15835. SSLClient cli("localhost", PORT);
  15836. cli.enable_server_certificate_verification(false);
  15837. max_timeout_test(svr, cli, timeout, threshold);
  15838. }
  15839. #endif
  15840. class EventDispatcher {
  15841. public:
  15842. EventDispatcher() {}
  15843. bool wait_event(DataSink *sink) {
  15844. unique_lock<mutex> lk(m_);
  15845. int id = id_;
  15846. // Wait with timeout to prevent hanging if client disconnects
  15847. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15848. [&] { return cid_ == id; })) {
  15849. return false; // Timeout occurred
  15850. }
  15851. sink->write(message_.data(), message_.size());
  15852. return true;
  15853. }
  15854. void send_event(const string &message) {
  15855. lock_guard<mutex> lk(m_);
  15856. cid_ = id_++;
  15857. message_ = message;
  15858. cv_.notify_all();
  15859. }
  15860. private:
  15861. mutex m_;
  15862. condition_variable cv_;
  15863. atomic_int id_{0};
  15864. atomic_int cid_{-1};
  15865. string message_;
  15866. };
  15867. TEST(ClientInThreadTest, Issue2068) {
  15868. EventDispatcher ed;
  15869. Server svr;
  15870. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15871. res.set_chunked_content_provider("text/event-stream",
  15872. [&](size_t /*offset*/, DataSink &sink) {
  15873. return ed.wait_event(&sink);
  15874. });
  15875. });
  15876. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15877. svr.wait_until_ready();
  15878. thread event_thread([&] {
  15879. int id = 0;
  15880. while (svr.is_running()) {
  15881. this_thread::sleep_for(chrono::milliseconds(500));
  15882. std::stringstream ss;
  15883. ss << "data: " << id << "\n\n";
  15884. ed.send_event(ss.str());
  15885. id++;
  15886. }
  15887. });
  15888. auto se = detail::scope_exit([&] {
  15889. svr.stop();
  15890. listen_thread.join();
  15891. event_thread.join();
  15892. ASSERT_FALSE(svr.is_running());
  15893. });
  15894. {
  15895. auto client = detail::make_unique<Client>(HOST, PORT);
  15896. client->set_read_timeout(std::chrono::minutes(10));
  15897. std::atomic<bool> stop{false};
  15898. std::thread t([&] {
  15899. client->Get("/event1",
  15900. [&](const char *, size_t) -> bool { return !stop; });
  15901. });
  15902. std::this_thread::sleep_for(std::chrono::seconds(2));
  15903. stop = true;
  15904. client->stop();
  15905. t.join();
  15906. // Reset client after thread has finished
  15907. client.reset();
  15908. }
  15909. }
  15910. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  15911. auto handled = false;
  15912. Server svr;
  15913. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15914. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15915. auto se = detail::scope_exit([&] {
  15916. svr.stop();
  15917. t.join();
  15918. ASSERT_FALSE(svr.is_running());
  15919. ASSERT_FALSE(handled);
  15920. });
  15921. svr.wait_until_ready();
  15922. // Two Content-Length headers with different values — must be rejected
  15923. auto req = "POST /test HTTP/1.1\r\n"
  15924. "Content-Length: 5\r\n"
  15925. "Content-Length: 10\r\n"
  15926. "\r\n"
  15927. "hello";
  15928. std::string response;
  15929. ASSERT_TRUE(send_request(1, req, &response));
  15930. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15931. response.substr(0, response.find("\r\n")));
  15932. }
  15933. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  15934. auto handled = false;
  15935. Server svr;
  15936. svr.Post("/test", [&](const Request &, Response &res) {
  15937. handled = true;
  15938. res.set_content("ok", "text/plain");
  15939. });
  15940. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15941. auto se = detail::scope_exit([&] {
  15942. svr.stop();
  15943. t.join();
  15944. ASSERT_FALSE(svr.is_running());
  15945. ASSERT_TRUE(handled);
  15946. });
  15947. svr.wait_until_ready();
  15948. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  15949. auto req = "POST /test HTTP/1.1\r\n"
  15950. "Content-Length: 5\r\n"
  15951. "Content-Length: 5\r\n"
  15952. "\r\n"
  15953. "hello";
  15954. std::string response;
  15955. ASSERT_TRUE(send_request(1, req, &response));
  15956. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  15957. }
  15958. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  15959. Server svr;
  15960. svr.Get("/", [](const Request &req, Response &res) {
  15961. EXPECT_EQ(2U, req.trailers.size());
  15962. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  15963. // Denied
  15964. EXPECT_FALSE(req.has_trailer("Content-Length"));
  15965. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  15966. // Accepted
  15967. EXPECT_TRUE(req.has_trailer("X-Hello"));
  15968. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  15969. EXPECT_TRUE(req.has_trailer("X-World"));
  15970. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  15971. res.set_content("ok", "text/plain");
  15972. });
  15973. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15974. auto se = detail::scope_exit([&] {
  15975. svr.stop();
  15976. t.join();
  15977. ASSERT_FALSE(svr.is_running());
  15978. });
  15979. svr.wait_until_ready();
  15980. const std::string req = "GET / HTTP/1.1\r\n"
  15981. "Transfer-Encoding: chunked\r\n"
  15982. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  15983. "\r\n"
  15984. "0\r\n"
  15985. "Content-Length: 10\r\n"
  15986. "Host: internal.local\r\n"
  15987. "Content-Type: malicious/content\r\n"
  15988. "Cookie: any\r\n"
  15989. "Set-Cookie: any\r\n"
  15990. "X-Forwarded-For: attacker.com\r\n"
  15991. "X-Real-Ip: 1.1.1.1\r\n"
  15992. "X-Hello: hello\r\n"
  15993. "X-World: world\r\n"
  15994. "\r\n";
  15995. std::string res;
  15996. ASSERT_TRUE(send_request(1, req, &res));
  15997. }
  15998. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  15999. // several field lines, and the combined value is what has to be parsed. A
  16000. // Trailer field split across lines therefore declares every name it lists;
  16001. // reading only the first line silently drops the trailers the later lines
  16002. // declare. The prohibited-trailer filter still applies to every line.
  16003. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16004. Server svr;
  16005. size_t observed_trailer_count = 0;
  16006. std::string observed_hello;
  16007. std::string observed_world;
  16008. bool observed_content_length = true;
  16009. svr.Get("/", [&](const Request &req, Response &res) {
  16010. observed_trailer_count = req.trailers.size();
  16011. observed_hello = req.get_trailer_value("X-Hello");
  16012. observed_world = req.get_trailer_value("X-World");
  16013. observed_content_length = req.has_trailer("Content-Length");
  16014. res.set_content("ok", "text/plain");
  16015. });
  16016. auto port = svr.bind_to_any_port(HOST);
  16017. thread t = thread([&]() { svr.listen_after_bind(); });
  16018. auto se = detail::scope_exit([&] {
  16019. svr.stop();
  16020. t.join();
  16021. ASSERT_FALSE(svr.is_running());
  16022. });
  16023. svr.wait_until_ready();
  16024. const std::string req = "GET / HTTP/1.1\r\n"
  16025. "Transfer-Encoding: chunked\r\n"
  16026. "Trailer: X-Hello\r\n"
  16027. "Trailer: X-World, Content-Length\r\n"
  16028. "\r\n"
  16029. "0\r\n"
  16030. "X-Hello: hello\r\n"
  16031. "X-World: world\r\n"
  16032. "Content-Length: 10\r\n"
  16033. "\r\n";
  16034. std::string res;
  16035. ASSERT_TRUE(send_request(1, req, &res, port));
  16036. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16037. // Accepted: both field lines contribute to the declared set
  16038. EXPECT_EQ(2U, observed_trailer_count);
  16039. EXPECT_EQ(observed_hello, "hello");
  16040. EXPECT_EQ(observed_world, "world");
  16041. // Denied: a prohibited name stays prohibited on a later field line
  16042. EXPECT_FALSE(observed_content_length);
  16043. }
  16044. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16045. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16046. // unbounded run of fields that are never declared, because the counter would
  16047. // only advance for declared fields.
  16048. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16049. Server svr;
  16050. bool handler_called = false;
  16051. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16052. handler_called = true;
  16053. res.set_content("ok", "text/plain");
  16054. });
  16055. auto port = svr.bind_to_any_port(HOST);
  16056. thread t = thread([&]() { svr.listen_after_bind(); });
  16057. auto se = detail::scope_exit([&] {
  16058. svr.stop();
  16059. t.join();
  16060. ASSERT_FALSE(svr.is_running());
  16061. });
  16062. svr.wait_until_ready();
  16063. // Declare nothing, then send far more undeclared trailer fields than the
  16064. // header-count limit. Parsing must stop and reject the request rather than
  16065. // read every line.
  16066. std::string req = "GET / HTTP/1.1\r\n"
  16067. "Transfer-Encoding: chunked\r\n"
  16068. "\r\n"
  16069. "0\r\n";
  16070. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16071. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16072. }
  16073. req += "\r\n";
  16074. std::string res;
  16075. ASSERT_TRUE(send_request(1, req, &res, port));
  16076. // The request is rejected before the handler runs.
  16077. EXPECT_FALSE(handler_called);
  16078. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16079. }
  16080. // The set of declared trailer names is capped so a peer cannot grow it without
  16081. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16082. // declared past the cap is not honored, even if the field is actually sent.
  16083. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16084. Server svr;
  16085. // One name inside the cap and one past it, so the test tracks the cap rather
  16086. // than a fixed count.
  16087. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16088. const std::string within_cap_name = "X-T-0";
  16089. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16090. bool observed_within_cap = false;
  16091. bool observed_past_cap = false;
  16092. svr.Get("/", [&](const Request &req, Response &res) {
  16093. observed_within_cap = req.has_trailer(within_cap_name);
  16094. observed_past_cap = req.has_trailer(past_cap_name);
  16095. res.set_content("ok", "text/plain");
  16096. });
  16097. auto port = svr.bind_to_any_port(HOST);
  16098. thread t = thread([&]() { svr.listen_after_bind(); });
  16099. auto se = detail::scope_exit([&] {
  16100. svr.stop();
  16101. t.join();
  16102. ASSERT_FALSE(svr.is_running());
  16103. });
  16104. svr.wait_until_ready();
  16105. // Declare more trailer names than the cap in a single Trailer field, then
  16106. // actually send the first (within the cap) and the last (past it).
  16107. std::string trailer_decl = "Trailer: ";
  16108. for (int i = 0; i < declared_count; i++) {
  16109. if (i != 0) { trailer_decl += ", "; }
  16110. trailer_decl += "X-T-" + std::to_string(i);
  16111. }
  16112. trailer_decl += "\r\n";
  16113. const std::string req = "GET / HTTP/1.1\r\n"
  16114. "Transfer-Encoding: chunked\r\n" +
  16115. trailer_decl +
  16116. "\r\n"
  16117. "0\r\n" +
  16118. within_cap_name + ": a\r\n" + past_cap_name +
  16119. ": b\r\n"
  16120. "\r\n";
  16121. std::string res;
  16122. ASSERT_TRUE(send_request(1, req, &res, port));
  16123. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16124. // A name within the cap is honored; one declared past the cap is dropped.
  16125. EXPECT_TRUE(observed_within_cap);
  16126. EXPECT_FALSE(observed_past_cap);
  16127. }
  16128. // A direct client that is not listed in trusted_proxies must not be able to
  16129. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16130. // the peer address on the actual TCP connection determines whether the
  16131. // header is honored.
  16132. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16133. Server svr;
  16134. // Deliberately does NOT include the loopback address the test client
  16135. // actually connects from, so the direct connection is not a trusted proxy.
  16136. svr.set_trusted_proxies({"203.0.113.66"});
  16137. std::string observed_remote_addr;
  16138. svr.Get("/ip", [&](const Request &req, Response &res) {
  16139. observed_remote_addr = req.remote_addr;
  16140. res.set_content("ok", "text/plain");
  16141. });
  16142. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16143. auto se = detail::scope_exit([&] {
  16144. svr.stop();
  16145. t.join();
  16146. ASSERT_FALSE(svr.is_running());
  16147. });
  16148. svr.wait_until_ready();
  16149. Client cli(HOST, PORT);
  16150. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16152. EXPECT_EQ(StatusCode::OK_200, res->status);
  16153. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16154. // ignored entirely and the real connection-level address retained.
  16155. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16156. observed_remote_addr == "127.0.0.1");
  16157. }
  16158. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16159. Server svr;
  16160. std::string observed_remote_addr;
  16161. std::string observed_xff;
  16162. svr.Get("/ip", [&](const Request &req, Response &res) {
  16163. observed_remote_addr = req.remote_addr;
  16164. observed_xff = req.get_header_value("X-Forwarded-For");
  16165. res.set_content("ok", "text/plain");
  16166. });
  16167. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16168. auto se = detail::scope_exit([&] {
  16169. svr.stop();
  16170. t.join();
  16171. ASSERT_FALSE(svr.is_running());
  16172. });
  16173. svr.wait_until_ready();
  16174. Client cli(HOST, PORT);
  16175. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16177. EXPECT_EQ(StatusCode::OK_200, res->status);
  16178. EXPECT_EQ(observed_xff, "203.0.113.66");
  16179. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16180. observed_remote_addr == "127.0.0.1");
  16181. }
  16182. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16183. Server svr;
  16184. svr.set_trusted_proxies({"203.0.113.66"});
  16185. std::string observed_remote_addr;
  16186. std::string observed_xff;
  16187. svr.Get("/ip", [&](const Request &req, Response &res) {
  16188. observed_remote_addr = req.remote_addr;
  16189. observed_xff = req.get_header_value("X-Forwarded-For");
  16190. res.set_content("ok", "text/plain");
  16191. });
  16192. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16193. auto se = detail::scope_exit([&] {
  16194. svr.stop();
  16195. t.join();
  16196. ASSERT_FALSE(svr.is_running());
  16197. });
  16198. svr.wait_until_ready();
  16199. Client cli(HOST, PORT);
  16200. auto res = cli.Get("/ip");
  16201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16202. EXPECT_EQ(StatusCode::OK_200, res->status);
  16203. EXPECT_EQ(observed_xff, "");
  16204. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16205. observed_remote_addr == "127.0.0.1");
  16206. }
  16207. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16208. Server svr;
  16209. // Include the loopback address the test client actually connects from, so
  16210. // the direct connection itself is recognized as the trusted proxy hop.
  16211. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16212. std::string observed_remote_addr;
  16213. std::string observed_xff;
  16214. svr.Get("/ip", [&](const Request &req, Response &res) {
  16215. observed_remote_addr = req.remote_addr;
  16216. observed_xff = req.get_header_value("X-Forwarded-For");
  16217. res.set_content("ok", "text/plain");
  16218. });
  16219. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16220. auto se = detail::scope_exit([&] {
  16221. svr.stop();
  16222. t.join();
  16223. ASSERT_FALSE(svr.is_running());
  16224. });
  16225. svr.wait_until_ready();
  16226. Client cli(HOST, PORT);
  16227. auto res = cli.Get(
  16228. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16230. EXPECT_EQ(StatusCode::OK_200, res->status);
  16231. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16232. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16233. }
  16234. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16235. Server svr;
  16236. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16237. std::string observed_remote_addr;
  16238. std::string observed_xff;
  16239. svr.Get("/ip", [&](const Request &req, Response &res) {
  16240. observed_remote_addr = req.remote_addr;
  16241. observed_xff = req.get_header_value("X-Forwarded-For");
  16242. res.set_content("ok", "text/plain");
  16243. });
  16244. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16245. auto se = detail::scope_exit([&] {
  16246. svr.stop();
  16247. t.join();
  16248. ASSERT_FALSE(svr.is_running());
  16249. });
  16250. svr.wait_until_ready();
  16251. Client cli(HOST, PORT);
  16252. auto res = cli.Get(
  16253. "/ip",
  16254. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16256. EXPECT_EQ(StatusCode::OK_200, res->status);
  16257. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16258. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16259. }
  16260. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16261. Server svr;
  16262. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16263. std::string observed_remote_addr;
  16264. std::string observed_xff;
  16265. svr.Get("/ip", [&](const Request &req, Response &res) {
  16266. observed_remote_addr = req.remote_addr;
  16267. observed_xff = req.get_header_value("X-Forwarded-For");
  16268. res.set_content("ok", "text/plain");
  16269. });
  16270. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16271. auto se = detail::scope_exit([&] {
  16272. svr.stop();
  16273. t.join();
  16274. ASSERT_FALSE(svr.is_running());
  16275. });
  16276. svr.wait_until_ready();
  16277. Client cli(HOST, PORT);
  16278. auto res = cli.Get(
  16279. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16281. EXPECT_EQ(StatusCode::OK_200, res->status);
  16282. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16283. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16284. // and must not be selected.
  16285. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16286. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16287. }
  16288. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16289. Server svr;
  16290. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16291. std::string observed_remote_addr;
  16292. svr.Get("/ip", [&](const Request &req, Response &res) {
  16293. observed_remote_addr = req.remote_addr;
  16294. res.set_content("ok", "text/plain");
  16295. });
  16296. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16297. auto se = detail::scope_exit([&] {
  16298. svr.stop();
  16299. t.join();
  16300. ASSERT_FALSE(svr.is_running());
  16301. });
  16302. svr.wait_until_ready();
  16303. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16304. // a forged address and the trusted proxy's own address; the forged value must
  16305. // not win over the address the trusted proxy actually recorded.
  16306. Client cli(HOST, PORT);
  16307. auto res = cli.Get(
  16308. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16310. EXPECT_EQ(StatusCode::OK_200, res->status);
  16311. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16312. }
  16313. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16314. Server svr;
  16315. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16316. std::string observed_remote_addr;
  16317. std::string observed_xff;
  16318. svr.Get("/ip", [&](const Request &req, Response &res) {
  16319. observed_remote_addr = req.remote_addr;
  16320. observed_xff = req.get_header_value("X-Forwarded-For");
  16321. res.set_content("ok", "text/plain");
  16322. });
  16323. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16324. auto se = detail::scope_exit([&] {
  16325. svr.stop();
  16326. t.join();
  16327. ASSERT_FALSE(svr.is_running());
  16328. });
  16329. svr.wait_until_ready();
  16330. Client cli(HOST, PORT);
  16331. auto res = cli.Get(
  16332. "/ip",
  16333. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16335. EXPECT_EQ(StatusCode::OK_200, res->status);
  16336. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16337. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16338. }
  16339. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16340. Server svr;
  16341. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16342. std::string observed_remote_addr;
  16343. std::string observed_xff;
  16344. svr.Get("/ip", [&](const Request &req, Response &res) {
  16345. observed_remote_addr = req.remote_addr;
  16346. observed_xff = req.get_header_value("X-Forwarded-For");
  16347. res.set_content("ok", "text/plain");
  16348. });
  16349. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16350. auto se = detail::scope_exit([&] {
  16351. svr.stop();
  16352. t.join();
  16353. ASSERT_FALSE(svr.is_running());
  16354. });
  16355. svr.wait_until_ready();
  16356. std::string raw_req =
  16357. "GET /ip HTTP/1.1\r\n"
  16358. "Host: localhost\r\n"
  16359. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16360. "Connection: close\r\n"
  16361. "\r\n";
  16362. std::string out;
  16363. ASSERT_TRUE(send_request(5, raw_req, &out));
  16364. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16365. // Header parser trims surrounding whitespace of the header value
  16366. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16367. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16368. }
  16369. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16370. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16371. // their own X-Forwarded-For as a separate field line rather than extending the
  16372. // one the client sent, so every occurrence has to be taken into account.
  16373. // Reading only the first one hands back the address the client chose.
  16374. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16375. Server svr;
  16376. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16377. std::string observed_remote_addr;
  16378. size_t observed_xff_count = 0;
  16379. svr.Get("/ip", [&](const Request &req, Response &res) {
  16380. observed_remote_addr = req.remote_addr;
  16381. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16382. res.set_content("ok", "text/plain");
  16383. });
  16384. auto port = svr.bind_to_any_port(HOST);
  16385. thread t = thread([&]() { svr.listen_after_bind(); });
  16386. auto se = detail::scope_exit([&] {
  16387. svr.stop();
  16388. t.join();
  16389. ASSERT_FALSE(svr.is_running());
  16390. });
  16391. svr.wait_until_ready();
  16392. // The client supplies the first field line; the trusted proxy appends the
  16393. // address it observed as a second one.
  16394. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16395. "Host: localhost\r\n"
  16396. "X-Forwarded-For: 1.2.3.4\r\n"
  16397. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16398. "Connection: close\r\n"
  16399. "\r\n";
  16400. std::string out;
  16401. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16402. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16403. EXPECT_EQ(observed_xff_count, 2U);
  16404. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16405. // The same chain spread over one field line per hop derives the same client
  16406. // address, i.e. the split and the comma-joined representations agree.
  16407. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16408. "Host: localhost\r\n"
  16409. "X-Forwarded-For: 1.2.3.4\r\n"
  16410. "X-Forwarded-For: 198.51.100.23\r\n"
  16411. "X-Forwarded-For: 192.0.2.45\r\n"
  16412. "Connection: close\r\n"
  16413. "\r\n";
  16414. out.clear();
  16415. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16416. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16417. EXPECT_EQ(observed_xff_count, 3U);
  16418. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16419. }
  16420. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16421. // crash the server (it used to call front() on an empty vector inside
  16422. // get_client_ip). The connection-level remote address must be retained instead.
  16423. static void run_malformed_xff_test(const std::string &xff_value) {
  16424. Server svr;
  16425. svr.set_trusted_proxies({"192.0.2.45"});
  16426. std::string observed_remote_addr;
  16427. svr.Get("/ip", [&](const Request &req, Response &res) {
  16428. observed_remote_addr = req.remote_addr;
  16429. res.set_content("ok", "text/plain");
  16430. });
  16431. int port = 0;
  16432. thread t = thread([&]() {
  16433. port = svr.bind_to_any_port(HOST);
  16434. svr.listen_after_bind();
  16435. });
  16436. auto se = detail::scope_exit([&] {
  16437. svr.stop();
  16438. t.join();
  16439. ASSERT_FALSE(svr.is_running());
  16440. });
  16441. svr.wait_until_ready();
  16442. Client cli(HOST, port);
  16443. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16445. EXPECT_EQ(StatusCode::OK_200, res->status);
  16446. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16447. observed_remote_addr == "127.0.0.1");
  16448. }
  16449. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16450. run_malformed_xff_test("");
  16451. }
  16452. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16453. run_malformed_xff_test(",");
  16454. }
  16455. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16456. run_malformed_xff_test(", , ,");
  16457. }
  16458. // The same rule applies to Accept: a request whose acceptable types are spread
  16459. // over several field lines must be negotiated against all of them.
  16460. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16461. // case-insensitive connection options. Comparing the whole field value against
  16462. // one option misses a client that sends several of them, and misses every
  16463. // casing but the one written in the comparison.
  16464. //
  16465. // Sends req, reads the response, then reuses the same socket for a second
  16466. // request to find out whether the server kept the connection.
  16467. static void probe_connection_reuse(int port, const std::string &req,
  16468. bool *announced_close, bool *reusable) {
  16469. auto error = Error::Success;
  16470. auto sock = detail::create_client_socket(
  16471. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16472. /*connection_timeout_sec=*/5, 0,
  16473. /*read_timeout_sec=*/1, 0,
  16474. /*write_timeout_sec=*/5, 0, std::string(), error);
  16475. ASSERT_NE(sock, INVALID_SOCKET);
  16476. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16477. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16478. "Host: localhost\r\n"
  16479. "Connection: close\r\n"
  16480. "\r\n";
  16481. std::string first_response;
  16482. std::string second_response;
  16483. detail::process_client_socket(
  16484. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16485. [&](Stream &strm) {
  16486. if (strm.write(req.data(), req.size()) !=
  16487. static_cast<ssize_t>(req.size())) {
  16488. return false;
  16489. }
  16490. char buf[512];
  16491. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16492. // Headers plus the two-byte body of the handler below
  16493. while (reader.getline()) {
  16494. first_response += reader.ptr();
  16495. if (first_response.find("ok") != std::string::npos) { break; }
  16496. }
  16497. if (strm.write(second.data(), second.size()) !=
  16498. static_cast<ssize_t>(second.size())) {
  16499. return true;
  16500. }
  16501. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16502. while (reader2.getline()) {
  16503. second_response += reader2.ptr();
  16504. if (second_response.find("ok") != std::string::npos) { break; }
  16505. }
  16506. return true;
  16507. });
  16508. *announced_close =
  16509. first_response.find("Connection: close") != std::string::npos;
  16510. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16511. }
  16512. class ConnectionTokenTest : public ::testing::Test {
  16513. protected:
  16514. void SetUp() override {
  16515. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16516. res.set_content("ok", "text/plain");
  16517. });
  16518. port_ = svr_.bind_to_any_port(HOST);
  16519. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16520. svr_.wait_until_ready();
  16521. }
  16522. void TearDown() override {
  16523. svr_.stop();
  16524. if (thread_.joinable()) { thread_.join(); }
  16525. }
  16526. Server svr_;
  16527. int port_ = 0;
  16528. thread thread_;
  16529. };
  16530. // "close" alongside another option still closes the connection, and the
  16531. // response says so rather than leaving the peer to discover it.
  16532. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16533. bool announced_close = false;
  16534. bool reusable = true;
  16535. probe_connection_reuse(port_,
  16536. "GET /keepalive HTTP/1.1\r\n"
  16537. "Host: localhost\r\n"
  16538. "Connection: keep-alive, close\r\n"
  16539. "\r\n",
  16540. &announced_close, &reusable);
  16541. EXPECT_TRUE(announced_close);
  16542. EXPECT_FALSE(reusable);
  16543. }
  16544. // "close" split over two field lines is the same list, so it is honored too.
  16545. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16546. bool announced_close = false;
  16547. bool reusable = true;
  16548. probe_connection_reuse(port_,
  16549. "GET /keepalive HTTP/1.1\r\n"
  16550. "Host: localhost\r\n"
  16551. "Connection: keep-alive\r\n"
  16552. "Connection: close\r\n"
  16553. "\r\n",
  16554. &announced_close, &reusable);
  16555. EXPECT_TRUE(announced_close);
  16556. EXPECT_FALSE(reusable);
  16557. }
  16558. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16559. // keep-alive in the spelling everyone actually sends keeps its connection.
  16560. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16561. bool announced_close = false;
  16562. bool reusable = false;
  16563. probe_connection_reuse(port_,
  16564. "GET /keepalive HTTP/1.0\r\n"
  16565. "Host: localhost\r\n"
  16566. "Connection: keep-alive\r\n"
  16567. "\r\n",
  16568. &announced_close, &reusable);
  16569. EXPECT_FALSE(announced_close);
  16570. EXPECT_TRUE(reusable);
  16571. }
  16572. // A token the value merely contains is not the token itself.
  16573. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16574. bool announced_close = false;
  16575. bool reusable = false;
  16576. probe_connection_reuse(port_,
  16577. "GET /keepalive HTTP/1.1\r\n"
  16578. "Host: localhost\r\n"
  16579. "Connection: notclose\r\n"
  16580. "\r\n",
  16581. &announced_close, &reusable);
  16582. EXPECT_FALSE(announced_close);
  16583. EXPECT_TRUE(reusable);
  16584. }
  16585. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16586. Server svr;
  16587. std::vector<std::string> observed_types;
  16588. svr.Get("/", [&](const Request &req, Response &res) {
  16589. observed_types = req.accept_content_types;
  16590. res.set_content("ok", "text/plain");
  16591. });
  16592. auto port = svr.bind_to_any_port(HOST);
  16593. thread t = thread([&]() { svr.listen_after_bind(); });
  16594. auto se = detail::scope_exit([&] {
  16595. svr.stop();
  16596. t.join();
  16597. ASSERT_FALSE(svr.is_running());
  16598. });
  16599. svr.wait_until_ready();
  16600. Client cli(HOST, port);
  16601. Headers headers;
  16602. headers.emplace("Accept", "text/plain;q=0.5");
  16603. headers.emplace("Accept", "application/json");
  16604. auto res = cli.Get("/", headers);
  16605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16606. EXPECT_EQ(StatusCode::OK_200, res->status);
  16607. // Sorted by q-value, so the second field line's type comes first
  16608. ASSERT_EQ(2U, observed_types.size());
  16609. EXPECT_EQ("application/json", observed_types[0]);
  16610. EXPECT_EQ("text/plain", observed_types[1]);
  16611. }
  16612. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16613. // empty field line must not contribute a bare comma to the combined value.
  16614. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16615. Server svr;
  16616. std::vector<std::string> observed_types;
  16617. svr.Get("/", [&](const Request &req, Response &res) {
  16618. observed_types = req.accept_content_types;
  16619. res.set_content("ok", "text/plain");
  16620. });
  16621. auto port = svr.bind_to_any_port(HOST);
  16622. thread t = thread([&]() { svr.listen_after_bind(); });
  16623. auto se = detail::scope_exit([&] {
  16624. svr.stop();
  16625. t.join();
  16626. ASSERT_FALSE(svr.is_running());
  16627. });
  16628. svr.wait_until_ready();
  16629. // Empty first field line, then a real one
  16630. std::string raw_req = "GET / HTTP/1.1\r\n"
  16631. "Host: localhost\r\n"
  16632. "Accept:\r\n"
  16633. "Accept: application/json\r\n"
  16634. "Connection: close\r\n"
  16635. "\r\n";
  16636. std::string out;
  16637. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16638. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16639. ASSERT_EQ(1U, observed_types.size());
  16640. EXPECT_EQ("application/json", observed_types[0]);
  16641. }
  16642. // The skip in get_combined_header_value() is what keeps an empty field line
  16643. // from contributing a bare comma. Only a trailing empty field line exercises
  16644. // it: a leading one is already covered by the "combined is still empty" check,
  16645. // and parse_accept_header() now ignores the empty element either way, so the
  16646. // request-level test above can no longer tell the two apart.
  16647. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16648. Headers headers;
  16649. headers.emplace("Accept", "text/html");
  16650. headers.emplace("Accept", "");
  16651. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16652. headers.clear();
  16653. headers.emplace("Accept", "");
  16654. headers.emplace("Accept", "application/json");
  16655. EXPECT_EQ("application/json",
  16656. detail::get_combined_header_value(headers, "Accept"));
  16657. }
  16658. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16659. // An encoding offered on a later Accept-Encoding field line is still offered.
  16660. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16661. Server svr;
  16662. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16663. res.set_content(std::string(1024, 'x'), "text/plain");
  16664. });
  16665. auto port = svr.bind_to_any_port(HOST);
  16666. thread t = thread([&]() { svr.listen_after_bind(); });
  16667. auto se = detail::scope_exit([&] {
  16668. svr.stop();
  16669. t.join();
  16670. ASSERT_FALSE(svr.is_running());
  16671. });
  16672. svr.wait_until_ready();
  16673. Client cli(HOST, port);
  16674. cli.set_decompress(false);
  16675. Headers headers;
  16676. headers.emplace("Accept-Encoding", "identity");
  16677. headers.emplace("Accept-Encoding", "gzip");
  16678. auto res = cli.Get("/", headers);
  16679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16680. EXPECT_EQ(StatusCode::OK_200, res->status);
  16681. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16682. }
  16683. #endif
  16684. #ifndef _WIN32
  16685. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16686. Server svr;
  16687. svr.Post("/post", [&](const Request &req, Response &res) {
  16688. res.set_content(req.body, "text/plain");
  16689. });
  16690. svr.Put("/put", [&](const Request &req, Response &res) {
  16691. res.set_content(req.body, "text/plain");
  16692. });
  16693. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16694. res.set_content(req.body, "text/plain");
  16695. });
  16696. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16697. res.set_content(req.body, "text/plain");
  16698. });
  16699. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16700. auto se = detail::scope_exit([&] {
  16701. svr.stop();
  16702. t.join();
  16703. ASSERT_FALSE(svr.is_running());
  16704. });
  16705. svr.wait_until_ready();
  16706. std::string resp;
  16707. // POST without Content-Length
  16708. ASSERT_TRUE(send_request(5,
  16709. "POST /post HTTP/1.1\r\n"
  16710. "Host: localhost\r\n"
  16711. "Connection: close\r\n"
  16712. "\r\n",
  16713. &resp));
  16714. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16715. // PUT without Content-Length
  16716. resp.clear();
  16717. ASSERT_TRUE(send_request(5,
  16718. "PUT /put HTTP/1.1\r\n"
  16719. "Host: localhost\r\n"
  16720. "Connection: close\r\n"
  16721. "\r\n",
  16722. &resp));
  16723. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16724. // PATCH without Content-Length
  16725. resp.clear();
  16726. ASSERT_TRUE(send_request(5,
  16727. "PATCH /patch HTTP/1.1\r\n"
  16728. "Host: localhost\r\n"
  16729. "Connection: close\r\n"
  16730. "\r\n",
  16731. &resp));
  16732. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16733. // DELETE without Content-Length
  16734. resp.clear();
  16735. ASSERT_TRUE(send_request(5,
  16736. "DELETE /delete HTTP/1.1\r\n"
  16737. "Host: localhost\r\n"
  16738. "Connection: close\r\n"
  16739. "\r\n",
  16740. &resp));
  16741. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16742. }
  16743. #endif
  16744. //==============================================================================
  16745. // open_stream() Tests
  16746. //==============================================================================
  16747. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16748. std::string result;
  16749. char buf[8192];
  16750. ssize_t n;
  16751. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16752. result.append(buf, static_cast<size_t>(n));
  16753. }
  16754. return result;
  16755. }
  16756. // Mock stream for unit tests
  16757. class MockStream : public Stream {
  16758. public:
  16759. std::string data;
  16760. size_t pos = 0;
  16761. ssize_t error_after = -1; // -1 = no error
  16762. explicit MockStream(const std::string &d, ssize_t err = -1)
  16763. : data(d), error_after(err) {}
  16764. bool is_readable() const override { return true; }
  16765. bool wait_readable() const override { return true; }
  16766. bool wait_writable() const override { return true; }
  16767. ssize_t read(char *ptr, size_t size) override {
  16768. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16769. if (pos >= data.size()) return 0;
  16770. size_t limit =
  16771. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16772. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16773. std::memcpy(ptr, data.data() + pos, to_read);
  16774. pos += to_read;
  16775. return static_cast<ssize_t>(to_read);
  16776. }
  16777. ssize_t write(const char *, size_t) override { return -1; }
  16778. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16779. ip = "127.0.0.1";
  16780. port = 0;
  16781. }
  16782. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16783. ip = "127.0.0.1";
  16784. port = 0;
  16785. }
  16786. socket_t socket() const override { return INVALID_SOCKET; }
  16787. time_t duration() const override { return 0; }
  16788. };
  16789. TEST(StreamHandleTest, Basic) {
  16790. ClientImpl::StreamHandle handle;
  16791. EXPECT_FALSE(handle.is_valid());
  16792. handle.response = detail::make_unique<Response>();
  16793. handle.error = Error::Connection;
  16794. EXPECT_FALSE(handle.is_valid());
  16795. handle.error = Error::Success;
  16796. EXPECT_TRUE(handle.is_valid());
  16797. }
  16798. TEST(BodyReaderTest, Basic) {
  16799. MockStream stream("Hello, World!");
  16800. detail::BodyReader reader;
  16801. reader.stream = &stream;
  16802. reader.content_length = 13;
  16803. char buf[32];
  16804. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16805. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16806. EXPECT_TRUE(reader.eof);
  16807. }
  16808. TEST(BodyReaderTest, NoStream) {
  16809. detail::BodyReader reader;
  16810. char buf[32];
  16811. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16812. EXPECT_EQ(Error::Connection, reader.last_error);
  16813. }
  16814. TEST(BodyReaderTest, Error) {
  16815. MockStream stream("Hello, World!", 5);
  16816. detail::BodyReader reader;
  16817. reader.stream = &stream;
  16818. reader.content_length = 13;
  16819. char buf[32];
  16820. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16821. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16822. EXPECT_EQ(Error::Read, reader.last_error);
  16823. }
  16824. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16825. // Mock-based StreamHandle tests relying on private internals are removed.
  16826. class OpenStreamTest : public ::testing::Test {
  16827. protected:
  16828. void SetUp() override {
  16829. svr_.Get("/hello", [](const Request &, Response &res) {
  16830. res.set_content("Hello World!", "text/plain");
  16831. });
  16832. svr_.Get("/large", [](const Request &, Response &res) {
  16833. res.set_content(std::string(10000, 'X'), "text/plain");
  16834. });
  16835. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16836. res.set_content("Hello World!", "image/jpeg");
  16837. res.set_header("Content-Encoding", "UTF-8");
  16838. });
  16839. svr_.Get("/chunked", [](const Request &, Response &res) {
  16840. res.set_chunked_content_provider("text/plain",
  16841. [](size_t offset, DataSink &sink) {
  16842. if (offset < 15) {
  16843. sink.write("chunk", 5);
  16844. return true;
  16845. }
  16846. sink.done();
  16847. return true;
  16848. });
  16849. });
  16850. svr_.Get("/compressible", [](const Request &, Response &res) {
  16851. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16852. DataSink &sink) {
  16853. if (offset < 100 * 1024) {
  16854. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16855. sink.write(chunk.data(), chunk.size());
  16856. return true;
  16857. }
  16858. sink.done();
  16859. return true;
  16860. });
  16861. });
  16862. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16863. [](const Request & /*req*/, Response &res) {
  16864. auto i = new int(0);
  16865. res.set_header("Trailer", "Content-Length, X-Allowed");
  16866. res.set_chunked_content_provider(
  16867. "text/plain",
  16868. [i](size_t /*offset*/, DataSink &sink) {
  16869. switch (*i) {
  16870. case 0: sink.os << "123"; break;
  16871. case 1: sink.os << "456"; break;
  16872. case 2: sink.os << "789"; break;
  16873. case 3: {
  16874. sink.done_with_trailer(
  16875. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16876. } break;
  16877. }
  16878. (*i)++;
  16879. return true;
  16880. },
  16881. [i](bool success) {
  16882. EXPECT_TRUE(success);
  16883. delete i;
  16884. });
  16885. });
  16886. // Echo headers endpoint for header-related tests
  16887. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16888. std::string body;
  16889. for (const auto &h : req.headers) {
  16890. body.append(h.first);
  16891. body.push_back(':');
  16892. body.append(h.second);
  16893. body.push_back('\n');
  16894. }
  16895. res.set_content(body, "text/plain");
  16896. });
  16897. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16898. std::string body;
  16899. for (const auto &h : req.headers) {
  16900. body.append(h.first);
  16901. body.push_back(':');
  16902. body.append(h.second);
  16903. body.push_back('\n');
  16904. }
  16905. res.set_content(body, "text/plain");
  16906. });
  16907. port_ = svr_.bind_to_any_port("127.0.0.1");
  16908. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16909. svr_.wait_until_ready();
  16910. }
  16911. void TearDown() override {
  16912. svr_.stop();
  16913. if (thread_.joinable()) thread_.join();
  16914. }
  16915. Server svr_;
  16916. std::thread thread_;
  16917. int port_ = 0;
  16918. };
  16919. TEST_F(OpenStreamTest, Basic) {
  16920. Client cli("127.0.0.1", port_);
  16921. auto handle = cli.open_stream("GET", "/hello");
  16922. EXPECT_TRUE(handle.is_valid());
  16923. EXPECT_EQ("Hello World!", read_all(handle));
  16924. }
  16925. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  16926. Client cli("127.0.0.1", port_);
  16927. auto handle = cli.open_stream("GET", "/unknown-encoding");
  16928. ASSERT_TRUE(handle.is_valid());
  16929. EXPECT_EQ("Hello World!", read_all(handle));
  16930. }
  16931. TEST_F(OpenStreamTest, SmallBuffer) {
  16932. Client cli("127.0.0.1", port_);
  16933. auto handle = cli.open_stream("GET", "/hello");
  16934. std::string result;
  16935. char buf[4];
  16936. ssize_t n;
  16937. while ((n = handle.read(buf, sizeof(buf))) > 0)
  16938. result.append(buf, static_cast<size_t>(n));
  16939. EXPECT_EQ("Hello World!", result);
  16940. }
  16941. TEST_F(OpenStreamTest, DefaultHeaders) {
  16942. Client cli("127.0.0.1", port_);
  16943. // open_stream GET should include Host, User-Agent and Accept-Encoding
  16944. {
  16945. auto handle = cli.open_stream("GET", "/echo-headers");
  16946. ASSERT_TRUE(handle.is_valid());
  16947. auto body = read_all(handle);
  16948. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  16949. std::string::npos);
  16950. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  16951. std::string::npos);
  16952. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  16953. }
  16954. // open_stream POST with body and no explicit content_type should NOT add
  16955. // text/plain Content-Type (behavior differs from non-streaming path), but
  16956. // should include Content-Length
  16957. {
  16958. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  16959. ASSERT_TRUE(handle.is_valid());
  16960. auto body = read_all(handle);
  16961. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  16962. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  16963. }
  16964. // open_stream POST with explicit Content-Type should preserve it
  16965. {
  16966. auto handle = cli.open_stream("POST", "/echo-headers", {},
  16967. {{"Content-Type", "application/custom"}},
  16968. "{}", "application/custom");
  16969. ASSERT_TRUE(handle.is_valid());
  16970. auto body = read_all(handle);
  16971. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  16972. }
  16973. // User-specified User-Agent must not be overwritten for stream API
  16974. {
  16975. auto handle = cli.open_stream("GET", "/echo-headers", {},
  16976. {{"User-Agent", "MyAgent/1.2"}});
  16977. ASSERT_TRUE(handle.is_valid());
  16978. auto body = read_all(handle);
  16979. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  16980. }
  16981. }
  16982. TEST_F(OpenStreamTest, Large) {
  16983. Client cli("127.0.0.1", port_);
  16984. auto handle = cli.open_stream("GET", "/large");
  16985. EXPECT_EQ(10000u, read_all(handle).size());
  16986. }
  16987. TEST_F(OpenStreamTest, ConnectionError) {
  16988. Client cli("127.0.0.1", 9999);
  16989. auto handle = cli.open_stream("GET", "/hello");
  16990. EXPECT_FALSE(handle.is_valid());
  16991. }
  16992. TEST_F(OpenStreamTest, Chunked) {
  16993. Client cli("127.0.0.1", port_);
  16994. auto handle = cli.open_stream("GET", "/chunked");
  16995. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16996. "Transfer-Encoding") == "chunked");
  16997. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  16998. }
  16999. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17000. Client cli("127.0.0.1", port_);
  17001. auto handle =
  17002. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17003. ASSERT_TRUE(handle.is_valid());
  17004. // Consume body to allow trailers to be received/parsed
  17005. auto body = read_all(handle);
  17006. // Explicitly parse trailers (ensure trailers are available for assertion)
  17007. handle.parse_trailers_if_needed();
  17008. EXPECT_EQ(std::string("123456789"), body);
  17009. // The response should include a Trailer header declaring both names
  17010. ASSERT_TRUE(handle.response);
  17011. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17012. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17013. handle.response->get_header_value("Trailer"));
  17014. // Prohibited trailer must not be present
  17015. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17016. // Allowed trailer should be present
  17017. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17018. EXPECT_EQ(std::string("yes"),
  17019. handle.response->get_trailer_value("X-Allowed"));
  17020. // Verify trailers are NOT present as regular headers
  17021. EXPECT_EQ(std::string(""),
  17022. handle.response->get_header_value("Content-Length"));
  17023. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17024. }
  17025. static std::thread serve_single_response(std::promise<int> &port_promise,
  17026. const std::string &response) {
  17027. return std::thread([&port_promise, response] {
  17028. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17029. default_socket_options(srv);
  17030. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17031. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17032. sockaddr_in addr{};
  17033. addr.sin_family = AF_INET;
  17034. addr.sin_port = htons(0); // Let OS assign a free port
  17035. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17036. int opt = 1;
  17037. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17038. #ifdef _WIN32
  17039. reinterpret_cast<const char *>(&opt),
  17040. #else
  17041. &opt,
  17042. #endif
  17043. sizeof(opt));
  17044. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17045. ::listen(srv, 1) != 0) {
  17046. port_promise.set_value(-1);
  17047. detail::close_socket(srv);
  17048. return;
  17049. }
  17050. socklen_t addr_len = sizeof(addr);
  17051. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17052. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17053. sockaddr_in cli_addr{};
  17054. socklen_t cli_len = sizeof(cli_addr);
  17055. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17056. if (cli != INVALID_SOCKET) {
  17057. // Read the complete HTTP request (until the blank line that terminates
  17058. // headers) before sending the response. If the server closes the socket
  17059. // while the client's request data is still unread in the kernel receive
  17060. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17061. // connection on both sides: it discards the client's receive buffer
  17062. // (which already holds our response) and causes any in-progress write on
  17063. // the client to fail with ECONNRESET. Reading all request data first
  17064. // ensures close() emits a graceful FIN.
  17065. {
  17066. char rbuf[256];
  17067. std::string req;
  17068. while (req.find("\r\n\r\n") == std::string::npos) {
  17069. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17070. if (n <= 0) { break; }
  17071. req.append(rbuf, static_cast<size_t>(n));
  17072. }
  17073. }
  17074. ::send(cli,
  17075. #ifdef _WIN32
  17076. static_cast<const char *>(response.c_str()),
  17077. static_cast<int>(response.size()),
  17078. #else
  17079. response.c_str(), response.size(),
  17080. #endif
  17081. 0);
  17082. detail::close_socket(cli);
  17083. }
  17084. detail::close_socket(srv);
  17085. });
  17086. }
  17087. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17088. #ifndef _WIN32
  17089. signal(SIGPIPE, SIG_IGN);
  17090. #endif
  17091. std::promise<int> port_promise;
  17092. auto port_future = port_promise.get_future();
  17093. auto server_thread =
  17094. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17095. "Content-Type: text/plain\r\n"
  17096. "Content-Length: not-a-number\r\n"
  17097. "Connection: close\r\n"
  17098. "\r\n"
  17099. "hello");
  17100. auto port = port_future.get();
  17101. ASSERT_GT(port, 0);
  17102. Client cli("127.0.0.1", port);
  17103. auto handle = cli.open_stream("GET", "/");
  17104. EXPECT_FALSE(handle.is_valid());
  17105. server_thread.join();
  17106. }
  17107. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17108. #ifndef _WIN32
  17109. signal(SIGPIPE, SIG_IGN);
  17110. #endif
  17111. std::promise<int> port_promise;
  17112. auto port_future = port_promise.get_future();
  17113. auto server_thread = serve_single_response(
  17114. port_promise, "HTTP/1.1 200 OK\r\n"
  17115. "Content-Type: text/plain\r\n"
  17116. "Content-Length: 99999999999999999999999999\r\n"
  17117. "Connection: close\r\n"
  17118. "\r\n"
  17119. "hello");
  17120. auto port = port_future.get();
  17121. ASSERT_GT(port, 0);
  17122. // Historically std::stoull would throw std::out_of_range here and crash
  17123. // the process, then parsing silently clamped to a bogus framing length and
  17124. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17125. // so the stream fails to open, matching the not-a-number case above. The
  17126. // process still must NOT terminate.
  17127. Client cli("127.0.0.1", port);
  17128. auto handle = cli.open_stream("GET", "/");
  17129. EXPECT_FALSE(handle.is_valid());
  17130. server_thread.join();
  17131. }
  17132. // Serves `response` to the single request `fn` makes with a fresh client.
  17133. template <typename Fn>
  17134. static void with_single_response(const std::string &response, Fn fn) {
  17135. #ifndef _WIN32
  17136. signal(SIGPIPE, SIG_IGN);
  17137. #endif
  17138. std::promise<int> port_promise;
  17139. auto port_future = port_promise.get_future();
  17140. auto server_thread = serve_single_response(port_promise, response);
  17141. auto se = detail::scope_exit([&] { server_thread.join(); });
  17142. auto port = port_future.get();
  17143. ASSERT_GT(port, 0);
  17144. Client cli("127.0.0.1", port);
  17145. fn(cli);
  17146. }
  17147. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17148. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17149. // the chunked coding and drop Content-Length, so a front-end that trusts
  17150. // Content-Length would disagree about where the body ends (response
  17151. // smuggling). The client must reject such a response.
  17152. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17153. for (const char *te : {"chunked", "gzip, chunked"}) {
  17154. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17155. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17156. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17157. "5\r\nhello\r\n0\r\n\r\n";
  17158. with_single_response(response, [&](Client &cli) {
  17159. auto res = cli.Get("/");
  17160. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17161. EXPECT_EQ(Error::Read, res.error()) << te;
  17162. });
  17163. with_single_response(response, [&](Client &cli) {
  17164. auto handle = cli.open_stream("GET", "/");
  17165. EXPECT_FALSE(handle.is_valid()) << te;
  17166. EXPECT_EQ(Error::Read, handle.error) << te;
  17167. });
  17168. }
  17169. }
  17170. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17171. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17172. // closing the connection (unlike a request, which must be rejected).
  17173. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17174. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17175. "Transfer-Encoding: chunked\r\n"
  17176. "Connection: close\r\n"
  17177. "\r\n"
  17178. "5\r\nhello\r\n0\r\n\r\n",
  17179. "HTTP/1.1 200 OK\r\n"
  17180. "Transfer-Encoding: gzip\r\n"
  17181. "Connection: close\r\n"
  17182. "\r\n"
  17183. "hello"}) {
  17184. with_single_response(response, [&](Client &cli) {
  17185. auto res = cli.Get("/");
  17186. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17187. EXPECT_EQ("hello", res->body);
  17188. });
  17189. with_single_response(response, [&](Client &cli) {
  17190. auto handle = cli.open_stream("GET", "/");
  17191. ASSERT_TRUE(handle.is_valid()) << response;
  17192. EXPECT_EQ("hello", read_all(handle));
  17193. });
  17194. }
  17195. }
  17196. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17197. // framing headers describe nothing to read and must not be rejected.
  17198. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17199. const std::string framing = "Content-Length: 5\r\n"
  17200. "Transfer-Encoding: chunked\r\n"
  17201. "Connection: close\r\n"
  17202. "\r\n";
  17203. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17204. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17205. });
  17206. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17207. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17208. });
  17209. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17210. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17211. with_single_response(response, [&](Client &cli) {
  17212. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17213. });
  17214. with_single_response(response, [&](Client &cli) {
  17215. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17216. });
  17217. }
  17218. }
  17219. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17220. TEST_F(OpenStreamTest, Gzip) {
  17221. Client cli("127.0.0.1", port_);
  17222. auto handle = cli.open_stream("GET", "/compressible", {},
  17223. {{"Accept-Encoding", "gzip"}});
  17224. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17225. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17226. }
  17227. #endif
  17228. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17229. TEST_F(OpenStreamTest, Brotli) {
  17230. Client cli("127.0.0.1", port_);
  17231. auto handle =
  17232. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17233. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17234. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17235. }
  17236. #endif
  17237. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17238. TEST_F(OpenStreamTest, Zstd) {
  17239. Client cli("127.0.0.1", port_);
  17240. auto handle = cli.open_stream("GET", "/compressible", {},
  17241. {{"Accept-Encoding", "zstd"}});
  17242. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17243. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17244. }
  17245. #endif
  17246. #ifdef CPPHTTPLIB_SSL_ENABLED
  17247. class SSLOpenStreamTest : public ::testing::Test {
  17248. protected:
  17249. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17250. void SetUp() override {
  17251. svr_.Get("/hello", [](const Request &, Response &res) {
  17252. res.set_content("Hello SSL World!", "text/plain");
  17253. });
  17254. svr_.Get("/chunked", [](const Request &, Response &res) {
  17255. res.set_chunked_content_provider("text/plain",
  17256. [](size_t offset, DataSink &sink) {
  17257. if (offset < 15) {
  17258. sink.write("chunk", 5);
  17259. return true;
  17260. }
  17261. sink.done();
  17262. return true;
  17263. });
  17264. });
  17265. svr_.Post("/echo", [](const Request &req, Response &res) {
  17266. res.set_content(req.body, req.get_header_value("Content-Type"));
  17267. });
  17268. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17269. std::string body = req.body;
  17270. res.set_chunked_content_provider(
  17271. "text/plain", [body](size_t offset, DataSink &sink) {
  17272. if (offset < body.size()) {
  17273. sink.write(body.data() + offset, body.size() - offset);
  17274. }
  17275. sink.done();
  17276. return true;
  17277. });
  17278. });
  17279. port_ = svr_.bind_to_any_port("127.0.0.1");
  17280. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17281. svr_.wait_until_ready();
  17282. }
  17283. void TearDown() override {
  17284. svr_.stop();
  17285. if (thread_.joinable()) thread_.join();
  17286. }
  17287. SSLServer svr_;
  17288. std::thread thread_;
  17289. int port_ = 0;
  17290. };
  17291. TEST_F(SSLOpenStreamTest, Basic) {
  17292. SSLClient cli("127.0.0.1", port_);
  17293. cli.enable_server_certificate_verification(false);
  17294. auto handle = cli.open_stream("GET", "/hello");
  17295. ASSERT_TRUE(handle.is_valid());
  17296. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17297. }
  17298. TEST_F(SSLOpenStreamTest, Chunked) {
  17299. SSLClient cli("127.0.0.1", port_);
  17300. cli.enable_server_certificate_verification(false);
  17301. auto handle = cli.open_stream("GET", "/chunked");
  17302. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17303. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17304. "Transfer-Encoding") == "chunked");
  17305. auto body = read_all(handle);
  17306. EXPECT_EQ("chunkchunkchunk", body);
  17307. }
  17308. TEST_F(SSLOpenStreamTest, Post) {
  17309. SSLClient cli("127.0.0.1", port_);
  17310. cli.enable_server_certificate_verification(false);
  17311. auto handle =
  17312. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17313. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17314. EXPECT_EQ(200, handle.response->status);
  17315. auto body = read_all(handle);
  17316. EXPECT_EQ("Hello SSL POST", body);
  17317. }
  17318. TEST_F(SSLOpenStreamTest, PostChunked) {
  17319. SSLClient cli("127.0.0.1", port_);
  17320. cli.enable_server_certificate_verification(false);
  17321. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17322. "Chunked SSL Data", "text/plain");
  17323. ASSERT_TRUE(handle.is_valid());
  17324. EXPECT_EQ(200, handle.response->status);
  17325. auto body = read_all(handle);
  17326. EXPECT_EQ("Chunked SSL Data", body);
  17327. }
  17328. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17329. // Content-Length is terminated by the server closing the connection. When the
  17330. // SSL peer sends a close_notify after the body, the client must treat it as a
  17331. // clean EOF and return a successful response rather than an error.
  17332. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17334. ASSERT_TRUE(svr.is_valid());
  17335. svr.set_keep_alive_max_count(1);
  17336. const std::string expected_body = "Hello from connection-close response!";
  17337. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17338. res.set_content_provider("text/plain",
  17339. [&](size_t offset, DataSink &sink) -> bool {
  17340. if (offset < expected_body.size()) {
  17341. sink.write(expected_body.data() + offset,
  17342. expected_body.size() - offset);
  17343. }
  17344. sink.done();
  17345. return true;
  17346. });
  17347. });
  17348. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17349. auto se = detail::scope_exit([&] {
  17350. svr.stop();
  17351. listen_thread.join();
  17352. ASSERT_FALSE(svr.is_running());
  17353. });
  17354. svr.wait_until_ready();
  17355. SSLClient cli(HOST, PORT);
  17356. cli.enable_server_certificate_verification(false);
  17357. auto res = cli.Get("/no-content-length");
  17358. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17359. EXPECT_EQ(StatusCode::OK_200, res->status);
  17360. EXPECT_EQ(expected_body, res->body);
  17361. }
  17362. #endif // CPPHTTPLIB_SSL_ENABLED
  17363. //==============================================================================
  17364. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17365. // results for various scenarios.
  17366. //==============================================================================
  17367. TEST(ParityTest, GetVsOpenStream) {
  17368. Server svr;
  17369. const std::string path = "/parity";
  17370. const std::string content = "Parity test content: hello world";
  17371. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17372. res.set_content(content, "text/plain");
  17373. });
  17374. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17375. auto se = detail::scope_exit([&] {
  17376. svr.stop();
  17377. t.join();
  17378. ASSERT_FALSE(svr.is_running());
  17379. });
  17380. svr.wait_until_ready();
  17381. Client cli(HOST, PORT);
  17382. // Non-stream path
  17383. auto r1 = cli.Get(path);
  17384. ASSERT_TRUE(r1);
  17385. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17386. // Stream path
  17387. auto h = cli.open_stream("GET", path);
  17388. ASSERT_TRUE(h.is_valid());
  17389. EXPECT_EQ(r1->body, read_all(h));
  17390. }
  17391. // Helper to compress data with provided compressor type T
  17392. template <typename Compressor>
  17393. static std::string compress_payload_for_parity(const std::string &in) {
  17394. std::string out;
  17395. Compressor compressor;
  17396. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17397. [&](const char *data, size_t n) {
  17398. out.append(data, n);
  17399. return true;
  17400. });
  17401. EXPECT_TRUE(ok);
  17402. return out;
  17403. }
  17404. // Helper function for compression parity tests
  17405. template <typename Compressor>
  17406. static void test_compression_parity(const std::string &original,
  17407. const std::string &path,
  17408. const std::string &encoding) {
  17409. const std::string compressed =
  17410. compress_payload_for_parity<Compressor>(original);
  17411. Server svr;
  17412. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17413. res.set_content(compressed, "application/octet-stream");
  17414. res.set_header("Content-Encoding", encoding);
  17415. });
  17416. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17417. auto se = detail::scope_exit([&] {
  17418. svr.stop();
  17419. t.join();
  17420. ASSERT_FALSE(svr.is_running());
  17421. });
  17422. svr.wait_until_ready();
  17423. Client cli(HOST, PORT);
  17424. // Non-streaming
  17425. {
  17426. auto res = cli.Get(path);
  17427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17428. EXPECT_EQ(StatusCode::OK_200, res->status);
  17429. EXPECT_EQ(original, res->body);
  17430. }
  17431. // Streaming
  17432. {
  17433. auto h = cli.open_stream("GET", path);
  17434. ASSERT_TRUE(h.is_valid());
  17435. EXPECT_EQ(original, read_all(h));
  17436. }
  17437. }
  17438. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17439. TEST(ParityTest, Gzip) {
  17440. test_compression_parity<detail::gzip_compressor>(
  17441. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17442. }
  17443. #endif
  17444. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17445. TEST(ParityTest, Brotli) {
  17446. test_compression_parity<detail::brotli_compressor>(
  17447. "Hello, brotli parity test payload", "/parity-br", "br");
  17448. }
  17449. #endif
  17450. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17451. TEST(ParityTest, Zstd) {
  17452. test_compression_parity<detail::zstd_compressor>(
  17453. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17454. }
  17455. #endif
  17456. //==============================================================================
  17457. // New Stream API Tests
  17458. //==============================================================================
  17459. inline std::string read_body(httplib::stream::Result &result) {
  17460. std::string body;
  17461. while (result.next()) {
  17462. body.append(result.data(), result.size());
  17463. }
  17464. return body;
  17465. }
  17466. TEST(ClientConnectionTest, Basic) {
  17467. httplib::ClientConnection conn;
  17468. EXPECT_FALSE(conn.is_open());
  17469. conn.sock = 1;
  17470. EXPECT_TRUE(conn.is_open());
  17471. httplib::ClientConnection conn2(std::move(conn));
  17472. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17473. conn2.sock = INVALID_SOCKET;
  17474. }
  17475. // Unified test server for all stream::* tests
  17476. class StreamApiTest : public ::testing::Test {
  17477. protected:
  17478. void SetUp() override {
  17479. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17480. res.set_content("Hello World!", "text/plain");
  17481. });
  17482. svr_.Get("/echo-params",
  17483. [](const httplib::Request &req, httplib::Response &res) {
  17484. std::string r;
  17485. for (const auto &p : req.params) {
  17486. if (!r.empty()) r += "&";
  17487. r += p.first + "=" + p.second;
  17488. }
  17489. res.set_content(r, "text/plain");
  17490. });
  17491. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17492. res.set_content(req.body, req.get_header_value("Content-Type"));
  17493. });
  17494. svr_.Post("/echo-headers",
  17495. [](const httplib::Request &req, httplib::Response &res) {
  17496. std::string r;
  17497. for (const auto &h : req.headers)
  17498. r += h.first + ": " + h.second + "\n";
  17499. res.set_content(r, "text/plain");
  17500. });
  17501. svr_.Post("/echo-params",
  17502. [](const httplib::Request &req, httplib::Response &res) {
  17503. std::string r = "params:";
  17504. for (const auto &p : req.params)
  17505. r += p.first + "=" + p.second + ";";
  17506. res.set_content(r + " body:" + req.body, "text/plain");
  17507. });
  17508. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17509. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17510. });
  17511. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17512. res.set_content("PUT:" + req.body, "text/plain");
  17513. });
  17514. svr_.Patch("/echo",
  17515. [](const httplib::Request &req, httplib::Response &res) {
  17516. res.set_content("PATCH:" + req.body, "text/plain");
  17517. });
  17518. svr_.Delete(
  17519. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17520. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17521. "text/plain");
  17522. });
  17523. svr_.Get("/head-test",
  17524. [](const httplib::Request &, httplib::Response &res) {
  17525. res.set_content("body for HEAD", "text/plain");
  17526. });
  17527. svr_.Options("/options",
  17528. [](const httplib::Request &, httplib::Response &res) {
  17529. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17530. });
  17531. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17532. svr_.wait_until_ready();
  17533. }
  17534. void TearDown() override {
  17535. svr_.stop();
  17536. if (thread_.joinable()) thread_.join();
  17537. }
  17538. httplib::Server svr_;
  17539. std::thread thread_;
  17540. };
  17541. // stream::Get tests
  17542. TEST_F(StreamApiTest, GetBasic) {
  17543. httplib::Client cli(HOST, PORT);
  17544. auto result = httplib::stream::Get(cli, "/hello");
  17545. ASSERT_TRUE(result.is_valid());
  17546. EXPECT_EQ(200, result.status());
  17547. EXPECT_EQ("Hello World!", read_body(result));
  17548. }
  17549. TEST_F(StreamApiTest, GetWithParams) {
  17550. httplib::Client cli(HOST, PORT);
  17551. httplib::Params params{{"foo", "bar"}};
  17552. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17553. ASSERT_TRUE(result.is_valid());
  17554. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17555. }
  17556. TEST_F(StreamApiTest, GetConnectionError) {
  17557. httplib::Client cli(HOST, 9999);
  17558. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17559. }
  17560. TEST_F(StreamApiTest, Get404) {
  17561. httplib::Client cli(HOST, PORT);
  17562. auto result = httplib::stream::Get(cli, "/nonexistent");
  17563. EXPECT_TRUE(result.is_valid());
  17564. EXPECT_EQ(404, result.status());
  17565. }
  17566. // stream::Post tests
  17567. TEST_F(StreamApiTest, PostBasic) {
  17568. httplib::Client cli(HOST, PORT);
  17569. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17570. "application/json");
  17571. ASSERT_TRUE(result.is_valid());
  17572. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17573. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17574. }
  17575. TEST_F(StreamApiTest, PostWithHeaders) {
  17576. httplib::Client cli(HOST, PORT);
  17577. httplib::Headers headers{{"X-Custom", "value"}};
  17578. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17579. "text/plain");
  17580. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17581. }
  17582. TEST_F(StreamApiTest, PostWithParams) {
  17583. httplib::Client cli(HOST, PORT);
  17584. httplib::Params params{{"k", "v"}};
  17585. auto result =
  17586. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17587. auto body = read_body(result);
  17588. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17589. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17590. }
  17591. TEST_F(StreamApiTest, PostLarge) {
  17592. httplib::Client cli(HOST, PORT);
  17593. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17594. size_t total = 0;
  17595. while (result.next()) {
  17596. total += result.size();
  17597. }
  17598. EXPECT_EQ(100u * 1024u, total);
  17599. }
  17600. // stream::Put/Patch tests
  17601. TEST_F(StreamApiTest, PutAndPatch) {
  17602. httplib::Client cli(HOST, PORT);
  17603. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17604. EXPECT_EQ("PUT:test", read_body(put));
  17605. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17606. EXPECT_EQ("PATCH:test", read_body(patch));
  17607. }
  17608. // stream::Delete tests
  17609. TEST_F(StreamApiTest, Delete) {
  17610. httplib::Client cli(HOST, PORT);
  17611. auto del1 = httplib::stream::Delete(cli, "/resource");
  17612. EXPECT_EQ("Deleted", read_body(del1));
  17613. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17614. EXPECT_EQ("Deleted:data", read_body(del2));
  17615. }
  17616. // stream::Head/Options tests
  17617. TEST_F(StreamApiTest, HeadAndOptions) {
  17618. httplib::Client cli(HOST, PORT);
  17619. auto head = httplib::stream::Head(cli, "/head-test");
  17620. EXPECT_TRUE(head.is_valid());
  17621. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17622. auto opts = httplib::stream::Options(cli, "/options");
  17623. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17624. }
  17625. // SSL stream::* tests
  17626. #ifdef CPPHTTPLIB_SSL_ENABLED
  17627. class SSLStreamApiTest : public ::testing::Test {
  17628. protected:
  17629. void SetUp() override {
  17630. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17631. res.set_content("Hello SSL!", "text/plain");
  17632. });
  17633. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17634. res.set_content(req.body, "text/plain");
  17635. });
  17636. port_ = svr_.bind_to_any_port("127.0.0.1");
  17637. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17638. svr_.wait_until_ready();
  17639. }
  17640. void TearDown() override {
  17641. svr_.stop();
  17642. if (thread_.joinable()) thread_.join();
  17643. }
  17644. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17645. std::thread thread_;
  17646. int port_ = 0;
  17647. };
  17648. TEST_F(SSLStreamApiTest, GetAndPost) {
  17649. httplib::SSLClient cli("127.0.0.1", port_);
  17650. cli.enable_server_certificate_verification(false);
  17651. auto get = httplib::stream::Get(cli, "/hello");
  17652. EXPECT_EQ("Hello SSL!", read_body(get));
  17653. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17654. EXPECT_EQ("test", read_body(post));
  17655. }
  17656. #endif
  17657. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17658. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17659. // BodyReader
  17660. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17661. // Test that read timeout during streaming is detected
  17662. // Use a large content-length response where server delays mid-stream
  17663. Server svr;
  17664. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17665. // Send a large response with delay in the middle
  17666. res.set_content_provider(
  17667. 1000, // content_length
  17668. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17669. if (offset < 100) {
  17670. // Send first 100 bytes immediately
  17671. std::string data(100, 'A');
  17672. sink.write(data.c_str(), data.size());
  17673. return true;
  17674. }
  17675. // Then delay longer than client timeout
  17676. std::this_thread::sleep_for(std::chrono::seconds(3));
  17677. std::string data(900, 'B');
  17678. sink.write(data.c_str(), data.size());
  17679. return true;
  17680. });
  17681. });
  17682. auto port = 8091;
  17683. std::thread t([&]() { svr.listen("localhost", port); });
  17684. svr.wait_until_ready();
  17685. Client cli("localhost", port);
  17686. cli.set_read_timeout(1, 0); // 1 second timeout
  17687. auto handle = cli.open_stream("GET", "/slow-stream");
  17688. ASSERT_TRUE(handle.is_valid());
  17689. char buf[256];
  17690. ssize_t total = 0;
  17691. ssize_t n;
  17692. bool got_error = false;
  17693. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17694. total += n;
  17695. }
  17696. if (n < 0) {
  17697. got_error = true;
  17698. // Should be timeout or read error
  17699. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17700. handle.get_read_error() == Error::Read)
  17701. << "Actual error: " << to_string(handle.get_read_error());
  17702. }
  17703. // Either we got an error, or we got less data than expected
  17704. EXPECT_TRUE(got_error || total < 1000)
  17705. << "Expected timeout but got all " << total << " bytes";
  17706. svr.stop();
  17707. t.join();
  17708. }
  17709. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17710. // Test connection closed detection via BodyReader
  17711. Server svr;
  17712. std::atomic<bool> close_now{false};
  17713. svr.Get("/will-close", [&](const Request &, Response &res) {
  17714. res.set_content_provider(
  17715. 10000, // Large content_length that we won't fully send
  17716. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17717. if (offset < 100) {
  17718. std::string data(100, 'X');
  17719. sink.write(data.c_str(), data.size());
  17720. return true;
  17721. }
  17722. // Wait for signal then abort
  17723. while (!close_now) {
  17724. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17725. }
  17726. return false; // Abort - server will close connection
  17727. });
  17728. });
  17729. auto port = 8092;
  17730. std::thread t([&]() { svr.listen("localhost", port); });
  17731. svr.wait_until_ready();
  17732. Client cli("localhost", port);
  17733. auto handle = cli.open_stream("GET", "/will-close");
  17734. ASSERT_TRUE(handle.is_valid());
  17735. char buf[256];
  17736. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17737. EXPECT_GT(n, 0) << "First read should succeed";
  17738. // Signal server to close
  17739. close_now = true;
  17740. // Keep reading until error or EOF
  17741. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17742. // Keep reading
  17743. }
  17744. // Should get an error since content_length wasn't satisfied
  17745. if (n < 0) {
  17746. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17747. handle.get_read_error() == Error::Read)
  17748. << "Actual error: " << to_string(handle.get_read_error());
  17749. }
  17750. svr.stop();
  17751. t.join();
  17752. }
  17753. #ifdef CPPHTTPLIB_SSL_ENABLED
  17754. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  17755. // Test that read timeout during SSL streaming is detected
  17756. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17757. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17758. res.set_content_provider(
  17759. 1000, "text/plain",
  17760. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17761. if (offset < 100) {
  17762. std::string data(100, 'A');
  17763. sink.write(data.c_str(), data.size());
  17764. return true;
  17765. }
  17766. std::this_thread::sleep_for(std::chrono::seconds(3));
  17767. std::string data(900, 'B');
  17768. sink.write(data.c_str(), data.size());
  17769. return true;
  17770. });
  17771. });
  17772. auto port = 8093;
  17773. std::thread t([&]() { svr.listen("localhost", port); });
  17774. svr.wait_until_ready();
  17775. SSLClient cli("localhost", port);
  17776. cli.enable_server_certificate_verification(false);
  17777. cli.set_read_timeout(1, 0); // 1 second timeout
  17778. auto handle = cli.open_stream("GET", "/slow-stream");
  17779. ASSERT_TRUE(handle.is_valid());
  17780. char buf[256];
  17781. ssize_t total = 0;
  17782. ssize_t n;
  17783. bool got_error = false;
  17784. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17785. total += n;
  17786. }
  17787. if (n < 0) {
  17788. got_error = true;
  17789. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17790. handle.get_read_error() == Error::Read)
  17791. << "Actual error: " << to_string(handle.get_read_error());
  17792. }
  17793. EXPECT_TRUE(got_error || total < 1000)
  17794. << "Expected timeout but got all " << total << " bytes";
  17795. svr.stop();
  17796. t.join();
  17797. }
  17798. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17799. // Test SSL connection closed detection
  17800. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17801. std::atomic<bool> close_now{false};
  17802. svr.Get("/will-close", [&](const Request &, Response &res) {
  17803. res.set_content_provider(
  17804. 10000, "text/plain",
  17805. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17806. if (offset < 100) {
  17807. std::string data(100, 'X');
  17808. sink.write(data.c_str(), data.size());
  17809. return true;
  17810. }
  17811. while (!close_now) {
  17812. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17813. }
  17814. return false;
  17815. });
  17816. });
  17817. auto port = 8094;
  17818. std::thread t([&]() { svr.listen("localhost", port); });
  17819. svr.wait_until_ready();
  17820. SSLClient cli("localhost", port);
  17821. cli.enable_server_certificate_verification(false);
  17822. auto handle = cli.open_stream("GET", "/will-close");
  17823. ASSERT_TRUE(handle.is_valid());
  17824. char buf[256];
  17825. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17826. EXPECT_GT(n, 0);
  17827. // Signal server to close
  17828. close_now = true;
  17829. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17830. // Keep reading
  17831. }
  17832. if (n < 0) {
  17833. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17834. handle.get_read_error() == Error::Read)
  17835. << "Actual error: " << to_string(handle.get_read_error());
  17836. }
  17837. svr.stop();
  17838. t.join();
  17839. }
  17840. #endif
  17841. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17842. using namespace httplib;
  17843. // Create a test file
  17844. const char *fname = "etag_testfile.txt";
  17845. const char *content = "etag-content";
  17846. {
  17847. std::ofstream ofs(fname);
  17848. ofs << content;
  17849. ASSERT_TRUE(ofs.good());
  17850. }
  17851. Server svr;
  17852. svr.set_mount_point("/static", ".");
  17853. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17854. svr.wait_until_ready();
  17855. Client cli(HOST, PORT);
  17856. // First request: should get 200 with ETag header
  17857. auto res1 = cli.Get("/static/etag_testfile.txt");
  17858. ASSERT_TRUE(res1);
  17859. ASSERT_EQ(200, res1->status);
  17860. ASSERT_TRUE(res1->has_header("ETag"));
  17861. std::string etag = res1->get_header_value("ETag");
  17862. EXPECT_FALSE(etag.empty());
  17863. // Verify ETag format: W/"hex-hex"
  17864. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17865. EXPECT_EQ('W', etag[0]);
  17866. EXPECT_EQ('/', etag[1]);
  17867. EXPECT_EQ('"', etag[2]);
  17868. EXPECT_EQ('"', etag.back());
  17869. // Exact match: expect 304 Not Modified
  17870. Headers h2 = {{"If-None-Match", etag}};
  17871. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17872. ASSERT_TRUE(res2);
  17873. EXPECT_EQ(304, res2->status);
  17874. // Wildcard match: expect 304 Not Modified
  17875. Headers h3 = {{"If-None-Match", "*"}};
  17876. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17877. ASSERT_TRUE(res3);
  17878. EXPECT_EQ(304, res3->status);
  17879. // Non-matching ETag: expect 200
  17880. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17881. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17882. ASSERT_TRUE(res4);
  17883. EXPECT_EQ(200, res4->status);
  17884. // Multiple ETags with one matching: expect 304
  17885. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17886. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17887. ASSERT_TRUE(res5);
  17888. EXPECT_EQ(304, res5->status);
  17889. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17890. // that equivalent to the single comma-separated list above, so the match on
  17891. // the second line must still be found.
  17892. Headers h6;
  17893. h6.emplace("If-None-Match", "W/\"other\"");
  17894. h6.emplace("If-None-Match", etag);
  17895. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17896. ASSERT_TRUE(res6);
  17897. EXPECT_EQ(304, res6->status);
  17898. svr.stop();
  17899. t.join();
  17900. std::remove(fname);
  17901. }
  17902. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  17903. using namespace httplib;
  17904. Server svr;
  17905. svr.set_mount_point("/static", ".");
  17906. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17907. svr.wait_until_ready();
  17908. Client cli(HOST, PORT);
  17909. // Send If-None-Match: * to a non-existent file
  17910. Headers h = {{"If-None-Match", "*"}};
  17911. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  17912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17913. EXPECT_EQ(404, res->status);
  17914. svr.stop();
  17915. t.join();
  17916. }
  17917. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  17918. using namespace httplib;
  17919. // Create a test file
  17920. const char *fname = "etag_boundary_testfile.txt";
  17921. const char *content = "boundary-test";
  17922. {
  17923. std::ofstream ofs(fname);
  17924. ofs << content;
  17925. ASSERT_TRUE(ofs.good());
  17926. }
  17927. Server svr;
  17928. svr.set_mount_point("/static", ".");
  17929. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17930. svr.wait_until_ready();
  17931. Client cli(HOST, PORT);
  17932. // Get the actual ETag
  17933. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  17934. ASSERT_TRUE(res1);
  17935. ASSERT_EQ(200, res1->status);
  17936. ASSERT_TRUE(res1->has_header("ETag"));
  17937. std::string etag = res1->get_header_value("ETag");
  17938. // Test 1: Very long ETag value (longer than actual ETag)
  17939. // Should NOT match and return 200 (not trigger out-of-bounds read)
  17940. Headers h1 = {{"If-None-Match", "W/"
  17941. "\"very-long-etag-value-that-is-much-longer-"
  17942. "than-the-actual-etag-value\""}};
  17943. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  17944. ASSERT_TRUE(res2);
  17945. EXPECT_EQ(200, res2->status); // Should not match
  17946. // Test 2: Long string followed by wildcard
  17947. // Should match on "*" and return 304 (without out-of-bounds read on the long
  17948. // string)
  17949. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  17950. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  17951. ASSERT_TRUE(res3);
  17952. EXPECT_EQ(304, res3->status); // Should match on "*"
  17953. // Test 3: Wildcard followed by long string
  17954. // Should match on "*" immediately and return 304
  17955. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  17956. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  17957. ASSERT_TRUE(res4);
  17958. EXPECT_EQ(304, res4->status); // Should match on "*"
  17959. // Test 4: Multiple long non-matching values
  17960. // Should NOT match and return 200 (test that all comparisons are safe)
  17961. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  17962. "W/\"second-long-non-matching-value\", "
  17963. "W/\"third-long-non-matching-value\""}};
  17964. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  17965. ASSERT_TRUE(res5);
  17966. EXPECT_EQ(200, res5->status); // Should not match
  17967. // Test 5: Single character that is not "*" (edge case)
  17968. Headers h5 = {{"If-None-Match", "X"}};
  17969. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  17970. ASSERT_TRUE(res6);
  17971. EXPECT_EQ(200, res6->status); // Should not match
  17972. svr.stop();
  17973. t.join();
  17974. std::remove(fname);
  17975. }
  17976. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  17977. using namespace httplib;
  17978. // Create a test file
  17979. const char *fname = "ims_testfile.txt";
  17980. const char *content = "if-modified-since-test";
  17981. {
  17982. std::ofstream ofs(fname);
  17983. ofs << content;
  17984. ASSERT_TRUE(ofs.good());
  17985. }
  17986. Server svr;
  17987. svr.set_mount_point("/static", ".");
  17988. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17989. svr.wait_until_ready();
  17990. Client cli(HOST, PORT);
  17991. // First request: should get 200 with Last-Modified header
  17992. auto res1 = cli.Get("/static/ims_testfile.txt");
  17993. ASSERT_TRUE(res1);
  17994. ASSERT_EQ(200, res1->status);
  17995. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17996. std::string last_modified = res1->get_header_value("Last-Modified");
  17997. EXPECT_FALSE(last_modified.empty());
  17998. // If-Modified-Since with same time: expect 304
  17999. Headers h2 = {{"If-Modified-Since", last_modified}};
  18000. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18001. ASSERT_TRUE(res2);
  18002. EXPECT_EQ(304, res2->status);
  18003. // If-Modified-Since with future time: expect 304
  18004. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18005. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18006. ASSERT_TRUE(res3);
  18007. EXPECT_EQ(304, res3->status);
  18008. // If-Modified-Since with past time: expect 200
  18009. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18010. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18011. ASSERT_TRUE(res4);
  18012. EXPECT_EQ(200, res4->status);
  18013. // If-None-Match takes precedence over If-Modified-Since
  18014. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18015. ASSERT_TRUE(res1->has_header("ETag"));
  18016. std::string etag = res1->get_header_value("ETag");
  18017. Headers h5 = {{"If-None-Match", etag},
  18018. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18019. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18020. ASSERT_TRUE(res5);
  18021. EXPECT_EQ(304, res5->status);
  18022. svr.stop();
  18023. t.join();
  18024. std::remove(fname);
  18025. }
  18026. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18027. using namespace httplib;
  18028. Server svr;
  18029. // Endpoint that returns compressible content
  18030. svr.Get("/compressible", [](const Request &, Response &res) {
  18031. // Return a large enough body to trigger compression
  18032. std::string body(1000, 'a');
  18033. res.set_content(body, "text/plain");
  18034. });
  18035. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18036. svr.wait_until_ready();
  18037. Client cli(HOST, PORT);
  18038. // Request with gzip support: should get Vary header when compressed
  18039. cli.set_compress(true);
  18040. auto res1 = cli.Get("/compressible");
  18041. ASSERT_TRUE(res1);
  18042. EXPECT_EQ(200, res1->status);
  18043. // If Content-Encoding is set, Vary should also be set
  18044. if (res1->has_header("Content-Encoding")) {
  18045. EXPECT_TRUE(res1->has_header("Vary"));
  18046. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18047. }
  18048. // Request without Accept-Encoding header: should not have compression
  18049. Headers h_no_compress;
  18050. auto res2 = cli.Get("/compressible", h_no_compress);
  18051. ASSERT_TRUE(res2);
  18052. EXPECT_EQ(200, res2->status);
  18053. // Verify Vary header is present when compression is applied
  18054. // (the exact behavior depends on server configuration)
  18055. svr.stop();
  18056. t.join();
  18057. }
  18058. TEST(ETagTest, IfRangeWithETag) {
  18059. using namespace httplib;
  18060. // Create a test file with known content
  18061. const char *fname = "if_range_testfile.txt";
  18062. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18063. {
  18064. std::ofstream ofs(fname);
  18065. ofs << content;
  18066. ASSERT_TRUE(ofs.good());
  18067. }
  18068. Server svr;
  18069. svr.set_mount_point("/static", ".");
  18070. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18071. svr.wait_until_ready();
  18072. Client cli(HOST, PORT);
  18073. // First request: get ETag
  18074. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18075. ASSERT_TRUE(res1);
  18076. ASSERT_EQ(200, res1->status);
  18077. ASSERT_TRUE(res1->has_header("ETag"));
  18078. std::string etag = res1->get_header_value("ETag");
  18079. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18080. // Since our server generates weak ETags (W/"..."), If-Range with our
  18081. // ETag should NOT result in partial content - it should return full content.
  18082. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18083. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18084. ASSERT_TRUE(res2);
  18085. // Weak ETag in If-Range -> full content (200), not partial (206)
  18086. EXPECT_EQ(200, res2->status);
  18087. EXPECT_EQ(content, res2->body);
  18088. EXPECT_FALSE(res2->has_header("Content-Range"));
  18089. // Range request with non-matching If-Range (ETag): should get 200 (full
  18090. // content)
  18091. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18092. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18093. ASSERT_TRUE(res3);
  18094. EXPECT_EQ(200, res3->status);
  18095. EXPECT_EQ(content, res3->body);
  18096. EXPECT_FALSE(res3->has_header("Content-Range"));
  18097. // Range request with strong ETag (hypothetical - our server doesn't generate
  18098. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18099. // should return full content)
  18100. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18101. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18102. ASSERT_TRUE(res4);
  18103. EXPECT_EQ(200, res4->status);
  18104. EXPECT_EQ(content, res4->body);
  18105. EXPECT_FALSE(res4->has_header("Content-Range"));
  18106. svr.stop();
  18107. t.join();
  18108. std::remove(fname);
  18109. }
  18110. TEST(ETagTest, IfRangeWithDate) {
  18111. using namespace httplib;
  18112. // Create a test file
  18113. const char *fname = "if_range_date_testfile.txt";
  18114. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18115. {
  18116. std::ofstream ofs(fname);
  18117. ofs << content;
  18118. ASSERT_TRUE(ofs.good());
  18119. }
  18120. Server svr;
  18121. svr.set_mount_point("/static", ".");
  18122. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18123. svr.wait_until_ready();
  18124. Client cli(HOST, PORT);
  18125. // First request: get Last-Modified
  18126. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18127. ASSERT_TRUE(res1);
  18128. ASSERT_EQ(200, res1->status);
  18129. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18130. std::string last_modified = res1->get_header_value("Last-Modified");
  18131. // Range request with matching If-Range (date): should get 206
  18132. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18133. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18134. ASSERT_TRUE(res2);
  18135. EXPECT_EQ(206, res2->status);
  18136. EXPECT_EQ("FGHIJ", res2->body);
  18137. // Range request with old If-Range date: should get 200 (full content)
  18138. Headers h3 = {{"Range", "bytes=5-9"},
  18139. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18140. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18141. ASSERT_TRUE(res3);
  18142. EXPECT_EQ(200, res3->status);
  18143. EXPECT_EQ(content, res3->body);
  18144. // Range request with future If-Range date: should get 206
  18145. Headers h4 = {{"Range", "bytes=0-4"},
  18146. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18147. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18148. ASSERT_TRUE(res4);
  18149. EXPECT_EQ(206, res4->status);
  18150. EXPECT_EQ("ABCDE", res4->body);
  18151. svr.stop();
  18152. t.join();
  18153. std::remove(fname);
  18154. }
  18155. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18156. using namespace httplib;
  18157. const char *fname = "etag_malformed.txt";
  18158. const char *content = "malformed-etag";
  18159. {
  18160. std::ofstream ofs(fname);
  18161. ofs << content;
  18162. ASSERT_TRUE(ofs.good());
  18163. }
  18164. Server svr;
  18165. svr.set_mount_point("/static", ".");
  18166. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18167. svr.wait_until_ready();
  18168. Client cli(HOST, PORT);
  18169. // baseline: should get 200 and an ETag
  18170. auto res1 = cli.Get("/static/etag_malformed.txt");
  18171. ASSERT_TRUE(res1);
  18172. ASSERT_EQ(200, res1->status);
  18173. ASSERT_TRUE(res1->has_header("ETag"));
  18174. // Malformed ETag value (missing quotes) should be treated as non-matching
  18175. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18176. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18177. ASSERT_TRUE(res_bad);
  18178. EXPECT_EQ(200, res_bad->status);
  18179. // Whitespace-only header value should be considered invalid / non-matching
  18180. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18181. "Host: localhost\r\n"
  18182. "If-None-Match: \r\n"
  18183. "Connection: close\r\n"
  18184. "\r\n";
  18185. std::string out;
  18186. ASSERT_TRUE(send_request(5, raw_req, &out));
  18187. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18188. svr.stop();
  18189. t.join();
  18190. std::remove(fname);
  18191. }
  18192. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18193. using namespace httplib;
  18194. const char *fname = "ims_invalid_format.txt";
  18195. const char *content = "ims-bad-format";
  18196. {
  18197. std::ofstream ofs(fname);
  18198. ofs << content;
  18199. ASSERT_TRUE(ofs.good());
  18200. }
  18201. Server svr;
  18202. svr.set_mount_point("/static", ".");
  18203. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18204. svr.wait_until_ready();
  18205. Client cli(HOST, PORT);
  18206. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18207. ASSERT_TRUE(res1);
  18208. ASSERT_EQ(200, res1->status);
  18209. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18210. // If-Modified-Since with invalid format should not result in 304
  18211. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18212. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18213. ASSERT_TRUE(res_bad);
  18214. EXPECT_EQ(200, res_bad->status);
  18215. // If-Range with invalid date format should be treated as mismatch -> full
  18216. // content (200)
  18217. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18218. {"If-Range", "invalid-date"}};
  18219. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18220. ASSERT_TRUE(res_ifrange);
  18221. EXPECT_EQ(200, res_ifrange->status);
  18222. svr.stop();
  18223. t.join();
  18224. std::remove(fname);
  18225. }
  18226. TEST(ETagTest, IfRangeWithMalformedETag) {
  18227. using namespace httplib;
  18228. const char *fname = "ifrange_malformed.txt";
  18229. const std::string content = "0123456789";
  18230. {
  18231. std::ofstream ofs(fname);
  18232. ofs << content;
  18233. ASSERT_TRUE(ofs.good());
  18234. }
  18235. Server svr;
  18236. svr.set_mount_point("/static", ".");
  18237. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18238. svr.wait_until_ready();
  18239. Client cli(HOST, PORT);
  18240. // First request: get ETag
  18241. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18242. ASSERT_TRUE(res1);
  18243. ASSERT_EQ(200, res1->status);
  18244. ASSERT_TRUE(res1->has_header("ETag"));
  18245. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18246. // full content (200)
  18247. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18248. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18249. ASSERT_TRUE(res2);
  18250. EXPECT_EQ(200, res2->status);
  18251. EXPECT_EQ(content, res2->body);
  18252. svr.stop();
  18253. t.join();
  18254. std::remove(fname);
  18255. }
  18256. TEST(ETagTest, ExtremeLargeDateValues) {
  18257. using namespace httplib;
  18258. const char *fname = "ims_extreme_date.txt";
  18259. const char *content = "ims-extreme-date";
  18260. {
  18261. std::ofstream ofs(fname);
  18262. ofs << content;
  18263. ASSERT_TRUE(ofs.good());
  18264. }
  18265. Server svr;
  18266. svr.set_mount_point("/static", ".");
  18267. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18268. svr.wait_until_ready();
  18269. Client cli(HOST, PORT);
  18270. auto res1 = cli.Get(std::string("/static/") + fname);
  18271. ASSERT_TRUE(res1);
  18272. ASSERT_EQ(200, res1->status);
  18273. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18274. // Extremely large year that may overflow date parsing routines.
  18275. Headers h_large_date = {
  18276. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18277. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18278. ASSERT_TRUE(res_bad);
  18279. // Expect server to treat this as invalid/mismatch and return full content
  18280. EXPECT_EQ(200, res_bad->status);
  18281. // If-Range with extremely large date should be treated as mismatch -> full
  18282. // content (200)
  18283. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18284. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18285. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18286. ASSERT_TRUE(res_ifrange);
  18287. EXPECT_EQ(200, res_ifrange->status);
  18288. svr.stop();
  18289. t.join();
  18290. std::remove(fname);
  18291. }
  18292. TEST(ETagTest, NegativeFileModificationTime) {
  18293. using namespace httplib;
  18294. const char *fname = "ims_negative_mtime.txt";
  18295. const std::string content = "negative-mtime";
  18296. {
  18297. std::ofstream ofs(fname);
  18298. ofs << content;
  18299. ASSERT_TRUE(ofs.good());
  18300. }
  18301. // Try to set file mtime to a negative value. This may fail on some
  18302. // platforms/filesystems; if it fails, the test will still verify server
  18303. // behaves safely by performing a regular conditional request.
  18304. #if defined(__APPLE__) || defined(__linux__)
  18305. bool set_negative = false;
  18306. do {
  18307. struct timeval times[2];
  18308. // access time: now
  18309. times[0].tv_sec = time(nullptr);
  18310. times[0].tv_usec = 0;
  18311. // modification time: negative (e.g., -1)
  18312. times[1].tv_sec = -1;
  18313. times[1].tv_usec = 0;
  18314. if (utimes(fname, times) == 0) { set_negative = true; }
  18315. } while (0);
  18316. #else
  18317. bool set_negative = false;
  18318. #endif
  18319. Server svr;
  18320. svr.set_mount_point("/static", ".");
  18321. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18322. svr.wait_until_ready();
  18323. Client cli(HOST, PORT);
  18324. auto res1 = cli.Get(std::string("/static/") + fname);
  18325. ASSERT_TRUE(res1);
  18326. ASSERT_EQ(200, res1->status);
  18327. bool has_last_modified = res1->has_header("Last-Modified");
  18328. std::string last_modified;
  18329. if (has_last_modified) {
  18330. last_modified = res1->get_header_value("Last-Modified");
  18331. }
  18332. if (set_negative) {
  18333. // If we successfully set a negative mtime, ensure server returns a
  18334. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18335. // with an old date and ensure server handles it without crash.
  18336. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18337. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18338. ASSERT_TRUE(res2);
  18339. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18340. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18341. } else {
  18342. // Could not set negative mtime on this platform; fall back to verifying
  18343. // that normal invalid/malformed dates are treated safely (non-304).
  18344. Headers h_bad_date = {
  18345. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18346. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18347. ASSERT_TRUE(res_bad);
  18348. EXPECT_EQ(200, res_bad->status);
  18349. }
  18350. svr.stop();
  18351. t.join();
  18352. std::remove(fname);
  18353. }
  18354. //==============================================================================
  18355. // SSE Parsing Tests
  18356. //==============================================================================
  18357. class SSEParsingTest : public ::testing::Test {
  18358. protected:
  18359. // Test helper that mimics SSE parsing behavior
  18360. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  18361. int &retry_ms) {
  18362. // Blank line signals end of event
  18363. if (line.empty() || line == "\r") { return true; }
  18364. // Lines starting with ':' are comments (ignored)
  18365. if (!line.empty() && line[0] == ':') { return false; }
  18366. // Find the colon separator
  18367. auto colon_pos = line.find(':');
  18368. if (colon_pos == std::string::npos) {
  18369. // Line with no colon is treated as field name with empty value
  18370. return false;
  18371. }
  18372. std::string field = line.substr(0, colon_pos);
  18373. std::string value;
  18374. // Value starts after colon, skip optional single space
  18375. if (colon_pos + 1 < line.size()) {
  18376. size_t value_start = colon_pos + 1;
  18377. if (line[value_start] == ' ') { value_start++; }
  18378. value = line.substr(value_start);
  18379. // Remove trailing \r if present
  18380. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  18381. }
  18382. // Handle known fields
  18383. if (field == "event") {
  18384. msg.event = value;
  18385. } else if (field == "data") {
  18386. // Multiple data lines are concatenated with newlines
  18387. if (!msg.data.empty()) { msg.data += "\n"; }
  18388. msg.data += value;
  18389. } else if (field == "id") {
  18390. // Empty id is valid (clears the last event ID)
  18391. msg.id = value;
  18392. } else if (field == "retry") {
  18393. // Parse retry interval in milliseconds
  18394. {
  18395. int v = 0;
  18396. auto res =
  18397. detail::from_chars(value.data(), value.data() + value.size(), v);
  18398. if (res.ec == std::errc{}) { retry_ms = v; }
  18399. }
  18400. }
  18401. // Unknown fields are ignored per SSE spec
  18402. return false;
  18403. }
  18404. };
  18405. // Test: Single-line data
  18406. TEST_F(SSEParsingTest, SingleLineData) {
  18407. sse::SSEMessage msg;
  18408. int retry_ms = 3000;
  18409. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  18410. EXPECT_EQ(msg.data, "hello");
  18411. EXPECT_EQ(msg.event, "message");
  18412. // Blank line ends event
  18413. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18414. }
  18415. // Test: Multi-line data
  18416. TEST_F(SSEParsingTest, MultiLineData) {
  18417. sse::SSEMessage msg;
  18418. int retry_ms = 3000;
  18419. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  18420. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  18421. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  18422. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  18423. }
  18424. // Test: Custom event types
  18425. TEST_F(SSEParsingTest, CustomEventType) {
  18426. sse::SSEMessage msg;
  18427. int retry_ms = 3000;
  18428. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  18429. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  18430. EXPECT_EQ(msg.event, "update");
  18431. EXPECT_EQ(msg.data, "payload");
  18432. }
  18433. // Test: Event ID handling
  18434. TEST_F(SSEParsingTest, EventIdHandling) {
  18435. sse::SSEMessage msg;
  18436. int retry_ms = 3000;
  18437. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  18438. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  18439. EXPECT_EQ(msg.id, "12345");
  18440. }
  18441. // Test: Empty event ID (clears last event ID)
  18442. TEST_F(SSEParsingTest, EmptyEventId) {
  18443. sse::SSEMessage msg;
  18444. msg.id = "previous";
  18445. int retry_ms = 3000;
  18446. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  18447. EXPECT_EQ(msg.id, "");
  18448. }
  18449. // Test: Retry field parsing
  18450. TEST_F(SSEParsingTest, RetryFieldParsing) {
  18451. sse::SSEMessage msg;
  18452. int retry_ms = 3000;
  18453. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  18454. EXPECT_EQ(retry_ms, 5000);
  18455. }
  18456. // Test: Invalid retry value
  18457. TEST_F(SSEParsingTest, InvalidRetryValue) {
  18458. sse::SSEMessage msg;
  18459. int retry_ms = 3000;
  18460. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  18461. EXPECT_EQ(retry_ms, 3000); // Unchanged
  18462. }
  18463. // Test: Comments (lines starting with :)
  18464. TEST_F(SSEParsingTest, CommentsIgnored) {
  18465. sse::SSEMessage msg;
  18466. int retry_ms = 3000;
  18467. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  18468. EXPECT_EQ(msg.data, "");
  18469. EXPECT_EQ(msg.event, "message");
  18470. }
  18471. // Test: Colon in value
  18472. TEST_F(SSEParsingTest, ColonInValue) {
  18473. sse::SSEMessage msg;
  18474. int retry_ms = 3000;
  18475. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  18476. EXPECT_EQ(msg.data, "hello:world:test");
  18477. }
  18478. // Test: Line with no colon (field name only)
  18479. TEST_F(SSEParsingTest, FieldNameOnly) {
  18480. sse::SSEMessage msg;
  18481. int retry_ms = 3000;
  18482. // According to SSE spec, this is treated as field name with empty value
  18483. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  18484. // Since we don't recognize "data" without colon, data should be empty
  18485. EXPECT_EQ(msg.data, "");
  18486. }
  18487. // Test: Trailing \r handling
  18488. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18489. sse::SSEMessage msg;
  18490. int retry_ms = 3000;
  18491. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  18492. EXPECT_EQ(msg.data, "hello");
  18493. }
  18494. // Test: Unknown fields ignored
  18495. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18496. sse::SSEMessage msg;
  18497. int retry_ms = 3000;
  18498. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  18499. EXPECT_EQ(msg.data, "");
  18500. EXPECT_EQ(msg.event, "message");
  18501. }
  18502. // Test: Space after colon is optional
  18503. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18504. sse::SSEMessage msg1, msg2;
  18505. int retry_ms = 3000;
  18506. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  18507. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  18508. EXPECT_EQ(msg1.data, "hello");
  18509. EXPECT_EQ(msg2.data, "hello");
  18510. }
  18511. // Test: SSEMessage clear
  18512. TEST_F(SSEParsingTest, MessageClear) {
  18513. sse::SSEMessage msg;
  18514. msg.event = "custom";
  18515. msg.data = "some data";
  18516. msg.id = "123";
  18517. msg.clear();
  18518. EXPECT_EQ(msg.event, "message");
  18519. EXPECT_EQ(msg.data, "");
  18520. EXPECT_EQ(msg.id, "");
  18521. }
  18522. // Test: Complete event parsing
  18523. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18524. sse::SSEMessage msg;
  18525. int retry_ms = 3000;
  18526. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  18527. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  18528. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  18529. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  18530. // Blank line ends event
  18531. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18532. EXPECT_EQ(msg.event, "notification");
  18533. EXPECT_EQ(msg.id, "evt-42");
  18534. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  18535. EXPECT_EQ(retry_ms, 1000);
  18536. }
  18537. //==============================================================================
  18538. // Integration Tests with Server
  18539. //==============================================================================
  18540. class SSEIntegrationTest : public ::testing::Test {
  18541. protected:
  18542. void SetUp() override {
  18543. stop_server_.store(false);
  18544. events_.clear();
  18545. server_ = httplib::detail::make_unique<Server>();
  18546. setup_server();
  18547. start_server();
  18548. }
  18549. void TearDown() override {
  18550. stop_server_.store(true);
  18551. event_cv_.notify_all();
  18552. server_->stop();
  18553. if (server_thread_.joinable()) { server_thread_.join(); }
  18554. }
  18555. void setup_server() {
  18556. // Simple SSE endpoint
  18557. server_->Get("/events", [this](const Request &req, Response &res) {
  18558. auto last_id = req.get_header_value("Last-Event-ID");
  18559. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18560. res.set_chunked_content_provider(
  18561. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18562. std::unique_lock<std::mutex> lock(event_mutex_);
  18563. if (event_cv_.wait_for(
  18564. lock, std::chrono::milliseconds(200), [this] {
  18565. return !events_.empty() || stop_server_.load();
  18566. })) {
  18567. if (stop_server_.load()) { return false; }
  18568. if (!events_.empty()) {
  18569. std::string event = events_.front();
  18570. events_.erase(events_.begin());
  18571. sink.write(event.data(), event.size());
  18572. return true;
  18573. }
  18574. }
  18575. return !stop_server_.load();
  18576. });
  18577. });
  18578. // Endpoint that returns error
  18579. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18580. res.status = 500;
  18581. res.set_content("Internal Server Error", "text/plain");
  18582. });
  18583. // Endpoint for custom event types
  18584. server_->Get("/custom-events", [](const Request &, Response &res) {
  18585. res.set_chunked_content_provider(
  18586. "text/event-stream", [](size_t offset, DataSink &sink) {
  18587. if (offset == 0) {
  18588. std::string event = "event: update\ndata: updated\n\n"
  18589. "event: delete\ndata: deleted\n\n";
  18590. sink.write(event.data(), event.size());
  18591. }
  18592. return false; // End stream after sending
  18593. });
  18594. });
  18595. }
  18596. void start_server() {
  18597. port_ = server_->bind_to_any_port(HOST);
  18598. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18599. // Wait for server to start
  18600. while (!server_->is_running()) {
  18601. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18602. }
  18603. }
  18604. int get_port() const { return port_; }
  18605. void send_event(const std::string &event) {
  18606. std::lock_guard<std::mutex> lock(event_mutex_);
  18607. events_.push_back(event);
  18608. event_cv_.notify_all();
  18609. }
  18610. std::unique_ptr<Server> server_;
  18611. std::thread server_thread_;
  18612. std::mutex event_mutex_;
  18613. std::condition_variable event_cv_;
  18614. std::vector<std::string> events_;
  18615. std::atomic<bool> stop_server_{false};
  18616. std::string last_received_event_id_;
  18617. int port_ = 0;
  18618. };
  18619. // Test: Successful connection and on_open callback
  18620. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18621. // Add a simple endpoint that sends one event and closes
  18622. server_->Get("/simple-event", [](const Request &, Response &res) {
  18623. res.set_chunked_content_provider(
  18624. "text/event-stream", [](size_t offset, DataSink &sink) {
  18625. if (offset == 0) {
  18626. std::string event = "data: hello\n\n";
  18627. sink.write(event.data(), event.size());
  18628. }
  18629. return false; // Close stream after sending
  18630. });
  18631. });
  18632. Client client("localhost", get_port());
  18633. sse::SSEClient sse(client, "/simple-event");
  18634. std::atomic<bool> open_called{false};
  18635. std::atomic<bool> message_received{false};
  18636. sse.on_open([&open_called]() { open_called.store(true); });
  18637. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18638. if (msg.data == "hello") { message_received.store(true); }
  18639. });
  18640. sse.set_reconnect_interval(100);
  18641. sse.set_max_reconnect_attempts(1);
  18642. // Start async
  18643. sse.start_async();
  18644. // Wait for message to be processed
  18645. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18646. sse.stop();
  18647. EXPECT_TRUE(open_called.load());
  18648. EXPECT_TRUE(message_received.load());
  18649. }
  18650. // Test: on_message callback
  18651. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18652. // Endpoint that sends multiple events then closes
  18653. server_->Get("/multi-event", [](const Request &, Response &res) {
  18654. res.set_chunked_content_provider(
  18655. "text/event-stream", [](size_t offset, DataSink &sink) {
  18656. if (offset == 0) {
  18657. std::string events = "data: message1\n\ndata: message2\n\n";
  18658. sink.write(events.data(), events.size());
  18659. }
  18660. return false;
  18661. });
  18662. });
  18663. Client client("localhost", get_port());
  18664. sse::SSEClient sse(client, "/multi-event");
  18665. std::vector<std::string> received_messages;
  18666. std::mutex messages_mutex;
  18667. sse.on_message([&](const sse::SSEMessage &msg) {
  18668. std::lock_guard<std::mutex> lock(messages_mutex);
  18669. received_messages.push_back(msg.data);
  18670. });
  18671. sse.set_reconnect_interval(100);
  18672. sse.set_max_reconnect_attempts(1);
  18673. sse.start_async();
  18674. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18675. sse.stop();
  18676. std::lock_guard<std::mutex> lock(messages_mutex);
  18677. EXPECT_GE(received_messages.size(), 2u);
  18678. if (received_messages.size() >= 2) {
  18679. EXPECT_EQ(received_messages[0], "message1");
  18680. EXPECT_EQ(received_messages[1], "message2");
  18681. }
  18682. }
  18683. // Test: on_event for specific types
  18684. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18685. Client client("localhost", get_port());
  18686. sse::SSEClient sse(client, "/custom-events");
  18687. std::atomic<bool> update_received{false};
  18688. std::atomic<bool> delete_received{false};
  18689. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18690. if (msg.data == "updated") { update_received.store(true); }
  18691. });
  18692. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18693. if (msg.data == "deleted") { delete_received.store(true); }
  18694. });
  18695. sse.set_max_reconnect_attempts(1);
  18696. sse.start_async();
  18697. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18698. sse.stop();
  18699. EXPECT_TRUE(update_received.load());
  18700. EXPECT_TRUE(delete_received.load());
  18701. }
  18702. // Test: on_error callback on connection failure
  18703. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18704. // Connect to a non-existent port
  18705. Client client("localhost", 59999);
  18706. sse::SSEClient sse(client, "/events");
  18707. std::atomic<bool> error_called{false};
  18708. Error received_error = Error::Success;
  18709. sse.on_error([&](Error err) {
  18710. error_called.store(true);
  18711. received_error = err;
  18712. });
  18713. sse.set_reconnect_interval(50);
  18714. sse.set_max_reconnect_attempts(1);
  18715. sse.start_async();
  18716. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18717. sse.stop();
  18718. EXPECT_TRUE(error_called.load());
  18719. EXPECT_NE(received_error, Error::Success);
  18720. }
  18721. // Test: Last-Event-ID header sent on reconnect
  18722. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18723. // Endpoint that sends event with ID
  18724. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18725. res.set_chunked_content_provider(
  18726. "text/event-stream", [](size_t offset, DataSink &sink) {
  18727. if (offset == 0) {
  18728. std::string event = "id: evt-123\ndata: test\n\n";
  18729. sink.write(event.data(), event.size());
  18730. }
  18731. return false;
  18732. });
  18733. });
  18734. Client client("localhost", get_port());
  18735. sse::SSEClient sse(client, "/event-with-id");
  18736. std::atomic<bool> id_received{false};
  18737. sse.on_message([&](const sse::SSEMessage &msg) {
  18738. if (!msg.id.empty()) { id_received.store(true); }
  18739. });
  18740. sse.set_reconnect_interval(100);
  18741. sse.set_max_reconnect_attempts(1);
  18742. sse.start_async();
  18743. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18744. sse.stop();
  18745. EXPECT_TRUE(id_received.load());
  18746. EXPECT_EQ(sse.last_event_id(), "evt-123");
  18747. }
  18748. // Test: Manual stop
  18749. TEST_F(SSEIntegrationTest, ManualStop) {
  18750. // Endpoint that sends one event and stays open briefly
  18751. std::atomic<bool> handler_running{true};
  18752. server_->Get("/stay-open", [&handler_running](const Request &,
  18753. Response &res) {
  18754. res.set_chunked_content_provider(
  18755. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  18756. if (offset == 0) {
  18757. std::string event = "data: connected\n\n";
  18758. sink.write(event.data(), event.size());
  18759. }
  18760. // Keep connection open while handler_running is true
  18761. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18762. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18763. }
  18764. return false;
  18765. });
  18766. });
  18767. Client client("localhost", get_port());
  18768. sse::SSEClient sse(client, "/stay-open");
  18769. std::atomic<bool> connected{false};
  18770. sse.on_open([&connected]() { connected.store(true); });
  18771. sse.set_reconnect_interval(100);
  18772. sse.set_max_reconnect_attempts(1);
  18773. sse.start_async();
  18774. // Wait for connection to establish
  18775. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18776. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18777. }
  18778. EXPECT_TRUE(connected.load());
  18779. EXPECT_TRUE(sse.is_connected());
  18780. // Signal handler to stop
  18781. handler_running.store(false);
  18782. // Stop SSE client
  18783. sse.stop();
  18784. EXPECT_FALSE(sse.is_connected());
  18785. }
  18786. // Test: SSEClient with custom headers
  18787. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18788. // Setup a server endpoint that checks for custom header
  18789. std::atomic<bool> header_received{false};
  18790. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18791. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18792. header_received.store(true);
  18793. }
  18794. res.set_chunked_content_provider("text/event-stream",
  18795. [](size_t, DataSink &) { return false; });
  18796. });
  18797. Client client("localhost", get_port());
  18798. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18799. sse::SSEClient sse(client, "/header-check", headers);
  18800. sse.set_max_reconnect_attempts(1);
  18801. sse.start_async();
  18802. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18803. sse.stop();
  18804. EXPECT_TRUE(header_received.load());
  18805. }
  18806. // Test: Reconnect interval configuration
  18807. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18808. Client client("localhost", get_port());
  18809. sse::SSEClient sse(client, "/events");
  18810. auto &result = sse.set_reconnect_interval(500);
  18811. // Builder pattern should return reference to self
  18812. EXPECT_EQ(&result, &sse);
  18813. }
  18814. // Test: Max reconnect attempts
  18815. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18816. // Connect to non-existent port to force reconnects
  18817. Client client("localhost", 59998);
  18818. sse::SSEClient sse(client, "/events");
  18819. std::atomic<int> error_count{0};
  18820. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18821. sse.set_reconnect_interval(50);
  18822. sse.set_max_reconnect_attempts(2);
  18823. auto start = std::chrono::steady_clock::now();
  18824. sse.start(); // Blocking call
  18825. auto end = std::chrono::steady_clock::now();
  18826. // Should have stopped after 2 failed attempts
  18827. EXPECT_GE(error_count.load(), 2);
  18828. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18829. auto duration =
  18830. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18831. #ifdef _WIN32
  18832. // Windows is much slower for socket connection failures
  18833. EXPECT_LT(duration.count(), 7000);
  18834. #else
  18835. EXPECT_LT(duration.count(), 1000);
  18836. #endif
  18837. }
  18838. // Test: Multi-line data in integration
  18839. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18840. // Endpoint with multi-line data
  18841. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18842. res.set_chunked_content_provider(
  18843. "text/event-stream", [](size_t offset, DataSink &sink) {
  18844. if (offset == 0) {
  18845. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18846. sink.write(event.data(), event.size());
  18847. }
  18848. return false;
  18849. });
  18850. });
  18851. Client client("localhost", get_port());
  18852. sse::SSEClient sse(client, "/multiline-data");
  18853. std::string received_data;
  18854. std::mutex data_mutex;
  18855. sse.on_message([&](const sse::SSEMessage &msg) {
  18856. std::lock_guard<std::mutex> lock(data_mutex);
  18857. received_data = msg.data;
  18858. });
  18859. sse.set_reconnect_interval(100);
  18860. sse.set_max_reconnect_attempts(1);
  18861. sse.start_async();
  18862. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18863. sse.stop();
  18864. std::lock_guard<std::mutex> lock(data_mutex);
  18865. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18866. }
  18867. // Test: Auto-reconnect after server disconnection
  18868. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18869. std::atomic<int> connection_count{0};
  18870. std::atomic<int> message_count{0};
  18871. // Endpoint that sends one event and closes, forcing reconnect
  18872. server_->Get("/reconnect-test",
  18873. [&connection_count](const Request &, Response &res) {
  18874. connection_count.fetch_add(1);
  18875. res.set_chunked_content_provider(
  18876. "text/event-stream", [](size_t offset, DataSink &sink) {
  18877. if (offset == 0) {
  18878. std::string event = "data: hello\n\n";
  18879. sink.write(event.data(), event.size());
  18880. }
  18881. return false; // Close connection after sending
  18882. });
  18883. });
  18884. Client client("localhost", get_port());
  18885. sse::SSEClient sse(client, "/reconnect-test");
  18886. sse.on_message([&message_count](const sse::SSEMessage &) {
  18887. message_count.fetch_add(1);
  18888. });
  18889. sse.set_reconnect_interval(100);
  18890. sse.set_max_reconnect_attempts(3);
  18891. sse.start_async();
  18892. // Wait long enough for multiple reconnects
  18893. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18894. sse.stop();
  18895. // Should have connected multiple times (initial + reconnects)
  18896. EXPECT_GE(connection_count.load(), 2);
  18897. // Should have received messages from multiple connections
  18898. EXPECT_GE(message_count.load(), 2);
  18899. }
  18900. // Test: Last-Event-ID sent on reconnect
  18901. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  18902. std::atomic<int> connection_count{0};
  18903. std::vector<std::string> received_last_event_ids;
  18904. std::mutex id_mutex;
  18905. // Endpoint that checks Last-Event-ID header and sends event with ID
  18906. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  18907. int conn = connection_count.fetch_add(1);
  18908. // Capture the Last-Event-ID header from each connection
  18909. {
  18910. std::lock_guard<std::mutex> lock(id_mutex);
  18911. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  18912. }
  18913. res.set_chunked_content_provider(
  18914. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  18915. if (offset == 0) {
  18916. std::string event =
  18917. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  18918. sink.write(event.data(), event.size());
  18919. }
  18920. return false;
  18921. });
  18922. });
  18923. Client client("localhost", get_port());
  18924. sse::SSEClient sse(client, "/reconnect-with-id");
  18925. sse.set_reconnect_interval(100);
  18926. sse.set_max_reconnect_attempts(3);
  18927. sse.start_async();
  18928. // Wait for at least 2 connections
  18929. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18930. sse.stop();
  18931. // Verify behavior
  18932. std::lock_guard<std::mutex> lock(id_mutex);
  18933. EXPECT_GE(received_last_event_ids.size(), 2u);
  18934. // First connection should have no Last-Event-ID
  18935. if (!received_last_event_ids.empty()) {
  18936. EXPECT_EQ(received_last_event_ids[0], "");
  18937. }
  18938. // Second connection should have Last-Event-ID from first connection
  18939. if (received_last_event_ids.size() >= 2) {
  18940. EXPECT_EQ(received_last_event_ids[1], "event-0");
  18941. }
  18942. }
  18943. // Test: set_headers updates headers used on reconnect
  18944. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  18945. std::vector<std::string> received_tokens;
  18946. std::mutex token_mutex;
  18947. // Endpoint that captures Authorization header
  18948. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  18949. {
  18950. std::lock_guard<std::mutex> lock(token_mutex);
  18951. received_tokens.push_back(req.get_header_value("Authorization"));
  18952. }
  18953. res.set_chunked_content_provider(
  18954. "text/event-stream", [](size_t offset, DataSink &sink) {
  18955. if (offset == 0) {
  18956. std::string event = "data: hello\n\n";
  18957. sink.write(event.data(), event.size());
  18958. }
  18959. return false; // Close connection to trigger reconnect
  18960. });
  18961. });
  18962. Client client("localhost", get_port());
  18963. Headers headers = {{"Authorization", "Bearer old-token"}};
  18964. sse::SSEClient sse(client, "/auth-check", headers);
  18965. // Update headers on each successful connection
  18966. sse.on_open(
  18967. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  18968. sse.set_reconnect_interval(100);
  18969. sse.set_max_reconnect_attempts(3);
  18970. sse.start_async();
  18971. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18972. sse.stop();
  18973. std::lock_guard<std::mutex> lock(token_mutex);
  18974. ASSERT_GE(received_tokens.size(), 2u);
  18975. // First connection uses original header
  18976. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  18977. // Second connection uses updated header from set_headers
  18978. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  18979. }
  18980. // Test: 401 allows reconnection (so on_error can refresh headers)
  18981. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  18982. std::atomic<int> connection_count{0};
  18983. // Endpoint: returns 401 on first attempt, 200 on second
  18984. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  18985. int conn = connection_count.fetch_add(1);
  18986. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  18987. res.status = StatusCode::Unauthorized_401;
  18988. res.set_content("Unauthorized", "text/plain");
  18989. return;
  18990. }
  18991. res.set_chunked_content_provider(
  18992. "text/event-stream", [](size_t offset, DataSink &sink) {
  18993. if (offset == 0) {
  18994. std::string event = "data: authenticated\n\n";
  18995. sink.write(event.data(), event.size());
  18996. }
  18997. return false;
  18998. });
  18999. });
  19000. Client client("localhost", get_port());
  19001. Headers headers = {{"Authorization", "Bearer expired"}};
  19002. sse::SSEClient sse(client, "/auth-retry", headers);
  19003. std::atomic<bool> message_received{false};
  19004. // Refresh token on error
  19005. sse.on_error(
  19006. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19007. sse.on_message([&](const sse::SSEMessage &msg) {
  19008. if (msg.data == "authenticated") { message_received.store(true); }
  19009. });
  19010. sse.set_reconnect_interval(100);
  19011. sse.set_max_reconnect_attempts(3);
  19012. sse.start_async();
  19013. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19014. sse.stop();
  19015. // Should have reconnected after 401 and succeeded with new token
  19016. EXPECT_GE(connection_count.load(), 2);
  19017. EXPECT_TRUE(message_received.load());
  19018. }
  19019. TEST(Issue2318Test, EmptyHostString) {
  19020. {
  19021. httplib::Client cli_empty("", PORT);
  19022. auto res = cli_empty.Get("/");
  19023. ASSERT_FALSE(res);
  19024. EXPECT_EQ(httplib::Error::Connection, res.error());
  19025. }
  19026. {
  19027. httplib::Client cli(" ", PORT);
  19028. auto res = cli.Get("/");
  19029. ASSERT_FALSE(res);
  19030. EXPECT_EQ(httplib::Error::Connection, res.error());
  19031. }
  19032. }
  19033. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19034. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19035. Server svr;
  19036. // Set a small payload limit (1KB)
  19037. svr.set_payload_max_length(1024);
  19038. svr.Post("/test", [&](const Request &req, Response &res) {
  19039. res.set_content("Body size: " + std::to_string(req.body.size()),
  19040. "text/plain");
  19041. });
  19042. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19043. auto se = detail::scope_exit([&] {
  19044. svr.stop();
  19045. listen_thread.join();
  19046. });
  19047. svr.wait_until_ready();
  19048. // Create data that compresses well but exceeds limit when decompressed
  19049. // 8KB of repeated null bytes compresses to a very small size
  19050. std::string original_data(8 * 1024, '\0');
  19051. // Compress the data using gzip
  19052. std::string compressed_data;
  19053. detail::gzip_compressor compressor;
  19054. compressor.compress(original_data.data(), original_data.size(), true,
  19055. [&](const char *data, size_t size) {
  19056. compressed_data.append(data, size);
  19057. return true;
  19058. });
  19059. // Verify compression worked (compressed should be much smaller)
  19060. ASSERT_LT(compressed_data.size(), original_data.size());
  19061. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19062. // Send compressed data with Content-Encoding: gzip
  19063. Client cli(HOST, PORT);
  19064. Headers headers = {{"Content-Encoding", "gzip"}};
  19065. auto res =
  19066. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19067. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19069. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19070. }
  19071. #endif
  19072. // ============================================================================
  19073. // OpenSSL-Specific Tests
  19074. // ============================================================================
  19075. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19076. X509 *readCertificate(const std::string &strFileName) {
  19077. std::ifstream inStream(strFileName);
  19078. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19079. std::istreambuf_iterator<char>());
  19080. if (strCertPEM.empty()) return (nullptr);
  19081. BIO *pbCert = BIO_new(BIO_s_mem());
  19082. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19083. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19084. BIO_free(pbCert);
  19085. return (pCert);
  19086. }
  19087. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19088. std::ifstream inStream(strFileName);
  19089. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19090. std::istreambuf_iterator<char>());
  19091. if (strPrivateKeyPEM.empty()) return (nullptr);
  19092. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19093. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19094. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19095. BIO_free(pbPrivKey);
  19096. return (pPrivateKey);
  19097. }
  19098. TEST(BindServerTest, UpdateCerts) {
  19099. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19100. int port = svr.bind_to_any_port("0.0.0.0");
  19101. ASSERT_TRUE(svr.is_valid());
  19102. ASSERT_TRUE(port > 0);
  19103. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19104. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19105. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19106. ASSERT_TRUE(cert != nullptr);
  19107. ASSERT_TRUE(ca_cert != nullptr);
  19108. ASSERT_TRUE(key != nullptr);
  19109. X509_STORE *cert_store = X509_STORE_new();
  19110. X509_STORE_add_cert(cert_store, ca_cert);
  19111. // svr.update_certs(cert, key, cert_store); // deprecated
  19112. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19113. CLIENT_CA_CERT_FILE);
  19114. ASSERT_TRUE(svr.is_valid());
  19115. svr.stop();
  19116. X509_STORE_free(cert_store);
  19117. X509_free(cert);
  19118. X509_free(ca_cert);
  19119. EVP_PKEY_free(key);
  19120. }
  19121. // Test that update_certs() updates client CA list correctly
  19122. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19123. // Start with file-based constructor
  19124. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19125. ASSERT_TRUE(svr.is_valid());
  19126. // Initially no client CA list should be set
  19127. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19128. ASSERT_TRUE(ssl_ctx != nullptr);
  19129. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19130. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19131. EXPECT_EQ(0, count_before);
  19132. // Now update with client CA (PEM string)
  19133. std::string cert_pem, key_pem, ca_pem;
  19134. read_file(SERVER_CERT_FILE, cert_pem);
  19135. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19136. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19137. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19138. ASSERT_TRUE(svr.is_valid());
  19139. // Now client CA list should be set
  19140. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19141. ASSERT_TRUE(ca_list_after != nullptr);
  19142. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19143. }
  19144. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19145. // Test that the file-path SSLServer constructor properly sets the client CA
  19146. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19147. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19148. ASSERT_TRUE(svr.is_valid());
  19149. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19150. ASSERT_TRUE(ssl_ctx != nullptr);
  19151. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19152. ASSERT_TRUE(ca_list != nullptr);
  19153. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19154. }
  19155. #endif
  19156. // ============================================================================
  19157. // MbedTLS-Specific Tests
  19158. // ============================================================================
  19159. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19160. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19161. using namespace httplib::tls;
  19162. // Track if callback was invoked
  19163. bool callback_invoked = false;
  19164. // The callback receives void* ctx which is actually MbedTlsContext*
  19165. // We can access the mbedtls_ssl_config via the context
  19166. auto setup_callback = [&callback_invoked](void *ctx) {
  19167. callback_invoked = true;
  19168. // Cast to MbedTlsContext* to access the ssl config
  19169. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19170. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19171. // Use static variables to hold certificate data (simplified for test)
  19172. static mbedtls_x509_crt own_cert;
  19173. static mbedtls_pk_context own_key;
  19174. static mbedtls_x509_crt ca_chain;
  19175. static bool initialized = false;
  19176. if (!initialized) {
  19177. mbedtls_x509_crt_init(&own_cert);
  19178. mbedtls_pk_init(&own_key);
  19179. mbedtls_x509_crt_init(&ca_chain);
  19180. // Load server certificate
  19181. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19182. return false;
  19183. }
  19184. // Load server private key.
  19185. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19186. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19187. #if MBEDTLS_VERSION_MAJOR == 3
  19188. ,
  19189. mbedtls_ctr_drbg_random, nullptr
  19190. #endif
  19191. ) != 0) {
  19192. return false;
  19193. }
  19194. // Load CA chain for client verification
  19195. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19196. return false;
  19197. }
  19198. initialized = true;
  19199. }
  19200. // Configure the SSL config
  19201. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19202. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19203. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19204. // Set minimum TLS version using mbedTLS native API
  19205. #if MBEDTLS_VERSION_MAJOR >= 3
  19206. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19207. #else
  19208. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19209. MBEDTLS_SSL_MINOR_VERSION_3);
  19210. #endif
  19211. return true;
  19212. };
  19213. SSLServer svr(setup_callback);
  19214. ASSERT_TRUE(svr.is_valid());
  19215. ASSERT_TRUE(callback_invoked);
  19216. svr.Get("/test", [&](const Request &req, Response &res) {
  19217. res.set_content("test", "text/plain");
  19218. auto cert = req.peer_cert();
  19219. ASSERT_TRUE(static_cast<bool>(cert));
  19220. auto common_name = cert.subject_cn();
  19221. EXPECT_EQ("Common Name", common_name);
  19222. });
  19223. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19224. auto se = detail::scope_exit([&] {
  19225. svr.stop();
  19226. t.join();
  19227. ASSERT_FALSE(svr.is_running());
  19228. });
  19229. svr.wait_until_ready();
  19230. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19231. cli.enable_server_certificate_verification(false);
  19232. cli.set_connection_timeout(30);
  19233. auto res = cli.Get("/test");
  19234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19235. ASSERT_EQ(StatusCode::OK_200, res->status);
  19236. }
  19237. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19238. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19239. // keep-alive SSL session, which reads through that config in
  19240. // mbedtls_ssl_close_notify.
  19241. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19242. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19243. ASSERT_TRUE(svr.is_valid());
  19244. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19245. res.set_content("test", "text/plain");
  19246. });
  19247. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19248. auto se = detail::scope_exit([&] {
  19249. svr.stop();
  19250. t.join();
  19251. ASSERT_FALSE(svr.is_running());
  19252. });
  19253. svr.wait_until_ready();
  19254. {
  19255. SSLClient cli(HOST, PORT);
  19256. cli.enable_server_certificate_verification(false);
  19257. cli.set_keep_alive(true);
  19258. auto res = cli.Get("/test");
  19259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19260. ASSERT_EQ(StatusCode::OK_200, res->status);
  19261. // cli is destructed here with the keep-alive SSL session still open.
  19262. }
  19263. }
  19264. #endif
  19265. // WebSocket Tests
  19266. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19267. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19268. // defining the meaning of these bits has been negotiated.
  19269. auto make_frame = [](uint8_t first_byte) {
  19270. std::string frame;
  19271. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19272. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19273. frame += "Hello";
  19274. return frame;
  19275. };
  19276. // RSV1 set (0x40)
  19277. {
  19278. detail::BufferStream strm;
  19279. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19280. ws::Opcode opcode;
  19281. std::string payload;
  19282. bool fin;
  19283. EXPECT_EQ(
  19284. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19285. ws::impl::FrameRead::Fail);
  19286. }
  19287. // RSV2 set (0x20)
  19288. {
  19289. detail::BufferStream strm;
  19290. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19291. ws::Opcode opcode;
  19292. std::string payload;
  19293. bool fin;
  19294. EXPECT_EQ(
  19295. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19296. ws::impl::FrameRead::Fail);
  19297. }
  19298. // RSV3 set (0x10)
  19299. {
  19300. detail::BufferStream strm;
  19301. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19302. ws::Opcode opcode;
  19303. std::string payload;
  19304. bool fin;
  19305. EXPECT_EQ(
  19306. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19307. ws::impl::FrameRead::Fail);
  19308. }
  19309. // No RSV bits set - should succeed
  19310. {
  19311. detail::BufferStream strm;
  19312. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19313. ws::Opcode opcode;
  19314. std::string payload;
  19315. bool fin;
  19316. EXPECT_EQ(
  19317. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19318. ws::impl::FrameRead::Ok);
  19319. EXPECT_EQ(ws::Opcode::Text, opcode);
  19320. EXPECT_EQ("Hello", payload);
  19321. EXPECT_TRUE(fin);
  19322. }
  19323. }
  19324. TEST(WebSocketTest, ControlFrameValidation) {
  19325. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19326. // payload length <= 125.
  19327. // Ping with FIN=0 - must be rejected
  19328. {
  19329. detail::BufferStream strm;
  19330. std::string frame;
  19331. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19332. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19333. strm.write(frame.data(), frame.size());
  19334. ws::Opcode opcode;
  19335. std::string payload;
  19336. bool fin;
  19337. EXPECT_EQ(
  19338. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19339. ws::impl::FrameRead::Fail);
  19340. }
  19341. // Close with FIN=0 - must be rejected
  19342. {
  19343. detail::BufferStream strm;
  19344. std::string frame;
  19345. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19346. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19347. strm.write(frame.data(), frame.size());
  19348. ws::Opcode opcode;
  19349. std::string payload;
  19350. bool fin;
  19351. EXPECT_EQ(
  19352. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19353. ws::impl::FrameRead::Fail);
  19354. }
  19355. // Ping with payload_len=126 (extended length) - must be rejected
  19356. {
  19357. detail::BufferStream strm;
  19358. std::string frame;
  19359. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19360. frame += static_cast<char>(126); // payload_len=126 (>125)
  19361. frame += static_cast<char>(0x00); // extended length high byte
  19362. frame += static_cast<char>(126); // extended length low byte
  19363. frame += std::string(126, 'x');
  19364. strm.write(frame.data(), frame.size());
  19365. ws::Opcode opcode;
  19366. std::string payload;
  19367. bool fin;
  19368. EXPECT_EQ(
  19369. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19370. ws::impl::FrameRead::Fail);
  19371. }
  19372. // Ping with FIN=1 and payload_len=125 - should succeed
  19373. {
  19374. detail::BufferStream strm;
  19375. std::string frame;
  19376. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19377. frame += static_cast<char>(125); // payload_len=125
  19378. frame += std::string(125, 'x');
  19379. strm.write(frame.data(), frame.size());
  19380. ws::Opcode opcode;
  19381. std::string payload;
  19382. bool fin;
  19383. EXPECT_EQ(
  19384. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19385. ws::impl::FrameRead::Ok);
  19386. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19387. EXPECT_EQ(125u, payload.size());
  19388. EXPECT_TRUE(fin);
  19389. }
  19390. }
  19391. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19392. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19393. // length MUST be 0.
  19394. // MSB set - must be rejected
  19395. {
  19396. detail::BufferStream strm;
  19397. std::string frame;
  19398. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19399. frame += static_cast<char>(127); // 64-bit extended length
  19400. frame += static_cast<char>(0x80); // MSB set (invalid)
  19401. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19402. strm.write(frame.data(), frame.size());
  19403. ws::Opcode opcode;
  19404. std::string payload;
  19405. bool fin;
  19406. EXPECT_EQ(
  19407. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19408. ws::impl::FrameRead::Fail);
  19409. }
  19410. // MSB clear - should pass length parsing (will be rejected by max_len,
  19411. // but that's a different check; use a small length to verify)
  19412. {
  19413. detail::BufferStream strm;
  19414. std::string frame;
  19415. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19416. frame += static_cast<char>(127); // 64-bit extended length
  19417. frame += std::string(7, '\0'); // high bytes = 0
  19418. frame += static_cast<char>(0x03); // length = 3
  19419. frame += "abc";
  19420. strm.write(frame.data(), frame.size());
  19421. ws::Opcode opcode;
  19422. std::string payload;
  19423. bool fin;
  19424. EXPECT_EQ(
  19425. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19426. ws::impl::FrameRead::Ok);
  19427. EXPECT_EQ(ws::Opcode::Text, opcode);
  19428. EXPECT_EQ("abc", payload);
  19429. }
  19430. }
  19431. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19432. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19433. // Valid UTF-8
  19434. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19435. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19436. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19437. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19438. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19439. // Invalid UTF-8
  19440. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19441. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19442. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19443. EXPECT_FALSE(
  19444. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19445. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19446. }
  19447. TEST(WebSocketTest, ConnectAndDisconnect) {
  19448. Server svr;
  19449. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19450. std::string msg;
  19451. while (ws.read(msg)) {}
  19452. });
  19453. auto port = svr.bind_to_any_port(HOST);
  19454. std::thread t([&]() { svr.listen_after_bind(); });
  19455. svr.wait_until_ready();
  19456. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19457. auto res = client.connect();
  19458. ASSERT_TRUE(res);
  19459. EXPECT_EQ(Error::Success, res.error());
  19460. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19461. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19462. EXPECT_TRUE(client.is_open());
  19463. client.close();
  19464. EXPECT_FALSE(client.is_open());
  19465. svr.stop();
  19466. t.join();
  19467. }
  19468. TEST(WebSocketTest, ValidURL) {
  19469. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19470. EXPECT_TRUE(ws1.is_valid());
  19471. ws::WebSocketClient ws2("ws://example.com/path");
  19472. EXPECT_TRUE(ws2.is_valid());
  19473. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19474. EXPECT_TRUE(ws3.is_valid());
  19475. #ifdef CPPHTTPLIB_SSL_ENABLED
  19476. ws::WebSocketClient wss1("wss://example.com/path");
  19477. EXPECT_TRUE(wss1.is_valid());
  19478. ws::WebSocketClient wss2("wss://example.com:443/path");
  19479. EXPECT_TRUE(wss2.is_valid());
  19480. #endif
  19481. }
  19482. TEST(WebSocketTest, InvalidURL) {
  19483. // No scheme
  19484. ws::WebSocketClient ws1("localhost:8080/path");
  19485. EXPECT_FALSE(ws1.is_valid());
  19486. // No path
  19487. ws::WebSocketClient ws2("ws://localhost:8080");
  19488. EXPECT_FALSE(ws2.is_valid());
  19489. // Empty string
  19490. ws::WebSocketClient ws3("");
  19491. EXPECT_FALSE(ws3.is_valid());
  19492. // Missing host
  19493. ws::WebSocketClient ws4("ws://:8080/path");
  19494. EXPECT_FALSE(ws4.is_valid());
  19495. // Port number overflow — should not crash
  19496. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19497. EXPECT_FALSE(ws5.is_valid());
  19498. // Port out of range
  19499. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19500. EXPECT_FALSE(ws6.is_valid());
  19501. }
  19502. TEST(WebSocketTest, UnsupportedScheme) {
  19503. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19504. ws::WebSocketClient ws1("http://localhost:8080/path");
  19505. EXPECT_FALSE(ws1.is_valid());
  19506. ws::WebSocketClient ws2("https://localhost:8080/path");
  19507. EXPECT_FALSE(ws2.is_valid());
  19508. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19509. EXPECT_FALSE(ws3.is_valid());
  19510. #else
  19511. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19512. std::invalid_argument);
  19513. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19514. std::invalid_argument);
  19515. #endif
  19516. }
  19517. TEST(WebSocketTest, ConnectWhenInvalid) {
  19518. ws::WebSocketClient ws("not a valid url");
  19519. EXPECT_FALSE(ws.is_valid());
  19520. auto res = ws.connect();
  19521. EXPECT_FALSE(res);
  19522. EXPECT_EQ(Error::Connection, res.error());
  19523. EXPECT_EQ(-1, res.status());
  19524. }
  19525. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19526. // Grab a port that is free, then close it again so nothing listens there
  19527. Server svr;
  19528. auto port = svr.bind_to_any_port(HOST);
  19529. svr.stop();
  19530. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19531. auto res = client.connect();
  19532. ASSERT_FALSE(res);
  19533. EXPECT_EQ(Error::Connection, res.error());
  19534. EXPECT_EQ(-1, res.status());
  19535. }
  19536. TEST(WebSocketTest, DefaultPort) {
  19537. ws::WebSocketClient ws1("ws://example.com/path");
  19538. EXPECT_TRUE(ws1.is_valid());
  19539. // ws:// defaults to port 80 (verified by successful parse)
  19540. #ifdef CPPHTTPLIB_SSL_ENABLED
  19541. ws::WebSocketClient ws2("wss://example.com/path");
  19542. EXPECT_TRUE(ws2.is_valid());
  19543. // wss:// defaults to port 443 (verified by successful parse)
  19544. #endif
  19545. }
  19546. TEST(WebSocketTest, IPv6LiteralAddress) {
  19547. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19548. EXPECT_TRUE(ws1.is_valid());
  19549. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  19550. EXPECT_TRUE(ws2.is_valid());
  19551. }
  19552. TEST(WebSocketTest, ComplexPath) {
  19553. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  19554. EXPECT_TRUE(ws1.is_valid());
  19555. ws::WebSocketClient ws2("ws://localhost:8080/");
  19556. EXPECT_TRUE(ws2.is_valid());
  19557. }
  19558. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  19559. Server svr;
  19560. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19561. std::string msg;
  19562. while (ws.read(msg)) {}
  19563. });
  19564. auto port = svr.bind_to_any_port(HOST);
  19565. std::thread t([&]() { svr.listen_after_bind(); });
  19566. svr.wait_until_ready();
  19567. auto another_host = "example.com";
  19568. auto wrong_ip = "192.0.2.1";
  19569. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19570. client.set_hostname_addr_map({{another_host, wrong_ip}});
  19571. ASSERT_TRUE(client.connect());
  19572. EXPECT_TRUE(client.is_open());
  19573. client.close();
  19574. svr.stop();
  19575. t.join();
  19576. }
  19577. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  19578. Server svr;
  19579. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19580. std::string msg;
  19581. while (ws.read(msg)) {}
  19582. });
  19583. auto port = svr.bind_to_any_port(HOST);
  19584. std::thread t([&]() { svr.listen_after_bind(); });
  19585. svr.wait_until_ready();
  19586. auto wrong_ip = "192.0.2.1";
  19587. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19588. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  19589. client.set_connection_timeout(1);
  19590. client.set_read_timeout(1);
  19591. client.set_write_timeout(1);
  19592. EXPECT_FALSE(client.connect());
  19593. EXPECT_FALSE(client.is_open());
  19594. svr.stop();
  19595. t.join();
  19596. }
  19597. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  19598. // A mapped value that is not an IP literal must be resolved. HOST resolves
  19599. // from the hosts file, so this test needs no external DNS. "target.invalid"
  19600. // (RFC 6761) is only a map key and the Host header value.
  19601. auto host = "target.invalid";
  19602. Server svr;
  19603. std::string received_host;
  19604. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19605. received_host = req.get_header_value("Host");
  19606. std::string msg;
  19607. while (ws.read(msg)) {}
  19608. });
  19609. auto port = svr.bind_to_any_port(HOST);
  19610. std::thread t([&]() { svr.listen_after_bind(); });
  19611. // ASSERT_* below returns from the test body, which would leave t joinable
  19612. // and make ~thread call std::terminate.
  19613. auto se = detail::scope_exit([&] {
  19614. svr.stop();
  19615. if (t.joinable()) { t.join(); }
  19616. });
  19617. svr.wait_until_ready();
  19618. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  19619. std::to_string(port) + "/ws");
  19620. client.set_hostname_addr_map({{host, HOST}});
  19621. ASSERT_TRUE(client.connect());
  19622. EXPECT_TRUE(client.is_open());
  19623. client.close();
  19624. svr.stop();
  19625. t.join();
  19626. // The mapping only redirects the connection; the identity stays host_.
  19627. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  19628. }
  19629. class WebSocketIntegrationTest : public ::testing::Test {
  19630. protected:
  19631. void SetUp() override {
  19632. server_ = httplib::detail::make_unique<Server>();
  19633. setup_server();
  19634. start_server();
  19635. }
  19636. void TearDown() override {
  19637. server_->stop();
  19638. if (server_thread_.joinable()) { server_thread_.join(); }
  19639. }
  19640. void setup_server() {
  19641. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19642. std::string msg;
  19643. ws::ReadResult ret;
  19644. while ((ret = ws.read(msg))) {
  19645. if (ret == ws::Binary) {
  19646. ws.send(msg.data(), msg.size());
  19647. } else {
  19648. ws.send(msg);
  19649. }
  19650. }
  19651. });
  19652. server_->WebSocket("/ws-echo-string",
  19653. [](const Request &, ws::WebSocket &ws) {
  19654. std::string msg;
  19655. while (ws.read(msg)) {
  19656. ws.send("echo: " + msg);
  19657. }
  19658. });
  19659. server_->WebSocket(
  19660. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19661. // Echo back request metadata
  19662. ws.send("path:" + req.path);
  19663. ws.send("header:" + req.get_header_value("X-Test-Header"));
  19664. std::string msg;
  19665. while (ws.read(msg)) {}
  19666. });
  19667. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  19668. std::string msg;
  19669. ws.read(msg); // wait for a message
  19670. ws.close();
  19671. });
  19672. server_->WebSocket("/ws-close-status",
  19673. [](const Request &, ws::WebSocket &ws) {
  19674. std::string msg;
  19675. ws.read(msg); // wait for a message
  19676. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  19677. });
  19678. server_->WebSocket(
  19679. "/ws-subprotocol",
  19680. [](const Request &, ws::WebSocket &ws) {
  19681. std::string msg;
  19682. while (ws.read(msg)) {
  19683. ws.send(msg);
  19684. }
  19685. },
  19686. [](const std::vector<std::string> &protocols) -> std::string {
  19687. for (const auto &p : protocols) {
  19688. if (p == "graphql-ws") { return p; }
  19689. }
  19690. return "";
  19691. });
  19692. }
  19693. void start_server() {
  19694. port_ = server_->bind_to_any_port(HOST);
  19695. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19696. server_->wait_until_ready();
  19697. }
  19698. std::unique_ptr<Server> server_;
  19699. std::thread server_thread_;
  19700. int port_ = 0;
  19701. };
  19702. TEST_F(WebSocketIntegrationTest, TextEcho) {
  19703. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19704. "/ws-echo");
  19705. ASSERT_TRUE(client.connect());
  19706. ASSERT_TRUE(client.is_open());
  19707. ASSERT_TRUE(client.send("Hello WebSocket"));
  19708. std::string msg;
  19709. EXPECT_EQ(ws::Text, client.read(msg));
  19710. EXPECT_EQ("Hello WebSocket", msg);
  19711. client.close();
  19712. }
  19713. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  19714. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19715. "/ws-echo");
  19716. ASSERT_TRUE(client.connect());
  19717. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  19718. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  19719. std::string msg;
  19720. EXPECT_EQ(ws::Binary, client.read(msg));
  19721. EXPECT_EQ(binary_data, msg);
  19722. client.close();
  19723. }
  19724. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  19725. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19726. "/ws-echo");
  19727. ASSERT_TRUE(client.connect());
  19728. for (int i = 0; i < 10; i++) {
  19729. auto text = "message " + std::to_string(i);
  19730. ASSERT_TRUE(client.send(text));
  19731. std::string msg;
  19732. ASSERT_TRUE(client.read(msg));
  19733. EXPECT_EQ(text, msg);
  19734. }
  19735. client.close();
  19736. }
  19737. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  19738. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19739. "/ws-close");
  19740. ASSERT_TRUE(client.connect());
  19741. // Send a message to trigger the server to close
  19742. ASSERT_TRUE(client.send("trigger close"));
  19743. // The server will close, so read should return false
  19744. std::string msg;
  19745. EXPECT_FALSE(client.read(msg));
  19746. EXPECT_FALSE(client.is_open());
  19747. }
  19748. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  19749. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19750. "/ws-echo");
  19751. ASSERT_TRUE(client.connect());
  19752. // 128KB message
  19753. std::string large_data(128 * 1024, 'X');
  19754. ASSERT_TRUE(client.send(large_data));
  19755. std::string msg;
  19756. ASSERT_TRUE(client.read(msg));
  19757. EXPECT_EQ(large_data, msg);
  19758. client.close();
  19759. }
  19760. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  19761. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19762. "/ws-echo");
  19763. ASSERT_TRUE(client.connect());
  19764. const int num_threads = 4;
  19765. std::vector<std::thread> threads;
  19766. std::atomic<int> send_count{0};
  19767. for (int t = 0; t < num_threads; t++) {
  19768. threads.emplace_back([&client, &send_count, t]() {
  19769. for (int i = 0; i < 5; i++) {
  19770. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19771. if (client.send(text)) { send_count++; }
  19772. }
  19773. });
  19774. }
  19775. for (auto &th : threads) {
  19776. th.join();
  19777. }
  19778. int received = 0;
  19779. std::string msg;
  19780. while (received < send_count.load()) {
  19781. if (!client.read(msg)) { break; }
  19782. received++;
  19783. }
  19784. EXPECT_EQ(send_count.load(), received);
  19785. client.close();
  19786. }
  19787. TEST_F(WebSocketIntegrationTest, ReadString) {
  19788. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19789. "/ws-echo-string");
  19790. ASSERT_TRUE(client.connect());
  19791. ASSERT_TRUE(client.send("hello"));
  19792. std::string msg;
  19793. ASSERT_TRUE(client.read(msg));
  19794. EXPECT_EQ("echo: hello", msg);
  19795. ASSERT_TRUE(client.send("world"));
  19796. ASSERT_TRUE(client.read(msg));
  19797. EXPECT_EQ("echo: world", msg);
  19798. client.close();
  19799. }
  19800. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19801. Headers headers = {{"X-Test-Header", "test-value"}};
  19802. ws::WebSocketClient client(
  19803. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19804. ASSERT_TRUE(client.connect());
  19805. std::string msg;
  19806. ASSERT_TRUE(client.read(msg));
  19807. EXPECT_EQ("path:/ws-request-info", msg);
  19808. ASSERT_TRUE(client.read(msg));
  19809. EXPECT_EQ("header:test-value", msg);
  19810. client.close();
  19811. }
  19812. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19814. "/ws-echo");
  19815. client.set_read_timeout(1, 0); // 1 second
  19816. ASSERT_TRUE(client.connect());
  19817. // Don't send anything — server echo handler waits for a message, so read()
  19818. // should time out. The connection survives it: nothing was consumed.
  19819. std::string msg;
  19820. EXPECT_EQ(client.read(msg), ws::Timeout);
  19821. EXPECT_TRUE(client.is_open());
  19822. // And it is still usable afterwards.
  19823. EXPECT_TRUE(client.send("after timeout"));
  19824. EXPECT_EQ(client.read(msg), ws::Text);
  19825. EXPECT_EQ(msg, "after timeout");
  19826. }
  19827. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  19828. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19829. "/ws-echo");
  19830. client.set_read_timeout(1, 0);
  19831. ASSERT_TRUE(client.connect());
  19832. ASSERT_TRUE(client.send("first"));
  19833. std::string msg;
  19834. ASSERT_EQ(client.read(msg), ws::Text);
  19835. ASSERT_EQ(msg, "first");
  19836. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  19837. // not be used with a read timeout: it would reprocess the previous message.
  19838. EXPECT_EQ(client.read(msg), ws::Timeout);
  19839. EXPECT_EQ(msg, "first");
  19840. }
  19841. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  19842. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19843. "/ws-echo");
  19844. ASSERT_TRUE(client.connect());
  19845. // Setting it once the connection is open reaches the live stream, not just
  19846. // the seed for the next connect().
  19847. client.set_read_timeout(1, 0);
  19848. std::string msg;
  19849. EXPECT_EQ(client.read(msg), ws::Timeout);
  19850. EXPECT_TRUE(client.is_open());
  19851. }
  19852. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  19853. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19854. "/ws-echo");
  19855. client.set_read_timeout(5, 0);
  19856. ASSERT_TRUE(client.connect());
  19857. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19858. // The server should reject it and close the connection.
  19859. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  19860. client.send(oversized);
  19861. // The server's read() should have failed due to payload limit,
  19862. // so our read() should return false (connection closed).
  19863. std::string msg;
  19864. EXPECT_FALSE(client.read(msg));
  19865. }
  19866. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  19867. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19868. "/ws-echo");
  19869. client.set_read_timeout(10, 0);
  19870. ASSERT_TRUE(client.connect());
  19871. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19872. // This should succeed.
  19873. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  19874. ASSERT_TRUE(client.send(at_limit));
  19875. std::string msg;
  19876. ASSERT_TRUE(client.read(msg));
  19877. EXPECT_EQ(at_limit.size(), msg.size());
  19878. client.close();
  19879. }
  19880. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  19881. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19882. "/nonexistent");
  19883. auto res = client.connect();
  19884. EXPECT_FALSE(res);
  19885. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19886. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  19887. EXPECT_FALSE(client.is_open());
  19888. }
  19889. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  19890. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19891. "/ws-echo");
  19892. ASSERT_TRUE(client.connect());
  19893. ASSERT_TRUE(client.send(""));
  19894. std::string msg;
  19895. EXPECT_EQ(ws::Text, client.read(msg));
  19896. EXPECT_EQ("", msg);
  19897. client.close();
  19898. }
  19899. TEST_F(WebSocketIntegrationTest, Reconnect) {
  19900. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19901. "/ws-echo");
  19902. // First connection
  19903. ASSERT_TRUE(client.connect());
  19904. ASSERT_TRUE(client.send("first"));
  19905. std::string msg;
  19906. ASSERT_TRUE(client.read(msg));
  19907. EXPECT_EQ("first", msg);
  19908. client.close();
  19909. EXPECT_FALSE(client.is_open());
  19910. // Reconnect using the same client object
  19911. ASSERT_TRUE(client.connect());
  19912. ASSERT_TRUE(client.is_open());
  19913. ASSERT_TRUE(client.send("second"));
  19914. ASSERT_TRUE(client.read(msg));
  19915. EXPECT_EQ("second", msg);
  19916. client.close();
  19917. }
  19918. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  19919. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19920. "/ws-close-status");
  19921. ASSERT_TRUE(client.connect());
  19922. // Trigger the server to close with GoingAway status
  19923. ASSERT_TRUE(client.send("trigger"));
  19924. // read() should return false after receiving the close frame
  19925. std::string msg;
  19926. EXPECT_FALSE(client.read(msg));
  19927. EXPECT_FALSE(client.is_open());
  19928. }
  19929. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  19930. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19931. "/ws-echo");
  19932. ASSERT_TRUE(client.connect());
  19933. client.close(ws::CloseStatus::GoingAway, "client leaving");
  19934. EXPECT_FALSE(client.is_open());
  19935. }
  19936. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  19937. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  19938. ws::WebSocketClient client(
  19939. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19940. ASSERT_TRUE(client.connect());
  19941. // Server should have selected graphql-ws
  19942. EXPECT_EQ("graphql-ws", client.subprotocol());
  19943. client.close();
  19944. }
  19945. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  19946. Headers headers;
  19947. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  19948. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  19949. ws::WebSocketClient client(
  19950. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19951. ASSERT_TRUE(client.connect());
  19952. // The offer on the second field line counts too, so graphql-ws is selected
  19953. EXPECT_EQ("graphql-ws", client.subprotocol());
  19954. client.close();
  19955. }
  19956. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  19957. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  19958. ws::WebSocketClient client(
  19959. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19960. ASSERT_TRUE(client.connect());
  19961. // Server should not have selected any subprotocol
  19962. EXPECT_TRUE(client.subprotocol().empty());
  19963. client.close();
  19964. }
  19965. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  19966. // Connect without requesting any subprotocol
  19967. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19968. "/ws-subprotocol");
  19969. ASSERT_TRUE(client.connect());
  19970. EXPECT_TRUE(client.subprotocol().empty());
  19971. client.close();
  19972. }
  19973. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  19974. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19975. "/ws-echo");
  19976. client.set_tcp_nodelay(true);
  19977. client.set_connection_timeout(3, 0);
  19978. bool socket_options_called = false;
  19979. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  19980. ASSERT_TRUE(client.connect());
  19981. ASSERT_TRUE(client.is_open());
  19982. EXPECT_TRUE(socket_options_called);
  19983. ASSERT_TRUE(client.send("hello"));
  19984. std::string msg;
  19985. auto result = client.read(msg);
  19986. EXPECT_EQ(result, ws::ReadResult::Text);
  19987. EXPECT_EQ(msg, "hello");
  19988. client.close();
  19989. }
  19990. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  19991. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19992. "/ws-echo");
  19993. client.set_connection_timeout(std::chrono::seconds(3));
  19994. client.set_write_timeout(std::chrono::seconds(3));
  19995. // A sub-second remainder exercises the seconds/microseconds split.
  19996. client.set_read_timeout(std::chrono::milliseconds(1500));
  19997. ASSERT_TRUE(client.connect());
  19998. auto start = std::chrono::steady_clock::now();
  19999. std::string msg;
  20000. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20001. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20002. std::chrono::steady_clock::now() - start)
  20003. .count();
  20004. // Above 1s so that dropping the microseconds half of the split fails here.
  20005. // Ignoring the setter altogether would not reach this line at all: a client
  20006. // waits forever by default.
  20007. EXPECT_GE(elapsed, 1400);
  20008. EXPECT_LT(elapsed, 30000);
  20009. }
  20010. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20011. Server svr;
  20012. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20013. if (!req.has_header("Authorization")) {
  20014. res.status = StatusCode::Unauthorized_401;
  20015. res.set_content("Unauthorized", "text/plain");
  20016. return Server::HandlerResponse::Handled;
  20017. }
  20018. return Server::HandlerResponse::Unhandled;
  20019. });
  20020. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20021. std::string msg;
  20022. while (ws.read(msg)) {
  20023. ws.send(msg);
  20024. }
  20025. });
  20026. auto port = svr.bind_to_any_port("localhost");
  20027. std::thread t([&]() { svr.listen_after_bind(); });
  20028. svr.wait_until_ready();
  20029. // Without Authorization header - should be rejected before upgrade
  20030. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20031. EXPECT_FALSE(client1.connect());
  20032. // The rejection is framed like any other HTTP response
  20033. {
  20034. Client cli("localhost", port);
  20035. Headers headers = {{"Upgrade", "websocket"},
  20036. {"Connection", "Upgrade"},
  20037. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20038. {"Sec-WebSocket-Version", "13"}};
  20039. auto res = cli.Get("/ws", headers);
  20040. ASSERT_TRUE(res);
  20041. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20042. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20043. EXPECT_EQ("Unauthorized", res->body);
  20044. }
  20045. // With Authorization header - should succeed
  20046. Headers headers = {{"Authorization", "Bearer token123"}};
  20047. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20048. headers);
  20049. ASSERT_TRUE(client2.connect());
  20050. ASSERT_TRUE(client2.send("hello"));
  20051. std::string msg;
  20052. ASSERT_TRUE(client2.read(msg));
  20053. EXPECT_EQ("hello", msg);
  20054. client2.close();
  20055. svr.stop();
  20056. t.join();
  20057. }
  20058. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20059. Server svr;
  20060. std::atomic<int> pre_request_calls{0};
  20061. std::atomic<bool> route_matched{false};
  20062. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20063. pre_request_calls++;
  20064. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20065. if (req.get_header_value("Authorization") != "Bearer token123") {
  20066. res.status = StatusCode::Unauthorized_401;
  20067. res.set_content("Unauthorized", "text/plain");
  20068. return Server::HandlerResponse::Handled;
  20069. }
  20070. return Server::HandlerResponse::Unhandled;
  20071. });
  20072. std::atomic<bool> handler_called{false};
  20073. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20074. handler_called = true;
  20075. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20076. });
  20077. auto port = svr.bind_to_any_port("localhost");
  20078. std::thread t([&]() { svr.listen_after_bind(); });
  20079. svr.wait_until_ready();
  20080. // Without Authorization header - should be rejected before upgrade
  20081. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20082. "/ws/1");
  20083. EXPECT_FALSE(client1.connect());
  20084. EXPECT_FALSE(handler_called);
  20085. EXPECT_EQ(1, pre_request_calls);
  20086. EXPECT_TRUE(route_matched);
  20087. // The rejection is an ordinary HTTP response, not a protocol switch
  20088. {
  20089. Client cli("localhost", port);
  20090. Headers headers = {{"Upgrade", "websocket"},
  20091. {"Connection", "Upgrade"},
  20092. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20093. {"Sec-WebSocket-Version", "13"}};
  20094. auto res = cli.Get("/ws/1", headers);
  20095. ASSERT_TRUE(res);
  20096. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20097. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20098. EXPECT_EQ("Unauthorized", res->body);
  20099. }
  20100. EXPECT_FALSE(handler_called);
  20101. // With Authorization header - should succeed
  20102. Headers headers = {{"Authorization", "Bearer token123"}};
  20103. ws::WebSocketClient client2(
  20104. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20105. ASSERT_TRUE(client2.connect());
  20106. std::string msg;
  20107. ASSERT_TRUE(client2.read(msg));
  20108. EXPECT_EQ("/ws/:id 2", msg);
  20109. EXPECT_TRUE(handler_called);
  20110. client2.close();
  20111. svr.stop();
  20112. t.join();
  20113. }
  20114. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20115. Server svr;
  20116. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20117. // A read timeout is how a handler gets control back. Without it, a handler
  20118. // parked in read() can never write on the connection it is reading.
  20119. ws.set_read_timeout(std::chrono::milliseconds(100));
  20120. std::string msg;
  20121. while (ws.is_open()) {
  20122. auto r = ws.read(msg);
  20123. if (r == httplib::ws::Timeout) {
  20124. ws.send("tick");
  20125. continue;
  20126. }
  20127. if (r == httplib::ws::Fail) { break; }
  20128. ws.send(msg);
  20129. }
  20130. });
  20131. auto port = svr.bind_to_any_port("localhost");
  20132. std::thread t([&]() { svr.listen_after_bind(); });
  20133. svr.wait_until_ready();
  20134. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20135. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20136. ASSERT_TRUE(client.connect());
  20137. // The client sends nothing, so anything it receives came out of the
  20138. // handler's timeout path.
  20139. std::string msg;
  20140. ASSERT_EQ(client.read(msg), ws::Text);
  20141. EXPECT_EQ("tick", msg);
  20142. client.close();
  20143. svr.stop();
  20144. t.join();
  20145. }
  20146. // Stream::read may return fewer bytes than asked for. This is that contract at
  20147. // its worst -- one byte per call -- which is what a frame header straddling a
  20148. // read buffer's boundary looks like to the frame parser.
  20149. class WsByteAtATimeStream : public Stream {
  20150. public:
  20151. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20152. bool is_readable() const override { return true; }
  20153. bool wait_readable() const override { return true; }
  20154. bool wait_writable() const override { return true; }
  20155. ssize_t read(char *ptr, size_t size) override {
  20156. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20157. *ptr = data_[pos_++];
  20158. return 1;
  20159. }
  20160. ssize_t write(const char *, size_t size) override {
  20161. return static_cast<ssize_t>(size);
  20162. }
  20163. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20164. ip = "127.0.0.1";
  20165. port = 0;
  20166. }
  20167. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20168. ip = "127.0.0.1";
  20169. port = 0;
  20170. }
  20171. socket_t socket() const override { return INVALID_SOCKET; }
  20172. time_t duration() const override { return 0; }
  20173. private:
  20174. std::string data_;
  20175. size_t pos_ = 0;
  20176. };
  20177. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20178. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20179. // length and the mask key are all multi-byte fields here. Each used to be
  20180. // read with a single read() call, which fails as soon as one is split.
  20181. std::string body(200, 'x');
  20182. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20183. std::string frame;
  20184. frame += static_cast<char>(0x81); // FIN + Text
  20185. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20186. frame += static_cast<char>(body.size() >> 8);
  20187. frame += static_cast<char>(body.size() & 0xff);
  20188. for (size_t i = 0; i < 4; i++) {
  20189. frame += static_cast<char>(mask[i]);
  20190. }
  20191. for (size_t i = 0; i < body.size(); i++) {
  20192. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20193. }
  20194. WsByteAtATimeStream strm(frame);
  20195. ws::Opcode opcode;
  20196. std::string payload;
  20197. bool fin = false;
  20198. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20199. /*expect_masked=*/true, 1024),
  20200. ws::impl::FrameRead::Ok);
  20201. EXPECT_TRUE(fin);
  20202. EXPECT_EQ(opcode, ws::Opcode::Text);
  20203. EXPECT_EQ(payload, body);
  20204. }
  20205. TEST(WebSocketTest, QueryStringInHandshake) {
  20206. Server svr;
  20207. std::mutex mtx;
  20208. std::string received_target;
  20209. std::string received_token;
  20210. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20211. {
  20212. std::lock_guard<std::mutex> lock(mtx);
  20213. received_target = req.target;
  20214. if (req.has_param("token")) {
  20215. received_token = req.get_param_value("token");
  20216. }
  20217. }
  20218. std::string msg;
  20219. while (ws.read(msg)) {
  20220. ws.send(msg);
  20221. }
  20222. });
  20223. auto port = svr.bind_to_any_port("localhost");
  20224. std::thread t([&]() { svr.listen_after_bind(); });
  20225. svr.wait_until_ready();
  20226. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20227. "/ws?token=ABC&session=123");
  20228. ASSERT_TRUE(client.connect());
  20229. // Round-trip ensures the handler has run and captured the request.
  20230. ASSERT_TRUE(client.send("hello"));
  20231. std::string msg;
  20232. ASSERT_TRUE(client.read(msg));
  20233. EXPECT_EQ("hello", msg);
  20234. client.close();
  20235. {
  20236. std::lock_guard<std::mutex> lock(mtx);
  20237. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20238. EXPECT_EQ("ABC", received_token);
  20239. }
  20240. svr.stop();
  20241. t.join();
  20242. }
  20243. // Run a handshake against a throwaway server and hand the request the server
  20244. // received back to the caller, so tests can assert on the headers the client
  20245. // actually put on the wire.
  20246. static void capture_websocket_handshake_request(
  20247. const Headers &client_headers,
  20248. std::function<void(const Request &, int port)> verify) {
  20249. Server svr;
  20250. std::mutex mtx;
  20251. Request received;
  20252. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20253. {
  20254. std::lock_guard<std::mutex> lock(mtx);
  20255. received = req;
  20256. }
  20257. std::string msg;
  20258. while (ws.read(msg)) {
  20259. ws.send(msg);
  20260. }
  20261. });
  20262. auto port = svr.bind_to_any_port("localhost");
  20263. std::thread t([&]() { svr.listen_after_bind(); });
  20264. auto se = detail::scope_exit([&] {
  20265. svr.stop();
  20266. t.join();
  20267. });
  20268. svr.wait_until_ready();
  20269. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20270. client_headers);
  20271. ASSERT_TRUE(client.connect());
  20272. ASSERT_TRUE(client.send("hello"));
  20273. std::string msg;
  20274. ASSERT_TRUE(client.read(msg));
  20275. client.close();
  20276. {
  20277. std::lock_guard<std::mutex> lock(mtx);
  20278. verify(received, port);
  20279. }
  20280. }
  20281. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20282. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20283. // Non-default port must be present in the Host header. Default ports
  20284. // (80/443) are omitted; that logic is covered by
  20285. // MakeHostAndPortStringTest.
  20286. EXPECT_EQ("localhost:" + std::to_string(port),
  20287. req.get_header_value("Host"));
  20288. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20289. req.get_header_value("User-Agent"));
  20290. EXPECT_FALSE(req.has_header("Accept"));
  20291. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20292. EXPECT_FALSE(req.has_header("Content-Length"));
  20293. });
  20294. }
  20295. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20296. capture_websocket_handshake_request(
  20297. {{"Host", "example.com"},
  20298. {"User-Agent", "custom-agent"},
  20299. {"X-Custom", "value"}},
  20300. [](const Request &req, int) {
  20301. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20302. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20303. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20304. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20305. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20306. });
  20307. }
  20308. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20309. capture_websocket_handshake_request(
  20310. {{"Upgrade", "bogus"},
  20311. {"Connection", "close"},
  20312. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20313. {"Sec-WebSocket-Version", "8"}},
  20314. [](const Request &req, int) {
  20315. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20316. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20317. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20318. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20319. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20320. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20321. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20322. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20323. req.get_header_value("Sec-WebSocket-Key"));
  20324. });
  20325. }
  20326. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20327. // A header the client refuses to send must abort the handshake before any
  20328. // part of it reaches the wire; a lone request line would otherwise sit in
  20329. // the peer's buffer as a truncated request.
  20330. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20331. ASSERT_NE(INVALID_SOCKET, srv);
  20332. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20333. sockaddr_in addr{};
  20334. addr.sin_family = AF_INET;
  20335. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20336. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20337. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20338. ASSERT_EQ(0, ::listen(srv, 1));
  20339. sockaddr_in bound{};
  20340. socklen_t bound_len = sizeof(bound);
  20341. ASSERT_EQ(
  20342. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20343. auto port = ntohs(bound.sin_port);
  20344. ssize_t received = -1;
  20345. std::thread t([&] {
  20346. // Bound every blocking call so a regression fails the test with a bad
  20347. // value instead of hanging the suite.
  20348. fd_set rfds;
  20349. FD_ZERO(&rfds);
  20350. FD_SET(srv, &rfds);
  20351. timeval tv{5, 0};
  20352. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20353. 0) {
  20354. return;
  20355. }
  20356. sockaddr_in cli_addr{};
  20357. socklen_t cli_len = sizeof(cli_addr);
  20358. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20359. if (cli == INVALID_SOCKET) { return; }
  20360. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20361. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20362. char buf[4096];
  20363. received = ::recv(cli, buf, sizeof(buf), 0);
  20364. });
  20365. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20366. // connect() has already shut the socket down by the time it returns false,
  20367. // so the peer sees EOF without waiting for the client to be destroyed.
  20368. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20369. {{"X-Bad", "a\r\nInjected: 1"}});
  20370. EXPECT_FALSE(client.connect());
  20371. t.join();
  20372. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20373. EXPECT_EQ(0, received);
  20374. }
  20375. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20376. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20377. // contains "upgrade" as a substring is a different token and must not
  20378. // start a WebSocket handshake.
  20379. auto make_request = [](const std::vector<std::string> &connection_values) {
  20380. Request req;
  20381. req.method = "GET";
  20382. req.headers.emplace("Upgrade", "websocket");
  20383. for (const auto &value : connection_values) {
  20384. req.headers.emplace("Connection", value);
  20385. }
  20386. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20387. req.headers.emplace("Sec-WebSocket-Version", "13");
  20388. return req;
  20389. };
  20390. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20391. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20392. EXPECT_TRUE(
  20393. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20394. EXPECT_TRUE(
  20395. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20396. EXPECT_TRUE(
  20397. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20398. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20399. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20400. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20401. EXPECT_FALSE(
  20402. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20403. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20404. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20405. }
  20406. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20407. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20408. // asks recipients to match each protocol-name case-insensitively, and RFC
  20409. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20410. // client naming websocket alongside another protocol, or on a second field
  20411. // line, is offering websocket; a value that merely contains "websocket" as a
  20412. // substring is a different protocol name and is not.
  20413. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20414. Request req;
  20415. req.method = "GET";
  20416. for (const auto &value : upgrade_values) {
  20417. req.headers.emplace("Upgrade", value);
  20418. }
  20419. req.headers.emplace("Connection", "Upgrade");
  20420. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20421. req.headers.emplace("Sec-WebSocket-Version", "13");
  20422. return req;
  20423. };
  20424. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20425. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20426. EXPECT_TRUE(
  20427. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20428. EXPECT_TRUE(
  20429. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20430. EXPECT_TRUE(
  20431. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20432. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20433. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20434. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20435. EXPECT_FALSE(
  20436. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20437. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20438. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20439. }
  20440. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20441. Server svr;
  20442. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20443. auto port = svr.bind_to_any_port("localhost");
  20444. std::thread t([&]() { svr.listen_after_bind(); });
  20445. auto se = detail::scope_exit([&] {
  20446. svr.stop();
  20447. t.join();
  20448. });
  20449. svr.wait_until_ready();
  20450. Headers headers = {{"Upgrade", "websocket"},
  20451. {"Connection", "notupgrade"},
  20452. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20453. {"Sec-WebSocket-Version", "13"}};
  20454. Client cli("localhost", port);
  20455. auto res = cli.Get("/ws", headers);
  20456. // The route exists only as a WebSocket route, so a request that fails the
  20457. // handshake check falls through to ordinary routing.
  20458. ASSERT_TRUE(res);
  20459. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20460. }
  20461. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20462. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20463. // Connection value is the only thing left for the client to reject.
  20464. Server svr;
  20465. svr.Get("/ws", [](const Request &req, Response &res) {
  20466. res.status = StatusCode::SwitchingProtocol_101;
  20467. res.set_header("Upgrade", "websocket");
  20468. res.set_header("Connection", "notupgrade");
  20469. res.set_header("Sec-WebSocket-Accept",
  20470. detail::websocket_accept_key(
  20471. req.get_header_value("Sec-WebSocket-Key")));
  20472. });
  20473. auto port = svr.bind_to_any_port("localhost");
  20474. std::thread t([&]() { svr.listen_after_bind(); });
  20475. auto se = detail::scope_exit([&] {
  20476. svr.stop();
  20477. t.join();
  20478. });
  20479. svr.wait_until_ready();
  20480. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20481. auto res = client.connect();
  20482. EXPECT_FALSE(res);
  20483. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20484. EXPECT_FALSE(client.is_open());
  20485. }
  20486. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20487. // The socket path doubles as the URL host, so it must not contain '/'.
  20488. const char *shard = getenv("GTEST_SHARD_INDEX");
  20489. const std::string sock_path =
  20490. shard ? std::string("httplib-ws-") + shard + ".sock"
  20491. : std::string("httplib-ws.sock");
  20492. std::remove(sock_path.c_str());
  20493. Server svr;
  20494. std::mutex mtx;
  20495. std::string received_host;
  20496. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20497. {
  20498. std::lock_guard<std::mutex> lock(mtx);
  20499. received_host = req.get_header_value("Host");
  20500. }
  20501. std::string msg;
  20502. while (ws.read(msg)) {
  20503. ws.send(msg);
  20504. }
  20505. });
  20506. svr.set_address_family(AF_UNIX);
  20507. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20508. auto se = detail::scope_exit([&] {
  20509. svr.stop();
  20510. t.join();
  20511. std::remove(sock_path.c_str());
  20512. });
  20513. svr.wait_until_ready();
  20514. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  20515. client.set_address_family(AF_UNIX);
  20516. ASSERT_TRUE(client.connect());
  20517. ASSERT_TRUE(client.send("hello"));
  20518. std::string msg;
  20519. ASSERT_TRUE(client.read(msg));
  20520. client.close();
  20521. {
  20522. std::lock_guard<std::mutex> lock(mtx);
  20523. // There is no host:port for a Unix socket, so the same "localhost"
  20524. // placeholder the HTTP client uses is expected.
  20525. EXPECT_EQ("localhost", received_host);
  20526. }
  20527. }
  20528. // Two threads must never parse WebSocket frames from the same stream.
  20529. // close() used to read the peer's Close reply with its own frame read, so it
  20530. // raced a reader thread that was in the middle of a payload: the payload loop
  20531. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  20532. // so bytes taken by close() were replaced with bytes from further along the
  20533. // stream. The message kept its length and silently changed content.
  20534. //
  20535. // The raw peer below sends a frame header plus part of the payload, waits for
  20536. // the handler to call close(), and only then sends the rest. Whichever thread
  20537. // would win the race for those bytes, the message must arrive intact, because
  20538. // close() must not touch the stream while read() owns it.
  20539. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  20540. #ifndef _WIN32
  20541. signal(SIGPIPE, SIG_IGN);
  20542. #endif
  20543. const size_t payload_len = 120; // fits the 7-bit length field
  20544. const size_t prefix_len = 8;
  20545. const int attempts = 8;
  20546. std::string expected(payload_len, '\0');
  20547. for (size_t i = 0; i < payload_len; i++) {
  20548. expected[i] = static_cast<char>('a' + i % 26);
  20549. }
  20550. std::atomic<bool> peer_stalled{false};
  20551. std::atomic<bool> handler_done{false};
  20552. std::mutex received_mutex;
  20553. std::vector<std::string> received;
  20554. // Bound every wait, so a regression fails the test instead of hanging the
  20555. // suite.
  20556. auto wait_for = [](const std::atomic<bool> &flag) {
  20557. for (int i = 0; i < 500 && !flag; i++) {
  20558. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20559. }
  20560. };
  20561. Server svr;
  20562. svr.set_websocket_ping_interval(0);
  20563. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  20564. std::thread reader([&]() {
  20565. std::string msg;
  20566. while (ws.read(msg)) {
  20567. std::lock_guard<std::mutex> guard(received_mutex);
  20568. received.push_back(msg);
  20569. }
  20570. });
  20571. // Wait until the peer stalls mid-payload, so the reader thread is parked
  20572. // inside read_websocket_frame() when close() runs.
  20573. wait_for(peer_stalled);
  20574. ws.close();
  20575. reader.join();
  20576. handler_done = true;
  20577. });
  20578. auto port = svr.bind_to_any_port("127.0.0.1");
  20579. std::thread t([&]() { svr.listen_after_bind(); });
  20580. auto se = detail::scope_exit([&] {
  20581. svr.stop();
  20582. t.join();
  20583. });
  20584. svr.wait_until_ready();
  20585. auto send_bytes = [](socket_t s, const std::string &data) {
  20586. #ifdef _WIN32
  20587. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  20588. #else
  20589. auto n = ::send(s, data.data(), data.size(), 0);
  20590. #endif
  20591. return n == static_cast<decltype(n)>(data.size());
  20592. };
  20593. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  20594. // Every length used here fits the 7-bit length field.
  20595. auto masked_header = [](uint8_t first_byte, size_t len) {
  20596. std::string h;
  20597. h += static_cast<char>(first_byte);
  20598. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  20599. h.append(4, '\0'); // mask key
  20600. return h;
  20601. };
  20602. for (int attempt = 0; attempt < attempts; attempt++) {
  20603. peer_stalled = false;
  20604. handler_done = false;
  20605. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  20606. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  20607. auto se_sock = detail::scope_exit([&] {
  20608. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  20609. });
  20610. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20611. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20612. sockaddr_in addr{};
  20613. addr.sin_family = AF_INET;
  20614. addr.sin_port = htons(static_cast<uint16_t>(port));
  20615. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20616. ASSERT_EQ(
  20617. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  20618. << "attempt " << attempt;
  20619. ASSERT_TRUE(send_bytes(sock,
  20620. "GET /ws HTTP/1.1\r\n"
  20621. "Host: 127.0.0.1\r\n"
  20622. "Upgrade: websocket\r\n"
  20623. "Connection: Upgrade\r\n"
  20624. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  20625. "Sec-WebSocket-Version: 13\r\n"
  20626. "\r\n"))
  20627. << "attempt " << attempt;
  20628. std::string response;
  20629. while (response.find("\r\n\r\n") == std::string::npos) {
  20630. char buf[512];
  20631. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  20632. if (n <= 0) { break; }
  20633. response.append(buf, static_cast<size_t>(n));
  20634. }
  20635. ASSERT_NE(std::string::npos, response.find(" 101 "))
  20636. << "attempt " << attempt;
  20637. // Send the header of a Binary message but only the first prefix_len bytes
  20638. // of its payload, leaving the reader thread stalled inside the payload.
  20639. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  20640. expected.substr(0, prefix_len)))
  20641. << "attempt " << attempt;
  20642. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20643. peer_stalled = true;
  20644. // Let close() send its Close frame and park in its own read before the
  20645. // rest of the payload arrives, so both threads are waiting for it.
  20646. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20647. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  20648. close_frame += static_cast<char>(0x03); // status 1000
  20649. close_frame += static_cast<char>(0xE8);
  20650. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  20651. << "attempt " << attempt;
  20652. // Closing the peer releases the reader thread even on the buggy path,
  20653. // where it waits for bytes another thread already consumed.
  20654. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20655. detail::close_socket(sock);
  20656. sock = INVALID_SOCKET;
  20657. wait_for(handler_done);
  20658. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  20659. }
  20660. std::lock_guard<std::mutex> guard(received_mutex);
  20661. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  20662. << "a message in flight when close() ran was dropped";
  20663. for (size_t i = 0; i < received.size(); i++) {
  20664. EXPECT_EQ(expected, received[i]) << "message " << i;
  20665. }
  20666. }
  20667. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20668. class WebSocketSSLIntegrationTest : public ::testing::Test {
  20669. protected:
  20670. void SetUp() override {
  20671. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  20672. SERVER_PRIVATE_KEY_FILE);
  20673. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20674. std::string msg;
  20675. ws::ReadResult ret;
  20676. while ((ret = ws.read(msg))) {
  20677. if (ret == ws::Binary) {
  20678. ws.send(msg.data(), msg.size());
  20679. } else {
  20680. ws.send(msg);
  20681. }
  20682. }
  20683. });
  20684. port_ = server_->bind_to_any_port(HOST);
  20685. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20686. server_->wait_until_ready();
  20687. }
  20688. void TearDown() override {
  20689. server_->stop();
  20690. if (server_thread_.joinable()) { server_thread_.join(); }
  20691. }
  20692. std::unique_ptr<SSLServer> server_;
  20693. std::thread server_thread_;
  20694. int port_ = 0;
  20695. };
  20696. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  20697. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20698. "/ws-echo");
  20699. client.enable_server_certificate_verification(false);
  20700. ASSERT_TRUE(client.connect());
  20701. ASSERT_TRUE(client.is_open());
  20702. ASSERT_TRUE(client.send("Hello WSS"));
  20703. std::string msg;
  20704. EXPECT_EQ(ws::Text, client.read(msg));
  20705. EXPECT_EQ("Hello WSS", msg);
  20706. client.close();
  20707. }
  20708. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  20709. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  20710. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  20711. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  20712. // client (without calling close() first) is the only path that runs
  20713. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  20714. // bug exactly.
  20715. //
  20716. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  20717. // when linked against an instrumented libssl; run under Valgrind to catch it
  20718. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  20719. // suite (the freed session otherwise stalls on the close handshake) — this test
  20720. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  20721. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  20722. {
  20723. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20724. "/ws-echo");
  20725. client.enable_server_certificate_verification(false);
  20726. client.set_read_timeout(2, 0);
  20727. client.set_write_timeout(2, 0);
  20728. ASSERT_TRUE(client.connect());
  20729. ASSERT_TRUE(client.is_open());
  20730. ASSERT_TRUE(client.send("still open"));
  20731. // Intentionally do NOT call client.close(): leaving scope runs
  20732. // shutdown_and_close() with the WebSocket still open, which must send the
  20733. // close frame while the TLS session is still alive.
  20734. }
  20735. }
  20736. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  20737. // shutdown_and_close() at the start of connect(), reproducing the same
  20738. // use-after-free within the test body rather than at scope exit. The second
  20739. // connect must succeed and echo, proving the close handshake ran over a live
  20740. // session. See the note above about memory-tool requirements.
  20741. TEST_F(WebSocketSSLIntegrationTest,
  20742. ReconnectWhileOpenSendsCloseOverLiveSession) {
  20743. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20744. "/ws-echo");
  20745. client.enable_server_certificate_verification(false);
  20746. client.set_read_timeout(2, 0);
  20747. client.set_write_timeout(2, 0);
  20748. ASSERT_TRUE(client.connect());
  20749. ASSERT_TRUE(client.is_open());
  20750. ASSERT_TRUE(client.send("still open"));
  20751. // Reconnect without closing first: connect() calls shutdown_and_close() on
  20752. // the still-open connection, which must not touch a freed TLS session.
  20753. ASSERT_TRUE(client.connect());
  20754. ASSERT_TRUE(client.is_open());
  20755. ASSERT_TRUE(client.send("after reconnect"));
  20756. std::string msg;
  20757. EXPECT_EQ(ws::Text, client.read(msg));
  20758. EXPECT_EQ("after reconnect", msg);
  20759. client.close();
  20760. }
  20761. #endif
  20762. #ifdef CPPHTTPLIB_SSL_ENABLED
  20763. class WebSocketSSLCATest : public ::testing::Test {
  20764. protected:
  20765. void SetUp() override {
  20766. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  20767. SERVER_PRIVATE_KEY_FILE);
  20768. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20769. std::string msg;
  20770. while (ws.read(msg)) {
  20771. ws.send(msg);
  20772. }
  20773. });
  20774. port_ = server_->bind_to_any_port("127.0.0.1");
  20775. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20776. server_->wait_until_ready();
  20777. }
  20778. void TearDown() override {
  20779. server_->stop();
  20780. if (server_thread_.joinable()) { server_thread_.join(); }
  20781. }
  20782. std::string url() const {
  20783. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  20784. }
  20785. std::unique_ptr<SSLServer> server_;
  20786. std::thread server_thread_;
  20787. int port_ = 0;
  20788. };
  20789. // A custom CA loaded as PEM verifies the server with full certificate
  20790. // verification enabled
  20791. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  20792. ws::WebSocketClient client(url());
  20793. std::string cert;
  20794. read_file(SERVER_CERT2_FILE, cert);
  20795. client.load_ca_cert_store(cert.c_str(), cert.size());
  20796. ASSERT_TRUE(client.connect());
  20797. ASSERT_TRUE(client.send("hello"));
  20798. std::string msg;
  20799. EXPECT_EQ(ws::Text, client.read(msg));
  20800. EXPECT_EQ("hello", msg);
  20801. client.close();
  20802. }
  20803. // A custom CA that does not cover the server must fail verification (the
  20804. // custom CA is exclusive; system certs are not loaded alongside it)
  20805. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  20806. ws::WebSocketClient client(url());
  20807. std::string cert;
  20808. read_file(CLIENT_CA_CERT_FILE, cert);
  20809. client.load_ca_cert_store(cert.c_str(), cert.size());
  20810. auto res = client.connect();
  20811. ASSERT_FALSE(res);
  20812. EXPECT_EQ(Error::SSLServerVerification, res.error());
  20813. EXPECT_EQ(-1, res.status());
  20814. EXPECT_NE(0u, res.ssl_backend_error());
  20815. }
  20816. // The same CA as a file path rather than PEM in memory
  20817. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  20818. ws::WebSocketClient client(url());
  20819. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20820. ASSERT_TRUE(client.connect());
  20821. ASSERT_TRUE(client.send("hello"));
  20822. std::string msg;
  20823. EXPECT_EQ(ws::Text, client.read(msg));
  20824. EXPECT_EQ("hello", msg);
  20825. client.close();
  20826. }
  20827. // ...and a CA file that does not cover the server still fails, so it is the
  20828. // path above that decides the outcome
  20829. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  20830. ws::WebSocketClient client(url());
  20831. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20832. ASSERT_FALSE(client.connect());
  20833. }
  20834. // Regression test: reconnecting with a native custom CA store used to reuse
  20835. // a store handle the previous TLS context had already freed (use-after-free
  20836. // under the OpenSSL backend). The context now lives as long as the client.
  20837. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  20838. ws::WebSocketClient client(url());
  20839. std::string cert;
  20840. read_file(SERVER_CERT2_FILE, cert);
  20841. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  20842. ASSERT_TRUE(client.connect());
  20843. client.close();
  20844. ASSERT_TRUE(client.connect());
  20845. ASSERT_TRUE(client.send("again"));
  20846. std::string msg;
  20847. EXPECT_EQ(ws::Text, client.read(msg));
  20848. EXPECT_EQ("again", msg);
  20849. client.close();
  20850. }
  20851. // Regression test: a certificate with a trusted chain but no identity match
  20852. // for the server IP must be rejected. The Mbed TLS backend used to skip
  20853. // verification entirely for IP hosts, so this connection succeeded there.
  20854. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  20855. // chain verification while the identity check must still fail.
  20856. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  20857. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20858. ASSERT_TRUE(svr.is_valid());
  20859. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20860. std::string msg;
  20861. while (ws.read(msg)) {
  20862. ws.send(msg);
  20863. }
  20864. });
  20865. auto port = svr.bind_to_any_port("127.0.0.1");
  20866. auto t = std::thread([&]() { svr.listen_after_bind(); });
  20867. auto se = detail::scope_exit([&] {
  20868. svr.stop();
  20869. t.join();
  20870. });
  20871. svr.wait_until_ready();
  20872. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  20873. "/echo");
  20874. std::string cert;
  20875. read_file(SERVER_CERT_FILE, cert);
  20876. client.load_ca_cert_store(cert.c_str(), cert.size());
  20877. ASSERT_FALSE(client.connect());
  20878. }
  20879. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  20880. // SNI, so nothing binds the host name to the TLS session. These bind the
  20881. // server to "localhost" instead, the only shape that exercises the SNI and
  20882. // hostname-verification path with certificate verification left enabled.
  20883. class WebSocketSSLDnsHostTest : public ::testing::Test {
  20884. protected:
  20885. void Start(const char *cert_file) {
  20886. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  20887. SERVER_PRIVATE_KEY_FILE);
  20888. ASSERT_TRUE(server_->is_valid());
  20889. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20890. std::string msg;
  20891. while (ws.read(msg)) {
  20892. ws.send(msg);
  20893. }
  20894. });
  20895. port_ = server_->bind_to_any_port("localhost");
  20896. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20897. server_->wait_until_ready();
  20898. }
  20899. void TearDown() override {
  20900. if (server_) { server_->stop(); }
  20901. if (server_thread_.joinable()) { server_thread_.join(); }
  20902. }
  20903. std::string url() const {
  20904. return "wss://localhost:" + std::to_string(port_) + "/echo";
  20905. }
  20906. std::unique_ptr<SSLServer> server_;
  20907. std::thread server_thread_;
  20908. int port_ = 0;
  20909. };
  20910. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  20911. // out and the connection is usable
  20912. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  20913. Start(SERVER_CERT2_FILE);
  20914. ws::WebSocketClient client(url());
  20915. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20916. ASSERT_TRUE(client.connect());
  20917. ASSERT_TRUE(client.send("hello"));
  20918. std::string msg;
  20919. EXPECT_EQ(ws::Text, client.read(msg));
  20920. EXPECT_EQ("hello", msg);
  20921. client.close();
  20922. }
  20923. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  20924. // while the identity check must still reject "localhost"
  20925. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  20926. Start(SERVER_CERT_FILE);
  20927. ws::WebSocketClient client(url());
  20928. client.set_ca_cert_path(SERVER_CERT_FILE);
  20929. auto res = client.connect();
  20930. ASSERT_FALSE(res);
  20931. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  20932. EXPECT_EQ(-1, res.status());
  20933. }
  20934. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  20935. // disabled: the chain is still checked, only the identity check is skipped
  20936. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  20937. Start(SERVER_CERT_FILE);
  20938. ws::WebSocketClient client(url());
  20939. client.set_ca_cert_path(SERVER_CERT_FILE);
  20940. client.enable_server_hostname_verification(false);
  20941. ASSERT_TRUE(client.connect());
  20942. ASSERT_TRUE(client.send("hello"));
  20943. std::string msg;
  20944. EXPECT_EQ(ws::Text, client.read(msg));
  20945. EXPECT_EQ("hello", msg);
  20946. client.close();
  20947. }
  20948. // A CA that did not sign the server certificate fails the chain, even though
  20949. // the name would match
  20950. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  20951. Start(SERVER_CERT2_FILE);
  20952. ws::WebSocketClient client(url());
  20953. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20954. ASSERT_FALSE(client.connect());
  20955. }
  20956. // With verification disabled, neither the chain nor the name is checked
  20957. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  20958. Start(SERVER_CERT_FILE);
  20959. ws::WebSocketClient client(url());
  20960. client.enable_server_certificate_verification(false);
  20961. ASSERT_TRUE(client.connect());
  20962. ASSERT_TRUE(client.send("hello"));
  20963. std::string msg;
  20964. EXPECT_EQ(ws::Text, client.read(msg));
  20965. EXPECT_EQ("hello", msg);
  20966. client.close();
  20967. }
  20968. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  20969. protected:
  20970. void SetUp() override {
  20971. server_ = httplib::detail::make_unique<SSLServer>(
  20972. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20973. ASSERT_TRUE(server_->is_valid());
  20974. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20975. std::string msg;
  20976. while (ws.read(msg)) {
  20977. ws.send(msg);
  20978. }
  20979. });
  20980. port_ = server_->bind_to_any_port("localhost");
  20981. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20982. server_->wait_until_ready();
  20983. }
  20984. void TearDown() override {
  20985. server_->stop();
  20986. if (server_thread_.joinable()) { server_thread_.join(); }
  20987. }
  20988. std::string url() const {
  20989. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  20990. }
  20991. void ConnectWithClientCert(const std::string &client_cert_file,
  20992. const std::string &client_private_key_file,
  20993. const char *private_key_password) {
  20994. std::string cert_pem, key_pem;
  20995. read_file(client_cert_file, cert_pem);
  20996. read_file(client_private_key_file, key_pem);
  20997. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  20998. key_pem.c_str(), key_pem.size(),
  20999. private_key_password};
  21000. ws::WebSocketClient client(url(), pem);
  21001. ASSERT_TRUE(client.is_valid());
  21002. client.enable_server_certificate_verification(false);
  21003. ASSERT_TRUE(client.connect());
  21004. ASSERT_TRUE(client.send("hello"));
  21005. std::string msg;
  21006. EXPECT_EQ(ws::Text, client.read(msg));
  21007. EXPECT_EQ("hello", msg);
  21008. client.close();
  21009. }
  21010. std::unique_ptr<SSLServer> server_;
  21011. std::thread server_thread_;
  21012. int port_ = 0;
  21013. };
  21014. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21015. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21016. }
  21017. // Control for the tests above: the fixture's server really does require a
  21018. // client certificate, so it is the PEM the constructor installed that decides
  21019. // the outcome.
  21020. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21021. ws::WebSocketClient client(url());
  21022. ASSERT_TRUE(client.is_valid());
  21023. client.enable_server_certificate_verification(false);
  21024. EXPECT_FALSE(client.connect());
  21025. }
  21026. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21027. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21028. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21029. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21030. }
  21031. #endif
  21032. #if !defined(_WIN32)
  21033. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21034. auto secret_dir = std::string("./symlink_test_secret");
  21035. auto served_dir = std::string("./symlink_test_served");
  21036. auto secret_file = secret_dir + "/secret.txt";
  21037. auto symlink_path = served_dir + "/escape";
  21038. // Setup: create directories and files
  21039. mkdir(secret_dir.c_str(), 0755);
  21040. mkdir(served_dir.c_str(), 0755);
  21041. {
  21042. std::ofstream ofs(secret_file);
  21043. ofs << "SECRET_DATA";
  21044. }
  21045. // Create symlink using absolute path so it resolves correctly
  21046. #ifdef PATH_MAX
  21047. char abs_secret[PATH_MAX];
  21048. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21049. #else
  21050. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21051. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21052. ASSERT_NE(nullptr, abs_secret);
  21053. #endif
  21054. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21055. auto se = detail::scope_exit([&] {
  21056. unlink(symlink_path.c_str());
  21057. unlink(secret_file.c_str());
  21058. rmdir(served_dir.c_str());
  21059. rmdir(secret_dir.c_str());
  21060. });
  21061. Server svr;
  21062. svr.set_mount_point("/", served_dir);
  21063. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21064. auto se2 = detail::scope_exit([&] {
  21065. svr.stop();
  21066. listen_thread.join();
  21067. });
  21068. svr.wait_until_ready();
  21069. Client cli("localhost", PORT);
  21070. // Symlink pointing outside base dir should be blocked
  21071. auto res = cli.Get("/escape/secret.txt");
  21072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21073. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21074. }
  21075. #endif
  21076. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21077. // A GET request with Content-Length to a static file handler must have its
  21078. // body drained before the keep-alive connection is reused. Otherwise the
  21079. // unread body bytes are interpreted as the next HTTP request.
  21080. //
  21081. // The body is sent AFTER receiving the first response (as in the original
  21082. // PoC) so that the stream_line_reader cannot buffer it together with the
  21083. // headers of the first request.
  21084. Server svr;
  21085. svr.set_mount_point("/", "./www");
  21086. std::atomic<int> smuggled_count(0);
  21087. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21088. smuggled_count++;
  21089. res.set_content("oops", "text/plain");
  21090. });
  21091. auto port = svr.bind_to_any_port("localhost");
  21092. thread t = thread([&] { svr.listen_after_bind(); });
  21093. auto se = detail::scope_exit([&] {
  21094. svr.stop();
  21095. t.join();
  21096. });
  21097. svr.wait_until_ready();
  21098. auto error = Error::Success;
  21099. auto sock = detail::create_client_socket(
  21100. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21101. /*connection_timeout_sec=*/2, 0,
  21102. /*read_timeout_sec=*/2, 0,
  21103. /*write_timeout_sec=*/2, 0, std::string(), error);
  21104. ASSERT_NE(INVALID_SOCKET, sock);
  21105. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21106. // The "smuggled" request will be sent as the body of the outer GET
  21107. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21108. "Host: localhost\r\n"
  21109. "Connection: close\r\n"
  21110. "\r\n";
  21111. // Step 1: Send only the outer request headers (no body yet)
  21112. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  21113. "Host: localhost\r\n"
  21114. "Content-Length: " +
  21115. std::to_string(smuggled.size()) +
  21116. "\r\n"
  21117. "\r\n";
  21118. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  21119. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  21120. // Step 2: Read the first response (server serves file without reading body)
  21121. std::string first_response;
  21122. char buf[4096];
  21123. for (;;) {
  21124. auto n = recv(sock, buf, sizeof(buf), 0);
  21125. if (n <= 0) break;
  21126. first_response.append(buf, static_cast<size_t>(n));
  21127. // Stop once we have a complete response (headers + body)
  21128. auto hdr_end = first_response.find("\r\n\r\n");
  21129. if (hdr_end != std::string::npos) {
  21130. // Check for Content-Length to know when the body is complete
  21131. auto cl_pos = first_response.find("Content-Length:");
  21132. if (cl_pos != std::string::npos) {
  21133. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21134. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21135. auto cl = std::stoul(
  21136. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21137. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21138. } else {
  21139. break; // No Content-Length, assume headers-only response
  21140. }
  21141. }
  21142. }
  21143. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  21144. // Step 3: Now send the body, which looks like a new HTTP request.
  21145. // On a vulnerable server the keep-alive loop reads this as a second request.
  21146. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  21147. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  21148. // Step 4: Try to read a second response (should NOT exist after fix)
  21149. std::string second_response;
  21150. for (;;) {
  21151. auto n = recv(sock, buf, sizeof(buf), 0);
  21152. if (n <= 0) break;
  21153. second_response.append(buf, static_cast<size_t>(n));
  21154. }
  21155. // The smuggled request must NOT have been processed
  21156. EXPECT_EQ(0, smuggled_count.load());
  21157. }
  21158. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21159. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21160. // must be rejected with 400 Bad Request.
  21161. Server svr;
  21162. svr.Post("/test", [&](const Request &, Response &res) {
  21163. res.set_content("ok", "text/plain");
  21164. });
  21165. thread t = thread([&] { svr.listen(HOST, PORT); });
  21166. auto se = detail::scope_exit([&] {
  21167. svr.stop();
  21168. t.join();
  21169. ASSERT_FALSE(svr.is_running());
  21170. });
  21171. svr.wait_until_ready();
  21172. // Exact "chunked"
  21173. {
  21174. auto req = "POST /test HTTP/1.1\r\n"
  21175. "Host: localhost\r\n"
  21176. "Content-Length: 5\r\n"
  21177. "Transfer-Encoding: chunked\r\n"
  21178. "Connection: close\r\n"
  21179. "\r\n"
  21180. "hello";
  21181. std::string response;
  21182. ASSERT_TRUE(send_request(1, req, &response));
  21183. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21184. response.substr(0, response.find("\r\n")));
  21185. }
  21186. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21187. {
  21188. auto req = "POST /test HTTP/1.1\r\n"
  21189. "Host: localhost\r\n"
  21190. "Content-Length: 5\r\n"
  21191. "Transfer-Encoding: gzip, chunked\r\n"
  21192. "Connection: close\r\n"
  21193. "\r\n"
  21194. "hello";
  21195. std::string response;
  21196. ASSERT_TRUE(send_request(1, req, &response));
  21197. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21198. response.substr(0, response.find("\r\n")));
  21199. }
  21200. }
  21201. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21202. Server svr;
  21203. svr.Post("/test", [&](const Request &, Response &res) {
  21204. res.set_content("ok", "text/plain");
  21205. });
  21206. thread t = thread([&] { svr.listen(HOST, PORT); });
  21207. auto se = detail::scope_exit([&] {
  21208. svr.stop();
  21209. t.join();
  21210. ASSERT_FALSE(svr.is_running());
  21211. });
  21212. svr.wait_until_ready();
  21213. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21214. // length cannot be determined, so the server must answer 400 and close
  21215. // rather than treat the request as bodyless and leave the body in the
  21216. // socket for the next request to pick up.
  21217. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21218. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21219. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21220. std::string response;
  21221. ASSERT_TRUE(send_request(1, req, &response));
  21222. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21223. response.substr(0, response.find("\r\n")))
  21224. << transfer_encoding;
  21225. }
  21226. // RFC 9110 5.3: the codings may also be split across several
  21227. // Transfer-Encoding lines, which combine in the order they were received.
  21228. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21229. // just like the single-line "chunked, gzip" above.
  21230. {
  21231. auto req = "POST /test HTTP/1.1\r\n"
  21232. "Host: localhost\r\n"
  21233. "Transfer-Encoding: chunked\r\n"
  21234. "Transfer-Encoding: gzip\r\n"
  21235. "\r\n"
  21236. "0\r\n\r\n";
  21237. std::string response;
  21238. ASSERT_TRUE(send_request(1, req, &response));
  21239. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21240. response.substr(0, response.find("\r\n")));
  21241. }
  21242. // A sequence ending in chunked stays valid.
  21243. auto req = "POST /test HTTP/1.1\r\n"
  21244. "Host: localhost\r\n"
  21245. "Transfer-Encoding: gzip, chunked\r\n"
  21246. "Connection: close\r\n"
  21247. "\r\n"
  21248. "0\r\n\r\n";
  21249. std::string response;
  21250. ASSERT_TRUE(send_request(1, req, &response));
  21251. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21252. // ...including when it is spread over several lines.
  21253. auto split_req = "POST /test HTTP/1.1\r\n"
  21254. "Host: localhost\r\n"
  21255. "Transfer-Encoding: gzip\r\n"
  21256. "Transfer-Encoding: chunked\r\n"
  21257. "Connection: close\r\n"
  21258. "\r\n"
  21259. "0\r\n\r\n";
  21260. std::string split_response;
  21261. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21262. EXPECT_EQ("HTTP/1.1 200 OK",
  21263. split_response.substr(0, split_response.find("\r\n")));
  21264. }
  21265. // Regression for issue #2450: a DELETE without Content-Length on a
  21266. // keep-alive connection must not let the post-response drain consume the
  21267. // next request's bytes.
  21268. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21269. Server svr;
  21270. std::atomic<int> delete_count(0);
  21271. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21272. delete_count++;
  21273. res.status = StatusCode::NoContent_204;
  21274. });
  21275. auto port = svr.bind_to_any_port(HOST);
  21276. thread t = thread([&] { svr.listen_after_bind(); });
  21277. auto se = detail::scope_exit([&] {
  21278. svr.stop();
  21279. t.join();
  21280. });
  21281. svr.wait_until_ready();
  21282. auto error = Error::Success;
  21283. auto sock = detail::create_client_socket(
  21284. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21285. /*connection_timeout_sec=*/2, 0,
  21286. /*read_timeout_sec=*/2, 0,
  21287. /*write_timeout_sec=*/2, 0, std::string(), error);
  21288. ASSERT_NE(INVALID_SOCKET, sock);
  21289. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21290. auto send_request_and_read_response = [&](const std::string &req,
  21291. std::string &out) -> bool {
  21292. auto sent = send(sock, req.data(), req.size(), 0);
  21293. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21294. char buf[4096];
  21295. for (;;) {
  21296. auto n = recv(sock, buf, sizeof(buf), 0);
  21297. if (n <= 0) { return !out.empty(); }
  21298. out.append(buf, static_cast<size_t>(n));
  21299. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21300. }
  21301. };
  21302. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21303. "Host: localhost\r\n"
  21304. "\r\n";
  21305. std::string resp1;
  21306. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21307. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21308. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21309. "Host: localhost\r\n"
  21310. "Connection: close\r\n"
  21311. "\r\n";
  21312. std::string resp2;
  21313. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21314. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21315. EXPECT_EQ(2, delete_count.load());
  21316. }
  21317. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21318. Server svr;
  21319. svr.Post("/ingest", [&](const Request &, Response &res,
  21320. const ContentReader &content_reader) {
  21321. auto consumed = content_reader([](const char *, size_t) { return false; });
  21322. EXPECT_FALSE(consumed);
  21323. res.status = StatusCode::Conflict_409;
  21324. res.set_header("Connection", "close");
  21325. });
  21326. auto port = svr.bind_to_any_port(HOST);
  21327. thread t = thread([&] { svr.listen_after_bind(); });
  21328. auto se = detail::scope_exit([&] {
  21329. svr.stop();
  21330. t.join();
  21331. });
  21332. svr.wait_until_ready();
  21333. auto error = Error::Success;
  21334. auto sock = detail::create_client_socket(
  21335. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21336. /*connection_timeout_sec=*/2, 0,
  21337. /*read_timeout_sec=*/1, 0,
  21338. /*write_timeout_sec=*/2, 0, std::string(), error);
  21339. ASSERT_NE(INVALID_SOCKET, sock);
  21340. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21341. std::string request = "POST /ingest HTTP/1.1\r\n"
  21342. "Host: localhost\r\n"
  21343. "Transfer-Encoding: chunked\r\n"
  21344. "\r\n"
  21345. "4\r\n"
  21346. "data\r\n";
  21347. auto sent = send(sock, request.data(), request.size(), 0);
  21348. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21349. std::string response;
  21350. ssize_t received = 0;
  21351. do {
  21352. char buf[4096];
  21353. received = recv(sock, buf, sizeof(buf), 0);
  21354. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21355. } while (received > 0);
  21356. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21357. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21358. EXPECT_EQ(0, received);
  21359. }
  21360. namespace no_proxy_test {
  21361. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21362. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21363. // calling listen().
  21364. class ScopedServer {
  21365. public:
  21366. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21367. ~ScopedServer() {
  21368. svr_.stop();
  21369. if (th_.joinable()) { th_.join(); }
  21370. }
  21371. Server &svr() { return svr_; }
  21372. int port() const { return port_; }
  21373. void listen() {
  21374. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21375. svr_.wait_until_ready();
  21376. }
  21377. private:
  21378. Server svr_;
  21379. std::thread th_;
  21380. int port_ = 0;
  21381. };
  21382. class ProxyAndTargetServers {
  21383. public:
  21384. ProxyAndTargetServers() {
  21385. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21386. proxy_hits_++;
  21387. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21388. res.set_content("via-proxy", "text/plain");
  21389. });
  21390. target_.Get(".*", [this](const Request &req, Response &res) {
  21391. target_hits_++;
  21392. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21393. res.set_content("direct", "text/plain");
  21394. });
  21395. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21396. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21397. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21398. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21399. proxy_mock_.wait_until_ready();
  21400. target_.wait_until_ready();
  21401. }
  21402. ~ProxyAndTargetServers() {
  21403. proxy_mock_.stop();
  21404. target_.stop();
  21405. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21406. if (target_thread_.joinable()) { target_thread_.join(); }
  21407. }
  21408. Server &proxy_mock() { return proxy_mock_; }
  21409. Server &target() { return target_; }
  21410. int proxy_port() const { return proxy_port_; }
  21411. int target_port() const { return target_port_; }
  21412. int proxy_hits() const { return proxy_hits_.load(); }
  21413. int target_hits() const { return target_hits_.load(); }
  21414. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21415. void reset_counters() {
  21416. proxy_hits_ = 0;
  21417. target_hits_ = 0;
  21418. last_had_proxy_authz_ = false;
  21419. }
  21420. private:
  21421. Server proxy_mock_;
  21422. Server target_;
  21423. std::thread proxy_thread_;
  21424. std::thread target_thread_;
  21425. int proxy_port_ = 0;
  21426. int target_port_ = 0;
  21427. std::atomic<int> proxy_hits_{0};
  21428. std::atomic<int> target_hits_{0};
  21429. std::atomic<bool> last_had_proxy_authz_{false};
  21430. };
  21431. inline std::unique_ptr<Client> make_client(const std::string &host,
  21432. ProxyAndTargetServers &s) {
  21433. auto cli = detail::make_unique<Client>(host, s.target_port());
  21434. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  21435. cli->set_proxy("127.0.0.1", s.proxy_port());
  21436. return cli;
  21437. }
  21438. } // namespace no_proxy_test
  21439. using no_proxy_test::make_client;
  21440. using no_proxy_test::ProxyAndTargetServers;
  21441. TEST(NoProxyTest, ExactHostnameBypasses) {
  21442. ProxyAndTargetServers s;
  21443. auto cli = make_client("example.com", s);
  21444. cli->set_no_proxy({"example.com"});
  21445. auto res = cli->Get("/");
  21446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21447. EXPECT_EQ(0, s.proxy_hits());
  21448. EXPECT_EQ(1, s.target_hits());
  21449. }
  21450. TEST(NoProxyTest, SubdomainBypasses) {
  21451. ProxyAndTargetServers s;
  21452. auto cli = make_client("foo.example.com", s);
  21453. cli->set_no_proxy({"example.com"});
  21454. auto res = cli->Get("/");
  21455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21456. EXPECT_EQ(0, s.proxy_hits());
  21457. EXPECT_EQ(1, s.target_hits());
  21458. }
  21459. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  21460. // Regression guard: "evilexample.com" must not be considered a subdomain
  21461. // of "example.com". Without the dot-boundary rule, a naive endsWith
  21462. // check would let traffic bypass the proxy and leak credentials direct
  21463. // to the attacker host.
  21464. ProxyAndTargetServers s;
  21465. auto cli = make_client("evilexample.com", s);
  21466. cli->set_no_proxy({"example.com"});
  21467. auto res = cli->Get("/");
  21468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21469. EXPECT_GE(s.proxy_hits(), 1);
  21470. EXPECT_EQ(0, s.target_hits());
  21471. }
  21472. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  21473. ProxyAndTargetServers s;
  21474. auto cli = make_client("example.com.evil.com", s);
  21475. cli->set_no_proxy({"example.com"});
  21476. auto res = cli->Get("/");
  21477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21478. EXPECT_GE(s.proxy_hits(), 1);
  21479. EXPECT_EQ(0, s.target_hits());
  21480. }
  21481. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  21482. ProxyAndTargetServers s;
  21483. auto cli = make_client("example.com", s);
  21484. cli->set_no_proxy({".example.com"});
  21485. auto res = cli->Get("/");
  21486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21487. EXPECT_EQ(0, s.proxy_hits());
  21488. EXPECT_EQ(1, s.target_hits());
  21489. }
  21490. TEST(NoProxyTest, CaseInsensitiveHostname) {
  21491. ProxyAndTargetServers s;
  21492. auto cli = make_client("Example.COM", s);
  21493. cli->set_no_proxy({"EXAMPLE.com"});
  21494. auto res = cli->Get("/");
  21495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21496. EXPECT_EQ(0, s.proxy_hits());
  21497. EXPECT_EQ(1, s.target_hits());
  21498. }
  21499. TEST(NoProxyTest, TrailingDotIsNormalized) {
  21500. ProxyAndTargetServers s;
  21501. auto cli = make_client("example.com.", s);
  21502. cli->set_no_proxy({"example.com"});
  21503. auto res = cli->Get("/");
  21504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21505. EXPECT_EQ(0, s.proxy_hits());
  21506. EXPECT_EQ(1, s.target_hits());
  21507. }
  21508. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  21509. // Trailing dots must be normalized on BOTH sides — host and entry.
  21510. // An implementation that only strips the host-side trailing dot would
  21511. // fail to match host "example.com" against entry "example.com." because
  21512. // a literal substring search would compare 11 chars against 12.
  21513. ProxyAndTargetServers s;
  21514. auto cli = make_client("example.com", s);
  21515. cli->set_no_proxy({"example.com."});
  21516. auto res = cli->Get("/");
  21517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21518. EXPECT_EQ(0, s.proxy_hits());
  21519. EXPECT_EQ(1, s.target_hits());
  21520. }
  21521. TEST(NoProxyTest, WildcardBypassesEverything) {
  21522. ProxyAndTargetServers s;
  21523. auto cli = make_client("anything.invalid.test", s);
  21524. cli->set_no_proxy({"*"});
  21525. auto res = cli->Get("/");
  21526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21527. EXPECT_EQ(0, s.proxy_hits());
  21528. EXPECT_EQ(1, s.target_hits());
  21529. }
  21530. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  21531. ProxyAndTargetServers s;
  21532. Client cli("127.0.0.1", s.target_port());
  21533. cli.set_proxy("127.0.0.1", s.proxy_port());
  21534. cli.set_no_proxy({"127.0.0.1"});
  21535. auto res = cli.Get("/");
  21536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21537. EXPECT_EQ(0, s.proxy_hits());
  21538. EXPECT_EQ(1, s.target_hits());
  21539. }
  21540. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  21541. ProxyAndTargetServers s;
  21542. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  21543. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  21544. cli.set_proxy("127.0.0.1", s.proxy_port());
  21545. cli.set_no_proxy({"::1"});
  21546. auto res = cli.Get("/");
  21547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21548. EXPECT_EQ(0, s.proxy_hits());
  21549. EXPECT_EQ(1, s.target_hits());
  21550. }
  21551. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  21552. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  21553. // must still be recognized as IPv6 for CIDR matching. Implementations
  21554. // that detect IPv6 only when the host begins with '[' would parse the
  21555. // host as a hostname and miss the match.
  21556. ProxyAndTargetServers s;
  21557. Client cli("fe80::1", s.target_port());
  21558. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21559. cli.set_proxy("127.0.0.1", s.proxy_port());
  21560. cli.set_no_proxy({"fe80::/10"});
  21561. auto res = cli.Get("/");
  21562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21563. EXPECT_EQ(0, s.proxy_hits());
  21564. EXPECT_EQ(1, s.target_hits());
  21565. }
  21566. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  21567. ProxyAndTargetServers s;
  21568. Client cli("::1", s.target_port());
  21569. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  21570. cli.set_proxy("127.0.0.1", s.proxy_port());
  21571. cli.set_no_proxy({"[::1]"});
  21572. auto res = cli.Get("/");
  21573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21574. EXPECT_EQ(0, s.proxy_hits());
  21575. EXPECT_EQ(1, s.target_hits());
  21576. }
  21577. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  21578. ProxyAndTargetServers s;
  21579. Client cli("fe80::1", s.target_port());
  21580. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21581. cli.set_proxy("127.0.0.1", s.proxy_port());
  21582. cli.set_no_proxy({"[fe80::]/10"});
  21583. auto res = cli.Get("/");
  21584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21585. EXPECT_EQ(0, s.proxy_hits());
  21586. EXPECT_EQ(1, s.target_hits());
  21587. }
  21588. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  21589. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  21590. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  21591. // tricks via address-family conversion.
  21592. ProxyAndTargetServers s;
  21593. Client cli("::ffff:127.0.0.1", s.target_port());
  21594. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  21595. cli.set_proxy("127.0.0.1", s.proxy_port());
  21596. cli.set_no_proxy({"127.0.0.1"});
  21597. auto res = cli.Get("/");
  21598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21599. EXPECT_GE(s.proxy_hits(), 1);
  21600. EXPECT_EQ(0, s.target_hits());
  21601. }
  21602. TEST(NoProxyTest, IPv4CidrMatch) {
  21603. ProxyAndTargetServers s;
  21604. Client cli("127.0.0.1", s.target_port());
  21605. cli.set_proxy("127.0.0.1", s.proxy_port());
  21606. cli.set_no_proxy({"127.0.0.0/8"});
  21607. auto res = cli.Get("/");
  21608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21609. EXPECT_EQ(0, s.proxy_hits());
  21610. EXPECT_EQ(1, s.target_hits());
  21611. }
  21612. TEST(NoProxyTest, IPv4CidrNonMatch) {
  21613. ProxyAndTargetServers s;
  21614. Client cli("127.0.0.1", s.target_port());
  21615. cli.set_proxy("127.0.0.1", s.proxy_port());
  21616. cli.set_no_proxy({"10.0.0.0/8"});
  21617. auto res = cli.Get("/");
  21618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21619. EXPECT_GE(s.proxy_hits(), 1);
  21620. EXPECT_EQ(0, s.target_hits());
  21621. }
  21622. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  21623. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  21624. // IPv4 target matches.
  21625. ProxyAndTargetServers s;
  21626. Client cli("127.0.0.1", s.target_port());
  21627. cli.set_proxy("127.0.0.1", s.proxy_port());
  21628. cli.set_no_proxy({"0.0.0.0/0"});
  21629. auto res = cli.Get("/");
  21630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21631. EXPECT_EQ(0, s.proxy_hits());
  21632. EXPECT_EQ(1, s.target_hits());
  21633. }
  21634. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  21635. ProxyAndTargetServers s;
  21636. Client cli("127.0.0.1", s.target_port());
  21637. cli.set_proxy("127.0.0.1", s.proxy_port());
  21638. cli.set_no_proxy({"127.0.0.1"});
  21639. auto res = cli.Get("/");
  21640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21641. EXPECT_EQ(0, s.proxy_hits());
  21642. EXPECT_EQ(1, s.target_hits());
  21643. }
  21644. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  21645. ProxyAndTargetServers s;
  21646. Client cli("127.0.0.1", s.target_port());
  21647. cli.set_proxy("127.0.0.1", s.proxy_port());
  21648. cli.set_no_proxy({"127.0.0.0/33"});
  21649. auto res = cli.Get("/");
  21650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21651. EXPECT_GE(s.proxy_hits(), 1);
  21652. EXPECT_EQ(0, s.target_hits());
  21653. }
  21654. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  21655. // Empty prefix after the slash must be rejected, not silently treated as /32.
  21656. ProxyAndTargetServers s;
  21657. Client cli("127.0.0.1", s.target_port());
  21658. cli.set_proxy("127.0.0.1", s.proxy_port());
  21659. cli.set_no_proxy({"127.0.0.1/"});
  21660. auto res = cli.Get("/");
  21661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21662. EXPECT_GE(s.proxy_hits(), 1);
  21663. EXPECT_EQ(0, s.target_hits());
  21664. }
  21665. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  21666. ProxyAndTargetServers s;
  21667. auto cli = make_client("internal.corp", s);
  21668. cli->set_proxy_basic_auth("u", "p");
  21669. cli->set_no_proxy({"internal.corp"});
  21670. auto res = cli->Get("/");
  21671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21672. EXPECT_EQ(1, s.target_hits());
  21673. EXPECT_EQ(0, s.proxy_hits());
  21674. EXPECT_FALSE(s.last_had_proxy_authz())
  21675. << "Proxy-Authorization must not be sent direct to the target";
  21676. }
  21677. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  21678. ProxyAndTargetServers s;
  21679. auto cli = make_client("public.example", s);
  21680. cli->set_proxy_basic_auth("u", "p");
  21681. cli->set_no_proxy({"internal.corp"}); // does not match
  21682. auto res = cli->Get("/");
  21683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21684. EXPECT_GE(s.proxy_hits(), 1);
  21685. EXPECT_TRUE(s.last_had_proxy_authz());
  21686. }
  21687. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  21688. ProxyAndTargetServers s;
  21689. auto cli = make_client("anything.test", s);
  21690. auto res = cli->Get("/");
  21691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21692. EXPECT_GE(s.proxy_hits(), 1);
  21693. EXPECT_EQ(0, s.target_hits());
  21694. }
  21695. TEST(NoProxyTest, PortSpecificEntryRejected) {
  21696. ProxyAndTargetServers s;
  21697. auto cli = make_client("example.com", s);
  21698. cli->set_no_proxy({"example.com:8080"});
  21699. auto res = cli->Get("/");
  21700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21701. EXPECT_GE(s.proxy_hits(), 1);
  21702. EXPECT_EQ(0, s.target_hits());
  21703. }
  21704. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  21705. ProxyAndTargetServers s;
  21706. auto cli = make_client("anything.test", s);
  21707. cli->set_no_proxy({"", " ", "\t"});
  21708. auto res = cli->Get("/");
  21709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21710. EXPECT_GE(s.proxy_hits(), 1);
  21711. EXPECT_EQ(0, s.target_hits());
  21712. }
  21713. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  21714. // An entry with leading/trailing whitespace must still match — env-style
  21715. // values are commonly pasted with stray spaces and an implementation
  21716. // that feeds the raw token directly to inet_pton would fail to match
  21717. // valid CIDRs because of the spaces.
  21718. ProxyAndTargetServers s;
  21719. Client cli("127.0.0.1", s.target_port());
  21720. cli.set_proxy("127.0.0.1", s.proxy_port());
  21721. cli.set_no_proxy({" 127.0.0.0/8 "});
  21722. auto res = cli.Get("/");
  21723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21724. EXPECT_EQ(0, s.proxy_hits());
  21725. EXPECT_EQ(1, s.target_hits());
  21726. }
  21727. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  21728. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  21729. // go direct and must NOT carry Proxy-Authorization.
  21730. std::atomic<int> proxy_hits{0};
  21731. std::atomic<int> target_hits{0};
  21732. std::atomic<bool> target_saw_authz{false};
  21733. no_proxy_test::ScopedServer proxy_mock, target;
  21734. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21735. proxy_hits++;
  21736. res.status = 302;
  21737. res.set_header("Location", "http://127.0.0.1:" +
  21738. std::to_string(target.port()) + "/landed");
  21739. });
  21740. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21741. target_hits++;
  21742. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  21743. res.set_content("direct", "text/plain");
  21744. });
  21745. proxy_mock.listen();
  21746. target.listen();
  21747. Client cli("public.example", target.port());
  21748. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21749. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21750. cli.set_proxy_basic_auth("u", "p");
  21751. cli.set_no_proxy({"127.0.0.1"});
  21752. cli.set_follow_location(true);
  21753. auto res = cli.Get("/redir");
  21754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21755. EXPECT_GE(proxy_hits.load(), 1);
  21756. EXPECT_GE(target_hits.load(), 1);
  21757. EXPECT_FALSE(target_saw_authz.load());
  21758. }
  21759. #ifdef CPPHTTPLIB_SSL_ENABLED
  21760. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  21761. // Direct origin replying 407 must not trigger the digest retry; otherwise
  21762. // proxy creds would be sent to the (possibly hostile) origin.
  21763. std::atomic<int> target_hits{0};
  21764. std::atomic<bool> target_saw_proxy_authz{false};
  21765. no_proxy_test::ScopedServer target;
  21766. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21767. target_hits++;
  21768. if (req.has_header("Proxy-Authorization")) {
  21769. target_saw_proxy_authz = true;
  21770. }
  21771. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21772. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  21773. "nonce=\"abc\", algorithm=MD5");
  21774. });
  21775. target.listen();
  21776. // The proxy address is set to the target's port: the bypass MUST kick in;
  21777. // if it doesn't, the test still routes "via proxy" to the same server and
  21778. // the Proxy-Authorization assertion below catches the leak.
  21779. Client cli("evil.example", target.port());
  21780. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  21781. cli.set_proxy("127.0.0.1", target.port());
  21782. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21783. cli.set_no_proxy({"evil.example"});
  21784. auto res = cli.Get("/x");
  21785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21786. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21787. EXPECT_EQ(1, target_hits.load());
  21788. EXPECT_FALSE(target_saw_proxy_authz.load());
  21789. }
  21790. #endif
  21791. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  21792. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  21793. std::atomic<int> proxy_hits{0};
  21794. std::atomic<int> bypass_hits{0};
  21795. std::atomic<bool> proxy_saw_c_url{false};
  21796. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  21797. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  21798. proxy_hits++;
  21799. if (req.path.find("/start") != std::string::npos) {
  21800. res.status = 302;
  21801. res.set_header("Location", "http://127.0.0.1:" +
  21802. std::to_string(bypass_server.port()) +
  21803. "/middle");
  21804. return;
  21805. }
  21806. if (req.path.find("/end") != std::string::npos) {
  21807. proxy_saw_c_url = true;
  21808. res.set_content("c-via-proxy", "text/plain");
  21809. return;
  21810. }
  21811. res.set_content("unexpected", "text/plain");
  21812. });
  21813. // public.example's "advertised" port is arbitrary (the request never lands
  21814. // there — it goes through the proxy), but use a dynamic value to stay
  21815. // friendly with sharded parallel runs.
  21816. int public_port = bypass_server.port();
  21817. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  21818. bypass_hits++;
  21819. res.status = 302;
  21820. res.set_header("Location", "http://public.example:" +
  21821. std::to_string(public_port) + "/end");
  21822. });
  21823. proxy_mock.listen();
  21824. bypass_server.listen();
  21825. Client cli("public.example", public_port);
  21826. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21827. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21828. cli.set_no_proxy({"127.0.0.1"});
  21829. cli.set_follow_location(true);
  21830. auto res = cli.Get("/start");
  21831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21832. EXPECT_EQ(StatusCode::OK_200, res->status);
  21833. EXPECT_EQ("c-via-proxy", res->body);
  21834. EXPECT_GE(proxy_hits.load(), 2);
  21835. EXPECT_GE(bypass_hits.load(), 1);
  21836. EXPECT_TRUE(proxy_saw_c_url.load());
  21837. }
  21838. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  21839. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  21840. // request reconnects to the correct endpoint.
  21841. std::atomic<int> proxy_hits{0};
  21842. std::atomic<int> target_hits{0};
  21843. no_proxy_test::ScopedServer proxy_mock, target;
  21844. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21845. proxy_hits++;
  21846. res.set_content("via-proxy", "text/plain");
  21847. });
  21848. target.svr().Get(".*", [&](const Request &, Response &res) {
  21849. target_hits++;
  21850. res.set_content("direct", "text/plain");
  21851. });
  21852. proxy_mock.listen();
  21853. target.listen();
  21854. Client cli("public.example", target.port());
  21855. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21856. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21857. cli.set_keep_alive(true);
  21858. auto res1 = cli.Get("/a");
  21859. ASSERT_TRUE(res1);
  21860. EXPECT_EQ("via-proxy", res1->body);
  21861. EXPECT_EQ(1, proxy_hits.load());
  21862. EXPECT_EQ(0, target_hits.load());
  21863. cli.set_no_proxy({"public.example"});
  21864. auto res2 = cli.Get("/b");
  21865. ASSERT_TRUE(res2);
  21866. EXPECT_EQ("direct", res2->body);
  21867. EXPECT_EQ(1, proxy_hits.load());
  21868. EXPECT_EQ(1, target_hits.load());
  21869. }
  21870. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  21871. namespace proxy_tunnel_test {
  21872. // SSLServer counterpart to no_proxy_test::ScopedServer.
  21873. class ScopedSSLServer {
  21874. public:
  21875. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  21876. port_ = svr_.bind_to_any_port("127.0.0.1");
  21877. }
  21878. ~ScopedSSLServer() {
  21879. svr_.stop();
  21880. if (th_.joinable()) { th_.join(); }
  21881. }
  21882. SSLServer &svr() { return svr_; }
  21883. int port() const { return port_; }
  21884. void listen() {
  21885. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21886. svr_.wait_until_ready();
  21887. }
  21888. private:
  21889. SSLServer svr_;
  21890. std::thread th_;
  21891. int port_ = 0;
  21892. };
  21893. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  21894. class ScopedConnectProxy {
  21895. public:
  21896. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  21897. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  21898. if (listen_fd_ < 0) { return; }
  21899. int yes = 1;
  21900. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  21901. sockaddr_in a{};
  21902. a.sin_family = AF_INET;
  21903. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21904. a.sin_port = 0;
  21905. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  21906. return;
  21907. }
  21908. socklen_t alen = sizeof(a);
  21909. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  21910. 0) {
  21911. return;
  21912. }
  21913. port_ = ntohs(a.sin_port);
  21914. if (::listen(listen_fd_, 1) != 0) { return; }
  21915. th_ = std::thread([this] { run(); });
  21916. }
  21917. ~ScopedConnectProxy() {
  21918. stop_ = true;
  21919. if (listen_fd_ >= 0) {
  21920. ::shutdown(listen_fd_, SHUT_RDWR);
  21921. ::close(listen_fd_);
  21922. }
  21923. if (th_.joinable()) { th_.join(); }
  21924. }
  21925. int port() const { return port_; }
  21926. int connect_hits() const { return connect_hits_.load(); }
  21927. // Head of the last CONNECT request, as the proxy saw it on the wire.
  21928. std::string connect_request() const {
  21929. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  21930. return connect_request_;
  21931. }
  21932. private:
  21933. void run() {
  21934. while (!stop_.load()) {
  21935. fd_set rfds;
  21936. FD_ZERO(&rfds);
  21937. FD_SET(listen_fd_, &rfds);
  21938. timeval tv{0, 100 * 1000};
  21939. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  21940. if (sel <= 0) { continue; }
  21941. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  21942. if (client_fd < 0) { continue; }
  21943. std::string req;
  21944. char buf[2048];
  21945. while (req.find("\r\n\r\n") == std::string::npos) {
  21946. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  21947. if (n <= 0) { break; }
  21948. req.append(buf, static_cast<size_t>(n));
  21949. }
  21950. if (req.compare(0, 7, "CONNECT") != 0) {
  21951. ::close(client_fd);
  21952. continue;
  21953. }
  21954. connect_hits_++;
  21955. {
  21956. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  21957. connect_request_ = req;
  21958. }
  21959. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  21960. ::send(client_fd, ok, std::strlen(ok), 0);
  21961. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  21962. sockaddr_in o{};
  21963. o.sin_family = AF_INET;
  21964. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21965. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  21966. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  21967. 0) {
  21968. ::close(client_fd);
  21969. ::close(origin_fd);
  21970. continue;
  21971. }
  21972. auto forward = [](int from, int to) {
  21973. char b[8192];
  21974. for (;;) {
  21975. ssize_t n = ::recv(from, b, sizeof(b), 0);
  21976. if (n <= 0) { break; }
  21977. ssize_t off = 0;
  21978. while (off < n) {
  21979. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  21980. if (s <= 0) {
  21981. off = n;
  21982. break;
  21983. }
  21984. off += s;
  21985. }
  21986. }
  21987. ::shutdown(to, SHUT_WR);
  21988. };
  21989. std::thread t1([&] { forward(client_fd, origin_fd); });
  21990. std::thread t2([&] { forward(origin_fd, client_fd); });
  21991. t1.join();
  21992. t2.join();
  21993. ::close(client_fd);
  21994. ::close(origin_fd);
  21995. }
  21996. }
  21997. int forward_port_ = -1;
  21998. int listen_fd_ = -1;
  21999. int port_ = 0;
  22000. std::thread th_;
  22001. std::atomic<bool> stop_{false};
  22002. std::atomic<int> connect_hits_{0};
  22003. mutable std::mutex connect_request_mutex_;
  22004. std::string connect_request_;
  22005. };
  22006. // Sends one request through the CONNECT proxy to the TLS origin with a
  22007. // credential configured for each hop, and checks that each credential reaches
  22008. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22009. // origin's (every header in origin_headers) on the tunnelled request.
  22010. void CredentialsStayWithTheirHop(
  22011. const std::function<void(SSLClient &)> &set_credentials,
  22012. const std::string &scheme,
  22013. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22014. std::atomic<int> origin_hits{0};
  22015. std::atomic<bool> origin_saw_proxy_authz{false};
  22016. std::atomic<bool> origin_saw_headers{false};
  22017. ScopedSSLServer origin;
  22018. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22019. origin_hits++;
  22020. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22021. origin_saw_headers =
  22022. std::all_of(origin_headers.begin(), origin_headers.end(),
  22023. [&](const std::string &h) { return req.has_header(h); });
  22024. res.set_content("ok", "text/plain");
  22025. });
  22026. origin.listen();
  22027. ScopedConnectProxy proxy(origin.port());
  22028. ASSERT_NE(0, proxy.port());
  22029. // Pinned to 127.0.0.1 for the same reason as the test below.
  22030. SSLClient cli("127.0.0.1", origin.port());
  22031. cli.enable_server_certificate_verification(false);
  22032. cli.set_proxy("127.0.0.1", proxy.port());
  22033. set_credentials(cli);
  22034. auto res = cli.Get("/x");
  22035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22036. EXPECT_EQ(StatusCode::OK_200, res->status);
  22037. EXPECT_EQ(1, origin_hits.load());
  22038. EXPECT_EQ(1, proxy.connect_hits());
  22039. EXPECT_TRUE(origin_saw_headers.load());
  22040. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22041. << "Proxy-Authorization must not be sent inside the tunnel";
  22042. auto connect_req = proxy.connect_request();
  22043. EXPECT_NE(std::string::npos,
  22044. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22045. for (const auto &h : origin_headers) {
  22046. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22047. << h << " must not be sent to the proxy on CONNECT";
  22048. }
  22049. }
  22050. } // namespace proxy_tunnel_test
  22051. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22052. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22053. [](SSLClient &cli) {
  22054. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22055. cli.set_basic_auth("origin-user", "origin-pass");
  22056. },
  22057. "Basic");
  22058. }
  22059. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22060. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22061. [](SSLClient &cli) {
  22062. cli.set_proxy_bearer_token_auth("proxy-token");
  22063. cli.set_bearer_token_auth("origin-token");
  22064. },
  22065. "Bearer");
  22066. }
  22067. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22068. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22069. [](SSLClient &cli) {
  22070. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22071. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22072. {"Cookie", "sid=origin-session"},
  22073. {"X-Api-Key", "origin-key"}});
  22074. },
  22075. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22076. }
  22077. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22078. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22079. // retry; otherwise proxy creds would be sent to the origin.
  22080. std::atomic<int> origin_hits{0};
  22081. std::atomic<bool> origin_saw_proxy_authz{false};
  22082. proxy_tunnel_test::ScopedSSLServer origin;
  22083. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22084. origin_hits++;
  22085. if (req.has_header("Proxy-Authorization")) {
  22086. origin_saw_proxy_authz = true;
  22087. }
  22088. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22089. res.set_header("Proxy-Authenticate",
  22090. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22091. "algorithm=MD5");
  22092. });
  22093. origin.listen();
  22094. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22095. ASSERT_NE(0, proxy.port());
  22096. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22097. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22098. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22099. // and answer with its own status, making this test flaky.
  22100. SSLClient cli("127.0.0.1", origin.port());
  22101. cli.enable_server_certificate_verification(false);
  22102. cli.set_proxy("127.0.0.1", proxy.port());
  22103. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22104. auto res = cli.Get("/x");
  22105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22106. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22107. EXPECT_EQ(1, origin_hits.load());
  22108. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22109. EXPECT_EQ(1, proxy.connect_hits());
  22110. }
  22111. #endif