test.cc 859 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577
  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, ControlCharsInPathAreEncoded) {
  3379. // Every control character is percent-encoded, not just CR/LF, so the target
  3380. // passes the request-target check in write_request_line.
  3381. Server svr;
  3382. std::string target;
  3383. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3384. target = req.target;
  3385. res.status = StatusCode::OK_200;
  3386. return Server::HandlerResponse::Handled;
  3387. });
  3388. auto port = svr.bind_to_any_port(HOST);
  3389. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3390. auto se = detail::scope_exit([&] {
  3391. svr.stop();
  3392. thread.join();
  3393. ASSERT_FALSE(svr.is_running());
  3394. });
  3395. svr.wait_until_ready();
  3396. {
  3397. Client cli(HOST, port);
  3398. auto res = cli.Get("/a\tb\x1b\x7f");
  3399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3400. EXPECT_EQ("/a%09b%1B%7F", target);
  3401. }
  3402. }
  3403. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3404. // Nothing may reach the wire: a raw CR/LF target would split the request
  3405. // line and inject headers.
  3406. Server svr;
  3407. // Pre-routing so that "not called" means nothing reached the server at all,
  3408. // rather than merely failing to match a handler pattern.
  3409. auto handler_called = false;
  3410. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3411. handler_called = true;
  3412. res.status = StatusCode::OK_200;
  3413. return Server::HandlerResponse::Handled;
  3414. });
  3415. auto port = svr.bind_to_any_port(HOST);
  3416. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3417. auto se = detail::scope_exit([&] {
  3418. svr.stop();
  3419. thread.join();
  3420. ASSERT_FALSE(svr.is_running());
  3421. });
  3422. svr.wait_until_ready();
  3423. {
  3424. Client cli(HOST, port);
  3425. cli.set_path_encode(false);
  3426. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3427. EXPECT_FALSE(handle.is_valid());
  3428. EXPECT_EQ(Error::Write, handle.error);
  3429. EXPECT_FALSE(handler_called);
  3430. }
  3431. }
  3432. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3433. // Which of the two branches runs is decided by whether the query component
  3434. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3435. // an empty query and must still fall back to building one from
  3436. // `req.params`, while a non-empty query must win over `req.params`.
  3437. Server svr;
  3438. std::string target;
  3439. svr.Get("/foo", [&](const Request &req, Response &res) {
  3440. target = req.target;
  3441. res.status = StatusCode::OK_200;
  3442. });
  3443. auto port = svr.bind_to_any_port(HOST);
  3444. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3445. auto se = detail::scope_exit([&] {
  3446. svr.stop();
  3447. thread.join();
  3448. ASSERT_FALSE(svr.is_running());
  3449. });
  3450. svr.wait_until_ready();
  3451. {
  3452. // Trailing `?` -> empty query component -> `req.params` is used.
  3453. Client cli(HOST, port);
  3454. Request req;
  3455. req.method = "GET";
  3456. req.path = "/foo?";
  3457. req.params.emplace("a", "1");
  3458. target.clear();
  3459. auto res = cli.send(req);
  3460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3461. EXPECT_EQ("/foo?a=1", target);
  3462. }
  3463. {
  3464. // Non-empty query in `req.path` -> `req.params` is not appended.
  3465. Client cli(HOST, port);
  3466. Request req;
  3467. req.method = "GET";
  3468. req.path = "/foo?b=2";
  3469. req.params.emplace("a", "1");
  3470. target.clear();
  3471. auto res = cli.send(req);
  3472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3473. EXPECT_EQ("/foo?b=2", target);
  3474. }
  3475. }
  3476. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3477. Server svr;
  3478. svr.Get("/", [](const Request &req, Response &) {
  3479. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3480. });
  3481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3482. auto se = detail::scope_exit([&] {
  3483. svr.stop();
  3484. thread.join();
  3485. ASSERT_FALSE(svr.is_running());
  3486. });
  3487. svr.wait_until_ready();
  3488. {
  3489. Client cli(HOST, PORT);
  3490. cli.set_path_encode(false);
  3491. auto res = cli.Get("/?something=%0A");
  3492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3493. EXPECT_EQ(StatusCode::OK_200, res->status);
  3494. }
  3495. }
  3496. TEST(BindServerTest, BindDualStack) {
  3497. Server svr;
  3498. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3499. res.set_content("Hello World!", "text/plain");
  3500. });
  3501. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3502. auto se = detail::scope_exit([&] {
  3503. svr.stop();
  3504. thread.join();
  3505. ASSERT_FALSE(svr.is_running());
  3506. });
  3507. svr.wait_until_ready();
  3508. {
  3509. Client cli("127.0.0.1", PORT);
  3510. auto res = cli.Get("/1");
  3511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3512. EXPECT_EQ(StatusCode::OK_200, res->status);
  3513. EXPECT_EQ("Hello World!", res->body);
  3514. }
  3515. {
  3516. Client cli("::1", PORT);
  3517. auto res = cli.Get("/1");
  3518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3519. EXPECT_EQ(StatusCode::OK_200, res->status);
  3520. EXPECT_EQ("Hello World!", res->body);
  3521. }
  3522. }
  3523. TEST(BindServerTest, BindAndListenSeparately) {
  3524. Server svr;
  3525. int port = svr.bind_to_any_port("0.0.0.0");
  3526. ASSERT_TRUE(svr.is_valid());
  3527. ASSERT_TRUE(port > 0);
  3528. svr.stop();
  3529. }
  3530. // Reports whether anything is still listening on a loopback port. A plain
  3531. // connect() is used instead of a Client request because a socket left bound by
  3532. // mistake accepts the connection into its backlog and never answers, which
  3533. // would hang the test instead of failing it.
  3534. static bool is_loopback_port_accepting(int port) {
  3535. sockaddr_in addr{};
  3536. addr.sin_family = AF_INET;
  3537. addr.sin_port = htons(static_cast<uint16_t>(port));
  3538. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3539. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3540. EXPECT_NE(sock, INVALID_SOCKET);
  3541. if (sock == INVALID_SOCKET) { return false; }
  3542. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3543. static_cast<socklen_t>(sizeof(addr)));
  3544. detail::close_socket(sock);
  3545. return ret == 0;
  3546. }
  3547. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3548. Server svr;
  3549. auto port = svr.bind_to_any_port("127.0.0.1");
  3550. ASSERT_TRUE(port > 0);
  3551. svr.stop();
  3552. // bind_to_any_port() already called listen(2), so until stop() closed the
  3553. // descriptor the port kept accepting connections into the backlog. ASSERT
  3554. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3555. // below blocks forever in the accept loop.
  3556. ASSERT_FALSE(is_loopback_port_accepting(port));
  3557. // Nothing is left to accept on, so listen_after_bind() must report failure
  3558. // instead of returning success without ever serving.
  3559. EXPECT_FALSE(svr.listen_after_bind());
  3560. // The failed listen marks the server decommissioned, so a waiter returns
  3561. // instead of spinning forever.
  3562. svr.wait_until_ready();
  3563. }
  3564. #ifdef CPPHTTPLIB_SSL_ENABLED
  3565. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3566. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3567. CLIENT_CA_CERT_DIR);
  3568. int port = svr.bind_to_any_port("0.0.0.0");
  3569. ASSERT_TRUE(svr.is_valid());
  3570. ASSERT_TRUE(port > 0);
  3571. svr.stop();
  3572. }
  3573. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3574. // or a rejected CustomRoute() registration would not stop the server binding.
  3575. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3576. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3577. CLIENT_CA_CERT_DIR);
  3578. ASSERT_TRUE(svr.is_valid());
  3579. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3580. EXPECT_FALSE(svr.is_valid());
  3581. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3582. }
  3583. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3584. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3585. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3586. int port = svr.bind_to_any_port("0.0.0.0");
  3587. ASSERT_TRUE(svr.is_valid());
  3588. ASSERT_TRUE(port > 0);
  3589. svr.stop();
  3590. }
  3591. TEST(BindServerTest, UpdateCertsPem) {
  3592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3593. int port = svr.bind_to_any_port("0.0.0.0");
  3594. ASSERT_TRUE(svr.is_valid());
  3595. ASSERT_TRUE(port > 0);
  3596. // Read PEM files
  3597. std::string cert_pem, key_pem, ca_pem;
  3598. read_file(SERVER_CERT_FILE, cert_pem);
  3599. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3600. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3601. // Update server certificates using PEM API
  3602. ASSERT_TRUE(
  3603. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3604. ASSERT_TRUE(svr.is_valid());
  3605. svr.stop();
  3606. }
  3607. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3608. // Start server with client CA (enables client auth)
  3609. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3610. ASSERT_TRUE(svr.is_valid());
  3611. bool handler_called = false;
  3612. svr.Get("/test", [&](const Request &req, Response &res) {
  3613. handler_called = true;
  3614. // Verify client certificate is present
  3615. auto cert = req.peer_cert();
  3616. EXPECT_TRUE(static_cast<bool>(cert));
  3617. res.set_content("ok", "text/plain");
  3618. });
  3619. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3620. auto se = detail::scope_exit([&] {
  3621. svr.stop();
  3622. t.join();
  3623. ASSERT_FALSE(svr.is_running());
  3624. });
  3625. svr.wait_until_ready();
  3626. // Read PEM files
  3627. std::string cert_pem, key_pem, ca_pem;
  3628. read_file(SERVER_CERT_FILE, cert_pem);
  3629. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3630. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3631. // Update server certificates and client CA using PEM API while server running
  3632. ASSERT_TRUE(
  3633. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3634. // Connect with client certificate
  3635. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3636. cli.enable_server_certificate_verification(false);
  3637. cli.set_connection_timeout(30);
  3638. auto res = cli.Get("/test");
  3639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3640. ASSERT_EQ(StatusCode::OK_200, res->status);
  3641. ASSERT_TRUE(handler_called);
  3642. EXPECT_EQ("ok", res->body);
  3643. }
  3644. #endif
  3645. TEST(ErrorHandlerTest, ContentLength) {
  3646. Server svr;
  3647. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3648. res.status = StatusCode::OK_200;
  3649. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3650. "text/html"); // <= Content-Length still 13
  3651. });
  3652. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3653. res.set_content("Hello World!\n", "text/plain");
  3654. res.status = 524;
  3655. });
  3656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3657. auto se = detail::scope_exit([&] {
  3658. svr.stop();
  3659. thread.join();
  3660. ASSERT_FALSE(svr.is_running());
  3661. });
  3662. svr.wait_until_ready();
  3663. {
  3664. Client cli(HOST, PORT);
  3665. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3667. EXPECT_EQ(StatusCode::OK_200, res->status);
  3668. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3669. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3670. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3671. }
  3672. }
  3673. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3674. TEST(ExceptionTest, WithoutExceptionHandler) {
  3675. Server svr;
  3676. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3677. throw std::runtime_error("exception...");
  3678. });
  3679. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3680. throw std::runtime_error("exception\r\n...");
  3681. });
  3682. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3683. auto se = detail::scope_exit([&] {
  3684. svr.stop();
  3685. listen_thread.join();
  3686. ASSERT_FALSE(svr.is_running());
  3687. });
  3688. svr.wait_until_ready();
  3689. Client cli("localhost", PORT);
  3690. {
  3691. auto res = cli.Get("/exception");
  3692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3693. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3694. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3695. }
  3696. {
  3697. auto res = cli.Get("/unknown");
  3698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3699. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3700. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3701. }
  3702. }
  3703. TEST(ExceptionTest, WithExceptionHandler) {
  3704. Server svr;
  3705. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3706. std::exception_ptr ep) {
  3707. EXPECT_FALSE(ep == nullptr);
  3708. try {
  3709. std::rethrow_exception(ep);
  3710. } catch (std::exception &e) {
  3711. EXPECT_EQ("abc", std::string(e.what()));
  3712. } catch (...) {}
  3713. res.status = StatusCode::InternalServerError_500;
  3714. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3715. "text/html"); // <= Content-Length still 13 at this point
  3716. });
  3717. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3718. res.set_content("Hello World!\n", "text/plain");
  3719. throw std::runtime_error("abc");
  3720. });
  3721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3722. auto se = detail::scope_exit([&] {
  3723. svr.stop();
  3724. thread.join();
  3725. ASSERT_FALSE(svr.is_running());
  3726. });
  3727. svr.wait_until_ready();
  3728. for (size_t i = 0; i < 10; i++) {
  3729. Client cli(HOST, PORT);
  3730. for (size_t j = 0; j < 100; j++) {
  3731. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3734. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3735. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3736. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3737. }
  3738. cli.set_keep_alive(true);
  3739. for (size_t j = 0; j < 100; j++) {
  3740. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3742. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3743. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3744. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3745. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3746. }
  3747. }
  3748. }
  3749. TEST(ExceptionTest, AndErrorHandler) {
  3750. Server svr;
  3751. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3752. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3753. });
  3754. svr.set_exception_handler(
  3755. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3756. EXPECT_FALSE(ep == nullptr);
  3757. try {
  3758. std::rethrow_exception(ep);
  3759. } catch (std::exception &e) {
  3760. res.set_content(e.what(), "text/html");
  3761. } catch (...) {}
  3762. res.status = StatusCode::InternalServerError_500;
  3763. });
  3764. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3765. throw std::runtime_error("EXCEPTION");
  3766. });
  3767. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3768. res.set_content("ERROR", "text/html");
  3769. res.status = StatusCode::InternalServerError_500;
  3770. });
  3771. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3772. auto se = detail::scope_exit([&] {
  3773. svr.stop();
  3774. thread.join();
  3775. ASSERT_FALSE(svr.is_running());
  3776. });
  3777. svr.wait_until_ready();
  3778. Client cli(HOST, PORT);
  3779. {
  3780. auto res = cli.Get("/exception");
  3781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3782. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3783. EXPECT_EQ("EXCEPTION", res->body);
  3784. }
  3785. {
  3786. auto res = cli.Get("/error");
  3787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3788. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3789. EXPECT_EQ("ERROR", res->body);
  3790. }
  3791. {
  3792. auto res = cli.Get("/invalid");
  3793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3794. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3795. EXPECT_EQ("NOT_FOUND", res->body);
  3796. }
  3797. }
  3798. #endif
  3799. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3800. // process_request() wraps only routing() in a try/catch, so an exception from
  3801. // any other user callback used to unwind into the task queue - which does not
  3802. // catch - and terminate the process. Each test below runs the server on a
  3803. // single worker thread: a guard that catches the exception but still loses the
  3804. // thread would otherwise be hidden by a spare worker serving the follow-up
  3805. // request. Note that a regression here aborts the whole test binary rather
  3806. // than failing one test.
  3807. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3808. Server svr;
  3809. svr.new_task_queue = [] { return new ThreadPool(1); };
  3810. std::atomic<int> reported{0};
  3811. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3812. if (err == Error::UserCallbackException) { reported++; }
  3813. });
  3814. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3815. res.set_content_provider(
  3816. 1024, "text/plain",
  3817. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3818. sink.write("hello", 5);
  3819. throw std::runtime_error("from the content provider");
  3820. });
  3821. });
  3822. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3823. res.set_content("ok", "text/plain");
  3824. });
  3825. auto port = svr.bind_to_any_port(HOST);
  3826. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3827. auto se = detail::scope_exit([&] {
  3828. svr.stop();
  3829. listen_thread.join();
  3830. ASSERT_FALSE(svr.is_running());
  3831. });
  3832. svr.wait_until_ready();
  3833. {
  3834. Client cli(HOST, port);
  3835. cli.set_read_timeout(5, 0);
  3836. EXPECT_FALSE(cli.Get("/throw"));
  3837. }
  3838. EXPECT_TRUE(svr.is_running());
  3839. EXPECT_EQ(1, reported.load());
  3840. // A request on a fresh connection is still served.
  3841. {
  3842. Client cli(HOST, port);
  3843. auto res = cli.Get("/ok");
  3844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3845. EXPECT_EQ(StatusCode::OK_200, res->status);
  3846. EXPECT_EQ("ok", res->body);
  3847. }
  3848. }
  3849. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3850. Server svr;
  3851. svr.new_task_queue = [] { return new ThreadPool(1); };
  3852. std::atomic<bool> should_throw{true};
  3853. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3854. res.set_content("hi", "text/plain");
  3855. });
  3856. svr.set_post_routing_handler(
  3857. [&](const Request & /*req*/, Response & /*res*/) {
  3858. if (should_throw) {
  3859. throw std::runtime_error("from the post-routing handler");
  3860. }
  3861. });
  3862. auto port = svr.bind_to_any_port(HOST);
  3863. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3864. auto se = detail::scope_exit([&] {
  3865. svr.stop();
  3866. listen_thread.join();
  3867. ASSERT_FALSE(svr.is_running());
  3868. });
  3869. svr.wait_until_ready();
  3870. {
  3871. Client cli(HOST, port);
  3872. cli.set_read_timeout(5, 0);
  3873. EXPECT_FALSE(cli.Get("/hi"));
  3874. }
  3875. EXPECT_TRUE(svr.is_running());
  3876. should_throw = false;
  3877. {
  3878. Client cli(HOST, port);
  3879. auto res = cli.Get("/hi");
  3880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3881. EXPECT_EQ(StatusCode::OK_200, res->status);
  3882. EXPECT_EQ("hi", res->body);
  3883. }
  3884. }
  3885. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3886. // The guard reports the caught exception through the error logger, which is
  3887. // a user callback too. A logger that throws has to be contained as well, or
  3888. // the process would terminate from inside the catch.
  3889. Server svr;
  3890. svr.new_task_queue = [] { return new ThreadPool(1); };
  3891. std::atomic<int> reported{0};
  3892. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3893. if (err == Error::UserCallbackException) {
  3894. reported++;
  3895. throw std::runtime_error("from the error logger");
  3896. }
  3897. });
  3898. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3899. res.set_content_provider(
  3900. 1024, "text/plain",
  3901. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3902. sink.write("hello", 5);
  3903. throw std::runtime_error("from the content provider");
  3904. });
  3905. });
  3906. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3907. res.set_content("ok", "text/plain");
  3908. });
  3909. auto port = svr.bind_to_any_port(HOST);
  3910. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3911. auto se = detail::scope_exit([&] {
  3912. svr.stop();
  3913. listen_thread.join();
  3914. ASSERT_FALSE(svr.is_running());
  3915. });
  3916. svr.wait_until_ready();
  3917. {
  3918. Client cli(HOST, port);
  3919. cli.set_read_timeout(5, 0);
  3920. EXPECT_FALSE(cli.Get("/throw"));
  3921. }
  3922. EXPECT_TRUE(svr.is_running());
  3923. EXPECT_EQ(1, reported.load());
  3924. {
  3925. Client cli(HOST, port);
  3926. auto res = cli.Get("/ok");
  3927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3928. EXPECT_EQ(StatusCode::OK_200, res->status);
  3929. EXPECT_EQ("ok", res->body);
  3930. }
  3931. }
  3932. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3933. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3934. // so the exception unwinds through the ws::WebSocket object on its way to
  3935. // the guard. None of the HTTP cases above cross that.
  3936. Server svr;
  3937. svr.new_task_queue = [] { return new ThreadPool(1); };
  3938. std::atomic<int> reported{0};
  3939. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3940. if (err == Error::UserCallbackException) { reported++; }
  3941. });
  3942. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3943. throw std::runtime_error("from the WebSocket handler");
  3944. });
  3945. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3946. res.set_content("ok", "text/plain");
  3947. });
  3948. auto port = svr.bind_to_any_port(HOST);
  3949. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3950. auto se = detail::scope_exit([&] {
  3951. svr.stop();
  3952. listen_thread.join();
  3953. ASSERT_FALSE(svr.is_running());
  3954. });
  3955. svr.wait_until_ready();
  3956. {
  3957. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3958. "/ws");
  3959. auto res = client.connect();
  3960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3961. // The server dropped the connection instead of dying.
  3962. std::string msg;
  3963. EXPECT_FALSE(client.read(msg));
  3964. client.close();
  3965. }
  3966. EXPECT_TRUE(svr.is_running());
  3967. EXPECT_EQ(1, reported.load());
  3968. {
  3969. Client cli(HOST, port);
  3970. auto res = cli.Get("/ok");
  3971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3972. EXPECT_EQ(StatusCode::OK_200, res->status);
  3973. EXPECT_EQ("ok", res->body);
  3974. }
  3975. }
  3976. #ifdef CPPHTTPLIB_SSL_ENABLED
  3977. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3978. // SSLServer::process_and_close_socket() is a separate overload with its own
  3979. // guard, so it is exercised on its own.
  3980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3981. ASSERT_TRUE(svr.is_valid());
  3982. svr.new_task_queue = [] { return new ThreadPool(1); };
  3983. std::atomic<int> reported{0};
  3984. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3985. if (err == Error::UserCallbackException) { reported++; }
  3986. });
  3987. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3988. res.set_content_provider(
  3989. 1024, "text/plain",
  3990. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3991. sink.write("hello", 5);
  3992. throw std::runtime_error("from the content provider");
  3993. });
  3994. });
  3995. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3996. res.set_content("ok", "text/plain");
  3997. });
  3998. auto port = svr.bind_to_any_port(HOST);
  3999. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4000. auto se = detail::scope_exit([&] {
  4001. svr.stop();
  4002. listen_thread.join();
  4003. ASSERT_FALSE(svr.is_running());
  4004. });
  4005. svr.wait_until_ready();
  4006. {
  4007. SSLClient cli(HOST, port);
  4008. cli.enable_server_certificate_verification(false);
  4009. cli.set_read_timeout(5, 0);
  4010. EXPECT_FALSE(cli.Get("/throw"));
  4011. }
  4012. EXPECT_TRUE(svr.is_running());
  4013. EXPECT_EQ(1, reported.load());
  4014. {
  4015. SSLClient cli(HOST, port);
  4016. cli.enable_server_certificate_verification(false);
  4017. auto res = cli.Get("/ok");
  4018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4019. EXPECT_EQ(StatusCode::OK_200, res->status);
  4020. EXPECT_EQ("ok", res->body);
  4021. }
  4022. }
  4023. #endif
  4024. #endif
  4025. TEST(NoContentTest, ContentLength) {
  4026. Server svr;
  4027. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4028. res.status = StatusCode::NoContent_204;
  4029. });
  4030. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4031. auto se = detail::scope_exit([&] {
  4032. svr.stop();
  4033. thread.join();
  4034. ASSERT_FALSE(svr.is_running());
  4035. });
  4036. svr.wait_until_ready();
  4037. {
  4038. Client cli(HOST, PORT);
  4039. auto res = cli.Get("/hi");
  4040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4041. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4042. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4043. }
  4044. }
  4045. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4046. #ifdef CPPHTTPLIB_SSL_ENABLED
  4047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4048. ASSERT_TRUE(svr.is_valid());
  4049. #else
  4050. Server svr;
  4051. #endif
  4052. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4053. if (req.path == "/routing_handler") {
  4054. res.set_header("PRE_ROUTING", "on");
  4055. res.set_content("Routing Handler", "text/plain");
  4056. return httplib::Server::HandlerResponse::Handled;
  4057. }
  4058. return httplib::Server::HandlerResponse::Unhandled;
  4059. });
  4060. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4061. res.set_content("Error", "text/html");
  4062. });
  4063. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4064. if (req.path == "/routing_handler") {
  4065. res.set_header("POST_ROUTING", "on");
  4066. }
  4067. });
  4068. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4069. res.set_content("Hello World!\n", "text/plain");
  4070. });
  4071. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4072. auto se = detail::scope_exit([&] {
  4073. svr.stop();
  4074. thread.join();
  4075. ASSERT_FALSE(svr.is_running());
  4076. });
  4077. svr.wait_until_ready();
  4078. {
  4079. #ifdef CPPHTTPLIB_SSL_ENABLED
  4080. SSLClient cli(HOST, PORT);
  4081. cli.enable_server_certificate_verification(false);
  4082. #else
  4083. Client cli(HOST, PORT);
  4084. #endif
  4085. auto res = cli.Get("/routing_handler");
  4086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4087. EXPECT_EQ(StatusCode::OK_200, res->status);
  4088. EXPECT_EQ("Routing Handler", res->body);
  4089. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4090. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4091. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4092. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4093. }
  4094. {
  4095. #ifdef CPPHTTPLIB_SSL_ENABLED
  4096. SSLClient cli(HOST, PORT);
  4097. cli.enable_server_certificate_verification(false);
  4098. #else
  4099. Client cli(HOST, PORT);
  4100. #endif
  4101. auto res = cli.Get("/hi");
  4102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4103. EXPECT_EQ(StatusCode::OK_200, res->status);
  4104. EXPECT_EQ("Hello World!\n", res->body);
  4105. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4106. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4107. }
  4108. {
  4109. #ifdef CPPHTTPLIB_SSL_ENABLED
  4110. SSLClient cli(HOST, PORT);
  4111. cli.enable_server_certificate_verification(false);
  4112. #else
  4113. Client cli(HOST, PORT);
  4114. #endif
  4115. auto res = cli.Get("/aaa");
  4116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4117. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4118. EXPECT_EQ("Error", res->body);
  4119. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4120. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4121. }
  4122. }
  4123. TEST(RequestHandlerTest, PreRequestHandler) {
  4124. auto route_path = "/user/:user";
  4125. Server svr;
  4126. svr.Get("/hi", [](const Request &, Response &res) {
  4127. res.set_content("hi", "text/plain");
  4128. });
  4129. svr.Get(route_path, [](const Request &req, Response &res) {
  4130. res.set_content(req.path_params.at("user"), "text/plain");
  4131. });
  4132. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4133. if (req.matched_route == route_path) {
  4134. auto user = req.path_params.at("user");
  4135. if (user != "john") {
  4136. res.status = StatusCode::Forbidden_403;
  4137. res.set_content("error", "text/html");
  4138. return Server::HandlerResponse::Handled;
  4139. }
  4140. }
  4141. return Server::HandlerResponse::Unhandled;
  4142. });
  4143. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4144. auto se = detail::scope_exit([&] {
  4145. svr.stop();
  4146. thread.join();
  4147. ASSERT_FALSE(svr.is_running());
  4148. });
  4149. svr.wait_until_ready();
  4150. Client cli(HOST, PORT);
  4151. {
  4152. auto res = cli.Get("/hi");
  4153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4154. EXPECT_EQ(StatusCode::OK_200, res->status);
  4155. EXPECT_EQ("hi", res->body);
  4156. }
  4157. {
  4158. auto res = cli.Get("/user/john");
  4159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4160. EXPECT_EQ(StatusCode::OK_200, res->status);
  4161. EXPECT_EQ("john", res->body);
  4162. }
  4163. {
  4164. auto res = cli.Get("/user/invalid-user");
  4165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4166. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4167. EXPECT_EQ("error", res->body);
  4168. }
  4169. }
  4170. // The pre-request handler must run before the request body is read, so a
  4171. // rejected request never forces the server to buffer a (potentially large)
  4172. // body. Here the posted body is larger than the payload limit: if the body
  4173. // were read first the server would answer 413, but because the pre-request
  4174. // handler runs first it answers 403 and the body is never read.
  4175. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4176. Server svr;
  4177. svr.set_payload_max_length(8);
  4178. auto handler_ran = false;
  4179. svr.Post("/reject", [&](const Request &req, Response &res) {
  4180. handler_ran = true;
  4181. res.set_content(req.body, "text/plain");
  4182. });
  4183. svr.Post("/accept", [](const Request &req, Response &res) {
  4184. res.set_content(req.body, "text/plain");
  4185. });
  4186. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4187. if (req.matched_route == "/reject") {
  4188. res.status = StatusCode::Forbidden_403;
  4189. res.set_content("denied", "text/plain");
  4190. return Server::HandlerResponse::Handled;
  4191. }
  4192. return Server::HandlerResponse::Unhandled;
  4193. });
  4194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4195. auto se = detail::scope_exit([&] {
  4196. svr.stop();
  4197. thread.join();
  4198. ASSERT_FALSE(svr.is_running());
  4199. });
  4200. svr.wait_until_ready();
  4201. Client cli(HOST, PORT);
  4202. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4203. // rejects with 403 before the body is read, so 413 is never reached.
  4204. {
  4205. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4207. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4208. EXPECT_EQ("denied", res->body);
  4209. EXPECT_FALSE(handler_ran);
  4210. }
  4211. // An approved route still reads the body and enforces the payload limit.
  4212. {
  4213. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4215. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4216. }
  4217. }
  4218. TEST(UserDataTest, BasicOperations) {
  4219. httplib::UserData ud;
  4220. // Initially empty
  4221. EXPECT_FALSE(ud.has("key"));
  4222. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4223. // set and get
  4224. ud.set("key", 42);
  4225. EXPECT_TRUE(ud.has("key"));
  4226. auto *p = ud.get<int>("key");
  4227. ASSERT_NE(nullptr, p);
  4228. EXPECT_EQ(42, *p);
  4229. // Type mismatch → nullptr
  4230. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4231. // Overwrite with different type
  4232. ud.set("key", std::string("hello"));
  4233. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4234. auto *s = ud.get<std::string>("key");
  4235. ASSERT_NE(nullptr, s);
  4236. EXPECT_EQ("hello", *s);
  4237. // erase
  4238. ud.erase("key");
  4239. EXPECT_FALSE(ud.has("key"));
  4240. // clear
  4241. ud.set("a", 1);
  4242. ud.set("b", 2);
  4243. ud.clear();
  4244. EXPECT_FALSE(ud.has("a"));
  4245. EXPECT_FALSE(ud.has("b"));
  4246. }
  4247. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4248. struct AuthCtx {
  4249. std::string user_id;
  4250. };
  4251. Server svr;
  4252. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4253. res.user_data.set("auth", AuthCtx{"alice"});
  4254. return Server::HandlerResponse::Unhandled;
  4255. });
  4256. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4257. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4258. ASSERT_NE(nullptr, ctx);
  4259. res.set_content("Hello " + ctx->user_id, "text/plain");
  4260. });
  4261. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4262. auto se = detail::scope_exit([&] {
  4263. svr.stop();
  4264. thread.join();
  4265. ASSERT_FALSE(svr.is_running());
  4266. });
  4267. svr.wait_until_ready();
  4268. Client cli(HOST, PORT);
  4269. auto res = cli.Get("/me");
  4270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4271. EXPECT_EQ(StatusCode::OK_200, res->status);
  4272. EXPECT_EQ("Hello alice", res->body);
  4273. }
  4274. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4275. struct RoleCtx {
  4276. std::string role;
  4277. };
  4278. Server svr;
  4279. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4280. res.user_data.set("role", RoleCtx{"admin"});
  4281. return Server::HandlerResponse::Unhandled;
  4282. });
  4283. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4284. auto *ctx = res.user_data.get<RoleCtx>("role");
  4285. ASSERT_NE(nullptr, ctx);
  4286. res.set_content(ctx->role, "text/plain");
  4287. });
  4288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4289. auto se = detail::scope_exit([&] {
  4290. svr.stop();
  4291. thread.join();
  4292. ASSERT_FALSE(svr.is_running());
  4293. });
  4294. svr.wait_until_ready();
  4295. Client cli(HOST, PORT);
  4296. auto res = cli.Get("/role");
  4297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4298. EXPECT_EQ(StatusCode::OK_200, res->status);
  4299. EXPECT_EQ("admin", res->body);
  4300. }
  4301. TEST(InvalidFormatTest, StatusCode) {
  4302. Server svr;
  4303. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4304. res.set_content("Hello World!\n", "text/plain");
  4305. res.status = 9999; // Status should be a three-digit code...
  4306. });
  4307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4308. auto se = detail::scope_exit([&] {
  4309. svr.stop();
  4310. thread.join();
  4311. ASSERT_FALSE(svr.is_running());
  4312. });
  4313. svr.wait_until_ready();
  4314. {
  4315. Client cli(HOST, PORT);
  4316. auto res = cli.Get("/hi");
  4317. ASSERT_FALSE(res);
  4318. }
  4319. }
  4320. TEST(URLFragmentTest, WithFragment) {
  4321. Server svr;
  4322. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4323. EXPECT_TRUE(req.target == "/hi");
  4324. });
  4325. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4326. auto se = detail::scope_exit([&] {
  4327. svr.stop();
  4328. thread.join();
  4329. ASSERT_FALSE(svr.is_running());
  4330. });
  4331. svr.wait_until_ready();
  4332. {
  4333. Client cli(HOST, PORT);
  4334. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4335. EXPECT_TRUE(res);
  4336. EXPECT_EQ(StatusCode::OK_200, res->status);
  4337. res = cli.Get("/hi%23key1=val1=key2=val2");
  4338. EXPECT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4340. }
  4341. }
  4342. TEST(HeaderWriter, SetHeaderWriter) {
  4343. Server svr;
  4344. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4345. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4346. return detail::write_headers(strm, hdrs);
  4347. });
  4348. svr.Get("/hi", [](const Request &req, Response &res) {
  4349. auto it = req.headers.find("CustomClientHeader");
  4350. EXPECT_TRUE(it != req.headers.end());
  4351. EXPECT_EQ(it->second, "CustomClientValue");
  4352. res.set_content("Hello World!\n", "text/plain");
  4353. });
  4354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4355. auto se = detail::scope_exit([&] {
  4356. svr.stop();
  4357. thread.join();
  4358. ASSERT_FALSE(svr.is_running());
  4359. });
  4360. svr.wait_until_ready();
  4361. {
  4362. Client cli(HOST, PORT);
  4363. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4364. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4365. return detail::write_headers(strm, hdrs);
  4366. });
  4367. auto res = cli.Get("/hi");
  4368. EXPECT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::OK_200, res->status);
  4370. auto it = res->headers.find("CustomServerHeader");
  4371. EXPECT_TRUE(it != res->headers.end());
  4372. EXPECT_EQ(it->second, "CustomServerValue");
  4373. }
  4374. }
  4375. class ServerTest : public ::testing::Test {
  4376. protected:
  4377. ServerTest()
  4378. : cli_(HOST, PORT)
  4379. #ifdef CPPHTTPLIB_SSL_ENABLED
  4380. ,
  4381. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4382. #endif
  4383. {
  4384. #ifdef CPPHTTPLIB_SSL_ENABLED
  4385. cli_.enable_server_certificate_verification(false);
  4386. #endif
  4387. // Allow LARGE_DATA (100MB) responses
  4388. cli_.set_payload_max_length(200 * 1024 * 1024);
  4389. }
  4390. virtual void SetUp() {
  4391. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4392. svr_.set_payload_max_length(200 * 1024 * 1024);
  4393. svr_.set_mount_point("/", "./www");
  4394. svr_.set_mount_point("/mount", "./www2");
  4395. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4396. svr_.Get("/hi",
  4397. [&](const Request & /*req*/, Response &res) {
  4398. res.set_content("Hello World!", "text/plain");
  4399. })
  4400. .Get("/file_content",
  4401. [&](const Request & /*req*/, Response &res) {
  4402. res.set_file_content("./www/dir/test.html");
  4403. })
  4404. .Get("/file_content_with_content_type",
  4405. [&](const Request & /*req*/, Response &res) {
  4406. res.set_file_content("./www/file", "text/plain");
  4407. })
  4408. .Get("/invalid_file_content",
  4409. [&](const Request & /*req*/, Response &res) {
  4410. res.set_file_content("./www/dir/invalid_file_path");
  4411. })
  4412. .Get("/http_response_splitting",
  4413. [&](const Request & /*req*/, Response &res) {
  4414. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4415. EXPECT_EQ(0U, res.headers.size());
  4416. EXPECT_FALSE(res.has_header("a"));
  4417. res.set_header("a", "1\nSet-Cookie: a=1");
  4418. EXPECT_EQ(0U, res.headers.size());
  4419. EXPECT_FALSE(res.has_header("a"));
  4420. res.set_header("a", "1\rSet-Cookie: a=1");
  4421. EXPECT_EQ(0U, res.headers.size());
  4422. EXPECT_FALSE(res.has_header("a"));
  4423. res.set_header("a\r\nb", "0");
  4424. EXPECT_EQ(0U, res.headers.size());
  4425. EXPECT_FALSE(res.has_header("a"));
  4426. res.set_header("a\rb", "0");
  4427. EXPECT_EQ(0U, res.headers.size());
  4428. EXPECT_FALSE(res.has_header("a"));
  4429. res.set_header("a\nb", "0");
  4430. EXPECT_EQ(0U, res.headers.size());
  4431. EXPECT_FALSE(res.has_header("a"));
  4432. res.set_redirect("1\r\nSet-Cookie: a=1");
  4433. EXPECT_EQ(0U, res.headers.size());
  4434. EXPECT_FALSE(res.has_header("Location"));
  4435. })
  4436. .Get("/slow",
  4437. [&](const Request & /*req*/, Response &res) {
  4438. std::this_thread::sleep_for(std::chrono::seconds(4));
  4439. res.set_content("slow", "text/plain");
  4440. })
  4441. #if 0
  4442. .Post("/slowpost",
  4443. [&](const Request & /*req*/, Response &res) {
  4444. std::this_thread::sleep_for(std::chrono::seconds(2));
  4445. res.set_content("slow", "text/plain");
  4446. })
  4447. #endif
  4448. .Get("/remote_addr",
  4449. [&](const Request &req, Response &res) {
  4450. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4451. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4452. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4453. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4454. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4455. #endif
  4456. res.set_content(req.remote_addr, "text/plain");
  4457. })
  4458. .Get("/local_addr",
  4459. [&](const Request &req, Response &res) {
  4460. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4461. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4462. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4463. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4464. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4465. #endif
  4466. auto local_addr = req.local_addr;
  4467. auto local_port = std::to_string(req.local_port);
  4468. res.set_content(local_addr.append(":").append(local_port),
  4469. "text/plain");
  4470. })
  4471. .Get("/endwith%",
  4472. [&](const Request & /*req*/, Response &res) {
  4473. res.set_content("Hello World!", "text/plain");
  4474. })
  4475. .Get("/a\\+\\+b",
  4476. [&](const Request &req, Response &res) {
  4477. ASSERT_TRUE(req.has_param("a +b"));
  4478. auto val = req.get_param_value("a +b");
  4479. res.set_content(val, "text/plain");
  4480. })
  4481. .Get("/", [&](const Request & /*req*/,
  4482. Response &res) { res.set_redirect("/hi"); })
  4483. .Post("/1",
  4484. [](const Request & /*req*/, Response &res) {
  4485. res.set_redirect("/2", StatusCode::SeeOther_303);
  4486. })
  4487. .Get("/2",
  4488. [](const Request & /*req*/, Response &res) {
  4489. res.set_content("redirected.", "text/plain");
  4490. res.status = StatusCode::OK_200;
  4491. })
  4492. .Post("/person",
  4493. [&](const Request &req, Response &res) {
  4494. if (req.has_param("name") && req.has_param("note")) {
  4495. persons_[req.get_param_value("name")] =
  4496. req.get_param_value("note");
  4497. } else {
  4498. res.status = StatusCode::BadRequest_400;
  4499. }
  4500. })
  4501. .Put("/person",
  4502. [&](const Request &req, Response &res) {
  4503. if (req.has_param("name") && req.has_param("note")) {
  4504. persons_[req.get_param_value("name")] =
  4505. req.get_param_value("note");
  4506. } else {
  4507. res.status = StatusCode::BadRequest_400;
  4508. }
  4509. })
  4510. .Get("/person/(.*)",
  4511. [&](const Request &req, Response &res) {
  4512. string name = req.matches[1];
  4513. if (persons_.find(name) != persons_.end()) {
  4514. auto note = persons_[name];
  4515. res.set_content(note, "text/plain");
  4516. } else {
  4517. res.status = StatusCode::NotFound_404;
  4518. }
  4519. })
  4520. .Delete("/person",
  4521. [&](const Request &req, Response &res) {
  4522. if (req.has_param("name")) {
  4523. string name = req.get_param_value("name");
  4524. if (persons_.find(name) != persons_.end()) {
  4525. persons_.erase(name);
  4526. res.set_content("DELETED", "text/plain");
  4527. } else {
  4528. res.status = StatusCode::NotFound_404;
  4529. }
  4530. } else {
  4531. res.status = StatusCode::BadRequest_400;
  4532. }
  4533. })
  4534. .Post("/x-www-form-urlencoded-json",
  4535. [&](const Request &req, Response &res) {
  4536. auto json = req.get_param_value("json");
  4537. ASSERT_EQ(JSON_DATA, json);
  4538. res.set_content(json, "appliation/json");
  4539. res.status = StatusCode::OK_200;
  4540. })
  4541. .Get("/streamed-chunked",
  4542. [&](const Request & /*req*/, Response &res) {
  4543. res.set_chunked_content_provider(
  4544. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4545. sink.os << "123";
  4546. sink.os << "456";
  4547. sink.os << "789";
  4548. sink.done();
  4549. return true;
  4550. });
  4551. })
  4552. .Get("/streamed-chunked-with-prohibited-trailer",
  4553. [&](const Request & /*req*/, Response &res) {
  4554. auto i = new int(0);
  4555. // Declare both a prohibited trailer (Content-Length) and an
  4556. // allowed one
  4557. res.set_header("Trailer", "Content-Length, X-Allowed");
  4558. res.set_chunked_content_provider(
  4559. "text/plain",
  4560. [i](size_t /*offset*/, DataSink &sink) {
  4561. switch (*i) {
  4562. case 0: sink.os << "123"; break;
  4563. case 1: sink.os << "456"; break;
  4564. case 2: sink.os << "789"; break;
  4565. case 3: {
  4566. sink.done_with_trailer(
  4567. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4568. } break;
  4569. }
  4570. (*i)++;
  4571. return true;
  4572. },
  4573. [i](bool success) {
  4574. EXPECT_TRUE(success);
  4575. delete i;
  4576. });
  4577. })
  4578. .Get("/streamed-chunked2",
  4579. [&](const Request & /*req*/, Response &res) {
  4580. auto i = new int(0);
  4581. res.set_chunked_content_provider(
  4582. "text/plain",
  4583. [i](size_t /*offset*/, DataSink &sink) {
  4584. switch (*i) {
  4585. case 0: sink.os << "123"; break;
  4586. case 1: sink.os << "456"; break;
  4587. case 2: sink.os << "789"; break;
  4588. case 3: sink.done(); break;
  4589. }
  4590. (*i)++;
  4591. return true;
  4592. },
  4593. [i](bool success) {
  4594. EXPECT_TRUE(success);
  4595. delete i;
  4596. });
  4597. })
  4598. .Get("/streamed-chunked-with-trailer",
  4599. [&](const Request & /*req*/, Response &res) {
  4600. auto i = new int(0);
  4601. res.set_header("Trailer", "Dummy1, Dummy2");
  4602. res.set_chunked_content_provider(
  4603. "text/plain",
  4604. [i](size_t /*offset*/, DataSink &sink) {
  4605. switch (*i) {
  4606. case 0: sink.os << "123"; break;
  4607. case 1: sink.os << "456"; break;
  4608. case 2: sink.os << "789"; break;
  4609. case 3: {
  4610. sink.done_with_trailer(
  4611. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4612. } break;
  4613. }
  4614. (*i)++;
  4615. return true;
  4616. },
  4617. [i](bool success) {
  4618. EXPECT_TRUE(success);
  4619. delete i;
  4620. });
  4621. })
  4622. .Get("/streamed",
  4623. [&](const Request & /*req*/, Response &res) {
  4624. res.set_content_provider(
  4625. 6, "text/plain",
  4626. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4627. sink.os << (offset < 3 ? "a" : "b");
  4628. return true;
  4629. });
  4630. })
  4631. .Get("/streamed-without-length",
  4632. [&](const Request & /*req*/, Response &res) {
  4633. auto data = new std::string("abcdefg");
  4634. res.set_content_provider(
  4635. "text/plain",
  4636. [data](size_t offset, DataSink &sink) {
  4637. if (offset < data->size()) {
  4638. sink.os << data->substr(offset);
  4639. }
  4640. sink.done();
  4641. return true;
  4642. },
  4643. [data](bool success) {
  4644. EXPECT_TRUE(success);
  4645. delete data;
  4646. });
  4647. })
  4648. .Get("/streamed-with-range",
  4649. [&](const Request &req, Response &res) {
  4650. auto data = new std::string("abcdefg");
  4651. // An explicit status keeps the server from picking the 206 it
  4652. // would otherwise choose for a ranged request, so the response
  4653. // is not a partial representation.
  4654. auto status = req.get_param_value("status");
  4655. if (status == "200") {
  4656. res.status = StatusCode::OK_200;
  4657. } else if (status == "403") {
  4658. res.status = StatusCode::Forbidden_403;
  4659. }
  4660. res.set_content_provider(
  4661. data->size(), "text/plain",
  4662. [data](size_t offset, size_t length, DataSink &sink) {
  4663. size_t DATA_CHUNK_SIZE = 4;
  4664. const auto &d = *data;
  4665. auto out_len =
  4666. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4667. auto ret =
  4668. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4669. EXPECT_TRUE(ret);
  4670. return true;
  4671. },
  4672. [data, &req](bool success) {
  4673. EXPECT_EQ(success, !req.has_param("error"));
  4674. delete data;
  4675. });
  4676. })
  4677. .Get("/streamed-cancel",
  4678. [&](const Request & /*req*/, Response &res) {
  4679. res.set_content_provider(
  4680. size_t(-1), "text/plain",
  4681. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4682. sink.os << "data_chunk";
  4683. return true;
  4684. });
  4685. })
  4686. .Get("/regex-with-delimiter",
  4687. [&](const Request &req, Response & /*res*/) {
  4688. ASSERT_TRUE(req.has_param("key"));
  4689. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4690. })
  4691. .Get("/with-range",
  4692. [&](const Request & /*req*/, Response &res) {
  4693. res.set_content("abcdefg", "text/plain");
  4694. })
  4695. .Get("/test-start-time",
  4696. [&](const Request &req, Response & /*res*/) {
  4697. EXPECT_NE(req.start_time_,
  4698. std::chrono::steady_clock::time_point::min());
  4699. })
  4700. .Get("/with-range-customized-response",
  4701. [&](const Request & /*req*/, Response &res) {
  4702. res.status = StatusCode::BadRequest_400;
  4703. res.set_content(JSON_DATA, "application/json");
  4704. })
  4705. .Post("/chunked",
  4706. [&](const Request &req, Response & /*res*/) {
  4707. EXPECT_EQ(req.body, "dechunked post body");
  4708. })
  4709. .Post("/large-chunked",
  4710. [&](const Request &req, Response & /*res*/) {
  4711. std::string expected(6 * 30 * 1024u, 'a');
  4712. EXPECT_EQ(req.body, expected);
  4713. })
  4714. .Post("/multipart",
  4715. [&](const Request &req, Response & /*res*/) {
  4716. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4717. req.form.get_field_count("text2") +
  4718. req.form.get_field_count("file3") +
  4719. req.form.get_field_count("file4"));
  4720. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4721. req.form.get_file_count("file2"));
  4722. ASSERT_TRUE(!req.form.has_file("???"));
  4723. ASSERT_TRUE(!req.form.has_field("???"));
  4724. ASSERT_TRUE(req.body.empty());
  4725. {
  4726. const auto &text = req.form.get_field("text1");
  4727. EXPECT_EQ("text default", text);
  4728. }
  4729. {
  4730. const auto &text = req.form.get_field("text2");
  4731. EXPECT_EQ("aωb", text);
  4732. }
  4733. {
  4734. const auto &file = req.form.get_file("file1");
  4735. EXPECT_EQ("hello.txt", file.filename);
  4736. EXPECT_EQ("text/plain", file.content_type);
  4737. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4738. }
  4739. {
  4740. const auto &file = req.form.get_file("file2");
  4741. EXPECT_EQ("world.json", file.filename);
  4742. EXPECT_EQ("application/json", file.content_type);
  4743. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4744. }
  4745. {
  4746. const auto &text = req.form.get_field("file3");
  4747. EXPECT_EQ(0u, text.size());
  4748. }
  4749. {
  4750. const auto &text = req.form.get_field("file4");
  4751. EXPECT_EQ(0u, text.size());
  4752. }
  4753. })
  4754. .Post("/multipart/multi_file_values",
  4755. [&](const Request &req, Response & /*res*/) {
  4756. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4757. req.form.get_field_count("multi_text1"));
  4758. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4759. ASSERT_TRUE(!req.form.has_file("???"));
  4760. ASSERT_TRUE(!req.form.has_field("???"));
  4761. ASSERT_TRUE(req.body.empty());
  4762. {
  4763. const auto &text = req.form.get_field("text");
  4764. EXPECT_EQ("default text", text);
  4765. }
  4766. {
  4767. const auto &text1_values = req.form.get_fields("multi_text1");
  4768. EXPECT_EQ(2u, text1_values.size());
  4769. EXPECT_EQ("aaaaa", text1_values[0]);
  4770. EXPECT_EQ("bbbbb", text1_values[1]);
  4771. }
  4772. {
  4773. const auto &file1_values = req.form.get_files("multi_file1");
  4774. EXPECT_EQ(2u, file1_values.size());
  4775. auto file1 = file1_values[0];
  4776. EXPECT_EQ(file1.filename, "hello.txt");
  4777. EXPECT_EQ(file1.content_type, "text/plain");
  4778. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4779. auto file2 = file1_values[1];
  4780. EXPECT_EQ(file2.filename, "world.json");
  4781. EXPECT_EQ(file2.content_type, "application/json");
  4782. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4783. }
  4784. })
  4785. .Post("/empty",
  4786. [&](const Request &req, Response &res) {
  4787. EXPECT_EQ(req.body, "");
  4788. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4789. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4790. res.set_content("empty", "text/plain");
  4791. })
  4792. .Post("/empty-no-content-type",
  4793. [&](const Request &req, Response &res) {
  4794. EXPECT_EQ(req.body, "");
  4795. EXPECT_FALSE(req.has_header("Content-Type"));
  4796. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4797. res.set_content("empty-no-content-type", "text/plain");
  4798. })
  4799. .Post("/path-only",
  4800. [&](const Request &req, Response &res) {
  4801. EXPECT_EQ(req.body, "");
  4802. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4803. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4804. res.set_content("path-only", "text/plain");
  4805. })
  4806. .Post("/path-headers-only",
  4807. [&](const Request &req, Response &res) {
  4808. EXPECT_EQ(req.body, "");
  4809. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4810. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4811. EXPECT_EQ("world", req.get_header_value("hello"));
  4812. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4813. res.set_content("path-headers-only", "text/plain");
  4814. })
  4815. .Post("/post-large",
  4816. [&](const Request &req, Response &res) {
  4817. EXPECT_EQ(req.body, LARGE_DATA);
  4818. res.set_content(req.body, "text/plain");
  4819. })
  4820. .Post("/post-loopback",
  4821. [&](const Request &, Response &res,
  4822. ContentReader const &content_reader) {
  4823. std::string body;
  4824. content_reader([&](const char *data, size_t data_length) {
  4825. body.append(data, data_length);
  4826. return true;
  4827. });
  4828. res.set_content(body, "text/plain");
  4829. })
  4830. .Put("/put-loopback",
  4831. [&](const Request &, Response &res,
  4832. ContentReader const &content_reader) {
  4833. std::string body;
  4834. content_reader([&](const char *data, size_t data_length) {
  4835. body.append(data, data_length);
  4836. return true;
  4837. });
  4838. res.set_content(body, "text/plain");
  4839. })
  4840. .Patch("/patch-loopback",
  4841. [&](const Request &, Response &res,
  4842. ContentReader const &content_reader) {
  4843. std::string body;
  4844. content_reader([&](const char *data, size_t data_length) {
  4845. body.append(data, data_length);
  4846. return true;
  4847. });
  4848. res.set_content(body, "text/plain");
  4849. })
  4850. .Put("/empty-no-content-type",
  4851. [&](const Request &req, Response &res) {
  4852. EXPECT_EQ(req.body, "");
  4853. EXPECT_FALSE(req.has_header("Content-Type"));
  4854. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4855. res.set_content("empty-no-content-type", "text/plain");
  4856. })
  4857. .Put("/put",
  4858. [&](const Request &req, Response &res) {
  4859. EXPECT_EQ(req.body, "PUT");
  4860. res.set_content(req.body, "text/plain");
  4861. })
  4862. .Put("/put-large",
  4863. [&](const Request &req, Response &res) {
  4864. EXPECT_EQ(req.body, LARGE_DATA);
  4865. res.set_content(req.body, "text/plain");
  4866. })
  4867. .Patch("/patch",
  4868. [&](const Request &req, Response &res) {
  4869. EXPECT_EQ(req.body, "PATCH");
  4870. res.set_content(req.body, "text/plain");
  4871. })
  4872. .Delete("/delete",
  4873. [&](const Request & /*req*/, Response &res) {
  4874. res.set_content("DELETE", "text/plain");
  4875. })
  4876. .Delete("/delete-body",
  4877. [&](const Request &req, Response &res) {
  4878. EXPECT_EQ(req.body, "content");
  4879. res.set_content(req.body, "text/plain");
  4880. })
  4881. .Options(R"(\*)",
  4882. [&](const Request & /*req*/, Response &res) {
  4883. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4884. })
  4885. .CustomRoute("PROPFIND", "/dav/:id",
  4886. [&](const Request &req, Response &res) {
  4887. res.set_header("x-body-size",
  4888. std::to_string(req.body.size()));
  4889. res.set_header("x-matched-route", req.matched_route);
  4890. res.set_header("x-dav-id", req.path_params.at("id"));
  4891. res.status = StatusCode::MultiStatus_207;
  4892. res.set_content(req.body, "application/xml");
  4893. })
  4894. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4895. [&](const Request &req, Response &res) {
  4896. res.set_header("x-dav-match", req.matches[1]);
  4897. res.status = StatusCode::MultiStatus_207;
  4898. })
  4899. .CustomRoute("MKCOL", "/dav-mkcol",
  4900. [&](const Request &req, Response &res) {
  4901. EXPECT_TRUE(req.body.empty());
  4902. res.status = StatusCode::Created_201;
  4903. })
  4904. .CustomRoute(
  4905. "REPORT", "/dav-report",
  4906. [&](const Request & /*req*/, Response &res,
  4907. const ContentReader &content_reader) {
  4908. std::string body;
  4909. content_reader([&](const char *data, size_t data_length) {
  4910. body.append(data, data_length);
  4911. return true;
  4912. });
  4913. res.set_header("x-body-size", std::to_string(body.size()));
  4914. res.status = StatusCode::MultiStatus_207;
  4915. res.set_content(body, "application/xml");
  4916. })
  4917. .Get("/request-target",
  4918. [&](const Request &req, Response & /*res*/) {
  4919. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4920. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4921. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4922. })
  4923. .Get("/long-query-value",
  4924. [&](const Request &req, Response & /*res*/) {
  4925. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4926. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4927. })
  4928. .Get("/too-long-query-value",
  4929. [&](const Request &req, Response & /*res*/) {
  4930. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4931. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4932. })
  4933. .Get("/array-param",
  4934. [&](const Request &req, Response & /*res*/) {
  4935. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4936. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4937. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4938. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4939. })
  4940. .Get("/array-param-values",
  4941. [&](const Request &req, Response & /*res*/) {
  4942. auto values = req.get_param_values("array");
  4943. EXPECT_EQ(3u, values.size());
  4944. EXPECT_EQ("value1", values[0]);
  4945. EXPECT_EQ("value2", values[1]);
  4946. EXPECT_EQ("value3", values[2]);
  4947. auto empty = req.get_param_values("nonexistent");
  4948. EXPECT_TRUE(empty.empty());
  4949. })
  4950. .Post("/validate-no-multiple-headers",
  4951. [&](const Request &req, Response & /*res*/) {
  4952. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4953. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4954. })
  4955. .Post("/content_receiver",
  4956. [&](const Request &req, Response &res,
  4957. const ContentReader &content_reader) {
  4958. if (req.is_multipart_form_data()) {
  4959. std::vector<FormData> items;
  4960. content_reader(
  4961. [&](const FormData &file) {
  4962. items.push_back(file);
  4963. return true;
  4964. },
  4965. [&](const char *data, size_t data_length) {
  4966. items.back().content.append(data, data_length);
  4967. return true;
  4968. });
  4969. EXPECT_EQ(5u, items.size());
  4970. {
  4971. const auto &file = get_file_value(items, "text1");
  4972. EXPECT_TRUE(file.filename.empty());
  4973. EXPECT_EQ("text default", file.content);
  4974. }
  4975. {
  4976. const auto &file = get_file_value(items, "text2");
  4977. EXPECT_TRUE(file.filename.empty());
  4978. EXPECT_EQ("aωb", file.content);
  4979. }
  4980. {
  4981. const auto &file = get_file_value(items, "file1");
  4982. EXPECT_EQ("hello.txt", file.filename);
  4983. EXPECT_EQ("text/plain", file.content_type);
  4984. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4985. }
  4986. {
  4987. const auto &file = get_file_value(items, "file2");
  4988. EXPECT_EQ("world.json", file.filename);
  4989. EXPECT_EQ("application/json", file.content_type);
  4990. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4991. }
  4992. {
  4993. const auto &file = get_file_value(items, "file3");
  4994. EXPECT_TRUE(file.filename.empty());
  4995. EXPECT_EQ("application/octet-stream", file.content_type);
  4996. EXPECT_EQ(0u, file.content.size());
  4997. }
  4998. } else {
  4999. std::string body;
  5000. content_reader([&](const char *data, size_t data_length) {
  5001. EXPECT_EQ(7U, data_length);
  5002. body.append(data, data_length);
  5003. return true;
  5004. });
  5005. EXPECT_EQ(body, "content");
  5006. res.set_content(body, "text/plain");
  5007. }
  5008. })
  5009. .Put("/content_receiver",
  5010. [&](const Request & /*req*/, Response &res,
  5011. const ContentReader &content_reader) {
  5012. std::string body;
  5013. content_reader([&](const char *data, size_t data_length) {
  5014. body.append(data, data_length);
  5015. return true;
  5016. });
  5017. EXPECT_EQ(body, "content");
  5018. res.set_content(body, "text/plain");
  5019. })
  5020. .Patch("/content_receiver",
  5021. [&](const Request & /*req*/, Response &res,
  5022. const ContentReader &content_reader) {
  5023. std::string body;
  5024. content_reader([&](const char *data, size_t data_length) {
  5025. body.append(data, data_length);
  5026. return true;
  5027. });
  5028. EXPECT_EQ(body, "content");
  5029. res.set_content(body, "text/plain");
  5030. })
  5031. .Post("/query-string-and-body",
  5032. [&](const Request &req, Response & /*res*/) {
  5033. ASSERT_TRUE(req.has_param("key"));
  5034. EXPECT_EQ(req.get_param_value("key"), "value");
  5035. EXPECT_EQ(req.body, "content");
  5036. })
  5037. .Get("/last-request",
  5038. [&](const Request &req, Response & /*res*/) {
  5039. EXPECT_EQ("close", req.get_header_value("Connection"));
  5040. })
  5041. .Get(R"(/redirect/(\d+))",
  5042. [&](const Request &req, Response &res) {
  5043. auto num = std::stoi(req.matches[1]) + 1;
  5044. std::string url = "/redirect/" + std::to_string(num);
  5045. res.set_redirect(url);
  5046. })
  5047. .Post("/binary",
  5048. [&](const Request &req, Response &res) {
  5049. EXPECT_EQ(4U, req.body.size());
  5050. EXPECT_EQ("application/octet-stream",
  5051. req.get_header_value("Content-Type"));
  5052. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5053. res.set_content(req.body, "application/octet-stream");
  5054. })
  5055. .Put("/binary",
  5056. [&](const Request &req, Response &res) {
  5057. EXPECT_EQ(4U, req.body.size());
  5058. EXPECT_EQ("application/octet-stream",
  5059. req.get_header_value("Content-Type"));
  5060. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5061. res.set_content(req.body, "application/octet-stream");
  5062. })
  5063. .Patch("/binary",
  5064. [&](const Request &req, Response &res) {
  5065. EXPECT_EQ(4U, req.body.size());
  5066. EXPECT_EQ("application/octet-stream",
  5067. req.get_header_value("Content-Type"));
  5068. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5069. res.set_content(req.body, "application/octet-stream");
  5070. })
  5071. .Delete("/binary",
  5072. [&](const Request &req, Response &res) {
  5073. EXPECT_EQ(4U, req.body.size());
  5074. EXPECT_EQ("application/octet-stream",
  5075. req.get_header_value("Content-Type"));
  5076. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5077. res.set_content(req.body, "application/octet-stream");
  5078. })
  5079. .Get("/issue1772",
  5080. [&](const Request & /*req*/, Response &res) {
  5081. res.status = 401;
  5082. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5083. })
  5084. .Delete("/issue609",
  5085. [](const httplib::Request &, httplib::Response &res,
  5086. const httplib::ContentReader &) {
  5087. res.set_content("ok", "text/plain");
  5088. })
  5089. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5090. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5091. .Get("/compress",
  5092. [&](const Request & /*req*/, Response &res) {
  5093. res.set_content(
  5094. "12345678901234567890123456789012345678901234567890123456789"
  5095. "01234567890123456789012345678901234567890",
  5096. "text/plain");
  5097. })
  5098. .Get("/compress-with-charset",
  5099. [&](const Request & /*req*/, Response &res) {
  5100. res.set_content(
  5101. "12345678901234567890123456789012345678901234567890123456789"
  5102. "01234567890123456789012345678901234567890",
  5103. "application/json; charset=utf-8");
  5104. })
  5105. .Get("/nocompress",
  5106. [&](const Request & /*req*/, Response &res) {
  5107. res.set_content(
  5108. "12345678901234567890123456789012345678901234567890123456789"
  5109. "01234567890123456789012345678901234567890",
  5110. "application/octet-stream");
  5111. })
  5112. .Post("/compress-multipart",
  5113. [&](const Request &req, Response & /*res*/) {
  5114. EXPECT_EQ(2u, req.form.fields.size());
  5115. ASSERT_TRUE(!req.form.has_field("???"));
  5116. {
  5117. const auto &text = req.form.get_field("key1");
  5118. EXPECT_EQ("test", text);
  5119. }
  5120. {
  5121. const auto &text = req.form.get_field("key2");
  5122. EXPECT_EQ("--abcdefg123", text);
  5123. }
  5124. })
  5125. #endif
  5126. ;
  5127. persons_["john"] = "programmer";
  5128. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5129. svr_.wait_until_ready();
  5130. }
  5131. virtual void TearDown() {
  5132. svr_.stop();
  5133. if (!request_threads_.empty()) {
  5134. std::this_thread::sleep_for(std::chrono::seconds(1));
  5135. for (auto &t : request_threads_) {
  5136. t.join();
  5137. }
  5138. }
  5139. t_.join();
  5140. }
  5141. map<string, string> persons_;
  5142. #ifdef CPPHTTPLIB_SSL_ENABLED
  5143. SSLClient cli_;
  5144. SSLServer svr_;
  5145. #else
  5146. Client cli_;
  5147. Server svr_;
  5148. #endif
  5149. thread t_;
  5150. std::vector<thread> request_threads_;
  5151. };
  5152. TEST_F(ServerTest, GetMethod200) {
  5153. auto res = cli_.Get("/hi");
  5154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5155. EXPECT_EQ("HTTP/1.1", res->version);
  5156. EXPECT_EQ(StatusCode::OK_200, res->status);
  5157. EXPECT_EQ("OK", res->reason);
  5158. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5159. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5160. EXPECT_EQ("Hello World!", res->body);
  5161. }
  5162. TEST_F(ServerTest, GetEmptyFile) {
  5163. auto res = cli_.Get("/empty_file");
  5164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5165. EXPECT_EQ(StatusCode::OK_200, res->status);
  5166. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5168. EXPECT_EQ("", res->body);
  5169. }
  5170. TEST_F(ServerTest, GetFileContent) {
  5171. auto res = cli_.Get("/file_content");
  5172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5173. EXPECT_EQ(StatusCode::OK_200, res->status);
  5174. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5175. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5176. EXPECT_EQ("test.html", res->body);
  5177. }
  5178. TEST_F(ServerTest, GetFileContentWithRange) {
  5179. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5181. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5182. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5183. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5184. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5185. EXPECT_EQ("est", res->body);
  5186. }
  5187. TEST_F(ServerTest, GetFileContentWithContentType) {
  5188. auto res = cli_.Get("/file_content_with_content_type");
  5189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5190. EXPECT_EQ(StatusCode::OK_200, res->status);
  5191. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5192. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5193. EXPECT_EQ("file\n", res->body);
  5194. }
  5195. TEST_F(ServerTest, GetInvalidFileContent) {
  5196. auto res = cli_.Get("/invalid_file_content");
  5197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5198. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5199. }
  5200. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5201. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5203. EXPECT_EQ("HTTP/1.1", res->version);
  5204. EXPECT_EQ(StatusCode::OK_200, res->status);
  5205. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5206. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5207. EXPECT_EQ("Hello World!", res->body);
  5208. }
  5209. TEST_F(ServerTest, GetMethod302) {
  5210. auto res = cli_.Get("/");
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. EXPECT_EQ(StatusCode::Found_302, res->status);
  5213. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5214. }
  5215. TEST_F(ServerTest, GetMethod302Redirect) {
  5216. cli_.set_follow_location(true);
  5217. auto res = cli_.Get("/");
  5218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5219. EXPECT_EQ(StatusCode::OK_200, res->status);
  5220. EXPECT_EQ("Hello World!", res->body);
  5221. EXPECT_EQ("/hi", res->location);
  5222. }
  5223. TEST_F(ServerTest, GetMethod404) {
  5224. auto res = cli_.Get("/invalid");
  5225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5226. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5227. }
  5228. TEST_F(ServerTest, HeadMethod200) {
  5229. auto res = cli_.Head("/hi");
  5230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5231. EXPECT_EQ(StatusCode::OK_200, res->status);
  5232. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5233. EXPECT_TRUE(res->body.empty());
  5234. }
  5235. TEST_F(ServerTest, HeadMethod200Static) {
  5236. auto res = cli_.Head("/mount/dir/index.html");
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. EXPECT_EQ(StatusCode::OK_200, res->status);
  5239. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5240. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5241. EXPECT_TRUE(res->body.empty());
  5242. }
  5243. TEST_F(ServerTest, HeadMethod404) {
  5244. auto res = cli_.Head("/invalid");
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5247. EXPECT_TRUE(res->body.empty());
  5248. }
  5249. TEST_F(ServerTest, GetMethodPersonJohn) {
  5250. auto res = cli_.Get("/person/john");
  5251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5254. EXPECT_EQ("programmer", res->body);
  5255. }
  5256. TEST_F(ServerTest, PostMethod1) {
  5257. auto res = cli_.Get("/person/john1");
  5258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5259. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5260. res = cli_.Post("/person", "name=john1&note=coder",
  5261. "application/x-www-form-urlencoded");
  5262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5263. ASSERT_EQ(StatusCode::OK_200, res->status);
  5264. res = cli_.Get("/person/john1");
  5265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5266. ASSERT_EQ(StatusCode::OK_200, res->status);
  5267. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5268. ASSERT_EQ("coder", res->body);
  5269. }
  5270. TEST_F(ServerTest, PostMethod2) {
  5271. auto res = cli_.Get("/person/john2");
  5272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5273. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5274. Params params;
  5275. params.emplace("name", "john2");
  5276. params.emplace("note", "coder");
  5277. res = cli_.Post("/person", params);
  5278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5279. ASSERT_EQ(StatusCode::OK_200, res->status);
  5280. res = cli_.Get("/person/john2");
  5281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5282. ASSERT_EQ(StatusCode::OK_200, res->status);
  5283. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5284. ASSERT_EQ("coder", res->body);
  5285. }
  5286. TEST_F(ServerTest, PutMethod3) {
  5287. auto res = cli_.Get("/person/john3");
  5288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5289. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5290. Params params;
  5291. params.emplace("name", "john3");
  5292. params.emplace("note", "coder");
  5293. res = cli_.Put("/person", params);
  5294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5295. ASSERT_EQ(StatusCode::OK_200, res->status);
  5296. res = cli_.Get("/person/john3");
  5297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5298. ASSERT_EQ(StatusCode::OK_200, res->status);
  5299. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5300. ASSERT_EQ("coder", res->body);
  5301. }
  5302. TEST_F(ServerTest, DeleteMethod1) {
  5303. auto res = cli_.Get("/person/john4");
  5304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5305. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5306. Params params;
  5307. params.emplace("name", "john4");
  5308. params.emplace("note", "coder");
  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/john4");
  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("coder", res->body);
  5317. Params delete_params;
  5318. delete_params.emplace("name", "john4");
  5319. res = cli_.Delete("/person", delete_params);
  5320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5321. ASSERT_EQ(StatusCode::OK_200, res->status);
  5322. ASSERT_EQ("DELETED", res->body);
  5323. res = cli_.Get("/person/john4");
  5324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5325. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5326. }
  5327. TEST_F(ServerTest, DeleteMethod2) {
  5328. auto res = cli_.Get("/person/john5");
  5329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5330. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5331. Params params;
  5332. params.emplace("name", "john5");
  5333. params.emplace("note", "developer");
  5334. res = cli_.Post("/person", params);
  5335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5336. ASSERT_EQ(StatusCode::OK_200, res->status);
  5337. res = cli_.Get("/person/john5");
  5338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5339. ASSERT_EQ(StatusCode::OK_200, res->status);
  5340. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5341. ASSERT_EQ("developer", res->body);
  5342. Params delete_params;
  5343. delete_params.emplace("name", "john5");
  5344. Headers headers;
  5345. headers.emplace("Custom-Header", "test-value");
  5346. res = cli_.Delete("/person", headers, delete_params);
  5347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5348. ASSERT_EQ(StatusCode::OK_200, res->status);
  5349. ASSERT_EQ("DELETED", res->body);
  5350. res = cli_.Get("/person/john5");
  5351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5352. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5353. }
  5354. TEST_F(ServerTest, DeleteMethod3) {
  5355. auto res = cli_.Get("/person/john6");
  5356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5357. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5358. Params params;
  5359. params.emplace("name", "john6");
  5360. params.emplace("note", "tester");
  5361. res = cli_.Post("/person", params);
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. ASSERT_EQ(StatusCode::OK_200, res->status);
  5364. res = cli_.Get("/person/john6");
  5365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5366. ASSERT_EQ(StatusCode::OK_200, res->status);
  5367. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5368. ASSERT_EQ("tester", res->body);
  5369. Params delete_params;
  5370. delete_params.emplace("name", "john6");
  5371. Headers headers;
  5372. headers.emplace("Custom-Header", "test-value");
  5373. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5375. ASSERT_EQ(StatusCode::OK_200, res->status);
  5376. ASSERT_EQ("DELETED", res->body);
  5377. res = cli_.Get("/person/john6");
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5380. }
  5381. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5382. Params params;
  5383. params.emplace("json", JSON_DATA);
  5384. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5386. ASSERT_EQ(StatusCode::OK_200, res->status);
  5387. ASSERT_EQ(JSON_DATA, res->body);
  5388. }
  5389. TEST_F(ServerTest, PostEmptyContent) {
  5390. auto res = cli_.Post("/empty", "", "text/plain");
  5391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5392. ASSERT_EQ(StatusCode::OK_200, res->status);
  5393. ASSERT_EQ("empty", res->body);
  5394. }
  5395. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5396. auto res = cli_.Post("/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, PostPathOnly) {
  5402. auto res = cli_.Post("/path-only");
  5403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5404. ASSERT_EQ(StatusCode::OK_200, res->status);
  5405. ASSERT_EQ("path-only", res->body);
  5406. }
  5407. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5408. auto res = cli_.Post("/path-headers-only",
  5409. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5411. ASSERT_EQ(StatusCode::OK_200, res->status);
  5412. ASSERT_EQ("path-headers-only", res->body);
  5413. }
  5414. TEST_F(ServerTest, PostLarge) {
  5415. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. ASSERT_EQ(StatusCode::OK_200, res->status);
  5418. EXPECT_EQ(LARGE_DATA, res->body);
  5419. }
  5420. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5421. auto res = cli_.Put("/empty-no-content-type");
  5422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5423. ASSERT_EQ(StatusCode::OK_200, res->status);
  5424. ASSERT_EQ("empty-no-content-type", res->body);
  5425. }
  5426. TEST_F(ServerTest, GetMethodDir) {
  5427. auto res = cli_.Get("/dir/");
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. EXPECT_EQ(StatusCode::OK_200, res->status);
  5430. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5431. auto body = R"(<html>
  5432. <head>
  5433. </head>
  5434. <body>
  5435. <a href="/dir/test.html">Test</a>
  5436. <a href="/hi">hi</a>
  5437. </body>
  5438. </html>
  5439. )";
  5440. EXPECT_EQ(body, res->body);
  5441. }
  5442. TEST_F(ServerTest, GetMethodDirTest) {
  5443. auto res = cli_.Get("/dir/test.html");
  5444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5445. EXPECT_EQ(StatusCode::OK_200, res->status);
  5446. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5447. EXPECT_EQ("test.html", res->body);
  5448. }
  5449. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5450. auto res = cli_.Get("/dir/../dir/test.html");
  5451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5452. EXPECT_EQ(StatusCode::OK_200, res->status);
  5453. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5454. EXPECT_EQ("test.html", res->body);
  5455. }
  5456. TEST_F(ServerTest, GetMethodInvalidPath) {
  5457. auto res = cli_.Get("/dir/../test.html");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5460. }
  5461. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5462. auto res = cli_.Get("/../www/dir/test.html");
  5463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5465. }
  5466. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5467. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5470. }
  5471. TEST_F(ServerTest, GetMethodDirMountTest) {
  5472. auto res = cli_.Get("/mount/dir/test.html");
  5473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5474. EXPECT_EQ(StatusCode::OK_200, res->status);
  5475. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5476. EXPECT_EQ("test.html", res->body);
  5477. }
  5478. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5479. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. EXPECT_EQ(StatusCode::OK_200, res->status);
  5482. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5483. EXPECT_EQ("test.html", res->body);
  5484. }
  5485. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5486. auto res = cli_.Get("/mount/dir/../test.html");
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5489. }
  5490. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5491. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5493. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5494. }
  5495. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5496. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5498. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5499. }
  5500. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5501. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5504. }
  5505. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5506. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5508. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5509. }
  5510. TEST_F(ServerTest, PostMethod303) {
  5511. auto res = cli_.Post("/1", "body", "text/plain");
  5512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5513. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5514. EXPECT_EQ("/2", res->get_header_value("Location"));
  5515. }
  5516. TEST_F(ServerTest, PostMethod303Redirect) {
  5517. cli_.set_follow_location(true);
  5518. auto res = cli_.Post("/1", "body", "text/plain");
  5519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5520. EXPECT_EQ(StatusCode::OK_200, res->status);
  5521. EXPECT_EQ("redirected.", res->body);
  5522. EXPECT_EQ("/2", res->location);
  5523. }
  5524. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5525. auto res = cli_.Get("/dir/test.abcde");
  5526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5527. EXPECT_EQ(StatusCode::OK_200, res->status);
  5528. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5529. EXPECT_EQ("abcde", res->body);
  5530. }
  5531. TEST_F(ServerTest, StaticFileRange) {
  5532. auto res =
  5533. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5535. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5536. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5537. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5538. EXPECT_EQ(true, res->has_header("Content-Range"));
  5539. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5540. EXPECT_EQ(std::string("cd"), res->body);
  5541. }
  5542. TEST_F(ServerTest, StaticFileRanges) {
  5543. auto res = cli_.Get("/dir/test.abcde",
  5544. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5546. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5547. EXPECT_TRUE(
  5548. res->get_header_value("Content-Type")
  5549. .find(
  5550. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5551. 0);
  5552. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5553. }
  5554. TEST_F(ServerTest, StaticFileRangeHead) {
  5555. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5557. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5558. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5559. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5560. EXPECT_EQ(true, res->has_header("Content-Range"));
  5561. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5562. }
  5563. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5564. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5566. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5567. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5568. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5569. EXPECT_EQ(true, res->has_header("Content-Range"));
  5570. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5571. res->get_header_value("Content-Range"));
  5572. EXPECT_EQ("LAST\n", res->body);
  5573. }
  5574. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5575. auto res =
  5576. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5578. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5579. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5580. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5581. EXPECT_EQ(true, res->has_header("Content-Range"));
  5582. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5583. }
  5584. TEST_F(ServerTest, StaticFileBigFile) {
  5585. auto res = cli_.Get("/dir/1MB.txt");
  5586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5587. EXPECT_EQ(StatusCode::OK_200, res->status);
  5588. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5589. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5590. }
  5591. TEST_F(ServerTest, InvalidBaseDirMount) {
  5592. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5593. }
  5594. TEST_F(ServerTest, Binary) {
  5595. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5596. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5597. "application/octet-stream");
  5598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5599. ASSERT_EQ(StatusCode::OK_200, res->status);
  5600. ASSERT_EQ(4U, res->body.size());
  5601. res = cli_.Put("/binary", binary.data(), binary.size(),
  5602. "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_.Patch("/binary", binary.data(), binary.size(),
  5607. "application/octet-stream");
  5608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5609. ASSERT_EQ(StatusCode::OK_200, res->status);
  5610. ASSERT_EQ(4U, res->body.size());
  5611. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5612. "application/octet-stream");
  5613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5614. ASSERT_EQ(StatusCode::OK_200, res->status);
  5615. ASSERT_EQ(4U, res->body.size());
  5616. }
  5617. TEST_F(ServerTest, BinaryString) {
  5618. auto binary = std::string("\x00\x01\x02\x03", 4);
  5619. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5621. ASSERT_EQ(StatusCode::OK_200, res->status);
  5622. ASSERT_EQ(4U, res->body.size());
  5623. res = cli_.Put("/binary", binary, "application/octet-stream");
  5624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5625. ASSERT_EQ(StatusCode::OK_200, res->status);
  5626. ASSERT_EQ(4U, res->body.size());
  5627. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5629. ASSERT_EQ(StatusCode::OK_200, res->status);
  5630. ASSERT_EQ(4U, res->body.size());
  5631. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5633. ASSERT_EQ(StatusCode::OK_200, res->status);
  5634. ASSERT_EQ(4U, res->body.size());
  5635. }
  5636. TEST_F(ServerTest, EmptyRequest) {
  5637. auto res = cli_.Get("");
  5638. ASSERT_TRUE(!res);
  5639. EXPECT_EQ(Error::Connection, res.error());
  5640. }
  5641. TEST_F(ServerTest, LongRequest) {
  5642. std::string request;
  5643. for (size_t i = 0; i < 545; i++) {
  5644. request += "/TooLongRequest";
  5645. }
  5646. request += "OK";
  5647. auto res = cli_.Get(request.c_str());
  5648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5649. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5650. }
  5651. TEST_F(ServerTest, TooLongRequest) {
  5652. std::string request;
  5653. for (size_t i = 0; i < 546; i++) {
  5654. request += "/TooLongRequest";
  5655. }
  5656. request += "_NG";
  5657. auto start = std::chrono::high_resolution_clock::now();
  5658. cli_.set_keep_alive(true);
  5659. auto res = cli_.Get(request.c_str());
  5660. auto end = std::chrono::high_resolution_clock::now();
  5661. auto elapsed =
  5662. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5663. .count();
  5664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5665. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5666. EXPECT_LE(elapsed, 1000);
  5667. EXPECT_EQ("close", res->get_header_value("Connection"));
  5668. EXPECT_FALSE(cli_.is_socket_open());
  5669. }
  5670. TEST_F(ServerTest, AlmostTooLongRequest) {
  5671. // test for #2046 - URI length check shouldn't include other content on req
  5672. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5673. // leading /, space, HTTP/1.1)
  5674. std::string request =
  5675. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5676. auto res = cli_.Get(request.c_str());
  5677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5678. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5679. }
  5680. TEST_F(ServerTest, LongHeader) {
  5681. Request req;
  5682. req.method = "GET";
  5683. req.path = "/hi";
  5684. std::string host_and_port;
  5685. host_and_port += HOST;
  5686. host_and_port += ":";
  5687. host_and_port += std::to_string(PORT);
  5688. req.headers.emplace("Host", host_and_port.c_str());
  5689. req.headers.emplace("Accept", "*/*");
  5690. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5691. req.headers.emplace(
  5692. "Header-Name",
  5693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5721. "@@@@@@@@@@@@@@@@");
  5722. auto res = std::make_shared<Response>();
  5723. auto error = Error::Success;
  5724. auto ret = cli_.send(req, *res, error);
  5725. ASSERT_TRUE(ret);
  5726. EXPECT_EQ(StatusCode::OK_200, res->status);
  5727. }
  5728. TEST_F(ServerTest, LongQueryValue) {
  5729. auto start = std::chrono::high_resolution_clock::now();
  5730. cli_.set_keep_alive(true);
  5731. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5732. auto end = std::chrono::high_resolution_clock::now();
  5733. auto elapsed =
  5734. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5735. .count();
  5736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5737. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5738. EXPECT_LE(elapsed, 1000);
  5739. EXPECT_EQ("close", res->get_header_value("Connection"));
  5740. EXPECT_FALSE(cli_.is_socket_open());
  5741. }
  5742. TEST_F(ServerTest, TooLongQueryValue) {
  5743. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5744. ASSERT_FALSE(res);
  5745. EXPECT_EQ(Error::Read, res.error());
  5746. }
  5747. TEST_F(ServerTest, TooLongHeader) {
  5748. Request req;
  5749. req.method = "GET";
  5750. req.path = "/hi";
  5751. std::string host_and_port;
  5752. host_and_port += HOST;
  5753. host_and_port += ":";
  5754. host_and_port += std::to_string(PORT);
  5755. req.headers.emplace("Host", host_and_port.c_str());
  5756. req.headers.emplace("Accept", "*/*");
  5757. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5758. req.headers.emplace(
  5759. "Header-Name",
  5760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5788. "@@@@@@@@@@@@@@@@@");
  5789. auto res = std::make_shared<Response>();
  5790. auto error = Error::Success;
  5791. auto ret = cli_.send(req, *res, error);
  5792. ASSERT_TRUE(ret);
  5793. EXPECT_EQ(StatusCode::OK_200, res->status);
  5794. }
  5795. TEST_F(ServerTest, HeaderCountAtLimit) {
  5796. // Test with headers just under the 100 limit
  5797. httplib::Headers headers;
  5798. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5799. // This should keep us just under the 100 header limit
  5800. for (int i = 0; i < 95; i++) {
  5801. std::string name = "X-Test-Header-" + std::to_string(i);
  5802. std::string value = "value" + std::to_string(i);
  5803. headers.emplace(name, value);
  5804. }
  5805. // This should work fine as we're under the limit
  5806. auto res = cli_.Get("/hi", headers);
  5807. EXPECT_TRUE(res);
  5808. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5809. }
  5810. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5811. // Test with many headers to exceed the 100 limit
  5812. httplib::Headers headers;
  5813. // Add 150 headers to definitely exceed the 100 limit
  5814. for (int i = 0; i < 150; i++) {
  5815. std::string name = "X-Test-Header-" + std::to_string(i);
  5816. std::string value = "value" + std::to_string(i);
  5817. headers.emplace(name, value);
  5818. }
  5819. // This should fail due to exceeding header count limit
  5820. cli_.set_keep_alive(true);
  5821. auto res = cli_.Get("/hi", headers);
  5822. // The server should respond with 400 Bad Request
  5823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5824. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5825. EXPECT_EQ("close", res->get_header_value("Connection"));
  5826. EXPECT_FALSE(cli_.is_socket_open());
  5827. }
  5828. TEST_F(ServerTest, PercentEncoding) {
  5829. auto res = cli_.Get("/e%6edwith%");
  5830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5831. EXPECT_EQ(StatusCode::OK_200, res->status);
  5832. }
  5833. TEST_F(ServerTest, PercentEncodingUnicode) {
  5834. auto res = cli_.Get("/e%u006edwith%");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. EXPECT_EQ(StatusCode::OK_200, res->status);
  5837. }
  5838. TEST_F(ServerTest, InvalidPercentEncoding) {
  5839. auto res = cli_.Get("/%endwith%");
  5840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5841. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5842. }
  5843. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5844. auto res = cli_.Get("/%uendwith%");
  5845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5846. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5847. }
  5848. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5849. auto res = cli_.Get("/hello?aaa=bbb%");
  5850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5851. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5852. }
  5853. TEST_F(ServerTest, PlusSignEncoding) {
  5854. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5856. EXPECT_EQ(StatusCode::OK_200, res->status);
  5857. EXPECT_EQ("a +b", res->body);
  5858. }
  5859. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5860. // This test simulates a potential DoS attack using many headers
  5861. // to verify our security fix prevents memory exhaustion
  5862. httplib::Headers attack_headers;
  5863. // Attempt to add many headers like an attacker would (200 headers to far
  5864. // exceed limit)
  5865. for (int i = 0; i < 200; i++) {
  5866. std::string name = "X-Attack-Header-" + std::to_string(i);
  5867. std::string value = "attack_payload_" + std::to_string(i);
  5868. attack_headers.emplace(name, value);
  5869. }
  5870. // Try to POST with excessive headers
  5871. cli_.set_keep_alive(true);
  5872. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5873. // Should either fail or return 400 Bad Request due to security limit
  5874. if (res) {
  5875. // If we get a response, it should be 400 Bad Request
  5876. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5877. EXPECT_EQ("close", res->get_header_value("Connection"));
  5878. }
  5879. EXPECT_FALSE(cli_.is_socket_open());
  5880. }
  5881. TEST_F(ServerTest, MultipartFormData) {
  5882. UploadFormDataItems items = {
  5883. {"text1", "text default", "", ""},
  5884. {"text2", "aωb", "", ""},
  5885. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5886. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5887. {"file3", "", "", "application/octet-stream"},
  5888. {"file4", "", "", " application/json tmp-string "}};
  5889. auto res = cli_.Post("/multipart", items);
  5890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5891. EXPECT_EQ(StatusCode::OK_200, res->status);
  5892. }
  5893. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5894. UploadFormDataItems items = {
  5895. {"text", "default text", "", ""},
  5896. {"multi_text1", "aaaaa", "", ""},
  5897. {"multi_text1", "bbbbb", "", ""},
  5898. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5899. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5900. "application/json"},
  5901. };
  5902. auto res = cli_.Post("/multipart/multi_file_values", items);
  5903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5904. EXPECT_EQ(StatusCode::OK_200, res->status);
  5905. }
  5906. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5907. auto res = cli_.Get("/hi");
  5908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5909. EXPECT_EQ(StatusCode::OK_200, res->status);
  5910. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5911. EXPECT_EQ("Hello World!", res->body);
  5912. }
  5913. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5914. Request req;
  5915. req.method = "POST";
  5916. req.path = "/chunked";
  5917. std::string host_and_port;
  5918. host_and_port += HOST;
  5919. host_and_port += ":";
  5920. host_and_port += std::to_string(PORT);
  5921. req.headers.emplace("Host", host_and_port.c_str());
  5922. req.headers.emplace("Accept", "*/*");
  5923. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5924. req.headers.emplace("Content-Type", "text/plain");
  5925. req.headers.emplace("Content-Length", "0");
  5926. req.headers.emplace(
  5927. "Transfer-Encoding",
  5928. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5929. // Client does not chunk, so make a chunked body manually.
  5930. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5931. auto res = std::make_shared<Response>();
  5932. auto error = Error::Success;
  5933. auto ret = cli_.send(req, *res, error);
  5934. ASSERT_TRUE(ret);
  5935. EXPECT_EQ(StatusCode::OK_200, res->status);
  5936. }
  5937. template <typename ClientT>
  5938. static void expect_chunked_body_status(ClientT &cli, const char *body,
  5939. int expected_status) {
  5940. Request req;
  5941. req.method = "POST";
  5942. req.path = "/chunked";
  5943. std::string host_and_port;
  5944. host_and_port += HOST;
  5945. host_and_port += ":";
  5946. host_and_port += std::to_string(PORT);
  5947. req.headers.emplace("Host", host_and_port.c_str());
  5948. req.headers.emplace("Content-Length", "0");
  5949. req.headers.emplace("Transfer-Encoding", "chunked");
  5950. req.body = body;
  5951. auto res = std::make_shared<Response>();
  5952. auto error = Error::Success;
  5953. ASSERT_TRUE(cli.send(req, *res, error));
  5954. EXPECT_EQ(expected_status, res->status);
  5955. }
  5956. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5957. // rather than treat them as valid lengths.
  5958. template <typename ClientT>
  5959. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5960. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  5961. }
  5962. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5963. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5964. }
  5965. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5966. expect_chunked_body_rejected(
  5967. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5968. }
  5969. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  5970. // chunk-size line carries no CR, LF or other control character ahead of its
  5971. // terminator. Such a line must be refused rather than read as extension text.
  5972. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  5973. expect_chunked_body_rejected(
  5974. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5975. }
  5976. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  5977. expect_chunked_body_rejected(
  5978. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5979. }
  5980. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  5981. expect_chunked_body_rejected(
  5982. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5983. }
  5984. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  5985. // The literal stays split: a hex escape consumes every hex digit that
  5986. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  5987. expect_chunked_body_rejected(
  5988. cli_, "4;a\x01"
  5989. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5990. }
  5991. TEST_F(ServerTest, AcceptsChunkExtension) {
  5992. expect_chunked_body_status(cli_,
  5993. "4;name=value\r\ndech\r\n"
  5994. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  5995. "0;last\r\n\r\n",
  5996. StatusCode::OK_200);
  5997. }
  5998. TEST_F(ServerTest, GetStreamed2) {
  5999. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6002. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6003. EXPECT_EQ(true, res->has_header("Content-Range"));
  6004. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6005. EXPECT_EQ(std::string("ab"), res->body);
  6006. }
  6007. TEST_F(ServerTest, GetStreamed) {
  6008. auto res = cli_.Get("/streamed");
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. EXPECT_EQ(StatusCode::OK_200, res->status);
  6011. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6012. EXPECT_EQ(std::string("aaabbb"), res->body);
  6013. }
  6014. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6015. auto res = cli_.Get("/streamed-without-length",
  6016. Headers{make_range_header({{0, -1}})});
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. EXPECT_EQ(false, res->has_header("Content-Length"));
  6020. EXPECT_EQ(false, res->has_header("Content-Range"));
  6021. EXPECT_EQ(std::string("abcdefg"), res->body);
  6022. }
  6023. TEST_F(ServerTest, GetStreamedWithRange1) {
  6024. auto res =
  6025. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6028. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6029. EXPECT_EQ(true, res->has_header("Content-Range"));
  6030. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6031. EXPECT_EQ(std::string("def"), res->body);
  6032. }
  6033. TEST_F(ServerTest, GetStreamedWithRange2) {
  6034. auto res =
  6035. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6037. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6038. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6039. EXPECT_EQ(true, res->has_header("Content-Range"));
  6040. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6041. EXPECT_EQ(std::string("bcdefg"), res->body);
  6042. }
  6043. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6044. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6047. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6048. EXPECT_EQ(true, res->has_header("Content-Range"));
  6049. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6050. EXPECT_EQ(std::string("efg"), res->body);
  6051. }
  6052. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6053. auto res =
  6054. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  6055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6056. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6057. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6058. EXPECT_EQ(false, res->has_header("Content-Range"));
  6059. EXPECT_EQ(0U, res->body.size());
  6060. }
  6061. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6062. // Only a 206 is served as a partial representation. Under any other status
  6063. // `apply_ranges()` reported the full content length, so the body must match
  6064. // that header, and the content provider must never be asked for an offset
  6065. // outside the representation.
  6066. auto check = [&](int status, const char *range) {
  6067. auto path =
  6068. std::string("/streamed-with-range?status=") + std::to_string(status);
  6069. auto ctx = path + " Range: " + range;
  6070. auto res = cli_.Get(path, Headers{{"Range", range}});
  6071. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6072. EXPECT_EQ(status, res->status) << ctx;
  6073. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6074. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6075. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6076. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6077. };
  6078. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6079. check(403, "bytes=3-5");
  6080. // The offset is far past the representation.
  6081. check(403, "bytes=100000-100200");
  6082. // `first_pos` is still -1 here, and the bounds asserts in
  6083. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6084. check(403, "bytes=-3");
  6085. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6086. // multipart branch would have written one that is empty.
  6087. check(403, "bytes=1-2, 4-5");
  6088. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6089. // covers the whole representation.
  6090. check(200, "bytes=3-5");
  6091. check(200, "bytes=1-2, 4-5");
  6092. }
  6093. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6094. auto res =
  6095. cli_.Get("/streamed-with-range",
  6096. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6097. "92233720368547758079223372036854775807"}});
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6100. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6101. EXPECT_EQ(false, res->has_header("Content-Range"));
  6102. EXPECT_EQ(0U, res->body.size());
  6103. }
  6104. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6105. auto res = cli_.Get(
  6106. "/with-range",
  6107. Headers{{"Range",
  6108. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6109. {"Accept-Encoding", ""}});
  6110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6111. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6112. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6113. EXPECT_EQ(true, res->has_header("Content-Range"));
  6114. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6115. EXPECT_EQ(std::string("abcdefg"), res->body);
  6116. }
  6117. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6118. auto res = cli_.Get("/with-range", Headers{
  6119. {"Range", "bytes=0-"},
  6120. {"Accept-Encoding", ""},
  6121. });
  6122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6123. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6124. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6125. EXPECT_EQ(true, res->has_header("Content-Range"));
  6126. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6127. EXPECT_EQ(std::string("abcdefg"), res->body);
  6128. }
  6129. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6130. auto res = cli_.Get("/streamed-with-range",
  6131. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6133. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6134. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6135. EXPECT_EQ(false, res->has_header("Content-Range"));
  6136. EXPECT_EQ(267U, res->body.size());
  6137. // Check that both range contents are present
  6138. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6139. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6140. // Check that Content-Range headers are present for both ranges
  6141. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6142. std::string::npos);
  6143. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6144. std::string::npos);
  6145. }
  6146. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6147. Ranges ranges;
  6148. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6149. ranges.emplace_back(0, -1);
  6150. }
  6151. auto res = cli_.Get("/streamed-with-range?error",
  6152. Headers{{make_range_header(ranges)}});
  6153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6154. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6155. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6156. EXPECT_EQ(false, res->has_header("Content-Range"));
  6157. EXPECT_EQ(0U, res->body.size());
  6158. }
  6159. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6160. auto res = cli_.Get("/streamed-with-range",
  6161. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6164. EXPECT_EQ(5U, res->body.size());
  6165. // Check that overlapping ranges are coalesced into a single range
  6166. EXPECT_EQ("bcdef", res->body);
  6167. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6168. // Should be single range, not multipart
  6169. EXPECT_TRUE(res->has_header("Content-Range"));
  6170. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6171. }
  6172. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6173. auto res = cli_.Get("/streamed-with-range",
  6174. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6177. EXPECT_EQ(268U, res->body.size());
  6178. // Check that both range contents are present
  6179. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6180. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6181. // Check that Content-Range headers are present for both ranges
  6182. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6183. std::string::npos);
  6184. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6185. std::string::npos);
  6186. }
  6187. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6188. auto res = cli_.Get("/streamed-with-range",
  6189. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6192. EXPECT_EQ(269U, res->body.size());
  6193. // Check that both duplicate range contents are present
  6194. size_t first_abc = res->body.find("abc\r\n");
  6195. EXPECT_TRUE(first_abc != std::string::npos);
  6196. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6197. EXPECT_TRUE(second_abc != std::string::npos);
  6198. // Check that Content-Range headers are present for both ranges
  6199. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6200. EXPECT_TRUE(first_range != std::string::npos);
  6201. size_t second_range =
  6202. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6203. EXPECT_TRUE(second_range != std::string::npos);
  6204. }
  6205. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6206. auto res =
  6207. cli_.Get("/streamed-with-range?error",
  6208. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6210. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6211. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6212. EXPECT_EQ(false, res->has_header("Content-Range"));
  6213. EXPECT_EQ(0U, res->body.size());
  6214. }
  6215. TEST_F(ServerTest, GetStreamedEndless) {
  6216. uint64_t offset = 0;
  6217. auto res = cli_.Get("/streamed-cancel",
  6218. [&](const char * /*data*/, uint64_t data_length) {
  6219. if (offset < 100) {
  6220. offset += data_length;
  6221. return true;
  6222. }
  6223. return false;
  6224. });
  6225. ASSERT_TRUE(!res);
  6226. EXPECT_EQ(Error::Canceled, res.error());
  6227. }
  6228. TEST_F(ServerTest, ClientStop) {
  6229. std::atomic_size_t count{4};
  6230. std::vector<std::thread> threads;
  6231. for (auto i = count.load(); i != 0; --i) {
  6232. threads.emplace_back([&]() {
  6233. auto res = cli_.Get("/streamed-cancel",
  6234. [&](const char *, uint64_t) { return true; });
  6235. --count;
  6236. ASSERT_TRUE(!res);
  6237. EXPECT_TRUE(res.error() == Error::Canceled ||
  6238. res.error() == Error::Read || res.error() == Error::Write);
  6239. });
  6240. }
  6241. std::this_thread::sleep_for(std::chrono::seconds(2));
  6242. while (count != 0) {
  6243. cli_.stop();
  6244. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6245. }
  6246. for (auto &t : threads) {
  6247. t.join();
  6248. }
  6249. }
  6250. TEST_F(ServerTest, GetWithRange1) {
  6251. auto res = cli_.Get("/with-range", Headers{
  6252. make_range_header({{3, 5}}),
  6253. {"Accept-Encoding", ""},
  6254. });
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6257. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6258. EXPECT_EQ(true, res->has_header("Content-Range"));
  6259. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6260. EXPECT_EQ(std::string("def"), res->body);
  6261. }
  6262. TEST_F(ServerTest, GetWithRange2) {
  6263. auto res = cli_.Get("/with-range", Headers{
  6264. make_range_header({{1, -1}}),
  6265. {"Accept-Encoding", ""},
  6266. });
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6269. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6270. EXPECT_EQ(true, res->has_header("Content-Range"));
  6271. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6272. EXPECT_EQ(std::string("bcdefg"), res->body);
  6273. }
  6274. TEST_F(ServerTest, GetWithRange3) {
  6275. auto res = cli_.Get("/with-range", Headers{
  6276. make_range_header({{0, 0}}),
  6277. {"Accept-Encoding", ""},
  6278. });
  6279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6281. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6282. EXPECT_EQ(true, res->has_header("Content-Range"));
  6283. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6284. EXPECT_EQ(std::string("a"), res->body);
  6285. }
  6286. TEST_F(ServerTest, GetWithRange4) {
  6287. auto res = cli_.Get("/with-range", Headers{
  6288. make_range_header({{-1, 2}}),
  6289. {"Accept-Encoding", ""},
  6290. });
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6293. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6294. EXPECT_EQ(true, res->has_header("Content-Range"));
  6295. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6296. EXPECT_EQ(std::string("fg"), res->body);
  6297. }
  6298. TEST_F(ServerTest, GetWithRange5) {
  6299. auto res = cli_.Get("/with-range", Headers{
  6300. make_range_header({{0, 5}}),
  6301. {"Accept-Encoding", ""},
  6302. });
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6305. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6306. EXPECT_EQ(true, res->has_header("Content-Range"));
  6307. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6308. EXPECT_EQ(std::string("abcdef"), res->body);
  6309. }
  6310. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6311. auto res =
  6312. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6314. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6315. }
  6316. TEST_F(ServerTest, GetWithRangeMultipart) {
  6317. auto res =
  6318. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6320. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6321. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6322. EXPECT_EQ(false, res->has_header("Content-Range"));
  6323. EXPECT_EQ(267U, res->body.size());
  6324. }
  6325. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6326. auto res = cli_.Get("/with-range",
  6327. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6329. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6330. }
  6331. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6332. auto res = cli_.Get("/with-range-customized-response",
  6333. Headers{{make_range_header({{1, 2}})}});
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6336. EXPECT_EQ(true, res->has_header("Content-Length"));
  6337. EXPECT_EQ(false, res->has_header("Content-Range"));
  6338. EXPECT_EQ(JSON_DATA, res->body);
  6339. }
  6340. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6341. auto res = cli_.Get("/with-range-customized-response",
  6342. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6344. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6345. EXPECT_EQ(true, res->has_header("Content-Length"));
  6346. EXPECT_EQ(false, res->has_header("Content-Range"));
  6347. EXPECT_EQ(JSON_DATA, res->body);
  6348. }
  6349. TEST_F(ServerTest, Issue1772) {
  6350. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6352. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6353. }
  6354. TEST_F(ServerTest, Issue609) {
  6355. auto res = cli_.Delete("/issue609");
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::OK_200, res->status);
  6358. EXPECT_EQ(std::string("ok"), res->body);
  6359. }
  6360. TEST_F(ServerTest, GetStreamedChunked) {
  6361. auto res = cli_.Get("/streamed-chunked");
  6362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6363. EXPECT_EQ(StatusCode::OK_200, res->status);
  6364. EXPECT_EQ(std::string("123456789"), res->body);
  6365. }
  6366. TEST_F(ServerTest, GetStreamedChunked2) {
  6367. auto res = cli_.Get("/streamed-chunked2");
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::OK_200, res->status);
  6370. EXPECT_EQ(std::string("123456789"), res->body);
  6371. }
  6372. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6373. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6375. EXPECT_EQ(StatusCode::OK_200, res->status);
  6376. EXPECT_EQ(std::string("123456789"), res->body);
  6377. EXPECT_TRUE(res->has_header("Trailer"));
  6378. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6379. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6380. // Trailers are now stored separately from headers (security fix)
  6381. EXPECT_EQ(2U, res->trailers.size());
  6382. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6383. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6384. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6385. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6386. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6387. // Verify trailers are NOT in headers (security verification)
  6388. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6389. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6390. }
  6391. TEST_F(ServerTest, LargeChunkedPost) {
  6392. Request req;
  6393. req.method = "POST";
  6394. req.path = "/large-chunked";
  6395. std::string host_and_port;
  6396. host_and_port += HOST;
  6397. host_and_port += ":";
  6398. host_and_port += std::to_string(PORT);
  6399. req.headers.emplace("Host", host_and_port.c_str());
  6400. req.headers.emplace("Accept", "*/*");
  6401. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6402. req.headers.emplace("Content-Type", "text/plain");
  6403. req.headers.emplace("Content-Length", "0");
  6404. req.headers.emplace("Transfer-Encoding", "chunked");
  6405. std::string long_string(30 * 1024u, 'a');
  6406. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6407. // Attempt to make a large enough post to exceed OS buffers, to test that
  6408. // the server handles short reads if the full chunk data isn't available.
  6409. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6410. auto res = std::make_shared<Response>();
  6411. auto error = Error::Success;
  6412. auto ret = cli_.send(req, *res, error);
  6413. ASSERT_TRUE(ret);
  6414. EXPECT_EQ(StatusCode::OK_200, res->status);
  6415. }
  6416. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6417. auto res = cli_.Get("/remote_addr");
  6418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6419. EXPECT_EQ(StatusCode::OK_200, res->status);
  6420. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6421. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6422. }
  6423. TEST_F(ServerTest, GetMethodLocalAddr) {
  6424. auto res = cli_.Get("/local_addr");
  6425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6426. EXPECT_EQ(StatusCode::OK_200, res->status);
  6427. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6428. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6429. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6430. }
  6431. TEST_F(ServerTest, HTTPResponseSplitting) {
  6432. auto res = cli_.Get("/http_response_splitting");
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::OK_200, res->status);
  6435. }
  6436. TEST_F(ServerTest, SlowRequest) {
  6437. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6438. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6439. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6440. }
  6441. #if 0
  6442. TEST_F(ServerTest, SlowPost) {
  6443. char buffer[64 * 1024];
  6444. memset(buffer, 0x42, sizeof(buffer));
  6445. auto res = cli_.Post(
  6446. "/slowpost", 64 * 1024 * 1024,
  6447. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6448. auto ret = sink.write(buffer, sizeof(buffer));
  6449. EXPECT_TRUE(ret);
  6450. return true;
  6451. },
  6452. "text/plain");
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. }
  6456. TEST_F(ServerTest, SlowPostFail) {
  6457. char buffer[64 * 1024];
  6458. memset(buffer, 0x42, sizeof(buffer));
  6459. cli_.set_write_timeout(std::chrono::seconds(0));
  6460. auto res = cli_.Post(
  6461. "/slowpost", 64 * 1024 * 1024,
  6462. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6463. sink.write(buffer, sizeof(buffer));
  6464. return true;
  6465. },
  6466. "text/plain");
  6467. ASSERT_TRUE(!res);
  6468. EXPECT_EQ(Error::Write, res.error());
  6469. }
  6470. #endif
  6471. TEST_F(ServerTest, Put) {
  6472. auto res = cli_.Put("/put", "PUT", "text/plain");
  6473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6474. EXPECT_EQ(StatusCode::OK_200, res->status);
  6475. EXPECT_EQ("PUT", res->body);
  6476. }
  6477. TEST_F(ServerTest, PutWithContentProvider) {
  6478. auto res = cli_.Put(
  6479. "/put", 3,
  6480. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6481. sink.os << "PUT";
  6482. return true;
  6483. },
  6484. "text/plain");
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. EXPECT_EQ(StatusCode::OK_200, res->status);
  6487. EXPECT_EQ("PUT", res->body);
  6488. }
  6489. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6490. auto res = cli_.Post(
  6491. "/post", 42,
  6492. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6493. return false;
  6494. },
  6495. "text/plain");
  6496. ASSERT_TRUE(!res);
  6497. EXPECT_EQ(Error::Canceled, res.error());
  6498. }
  6499. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6500. auto res = cli_.Put(
  6501. "/put",
  6502. [](size_t /*offset*/, DataSink &sink) {
  6503. sink.os << "PUT";
  6504. sink.done();
  6505. return true;
  6506. },
  6507. "text/plain");
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. EXPECT_EQ(StatusCode::OK_200, res->status);
  6510. EXPECT_EQ("PUT", res->body);
  6511. }
  6512. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6513. auto res = cli_.Post(
  6514. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6515. "text/plain");
  6516. ASSERT_TRUE(!res);
  6517. EXPECT_EQ(Error::Canceled, res.error());
  6518. }
  6519. TEST_F(ServerTest, PostLoopBack) {
  6520. std::string body;
  6521. auto res = cli_.Post(
  6522. "/post-loopback", 9,
  6523. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6524. EXPECT_EQ(9u, length);
  6525. sink.write("123", 3);
  6526. sink.write("456", 3);
  6527. sink.write("789", 3);
  6528. return true;
  6529. },
  6530. "text/plain",
  6531. [&body](const char *data, size_t data_length) {
  6532. body.append(data, data_length);
  6533. return true;
  6534. });
  6535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6536. EXPECT_EQ(StatusCode::OK_200, res->status);
  6537. EXPECT_EQ("123456789", body);
  6538. }
  6539. TEST_F(ServerTest, PutLoopBack) {
  6540. std::string body;
  6541. auto res = cli_.Put(
  6542. "/put-loopback", 9,
  6543. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6544. EXPECT_EQ(9u, length);
  6545. sink.write("123", 3);
  6546. sink.write("456", 3);
  6547. sink.write("789", 3);
  6548. return true;
  6549. },
  6550. "text/plain",
  6551. [&body](const char *data, size_t data_length) {
  6552. body.append(data, data_length);
  6553. return true;
  6554. });
  6555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6556. EXPECT_EQ(StatusCode::OK_200, res->status);
  6557. EXPECT_EQ("123456789", body);
  6558. }
  6559. TEST_F(ServerTest, PatchLoopBack) {
  6560. std::string body;
  6561. auto res = cli_.Patch(
  6562. "/patch-loopback", 9,
  6563. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6564. EXPECT_EQ(9u, length);
  6565. sink.write("123", 3);
  6566. sink.write("456", 3);
  6567. sink.write("789", 3);
  6568. return true;
  6569. },
  6570. "text/plain",
  6571. [&body](const char *data, size_t data_length) {
  6572. body.append(data, data_length);
  6573. return true;
  6574. });
  6575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6576. EXPECT_EQ(StatusCode::OK_200, res->status);
  6577. EXPECT_EQ("123456789", body);
  6578. }
  6579. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6580. std::string body;
  6581. auto res = cli_.Post(
  6582. "/post-loopback",
  6583. [](size_t /*offset*/, DataSink &sink) {
  6584. sink.write("123", 3);
  6585. sink.write("456", 3);
  6586. sink.write("789", 3);
  6587. sink.done();
  6588. return true;
  6589. },
  6590. "text/plain",
  6591. [&body](const char *data, size_t data_length) {
  6592. body.append(data, data_length);
  6593. return true;
  6594. });
  6595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6596. EXPECT_EQ(StatusCode::OK_200, res->status);
  6597. EXPECT_EQ("123456789", body);
  6598. }
  6599. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6600. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6601. cli_.set_compress(true);
  6602. auto res = cli_.Put(
  6603. "/put", 3,
  6604. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6605. sink.os << "PUT";
  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, PostWithContentProviderWithGzipAbort) {
  6614. cli_.set_compress(true);
  6615. auto res = cli_.Post(
  6616. "/post", 42,
  6617. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6618. return false;
  6619. },
  6620. "text/plain");
  6621. ASSERT_TRUE(!res);
  6622. EXPECT_EQ(Error::Canceled, res.error());
  6623. }
  6624. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6625. cli_.set_compress(true);
  6626. auto res = cli_.Put(
  6627. "/put",
  6628. [](size_t /*offset*/, DataSink &sink) {
  6629. sink.os << "PUT";
  6630. sink.done();
  6631. return true;
  6632. },
  6633. "text/plain");
  6634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6635. EXPECT_EQ(StatusCode::OK_200, res->status);
  6636. EXPECT_EQ("PUT", res->body);
  6637. }
  6638. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6639. cli_.set_compress(true);
  6640. auto res = cli_.Post(
  6641. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6642. "text/plain");
  6643. ASSERT_TRUE(!res);
  6644. EXPECT_EQ(Error::Canceled, res.error());
  6645. }
  6646. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6647. cli_.set_compress(true);
  6648. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6650. EXPECT_EQ(StatusCode::OK_200, res->status);
  6651. EXPECT_EQ(LARGE_DATA, res->body);
  6652. }
  6653. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6654. #ifdef CPPHTTPLIB_SSL_ENABLED
  6655. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6656. Client cli(s.c_str());
  6657. cli.enable_server_certificate_verification(false);
  6658. #else
  6659. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6660. Client cli(s.c_str());
  6661. #endif
  6662. cli.set_compress(true);
  6663. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6665. EXPECT_EQ(StatusCode::OK_200, res->status);
  6666. EXPECT_EQ(LARGE_DATA, res->body);
  6667. // The compressed size should be less than a 10th of the original. May vary
  6668. // depending on the zlib library.
  6669. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6670. static_cast<uint64_t>(10 * 1024 * 1024));
  6671. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6672. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6673. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6674. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6675. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6676. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6677. #endif
  6678. }
  6679. TEST_F(ServerTest, PutContentWithDeflate) {
  6680. cli_.set_compress(false);
  6681. Headers headers;
  6682. headers.emplace("Content-Encoding", "deflate");
  6683. // PUT in deflate format:
  6684. auto res = cli_.Put("/put", headers,
  6685. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6687. EXPECT_EQ(StatusCode::OK_200, res->status);
  6688. EXPECT_EQ("PUT", res->body);
  6689. }
  6690. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6691. Headers headers;
  6692. headers.emplace("Accept-Encoding", "gzip, deflate");
  6693. auto res = cli_.Get("/streamed-chunked", headers);
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. EXPECT_EQ(StatusCode::OK_200, res->status);
  6696. EXPECT_EQ(std::string("123456789"), res->body);
  6697. }
  6698. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6699. Headers headers;
  6700. headers.emplace("Accept-Encoding", "gzip, deflate");
  6701. auto res = cli_.Get("/streamed-chunked2", headers);
  6702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6703. EXPECT_EQ(StatusCode::OK_200, res->status);
  6704. EXPECT_EQ(std::string("123456789"), res->body);
  6705. }
  6706. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6707. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::OK_200, res->status);
  6710. }
  6711. TEST(GzipDecompressor, ChunkedDecompression) {
  6712. std::string data;
  6713. for (size_t i = 0; i < 32 * 1024; ++i) {
  6714. data.push_back(static_cast<char>('a' + i % 26));
  6715. }
  6716. std::string compressed_data;
  6717. {
  6718. httplib::detail::gzip_compressor compressor;
  6719. bool result = compressor.compress(
  6720. data.data(), data.size(),
  6721. /*last=*/true,
  6722. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6723. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6724. compressed_data_size);
  6725. return true;
  6726. });
  6727. ASSERT_TRUE(result);
  6728. }
  6729. std::string decompressed_data;
  6730. {
  6731. httplib::detail::gzip_decompressor decompressor;
  6732. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6733. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6734. size_t chunk_size = 130;
  6735. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6736. chunk_begin += chunk_size) {
  6737. size_t current_chunk_size =
  6738. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6739. bool result = decompressor.decompress(
  6740. compressed_data.data() + chunk_begin, current_chunk_size,
  6741. [&](const char *decompressed_data_chunk,
  6742. size_t decompressed_data_chunk_size) {
  6743. decompressed_data.insert(decompressed_data.size(),
  6744. decompressed_data_chunk,
  6745. decompressed_data_chunk_size);
  6746. return true;
  6747. });
  6748. ASSERT_TRUE(result);
  6749. }
  6750. }
  6751. ASSERT_EQ(data, decompressed_data);
  6752. }
  6753. TEST(GzipDecompressor, DeflateDecompression) {
  6754. std::string original_text = "Raw deflate without gzip";
  6755. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6756. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6757. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6758. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6759. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6760. std::string decompressed_data;
  6761. {
  6762. httplib::detail::gzip_decompressor decompressor;
  6763. bool result = decompressor.decompress(
  6764. compressed_data.data(), compressed_data.size(),
  6765. [&](const char *decompressed_data_chunk,
  6766. size_t decompressed_data_chunk_size) {
  6767. decompressed_data.insert(decompressed_data.size(),
  6768. decompressed_data_chunk,
  6769. decompressed_data_chunk_size);
  6770. return true;
  6771. });
  6772. ASSERT_TRUE(result);
  6773. }
  6774. ASSERT_EQ(original_text, decompressed_data);
  6775. }
  6776. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6777. std::string original_text = "Raw deflate without gzip";
  6778. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6779. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6780. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6781. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6782. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6783. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6784. std::string decompressed_data;
  6785. {
  6786. httplib::detail::gzip_decompressor decompressor;
  6787. bool result = decompressor.decompress(
  6788. compressed_data.data(), compressed_data.size(),
  6789. [&](const char *decompressed_data_chunk,
  6790. size_t decompressed_data_chunk_size) {
  6791. decompressed_data.insert(decompressed_data.size(),
  6792. decompressed_data_chunk,
  6793. decompressed_data_chunk_size);
  6794. return true;
  6795. });
  6796. ASSERT_TRUE(result);
  6797. }
  6798. ASSERT_EQ(original_text, decompressed_data);
  6799. }
  6800. #endif
  6801. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6802. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6803. Headers headers;
  6804. headers.emplace("Accept-Encoding", "br");
  6805. auto res = cli_.Get("/streamed-chunked", headers);
  6806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. EXPECT_EQ(std::string("123456789"), res->body);
  6809. }
  6810. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6811. Headers headers;
  6812. headers.emplace("Accept-Encoding", "br");
  6813. auto res = cli_.Get("/streamed-chunked2", headers);
  6814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6815. EXPECT_EQ(StatusCode::OK_200, res->status);
  6816. EXPECT_EQ(std::string("123456789"), res->body);
  6817. }
  6818. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6819. cli_.set_compress(true);
  6820. auto res = cli_.Put(
  6821. "/put", 3,
  6822. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6823. sink.os << "PUT";
  6824. return true;
  6825. },
  6826. "text/plain");
  6827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6828. EXPECT_EQ(StatusCode::OK_200, res->status);
  6829. EXPECT_EQ("PUT", res->body);
  6830. }
  6831. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6832. cli_.set_compress(true);
  6833. auto res = cli_.Put(
  6834. "/put",
  6835. [](size_t /*offset*/, DataSink &sink) {
  6836. sink.os << "PUT";
  6837. sink.done();
  6838. return true;
  6839. },
  6840. "text/plain");
  6841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6842. EXPECT_EQ(StatusCode::OK_200, res->status);
  6843. EXPECT_EQ("PUT", res->body);
  6844. }
  6845. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6846. cli_.set_compress(true);
  6847. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::OK_200, res->status);
  6850. EXPECT_EQ(LARGE_DATA, res->body);
  6851. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6852. }
  6853. #endif
  6854. TEST_F(ServerTest, Patch) {
  6855. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. EXPECT_EQ(StatusCode::OK_200, res->status);
  6858. EXPECT_EQ("PATCH", res->body);
  6859. }
  6860. TEST_F(ServerTest, Delete) {
  6861. auto res = cli_.Delete("/delete");
  6862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6863. EXPECT_EQ(StatusCode::OK_200, res->status);
  6864. EXPECT_EQ("DELETE", res->body);
  6865. }
  6866. TEST_F(ServerTest, DeleteContentReceiver) {
  6867. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. EXPECT_EQ("content", res->body);
  6871. }
  6872. TEST_F(ServerTest, Options) {
  6873. auto res = cli_.Options("*");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6877. EXPECT_TRUE(res->body.empty());
  6878. }
  6879. TEST_F(ServerTest, URL) {
  6880. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ(StatusCode::OK_200, res->status);
  6883. }
  6884. TEST_F(ServerTest, ArrayParam) {
  6885. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6887. EXPECT_EQ(StatusCode::OK_200, res->status);
  6888. }
  6889. TEST_F(ServerTest, ArrayParamValues) {
  6890. auto res =
  6891. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6893. EXPECT_EQ(StatusCode::OK_200, res->status);
  6894. }
  6895. TEST_F(ServerTest, NoMultipleHeaders) {
  6896. Headers headers = {{"Content-Length", "5"}};
  6897. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6898. "text/plain");
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ(StatusCode::OK_200, res->status);
  6901. }
  6902. TEST_F(ServerTest, PostContentReceiver) {
  6903. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6905. ASSERT_EQ(StatusCode::OK_200, res->status);
  6906. ASSERT_EQ("content", res->body);
  6907. }
  6908. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6909. UploadFormDataItems items = {
  6910. {"text1", "text default", "", ""},
  6911. {"text2", "aωb", "", ""},
  6912. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6913. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6914. {"file3", "", "", "application/octet-stream"},
  6915. };
  6916. auto res = cli_.Post("/content_receiver", items);
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::OK_200, res->status);
  6919. }
  6920. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6921. UploadFormDataItems items = {
  6922. {"text1", "text default", "", ""},
  6923. {"text2", "aωb", "", ""},
  6924. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6925. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6926. {"file3", "", "", "application/octet-stream"},
  6927. };
  6928. auto boundary = std::string("+++++");
  6929. std::string body;
  6930. for (const auto &item : items) {
  6931. body += "--" + boundary + "\r\n";
  6932. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6933. if (!item.filename.empty()) {
  6934. body += "; filename=\"" + item.filename + "\"";
  6935. }
  6936. body += "\r\n";
  6937. if (!item.content_type.empty()) {
  6938. body += "Content-Type: " + item.content_type + "\r\n";
  6939. }
  6940. body += "\r\n";
  6941. body += item.content + "\r\n";
  6942. }
  6943. body += "--" + boundary + "--\r\n";
  6944. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6945. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::OK_200, res->status);
  6948. }
  6949. TEST(MultipartFormDataTest, FieldEscaping) {
  6950. Server svr;
  6951. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6952. const ContentReader &content_reader) {
  6953. ASSERT_TRUE(req.is_multipart_form_data());
  6954. std::vector<FormData> received;
  6955. content_reader(
  6956. [&](const FormData &file) {
  6957. received.push_back(file);
  6958. return true;
  6959. },
  6960. [&](const char *data, size_t data_length) {
  6961. received.back().content.append(data, data_length);
  6962. return true;
  6963. });
  6964. // '"', CR and LF in names and filenames are escaped following the
  6965. // WHATWG HTML standard, so each part still parses as a single part
  6966. // with no injected headers. Content types get CR/LF escaped too,
  6967. // while '"' (legal there, e.g. quoted charset) is preserved.
  6968. ASSERT_EQ(4U, received.size());
  6969. EXPECT_EQ("na%22me", received[0].name);
  6970. EXPECT_EQ("quoted name", received[0].content);
  6971. EXPECT_EQ("file", received[1].name);
  6972. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6973. received[1].filename);
  6974. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6975. EXPECT_EQ("injected", received[1].content);
  6976. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6977. EXPECT_EQ("my%22file.txt", received[2].filename);
  6978. EXPECT_EQ("cr lf name", received[2].content);
  6979. EXPECT_EQ("typed", received[3].name);
  6980. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6981. received[3].content_type);
  6982. EXPECT_EQ("typed content", received[3].content);
  6983. });
  6984. auto port = svr.bind_to_any_port("localhost");
  6985. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6986. auto se = detail::scope_exit([&] {
  6987. svr.stop();
  6988. t.join();
  6989. ASSERT_FALSE(svr.is_running());
  6990. });
  6991. svr.wait_until_ready();
  6992. Client cli("localhost", port);
  6993. UploadFormDataItems items = {
  6994. {"na\"me", "quoted name", "", ""},
  6995. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6996. "application/octet-stream"},
  6997. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6998. {"typed", "typed content", "",
  6999. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7000. };
  7001. auto res = cli.Post("/post", items);
  7002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7003. EXPECT_EQ(StatusCode::OK_200, res->status);
  7004. }
  7005. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7006. const UploadFormDataItems items = {
  7007. {"name1", "Content 1", "", ""},
  7008. {"name2", "Content 2", "file2.txt", "text/plain"},
  7009. };
  7010. Server svr;
  7011. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7012. const ContentReader &content_reader) {
  7013. ASSERT_TRUE(req.is_multipart_form_data());
  7014. std::vector<FormData> received;
  7015. content_reader(
  7016. [&](const FormData &file) {
  7017. received.push_back(file);
  7018. return true;
  7019. },
  7020. [&](const char *data, size_t data_length) {
  7021. received.back().content.append(data, data_length);
  7022. return true;
  7023. });
  7024. ASSERT_EQ(2U, received.size());
  7025. EXPECT_EQ("name1", received[0].name);
  7026. EXPECT_EQ("Content 1", received[0].content);
  7027. EXPECT_EQ("name2", received[1].name);
  7028. EXPECT_EQ("Content 2", received[1].content);
  7029. EXPECT_EQ("file2.txt", received[1].filename);
  7030. EXPECT_EQ("text/plain", received[1].content_type);
  7031. });
  7032. auto port = svr.bind_to_any_port("localhost");
  7033. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7034. auto se = detail::scope_exit([&] {
  7035. svr.stop();
  7036. t.join();
  7037. ASSERT_FALSE(svr.is_running());
  7038. });
  7039. svr.wait_until_ready();
  7040. Client cli("localhost", port);
  7041. // Whole-body serialization with a generated boundary
  7042. {
  7043. MultipartFormDataWriter writer;
  7044. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7045. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7046. writer.content_type());
  7047. auto body = writer.serialize(items);
  7048. EXPECT_EQ(body.size(), writer.content_length(items));
  7049. auto res = cli.Post("/post", body, writer.content_type());
  7050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7051. EXPECT_EQ(StatusCode::OK_200, res->status);
  7052. }
  7053. // Per-part framing with a custom boundary via a content provider
  7054. {
  7055. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7056. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7057. MultipartFormDataWriter writer("custom-boundary_123");
  7058. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7059. std::string body;
  7060. for (const auto &item : items) {
  7061. body += writer.item_begin(item);
  7062. body += item.content;
  7063. body += MultipartFormDataWriter::item_end();
  7064. }
  7065. body += writer.finish();
  7066. EXPECT_EQ(body.size(), writer.content_length(items));
  7067. auto res = cli.Post(
  7068. "/post", body.size(),
  7069. [&](size_t offset, size_t length, DataSink &sink) {
  7070. sink.write(body.data() + offset, length);
  7071. return true;
  7072. },
  7073. writer.content_type());
  7074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7075. EXPECT_EQ(StatusCode::OK_200, res->status);
  7076. }
  7077. }
  7078. TEST_F(ServerTest, PostContentReceiverGzip) {
  7079. cli_.set_compress(true);
  7080. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. ASSERT_EQ(StatusCode::OK_200, res->status);
  7083. ASSERT_EQ("content", res->body);
  7084. }
  7085. TEST_F(ServerTest, PutContentReceiver) {
  7086. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. ASSERT_EQ(StatusCode::OK_200, res->status);
  7089. ASSERT_EQ("content", res->body);
  7090. }
  7091. TEST_F(ServerTest, PatchContentReceiver) {
  7092. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7094. ASSERT_EQ(StatusCode::OK_200, res->status);
  7095. ASSERT_EQ("content", res->body);
  7096. }
  7097. template <typename ClientType>
  7098. void TestWithHeadersAndContentReceiver(
  7099. ClientType &cli,
  7100. std::function<Result(ClientType &, const std::string &, const Headers &,
  7101. const std::string &, const std::string &,
  7102. ContentReceiver, DownloadProgress)>
  7103. request_func) {
  7104. Headers headers;
  7105. headers.emplace("X-Custom-Header", "test-value");
  7106. std::string received_body;
  7107. auto res = request_func(
  7108. cli, "/content_receiver", headers, "content", "application/json",
  7109. [&](const char *data, size_t data_length) {
  7110. received_body.append(data, data_length);
  7111. return true;
  7112. },
  7113. nullptr);
  7114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7115. EXPECT_EQ(StatusCode::OK_200, res->status);
  7116. EXPECT_EQ("content", received_body);
  7117. }
  7118. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7119. #ifdef CPPHTTPLIB_SSL_ENABLED
  7120. using ClientT = SSLClient;
  7121. #else
  7122. using ClientT = Client;
  7123. #endif
  7124. TestWithHeadersAndContentReceiver<ClientT>(
  7125. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7126. const std::string &body, const std::string &content_type,
  7127. ContentReceiver receiver, DownloadProgress progress) {
  7128. return cli.Post(path, headers, body, content_type, receiver, progress);
  7129. });
  7130. }
  7131. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7132. #ifdef CPPHTTPLIB_SSL_ENABLED
  7133. using ClientT = SSLClient;
  7134. #else
  7135. using ClientT = Client;
  7136. #endif
  7137. TestWithHeadersAndContentReceiver<ClientT>(
  7138. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7139. const std::string &body, const std::string &content_type,
  7140. ContentReceiver receiver, DownloadProgress progress) {
  7141. return cli.Put(path, headers, body, content_type, receiver, progress);
  7142. });
  7143. }
  7144. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7145. #ifdef CPPHTTPLIB_SSL_ENABLED
  7146. using ClientT = SSLClient;
  7147. #else
  7148. using ClientT = Client;
  7149. #endif
  7150. TestWithHeadersAndContentReceiver<ClientT>(
  7151. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7152. const std::string &body, const std::string &content_type,
  7153. ContentReceiver receiver, DownloadProgress progress) {
  7154. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7155. });
  7156. }
  7157. template <typename ClientType>
  7158. void TestWithHeadersAndContentReceiverWithProgress(
  7159. ClientType &cli,
  7160. std::function<Result(ClientType &, const std::string &, const Headers &,
  7161. const std::string &, const std::string &,
  7162. ContentReceiver, DownloadProgress)>
  7163. request_func) {
  7164. Headers headers;
  7165. headers.emplace("X-Test-Header", "progress-test");
  7166. std::string received_body;
  7167. auto progress_called = false;
  7168. auto res = request_func(
  7169. cli, "/content_receiver", headers, "content", "text/plain",
  7170. [&](const char *data, size_t data_length) {
  7171. received_body.append(data, data_length);
  7172. return true;
  7173. },
  7174. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7175. progress_called = true;
  7176. return true;
  7177. });
  7178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7179. EXPECT_EQ(StatusCode::OK_200, res->status);
  7180. EXPECT_EQ("content", received_body);
  7181. EXPECT_TRUE(progress_called);
  7182. }
  7183. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7184. #ifdef CPPHTTPLIB_SSL_ENABLED
  7185. using ClientT = SSLClient;
  7186. #else
  7187. using ClientT = Client;
  7188. #endif
  7189. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7190. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7191. const std::string &body, const std::string &content_type,
  7192. ContentReceiver receiver, DownloadProgress progress) {
  7193. return cli.Post(path, headers, body, content_type, receiver, progress);
  7194. });
  7195. }
  7196. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7197. #ifdef CPPHTTPLIB_SSL_ENABLED
  7198. using ClientT = SSLClient;
  7199. #else
  7200. using ClientT = Client;
  7201. #endif
  7202. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7203. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7204. const std::string &body, const std::string &content_type,
  7205. ContentReceiver receiver, DownloadProgress progress) {
  7206. return cli.Put(path, headers, body, content_type, receiver, progress);
  7207. });
  7208. }
  7209. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7210. #ifdef CPPHTTPLIB_SSL_ENABLED
  7211. using ClientT = SSLClient;
  7212. #else
  7213. using ClientT = Client;
  7214. #endif
  7215. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7216. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7217. const std::string &body, const std::string &content_type,
  7218. ContentReceiver receiver, DownloadProgress progress) {
  7219. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7220. });
  7221. }
  7222. template <typename ClientType>
  7223. void TestWithHeadersAndContentReceiverError(
  7224. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7225. const Headers &, const std::string &,
  7226. const std::string &, ContentReceiver)>
  7227. request_func) {
  7228. Headers headers;
  7229. headers.emplace("X-Error-Test", "true");
  7230. std::string received_body;
  7231. auto receiver_failed = false;
  7232. auto res =
  7233. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7234. [&](const char *data, size_t data_length) {
  7235. received_body.append(data, data_length);
  7236. receiver_failed = true;
  7237. return false;
  7238. });
  7239. ASSERT_FALSE(res);
  7240. EXPECT_TRUE(receiver_failed);
  7241. }
  7242. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7243. #ifdef CPPHTTPLIB_SSL_ENABLED
  7244. using ClientT = SSLClient;
  7245. #else
  7246. using ClientT = Client;
  7247. #endif
  7248. TestWithHeadersAndContentReceiverError<ClientT>(
  7249. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7250. const std::string &body, const std::string &content_type,
  7251. ContentReceiver receiver) {
  7252. return cli.Post(path, headers, body, content_type, receiver);
  7253. });
  7254. }
  7255. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7256. #ifdef CPPHTTPLIB_SSL_ENABLED
  7257. using ClientT = SSLClient;
  7258. #else
  7259. using ClientT = Client;
  7260. #endif
  7261. TestWithHeadersAndContentReceiverError<ClientT>(
  7262. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7263. const std::string &body, const std::string &content_type,
  7264. ContentReceiver receiver) {
  7265. return cli.Put(path, headers, body, content_type, receiver);
  7266. });
  7267. }
  7268. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7269. #ifdef CPPHTTPLIB_SSL_ENABLED
  7270. using ClientT = SSLClient;
  7271. #else
  7272. using ClientT = Client;
  7273. #endif
  7274. TestWithHeadersAndContentReceiverError<ClientT>(
  7275. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7276. const std::string &body, const std::string &content_type,
  7277. ContentReceiver receiver) {
  7278. return cli.Patch(path, headers, body, content_type, receiver);
  7279. });
  7280. }
  7281. TEST_F(ServerTest, PostQueryStringAndBody) {
  7282. auto res =
  7283. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7285. ASSERT_EQ(StatusCode::OK_200, res->status);
  7286. }
  7287. TEST_F(ServerTest, HTTP2Magic) {
  7288. Request req;
  7289. req.method = "PRI";
  7290. req.path = "*";
  7291. req.body = "SM";
  7292. auto res = std::make_shared<Response>();
  7293. auto error = Error::Success;
  7294. auto ret = cli_.send(req, *res, error);
  7295. ASSERT_TRUE(ret);
  7296. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7297. }
  7298. TEST_F(ServerTest, KeepAlive) {
  7299. auto res = cli_.Get("/hi");
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::OK_200, res->status);
  7302. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7303. EXPECT_EQ("Hello World!", res->body);
  7304. res = cli_.Get("/hi");
  7305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7306. EXPECT_EQ(StatusCode::OK_200, res->status);
  7307. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7308. EXPECT_EQ("Hello World!", res->body);
  7309. res = cli_.Get("/hi");
  7310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7311. EXPECT_EQ(StatusCode::OK_200, res->status);
  7312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7313. EXPECT_EQ("Hello World!", res->body);
  7314. res = cli_.Get("/not-exist");
  7315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7316. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7317. res = cli_.Post("/empty", "", "text/plain");
  7318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7319. EXPECT_EQ(StatusCode::OK_200, res->status);
  7320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7321. EXPECT_EQ("empty", res->body);
  7322. EXPECT_EQ("close", res->get_header_value("Connection"));
  7323. res = cli_.Post(
  7324. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7325. "text/plain");
  7326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7327. EXPECT_EQ(StatusCode::OK_200, res->status);
  7328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7329. EXPECT_EQ("empty", res->body);
  7330. cli_.set_keep_alive(false);
  7331. res = cli_.Get("/last-request");
  7332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7333. EXPECT_EQ(StatusCode::OK_200, res->status);
  7334. EXPECT_EQ("close", res->get_header_value("Connection"));
  7335. }
  7336. TEST_F(ServerTest, TooManyRedirect) {
  7337. cli_.set_follow_location(true);
  7338. auto res = cli_.Get("/redirect/0");
  7339. ASSERT_TRUE(!res);
  7340. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7341. }
  7342. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7343. Request req;
  7344. req.method = "FOOBAR";
  7345. req.path = "/hi";
  7346. cli_.set_keep_alive(true);
  7347. auto res = cli_.send(req);
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7350. EXPECT_EQ("close", res->get_header_value("Connection"));
  7351. EXPECT_FALSE(cli_.is_socket_open());
  7352. }
  7353. TEST_F(ServerTest, CustomRouteReadsBody) {
  7354. const std::string xml =
  7355. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7356. Request req;
  7357. req.method = "PROPFIND";
  7358. req.path = "/dav/dir";
  7359. req.set_header("Depth", "1");
  7360. req.body = xml;
  7361. auto res = cli_.send(req);
  7362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7363. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7364. EXPECT_EQ(xml, res->body);
  7365. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7366. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7367. }
  7368. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7369. Request req;
  7370. req.method = "PROPFIND";
  7371. req.path = "/dav/42";
  7372. auto res = cli_.send(req);
  7373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7374. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7375. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7376. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7377. }
  7378. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7379. Request req;
  7380. req.method = "PROPFIND";
  7381. req.path = "/dav-re/123";
  7382. auto res = cli_.send(req);
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7385. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7386. }
  7387. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7388. Request req;
  7389. req.method = "MKCOL";
  7390. req.path = "/dav-mkcol";
  7391. auto res = cli_.send(req);
  7392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7393. EXPECT_EQ(StatusCode::Created_201, res->status);
  7394. }
  7395. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7396. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7397. Request req;
  7398. req.method = "REPORT";
  7399. req.path = "/dav-report";
  7400. req.body = xml;
  7401. auto res = cli_.send(req);
  7402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7403. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7404. EXPECT_EQ(xml, res->body);
  7405. }
  7406. // A content reader route must fire even when the request carries no body,
  7407. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7408. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7409. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7410. Request req;
  7411. req.method = "REPORT";
  7412. req.path = "/dav-report";
  7413. auto res = cli_.send(req);
  7414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7415. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7416. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7417. }
  7418. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7419. Request req;
  7420. req.method = "PROPFIND";
  7421. req.path = "/not-dav";
  7422. auto res = cli_.send(req);
  7423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7425. }
  7426. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7427. Request req;
  7428. req.method = "UNLOCK";
  7429. req.path = "/dav/dir";
  7430. cli_.set_keep_alive(true);
  7431. auto res = cli_.send(req);
  7432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7433. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7434. EXPECT_EQ("close", res->get_header_value("Connection"));
  7435. EXPECT_FALSE(cli_.is_socket_open());
  7436. }
  7437. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7438. // The mount point serves this path, but only for GET and HEAD.
  7439. auto get_res = cli_.Get("/dir/index.html");
  7440. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7441. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7442. Request req;
  7443. req.method = "PROPFIND";
  7444. req.path = "/dir/index.html";
  7445. auto res = cli_.send(req);
  7446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7447. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7448. }
  7449. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7450. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7451. cli_.set_keep_alive(true);
  7452. for (auto i = 0; i < 2; i++) {
  7453. Request req;
  7454. req.method = "PROPFIND";
  7455. req.path = "/dav/dir";
  7456. req.body = xml;
  7457. auto res = cli_.send(req);
  7458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7459. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7460. EXPECT_EQ(xml, res->body);
  7461. EXPECT_TRUE(cli_.is_socket_open());
  7462. }
  7463. // A built-in method must still be served on the same connection.
  7464. cli_.set_keep_alive(false);
  7465. auto res = cli_.Get("/hi");
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. EXPECT_EQ("close", res->get_header_value("Connection"));
  7469. }
  7470. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7471. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7472. Request req;
  7473. req.method = "PROPFIND";
  7474. req.path = "/dav/dir";
  7475. req.set_header("Expect", "100-continue");
  7476. req.body = xml;
  7477. auto res = cli_.send(req);
  7478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7479. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7480. EXPECT_EQ(xml, res->body);
  7481. }
  7482. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7483. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7484. TEST_F(ServerTest, Gzip) {
  7485. Headers headers;
  7486. headers.emplace("Accept-Encoding", "gzip, deflate");
  7487. auto res = cli_.Get("/compress", headers);
  7488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7489. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7490. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7491. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7492. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7493. "7890123456789012345678901234567890",
  7494. res->body);
  7495. EXPECT_EQ(StatusCode::OK_200, res->status);
  7496. }
  7497. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7498. Headers headers;
  7499. headers.emplace("Accept-Encoding", "gzip, deflate");
  7500. auto res = cli_.Get("/compress-with-charset", headers);
  7501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7502. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7503. EXPECT_EQ("application/json; charset=utf-8",
  7504. res->get_header_value("Content-Type"));
  7505. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7506. "7890123456789012345678901234567890",
  7507. res->body);
  7508. EXPECT_EQ(StatusCode::OK_200, res->status);
  7509. }
  7510. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7511. Headers headers;
  7512. headers.emplace("Accept-Encoding", "");
  7513. auto res = cli_.Get("/compress", headers);
  7514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7515. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7516. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7517. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7518. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7519. "7890123456789012345678901234567890",
  7520. res->body);
  7521. EXPECT_EQ(StatusCode::OK_200, res->status);
  7522. }
  7523. TEST_F(ServerTest, GzipWithContentReceiver) {
  7524. Headers headers;
  7525. headers.emplace("Accept-Encoding", "gzip, deflate");
  7526. std::string body;
  7527. auto res = cli_.Get("/compress", headers,
  7528. [&](const char *data, uint64_t data_length) {
  7529. EXPECT_EQ(100U, data_length);
  7530. body.append(data, data_length);
  7531. return true;
  7532. });
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7535. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7536. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7537. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7538. "7890123456789012345678901234567890",
  7539. body);
  7540. EXPECT_EQ(StatusCode::OK_200, res->status);
  7541. }
  7542. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7543. Headers headers;
  7544. headers.emplace("Accept-Encoding", "gzip, deflate");
  7545. cli_.set_decompress(false);
  7546. auto res = cli_.Get("/compress", headers);
  7547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7548. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7549. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7550. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7551. EXPECT_EQ(33U, res->body.size());
  7552. EXPECT_EQ(StatusCode::OK_200, res->status);
  7553. }
  7554. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7555. Headers headers;
  7556. headers.emplace("Accept-Encoding", "");
  7557. std::string body;
  7558. auto res = cli_.Get("/compress", headers,
  7559. [&](const char *data, uint64_t data_length) {
  7560. EXPECT_EQ(100U, data_length);
  7561. body.append(data, data_length);
  7562. return true;
  7563. });
  7564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7565. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7567. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7568. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7569. "7890123456789012345678901234567890",
  7570. body);
  7571. EXPECT_EQ(StatusCode::OK_200, res->status);
  7572. }
  7573. TEST_F(ServerTest, NoGzip) {
  7574. Headers headers;
  7575. headers.emplace("Accept-Encoding", "gzip, deflate");
  7576. auto res = cli_.Get("/nocompress", headers);
  7577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7578. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7579. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7580. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7581. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7582. "7890123456789012345678901234567890",
  7583. res->body);
  7584. EXPECT_EQ(StatusCode::OK_200, res->status);
  7585. }
  7586. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7587. Headers headers;
  7588. headers.emplace("Accept-Encoding", "gzip, deflate");
  7589. std::string body;
  7590. auto res = cli_.Get("/nocompress", headers,
  7591. [&](const char *data, uint64_t data_length) {
  7592. EXPECT_EQ(100U, data_length);
  7593. body.append(data, data_length);
  7594. return true;
  7595. });
  7596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7597. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7598. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7599. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7600. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7601. "7890123456789012345678901234567890",
  7602. body);
  7603. EXPECT_EQ(StatusCode::OK_200, res->status);
  7604. }
  7605. TEST_F(ServerTest, MultipartFormDataGzip) {
  7606. UploadFormDataItems items = {
  7607. {"key1", "test", "", ""},
  7608. {"key2", "--abcdefg123", "", ""},
  7609. };
  7610. cli_.set_compress(true);
  7611. auto res = cli_.Post("/compress-multipart", items);
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ(StatusCode::OK_200, res->status);
  7614. }
  7615. #endif
  7616. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7617. // Static file compression is opt-in, so these run their own server rather than
  7618. // flipping it on for the shared ServerTest fixture, which would silently
  7619. // rewrite what every other static file test is asserting.
  7620. class StaticFileCompressionTest : public ::testing::Test {
  7621. protected:
  7622. void TearDown() override {
  7623. if (t_.joinable()) {
  7624. svr_.stop();
  7625. t_.join();
  7626. }
  7627. }
  7628. int start(const std::function<void(Server &)> &configure = nullptr) {
  7629. // Serves the same tree as a directory of build-time compressed assets
  7630. // would be served: the mount point names the coding the files are already
  7631. // stored in. Registered before "/" so it is the one that matches.
  7632. svr_.set_mount_point("/pre-encoded", "./www",
  7633. {{"Content-Encoding", "gzip"}});
  7634. svr_.set_mount_point("/", "./www");
  7635. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7636. res.set_file_content("./www/dir/index.html", "text/html");
  7637. });
  7638. svr_.Get("/pre-encoded-file-content",
  7639. [](const Request & /*req*/, Response &res) {
  7640. res.set_header("Content-Encoding", "gzip");
  7641. res.set_file_content("./www/dir/index.html", "text/html");
  7642. });
  7643. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7644. res.set_content_provider(
  7645. 6, "text/plain",
  7646. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7647. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7648. return true;
  7649. });
  7650. });
  7651. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7652. res.set_content_provider(
  7653. 1000, "text/plain",
  7654. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7655. if (offset < 100) {
  7656. std::string data(100, 'A');
  7657. sink.write(data.data(), data.size());
  7658. return true;
  7659. }
  7660. std::this_thread::sleep_for(std::chrono::seconds(2));
  7661. std::string data(900, 'B');
  7662. sink.write(data.data(), data.size());
  7663. return true;
  7664. });
  7665. });
  7666. if (configure) { configure(svr_); }
  7667. auto port = svr_.bind_to_any_port(HOST);
  7668. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7669. svr_.wait_until_ready();
  7670. return port;
  7671. }
  7672. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7673. // Every file under ./www except 1MB.txt is smaller than the default
  7674. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7675. // it out of the way.
  7676. static void enable_without_floor(Server &svr) {
  7677. svr.set_static_file_compression(true);
  7678. svr.set_static_file_compression_min_length(0);
  7679. }
  7680. Server svr_;
  7681. std::thread t_;
  7682. };
  7683. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7684. auto port = start();
  7685. Client cli(HOST, port);
  7686. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7688. EXPECT_EQ(StatusCode::OK_200, res->status);
  7689. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7690. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7691. EXPECT_EQ(1048576U, res->body.size());
  7692. }
  7693. TEST_F(StaticFileCompressionTest, MountPoint) {
  7694. auto port = start(enable);
  7695. Client cli(HOST, port);
  7696. cli.set_decompress(false);
  7697. auto res = cli.Get("/dir/1MB.txt", 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/plain", res->get_header_value("Content-Type"));
  7701. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7702. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7703. // The response stays self-delimiting: a length, not a chunked body.
  7704. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7705. EXPECT_EQ(std::to_string(res->body.size()),
  7706. res->get_header_value("Content-Length"));
  7707. EXPECT_LT(res->body.size(), 1048576U);
  7708. EXPECT_FALSE(res->body.empty());
  7709. }
  7710. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7711. auto port = start(enable);
  7712. Client cli(HOST, port);
  7713. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7715. EXPECT_EQ(StatusCode::OK_200, res->status);
  7716. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7717. EXPECT_EQ(1048576U, res->body.size());
  7718. }
  7719. TEST_F(StaticFileCompressionTest, FileContent) {
  7720. auto port = start(enable_without_floor);
  7721. Client cli(HOST, port);
  7722. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7724. EXPECT_EQ(StatusCode::OK_200, res->status);
  7725. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7726. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7727. EXPECT_EQ(104U, res->body.size());
  7728. }
  7729. // A handler that serves an already-encoded file names the coding itself. The
  7730. // file-backed path decided its coding from Accept-Encoding and the content
  7731. // type alone, so it compressed the stored bytes a second time and appended a
  7732. // second Content-Encoding field line.
  7733. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7734. auto port = start(enable_without_floor);
  7735. Client cli(HOST, port);
  7736. cli.set_decompress(false);
  7737. auto res = cli.Get("/pre-encoded-file-content",
  7738. Headers{{"Accept-Encoding", "gzip"}});
  7739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7740. EXPECT_EQ(StatusCode::OK_200, res->status);
  7741. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7742. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7743. // Vary belongs to a coding the server chose, and it chose none here.
  7744. EXPECT_FALSE(res->has_header("Vary"));
  7745. // The file travels exactly as it is stored on disk.
  7746. EXPECT_EQ(104U, res->body.size());
  7747. }
  7748. // The 1MB file clears the default floor, so this one runs the configuration a
  7749. // deployment would actually have.
  7750. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7751. auto port = start(enable);
  7752. Client cli(HOST, port);
  7753. cli.set_decompress(false);
  7754. auto res =
  7755. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::OK_200, res->status);
  7758. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7759. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7760. EXPECT_FALSE(res->has_header("Vary"));
  7761. EXPECT_EQ(1048576U, res->body.size());
  7762. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7763. }
  7764. TEST_F(StaticFileCompressionTest, Head) {
  7765. auto port = start(enable);
  7766. Client cli(HOST, port);
  7767. cli.set_decompress(false);
  7768. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7769. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7770. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::OK_200, res->status);
  7773. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7774. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7775. // HEAD still reports the size a GET would return.
  7776. EXPECT_EQ(get->get_header_value("Content-Length"),
  7777. res->get_header_value("Content-Length"));
  7778. EXPECT_TRUE(res->body.empty());
  7779. }
  7780. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7781. auto port = start(enable);
  7782. Client cli(HOST, port);
  7783. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7784. {"Accept-Encoding", "gzip"}});
  7785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7786. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7787. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7788. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7789. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7790. EXPECT_EQ("cd", res->body);
  7791. }
  7792. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7793. auto port = start(enable);
  7794. Client cli(HOST, port);
  7795. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7797. EXPECT_EQ(StatusCode::OK_200, res->status);
  7798. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7799. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7800. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7801. }
  7802. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7803. auto port = start(enable);
  7804. Client cli(HOST, port);
  7805. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7807. EXPECT_EQ(StatusCode::OK_200, res->status);
  7808. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7809. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7810. EXPECT_TRUE(res->body.empty());
  7811. }
  7812. TEST_F(StaticFileCompressionTest, MinLength) {
  7813. auto port = start(enable);
  7814. Client cli(HOST, port);
  7815. // 104 bytes, well under the default floor. Compressing it would add the
  7816. // gzip header and trailer to a body that already fits in one packet.
  7817. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7819. EXPECT_EQ(StatusCode::OK_200, res->status);
  7820. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7821. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7822. }
  7823. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7824. auto port = start([](Server &svr) {
  7825. svr.set_static_file_compression(true);
  7826. svr.set_static_file_compression_min_length(1);
  7827. });
  7828. Client cli(HOST, port);
  7829. cli.set_decompress(false);
  7830. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7832. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7833. // A 9-byte file comes back larger than it went in, because gzip's header and
  7834. // trailer outweigh anything deflate can save. That is the end of the range
  7835. // the floor exists to keep out.
  7836. EXPECT_GT(res->body.size(), 9U);
  7837. }
  7838. TEST_F(StaticFileCompressionTest, MaxLength) {
  7839. auto port = start([](Server &svr) {
  7840. svr.set_static_file_compression(true);
  7841. svr.set_static_file_compression_min_length(0);
  7842. svr.set_static_file_compression_max_length(1024);
  7843. });
  7844. Client cli(HOST, port);
  7845. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7846. // defines `small` as a macro on Windows.
  7847. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7848. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7849. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7850. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7851. // Under it: compressed.
  7852. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7853. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7854. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7855. }
  7856. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7857. auto port = start(enable_without_floor);
  7858. Client cli(HOST, port);
  7859. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7860. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7861. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7862. auto identity_etag = identity->get_header_value("ETag");
  7863. ASSERT_FALSE(identity_etag.empty());
  7864. auto gzipped =
  7865. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7866. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7867. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7868. auto gzip_etag = gzipped->get_header_value("ETag");
  7869. ASSERT_FALSE(gzip_etag.empty());
  7870. // Two representations, two validators.
  7871. EXPECT_NE(identity_etag, gzip_etag);
  7872. // Each one revalidates against the request that would produce it...
  7873. auto fresh =
  7874. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7875. {"If-None-Match", gzip_etag}});
  7876. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7877. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7878. auto fresh_identity =
  7879. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7880. {"If-None-Match", identity_etag}});
  7881. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7882. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7883. // ...and not against the other representation.
  7884. auto crossed =
  7885. cli.Get("/dir/index.html",
  7886. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7887. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7888. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7889. }
  7890. // The opt-in covers responses the server reads off disk itself. A caller's own
  7891. // known-length provider keeps its Content-Length and, more importantly, keeps
  7892. // delivering incrementally: routing it through a compressor would hold every
  7893. // write back until zlib's window filled.
  7894. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7895. auto port = start(enable);
  7896. Client cli(HOST, port);
  7897. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7901. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7902. EXPECT_EQ("aaabbb", res->body);
  7903. }
  7904. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7905. auto port = start(enable);
  7906. Client cli(HOST, port);
  7907. cli.set_read_timeout(1, 0);
  7908. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7909. Headers{{"Accept-Encoding", "gzip"}});
  7910. ASSERT_TRUE(handle.is_valid());
  7911. // The provider writes 100 bytes and then stalls for longer than the read
  7912. // timeout. Those first bytes have to arrive anyway: run the response through
  7913. // a compressor and zlib holds them until its window fills, so the read would
  7914. // come back empty instead.
  7915. char buf[256];
  7916. auto n = handle.read(buf, sizeof(buf));
  7917. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7918. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7919. }
  7920. #endif
  7921. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7922. TEST_F(ServerTest, Brotli) {
  7923. Headers headers;
  7924. headers.emplace("Accept-Encoding", "br");
  7925. auto res = cli_.Get("/compress", headers);
  7926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7927. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7929. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7930. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7931. "7890123456789012345678901234567890",
  7932. res->body);
  7933. EXPECT_EQ(StatusCode::OK_200, res->status);
  7934. }
  7935. #endif
  7936. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7937. TEST_F(ServerTest, Zstd) {
  7938. Headers headers;
  7939. headers.emplace("Accept-Encoding", "zstd");
  7940. auto res = cli_.Get("/compress", headers);
  7941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7942. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7944. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7945. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7946. "7890123456789012345678901234567890",
  7947. res->body);
  7948. EXPECT_EQ(StatusCode::OK_200, res->status);
  7949. }
  7950. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7951. Headers headers;
  7952. headers.emplace("Accept-Encoding", "");
  7953. auto res = cli_.Get("/compress", headers);
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7956. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7957. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7958. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7959. "7890123456789012345678901234567890",
  7960. res->body);
  7961. EXPECT_EQ(StatusCode::OK_200, res->status);
  7962. }
  7963. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7964. Headers headers;
  7965. headers.emplace("Accept-Encoding", "zstd");
  7966. std::string body;
  7967. auto res = cli_.Get("/compress", headers,
  7968. [&](const char *data, uint64_t data_length) {
  7969. EXPECT_EQ(100U, data_length);
  7970. body.append(data, data_length);
  7971. return true;
  7972. });
  7973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7974. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7975. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7976. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7977. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7978. "7890123456789012345678901234567890",
  7979. body);
  7980. EXPECT_EQ(StatusCode::OK_200, res->status);
  7981. }
  7982. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7983. Headers headers;
  7984. headers.emplace("Accept-Encoding", "zstd");
  7985. cli_.set_decompress(false);
  7986. auto res = cli_.Get("/compress", headers);
  7987. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7988. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7989. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7990. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7992. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7994. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7995. EXPECT_EQ(StatusCode::OK_200, res->status);
  7996. ASSERT_EQ(26U, res->body.size());
  7997. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7998. 0);
  7999. }
  8000. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8001. Headers headers;
  8002. headers.emplace("Accept-Encoding", "");
  8003. std::string body;
  8004. auto res = cli_.Get("/compress", headers,
  8005. [&](const char *data, uint64_t data_length) {
  8006. EXPECT_EQ(100U, data_length);
  8007. body.append(data, data_length);
  8008. return true;
  8009. });
  8010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8011. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8012. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8013. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8014. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8015. "7890123456789012345678901234567890",
  8016. body);
  8017. EXPECT_EQ(StatusCode::OK_200, res->status);
  8018. }
  8019. TEST_F(ServerTest, NoZstd) {
  8020. Headers headers;
  8021. headers.emplace("Accept-Encoding", "zstd");
  8022. auto res = cli_.Get("/nocompress", headers);
  8023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8024. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8025. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8026. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8027. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8028. "7890123456789012345678901234567890",
  8029. res->body);
  8030. EXPECT_EQ(StatusCode::OK_200, res->status);
  8031. }
  8032. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8033. Headers headers;
  8034. headers.emplace("Accept-Encoding", "zstd");
  8035. std::string body;
  8036. auto res = cli_.Get("/nocompress", headers,
  8037. [&](const char *data, uint64_t data_length) {
  8038. EXPECT_EQ(100U, data_length);
  8039. body.append(data, data_length);
  8040. return true;
  8041. });
  8042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8043. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8044. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8045. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8046. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8047. "7890123456789012345678901234567890",
  8048. body);
  8049. EXPECT_EQ(StatusCode::OK_200, res->status);
  8050. }
  8051. // TODO: How to enable zstd ??
  8052. TEST_F(ServerTest, MultipartFormDataZstd) {
  8053. UploadFormDataItems items = {
  8054. {"key1", "test", "", ""},
  8055. {"key2", "--abcdefg123", "", ""},
  8056. };
  8057. Headers headers;
  8058. headers.emplace("Accept-Encoding", "zstd");
  8059. cli_.set_compress(true);
  8060. auto res = cli_.Post("/compress-multipart", headers, items);
  8061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8062. EXPECT_EQ(StatusCode::OK_200, res->status);
  8063. }
  8064. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8065. Headers headers;
  8066. headers.emplace("Accept-Encoding", "zstd");
  8067. cli_.set_compress(true);
  8068. auto res = cli_.Put(
  8069. "/put", headers, 3,
  8070. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8071. sink.os << "PUT";
  8072. return true;
  8073. },
  8074. "text/plain");
  8075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8076. EXPECT_EQ(StatusCode::OK_200, res->status);
  8077. EXPECT_EQ("PUT", res->body);
  8078. }
  8079. // Pre-compression logging tests
  8080. TEST_F(ServerTest, PreCompressionLogging) {
  8081. // Test data for compression (matches the actual /compress endpoint content)
  8082. const std::string test_content =
  8083. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8084. "3456789012345678901234567890";
  8085. // Variables to capture logging data
  8086. std::string pre_compression_body;
  8087. std::string pre_compression_content_type;
  8088. std::string pre_compression_content_encoding;
  8089. std::string post_compression_body;
  8090. std::string post_compression_content_type;
  8091. std::string post_compression_content_encoding;
  8092. // Set up pre-compression logger
  8093. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8094. const Response &res) {
  8095. pre_compression_body = res.body;
  8096. pre_compression_content_type = res.get_header_value("Content-Type");
  8097. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8098. });
  8099. // Set up post-compression logger
  8100. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8101. post_compression_body = res.body;
  8102. post_compression_content_type = res.get_header_value("Content-Type");
  8103. post_compression_content_encoding =
  8104. res.get_header_value("Content-Encoding");
  8105. });
  8106. // Test with gzip compression
  8107. Headers headers;
  8108. headers.emplace("Accept-Encoding", "gzip");
  8109. auto res = cli_.Get("/compress", headers);
  8110. // Verify response was compressed
  8111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8112. EXPECT_EQ(StatusCode::OK_200, res->status);
  8113. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8114. // Verify pre-compression logger captured uncompressed content
  8115. EXPECT_EQ(test_content, pre_compression_body);
  8116. EXPECT_EQ("text/plain", pre_compression_content_type);
  8117. EXPECT_TRUE(pre_compression_content_encoding
  8118. .empty()); // No encoding header before compression
  8119. // Verify post-compression logger captured compressed content
  8120. EXPECT_NE(test_content,
  8121. post_compression_body); // Should be different after compression
  8122. EXPECT_EQ("text/plain", post_compression_content_type);
  8123. EXPECT_EQ("gzip", post_compression_content_encoding);
  8124. // Verify compressed content is smaller
  8125. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8126. }
  8127. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  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. Headers headers;
  8141. headers.emplace("Accept-Encoding", "br");
  8142. auto res = cli_.Get("/compress", headers);
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8146. // Verify pre-compression content is uncompressed
  8147. EXPECT_EQ(test_content, pre_compression_body);
  8148. // Verify post-compression content is compressed
  8149. EXPECT_NE(test_content, post_compression_body);
  8150. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8151. }
  8152. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8153. const std::string test_content =
  8154. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8155. "3456789012345678901234567890";
  8156. std::string pre_compression_body;
  8157. std::string post_compression_body;
  8158. svr_.set_pre_compression_logger(
  8159. [&](const Request & /*req*/, const Response &res) {
  8160. pre_compression_body = res.body;
  8161. });
  8162. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8163. post_compression_body = res.body;
  8164. });
  8165. // Request without compression (use /nocompress endpoint)
  8166. Headers headers;
  8167. auto res = cli_.Get("/nocompress", headers);
  8168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8169. EXPECT_EQ(StatusCode::OK_200, res->status);
  8170. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8171. // Pre-compression logger should not be called when no compression is applied
  8172. EXPECT_TRUE(
  8173. pre_compression_body.empty()); // Pre-compression logger not called
  8174. EXPECT_EQ(
  8175. test_content,
  8176. post_compression_body); // Post-compression logger captures final content
  8177. }
  8178. TEST_F(ServerTest, LoggerSeesContentLength) {
  8179. size_t logged_content_length = 0;
  8180. std::string logged_content_length_header;
  8181. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8182. logged_content_length = res.content_length_;
  8183. logged_content_length_header = res.get_header_value("Content-Length");
  8184. });
  8185. auto res = cli_.Get("/nocompress");
  8186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8187. EXPECT_EQ(StatusCode::OK_200, res->status);
  8188. EXPECT_EQ(res->body.size(), logged_content_length);
  8189. EXPECT_EQ(std::to_string(logged_content_length),
  8190. logged_content_length_header);
  8191. }
  8192. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8193. const std::string test_content =
  8194. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8195. "3456789012345678901234567890";
  8196. std::string pre_compression_body;
  8197. bool pre_logger_called = false;
  8198. // Set only pre-compression logger
  8199. svr_.set_pre_compression_logger(
  8200. [&](const Request & /*req*/, const Response &res) {
  8201. pre_compression_body = res.body;
  8202. pre_logger_called = true;
  8203. });
  8204. Headers headers;
  8205. headers.emplace("Accept-Encoding", "gzip");
  8206. auto res = cli_.Get("/compress", headers);
  8207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8208. EXPECT_EQ(StatusCode::OK_200, res->status);
  8209. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8210. // Verify pre-compression logger was called
  8211. EXPECT_TRUE(pre_logger_called);
  8212. EXPECT_EQ(test_content, pre_compression_body);
  8213. }
  8214. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8215. {
  8216. // Test with Expect: 100-continue header - success case
  8217. // Server returns 100 Continue, client sends body, server returns 200 OK
  8218. Request req;
  8219. req.method = "POST";
  8220. req.path = "/post-large";
  8221. req.set_header("Expect", "100-continue");
  8222. req.body = LARGE_DATA;
  8223. Response res;
  8224. auto error = Error::Success;
  8225. cli_.set_keep_alive(true);
  8226. auto ret = cli_.send(req, res, error);
  8227. EXPECT_TRUE(ret);
  8228. EXPECT_EQ(StatusCode::OK_200, res.status);
  8229. EXPECT_EQ(LARGE_DATA, res.body);
  8230. }
  8231. {
  8232. // Test with Expect: 100-continue header - error case
  8233. // Client should not send the body when server returns an error
  8234. Request req;
  8235. req.method = "POST";
  8236. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8237. req.set_header("Expect", "100-continue");
  8238. req.body = LARGE_DATA;
  8239. Response res;
  8240. auto error = Error::Success;
  8241. auto start = std::chrono::high_resolution_clock::now();
  8242. cli_.set_keep_alive(true);
  8243. auto ret = cli_.send(req, res, error);
  8244. auto end = std::chrono::high_resolution_clock::now();
  8245. auto elapsed =
  8246. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8247. .count();
  8248. // With Expect: 100-continue, request completes successfully but with error
  8249. EXPECT_TRUE(ret);
  8250. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8251. EXPECT_EQ("close", res.get_header_value("Connection"));
  8252. EXPECT_FALSE(cli_.is_socket_open());
  8253. EXPECT_LE(elapsed, 2000);
  8254. }
  8255. {
  8256. // Send an extra GET request to ensure error recovery without hanging
  8257. Request req;
  8258. req.method = "GET";
  8259. req.path = "/hi";
  8260. auto start = std::chrono::high_resolution_clock::now();
  8261. auto res = cli_.send(req);
  8262. auto end = std::chrono::high_resolution_clock::now();
  8263. auto elapsed =
  8264. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8265. .count();
  8266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8267. EXPECT_EQ(StatusCode::OK_200, res->status);
  8268. EXPECT_EQ("Hello World!", res->body);
  8269. EXPECT_LE(elapsed, 500);
  8270. }
  8271. }
  8272. TEST(ZstdDecompressor, ChunkedDecompression) {
  8273. std::string data;
  8274. for (size_t i = 0; i < 32 * 1024; ++i) {
  8275. data.push_back(static_cast<char>('a' + i % 26));
  8276. }
  8277. std::string compressed_data;
  8278. {
  8279. httplib::detail::zstd_compressor compressor;
  8280. bool result = compressor.compress(
  8281. data.data(), data.size(),
  8282. /*last=*/true,
  8283. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8284. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8285. compressed_data_size);
  8286. return true;
  8287. });
  8288. ASSERT_TRUE(result);
  8289. }
  8290. std::string decompressed_data;
  8291. {
  8292. httplib::detail::zstd_decompressor decompressor;
  8293. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8294. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8295. size_t chunk_size = 130;
  8296. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8297. chunk_begin += chunk_size) {
  8298. size_t current_chunk_size =
  8299. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8300. bool result = decompressor.decompress(
  8301. compressed_data.data() + chunk_begin, current_chunk_size,
  8302. [&](const char *decompressed_data_chunk,
  8303. size_t decompressed_data_chunk_size) {
  8304. decompressed_data.insert(decompressed_data.size(),
  8305. decompressed_data_chunk,
  8306. decompressed_data_chunk_size);
  8307. return true;
  8308. });
  8309. ASSERT_TRUE(result);
  8310. }
  8311. }
  8312. ASSERT_EQ(data, decompressed_data);
  8313. }
  8314. TEST(ZstdDecompressor, Decompress) {
  8315. std::string original_text = "Compressed with ZSTD";
  8316. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8317. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8318. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8319. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8320. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8321. std::string decompressed_data;
  8322. {
  8323. httplib::detail::zstd_decompressor decompressor;
  8324. bool result = decompressor.decompress(
  8325. compressed_data.data(), compressed_data.size(),
  8326. [&](const char *decompressed_data_chunk,
  8327. size_t decompressed_data_chunk_size) {
  8328. decompressed_data.insert(decompressed_data.size(),
  8329. decompressed_data_chunk,
  8330. decompressed_data_chunk_size);
  8331. return true;
  8332. });
  8333. ASSERT_TRUE(result);
  8334. }
  8335. ASSERT_EQ(original_text, decompressed_data);
  8336. }
  8337. #endif
  8338. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8339. // separate chunks so that the server sees each part in its own read(). Used to
  8340. // place a read boundary at a specific offset of a request body.
  8341. static bool send_request_in_parts(time_t read_timeout_sec,
  8342. const std::vector<std::string> &parts,
  8343. std::string *resp = nullptr,
  8344. int port = PORT) {
  8345. auto error = Error::Success;
  8346. auto client_sock = detail::create_client_socket(
  8347. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8348. /*connection_timeout_sec=*/5, 0,
  8349. /*read_timeout_sec=*/5, 0,
  8350. /*write_timeout_sec=*/5, 0, std::string(), error);
  8351. if (client_sock == INVALID_SOCKET) { return false; }
  8352. auto ret = detail::process_client_socket(
  8353. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8354. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8355. for (size_t i = 0; i < parts.size(); i++) {
  8356. const auto &part = parts[i];
  8357. if (part.size() !=
  8358. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8359. return false;
  8360. }
  8361. if (i + 1 < parts.size()) {
  8362. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8363. }
  8364. }
  8365. char buf[512];
  8366. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8367. while (line_reader.getline()) {
  8368. if (resp) { *resp += line_reader.ptr(); }
  8369. }
  8370. return true;
  8371. });
  8372. detail::close_socket(client_sock);
  8373. return ret;
  8374. }
  8375. // Sends a raw request to a server listening at HOST:PORT.
  8376. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8377. std::string *resp = nullptr, int port = PORT) {
  8378. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8379. }
  8380. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8381. Server svr;
  8382. std::string header_value;
  8383. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8384. header_value = req.get_header_value("foo");
  8385. res.set_content("ok", "text/plain");
  8386. });
  8387. thread t = thread([&] { svr.listen(HOST, PORT); });
  8388. auto se = detail::scope_exit([&] {
  8389. svr.stop();
  8390. t.join();
  8391. ASSERT_FALSE(svr.is_running());
  8392. });
  8393. svr.wait_until_ready();
  8394. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8395. // like characters are not treated the same - use vertical tab and escape.
  8396. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8397. "foo: \t \v bar \x1B\t \r\n"
  8398. "Connection: close\r\n"
  8399. "\r\n";
  8400. std::string res;
  8401. ASSERT_TRUE(send_request(5, req, &res));
  8402. EXPECT_EQ(header_value, "");
  8403. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8404. }
  8405. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8406. Server svr;
  8407. std::string received;
  8408. svr.Get("/order", [&](const Request &req, Response &res) {
  8409. received = entries_to_string(req.headers);
  8410. res.set_content("ok", "text/plain");
  8411. });
  8412. auto port = svr.bind_to_any_port(HOST);
  8413. thread t = thread([&] { svr.listen_after_bind(); });
  8414. auto se = detail::scope_exit([&] {
  8415. svr.stop();
  8416. t.join();
  8417. ASSERT_FALSE(svr.is_running());
  8418. });
  8419. svr.wait_until_ready();
  8420. const std::string req = "GET /order HTTP/1.1\r\n"
  8421. "X-First: 1\r\n"
  8422. "X-Dup: a\r\n"
  8423. "X-Second: 2\r\n"
  8424. "X-Dup: b\r\n"
  8425. "Connection: close\r\n"
  8426. "\r\n";
  8427. std::string res;
  8428. ASSERT_TRUE(send_request(5, req, &res, port));
  8429. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8430. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8431. }
  8432. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8433. Server svr;
  8434. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8435. res.set_header("Set-Cookie", "first=1");
  8436. res.set_header("X-Between", "y");
  8437. res.set_header("Set-Cookie", "second=2");
  8438. res.set_content("ok", "text/plain");
  8439. });
  8440. auto port = svr.bind_to_any_port(HOST);
  8441. thread t = thread([&] { svr.listen_after_bind(); });
  8442. auto se = detail::scope_exit([&] {
  8443. svr.stop();
  8444. t.join();
  8445. ASSERT_FALSE(svr.is_running());
  8446. });
  8447. svr.wait_until_ready();
  8448. Client cli(HOST, port);
  8449. auto res = cli.Get("/cookies");
  8450. ASSERT_TRUE(res);
  8451. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8452. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8453. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8454. }
  8455. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8456. Server svr;
  8457. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8458. auto i = new int(0);
  8459. res.set_header("Trailer", "X-Safe, X-Reflected");
  8460. res.set_chunked_content_provider(
  8461. "text/plain",
  8462. [i](size_t /*offset*/, DataSink &sink) {
  8463. if (*i == 0) {
  8464. sink.os << "body";
  8465. } else {
  8466. Headers trailer;
  8467. // A valid trailer that must survive.
  8468. trailer.emplace("X-Safe", "safe");
  8469. // Attacker-controlled value carrying CR/LF (response splitting).
  8470. trailer.emplace("X-Reflected",
  8471. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8472. // Attacker-controlled name carrying CR/LF.
  8473. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8474. sink.done_with_trailer(trailer);
  8475. }
  8476. (*i)++;
  8477. return true;
  8478. },
  8479. [i](bool /*success*/) { delete i; });
  8480. });
  8481. thread t = thread([&] { svr.listen(HOST, PORT); });
  8482. auto se = detail::scope_exit([&] {
  8483. svr.stop();
  8484. t.join();
  8485. ASSERT_FALSE(svr.is_running());
  8486. });
  8487. svr.wait_until_ready();
  8488. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8489. "Host: " + HOST +
  8490. "\r\n"
  8491. "Connection: close\r\n"
  8492. "\r\n";
  8493. std::string res;
  8494. ASSERT_TRUE(send_request(5, req, &res));
  8495. // The injected fields must not appear anywhere in the raw response.
  8496. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8497. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8498. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8499. // Invalid trailers are dropped entirely, matching set_header().
  8500. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8501. // The valid trailer still passes through.
  8502. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8503. }
  8504. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8505. Server svr;
  8506. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8507. // res.headers is a public field an application can populate directly,
  8508. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8509. // A valid header that must survive.
  8510. res.headers.emplace("X-Safe", "safe");
  8511. // Attacker-controlled value carrying CR/LF (response splitting).
  8512. res.headers.emplace("X-Reflected",
  8513. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8514. // Attacker-controlled name carrying CR/LF.
  8515. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8516. res.set_content("body", "text/plain");
  8517. });
  8518. thread t = thread([&] { svr.listen(HOST, PORT); });
  8519. auto se = detail::scope_exit([&] {
  8520. svr.stop();
  8521. t.join();
  8522. ASSERT_FALSE(svr.is_running());
  8523. });
  8524. svr.wait_until_ready();
  8525. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8526. "Host: " + HOST +
  8527. "\r\n"
  8528. "Connection: close\r\n"
  8529. "\r\n";
  8530. std::string res;
  8531. ASSERT_TRUE(send_request(5, req, &res));
  8532. // The injected fields must not appear anywhere in the raw response.
  8533. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8534. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8535. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8536. // Invalid headers are dropped entirely, matching set_header().
  8537. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8538. // The valid header still passes through.
  8539. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8540. }
  8541. // Forward declaration: in split builds split.py strips `inline` and moves the
  8542. // definition into httplib.cc, so detail::write_request_line is not visible from
  8543. // the public httplib.h. Re-declaring it here lets the tests link against the
  8544. // symbol in both header-only and split builds.
  8545. namespace httplib {
  8546. namespace detail {
  8547. ssize_t write_request_line(Stream &strm, const std::string &method,
  8548. const std::string &path);
  8549. } // namespace detail
  8550. } // namespace httplib
  8551. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8552. // A well-formed target is written verbatim.
  8553. {
  8554. detail::BufferStream strm;
  8555. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8556. EXPECT_GT(n, 0);
  8557. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8558. }
  8559. // A target carrying CR/LF, SP or other control octets must be rejected
  8560. // before anything reaches the wire, otherwise it splits the request line and
  8561. // injects a header or a whole request. This is what a decoded redirect
  8562. // Location ("%0D%0A") turns into when path encoding is disabled.
  8563. const std::string evil_targets[] = {
  8564. "/a\r\nInjected: pwned",
  8565. "/a\rInjected",
  8566. "/a\nInjected",
  8567. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8568. "/a b",
  8569. "/a\tb",
  8570. "/a\x7f",
  8571. };
  8572. for (const auto &evil : evil_targets) {
  8573. detail::BufferStream strm;
  8574. auto n = detail::write_request_line(strm, "GET", evil);
  8575. EXPECT_LT(n, 0);
  8576. EXPECT_TRUE(strm.get_buffer().empty());
  8577. }
  8578. }
  8579. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8580. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8581. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8582. // target -- what a redirect Location "%0D%0A" decodes to -- reaches
  8583. // write_request. The client must fail cleanly with Error::Write instead of
  8584. // putting a request-line-less, header-injecting request on the wire.
  8585. Server svr;
  8586. svr.Get("/a", [](const Request &, Response &res) {
  8587. res.set_content("ok", "text/plain");
  8588. });
  8589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8590. auto se = detail::scope_exit([&] {
  8591. svr.stop();
  8592. thread.join();
  8593. ASSERT_FALSE(svr.is_running());
  8594. });
  8595. svr.wait_until_ready();
  8596. {
  8597. Client cli(HOST, PORT);
  8598. cli.set_path_encode(false);
  8599. // The request is rejected before anything is written, so the connection
  8600. // stays silent and the subsequent response read would otherwise block for
  8601. // the full default read timeout. Shorten it -- the assertion is on the
  8602. // error, not the timeout.
  8603. cli.set_read_timeout(1, 0);
  8604. auto res = cli.Get("/a\r\nInjected: pwned");
  8605. EXPECT_FALSE(res);
  8606. EXPECT_EQ(Error::Write, res.error());
  8607. }
  8608. }
  8609. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8610. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8611. // including extension methods.
  8612. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8613. for (const auto &method : good_methods) {
  8614. detail::BufferStream strm;
  8615. auto n = detail::write_request_line(strm, method, "/");
  8616. EXPECT_GT(n, 0);
  8617. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8618. }
  8619. // A method carrying CR/LF would split the request line and smuggle a whole
  8620. // request ahead of the real one. A space or an empty method corrupts the
  8621. // request line. All must be rejected before anything reaches the wire.
  8622. const std::string evil_methods[] = {
  8623. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8624. "GET\r\nInjected: pwned",
  8625. "GET\r",
  8626. "GET\n",
  8627. "GE T",
  8628. "",
  8629. };
  8630. for (const auto &evil : evil_methods) {
  8631. detail::BufferStream strm;
  8632. auto n = detail::write_request_line(strm, evil, "/");
  8633. EXPECT_LT(n, 0);
  8634. EXPECT_TRUE(strm.get_buffer().empty());
  8635. }
  8636. }
  8637. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8638. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8639. // through Client::send must fail with Error::Write and no request, neither
  8640. // the smuggled one nor the real one, may reach the server.
  8641. Server svr;
  8642. std::atomic<int> request_count(0);
  8643. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8644. request_count++;
  8645. res.status = StatusCode::OK_200;
  8646. return Server::HandlerResponse::Handled;
  8647. });
  8648. auto port = svr.bind_to_any_port(HOST);
  8649. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8650. auto se = detail::scope_exit([&] {
  8651. svr.stop();
  8652. thread.join();
  8653. ASSERT_FALSE(svr.is_running());
  8654. });
  8655. svr.wait_until_ready();
  8656. {
  8657. Client cli(HOST, port);
  8658. const std::string evil_methods[] = {
  8659. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8660. "GE T",
  8661. "",
  8662. };
  8663. for (const auto &evil : evil_methods) {
  8664. Request req;
  8665. req.method = evil;
  8666. req.path = "/";
  8667. auto res = cli.send(req);
  8668. EXPECT_FALSE(res);
  8669. EXPECT_EQ(Error::Write, res.error());
  8670. }
  8671. auto handle =
  8672. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8673. EXPECT_FALSE(handle.is_valid());
  8674. EXPECT_EQ(Error::Write, handle.error);
  8675. // A valid request on the same client still goes through.
  8676. auto res = cli.Get("/");
  8677. ASSERT_TRUE(res);
  8678. EXPECT_EQ(StatusCode::OK_200, res->status);
  8679. }
  8680. EXPECT_EQ(1, request_count.load());
  8681. }
  8682. // Sends a raw request and verifies that there isn't a crash or exception.
  8683. static void test_raw_request(const std::string &req,
  8684. std::string *out = nullptr) {
  8685. Server svr;
  8686. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8687. res.set_content("ok", "text/plain");
  8688. });
  8689. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8690. res.set_content("ok", "text/plain");
  8691. });
  8692. svr.Get("/header_field_value_check",
  8693. [&](const Request & /*req*/, Response &res) {
  8694. res.set_content("ok", "text/plain");
  8695. });
  8696. svr.CustomRoute("PROPFIND", "/dav",
  8697. [&](const Request & /*req*/, Response &res) {
  8698. res.status = StatusCode::MultiStatus_207;
  8699. });
  8700. // Server read timeout must be longer than the client read timeout for the
  8701. // bug to reproduce, probably to force the server to process a request
  8702. // without a trailing blank line.
  8703. const time_t client_read_timeout_sec = 1;
  8704. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8705. bool listen_thread_ok = false;
  8706. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8707. auto se = detail::scope_exit([&] {
  8708. svr.stop();
  8709. t.join();
  8710. ASSERT_FALSE(svr.is_running());
  8711. EXPECT_TRUE(listen_thread_ok);
  8712. });
  8713. svr.wait_until_ready();
  8714. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8715. }
  8716. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8717. // A certain header line causes an exception if the header property is parsed
  8718. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8719. test_raw_request(
  8720. "GET /hi HTTP/1.1\r\n"
  8721. " : "
  8722. " "
  8723. " ");
  8724. }
  8725. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8726. // A certain header line causes an exception if the header property *name* is
  8727. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8728. // greedy matcher and requires backtracking when there are a lot of ":"
  8729. // characters.
  8730. // This occurs with libc++ but not libstdc++.
  8731. test_raw_request(
  8732. "GET /hi HTTP/1.1\r\n"
  8733. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8734. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8735. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8736. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8737. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8738. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8739. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8740. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8741. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8742. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8743. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8744. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8745. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8746. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8747. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8748. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8749. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8750. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8751. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8752. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8753. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8754. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8755. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8756. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8757. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8758. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8759. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8760. "&&&%%%");
  8761. }
  8762. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8763. // Make sure this doesn't crash the server.
  8764. // In a previous version of the header line regex, the "\r" rendered the line
  8765. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8766. // a new position where the leading white space ended and the field value
  8767. // began.
  8768. // The crash occurs with libc++ but not libstdc++.
  8769. test_raw_request("GET /hi HTTP/1.1\r\n"
  8770. "a:" +
  8771. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8772. "\r\n"
  8773. "\r\n");
  8774. }
  8775. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8776. std::string out;
  8777. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8778. "Content-Type: text/plain\r\n"
  8779. "Transfer-Encoding: chunked\r\n"
  8780. "\r\n"
  8781. "nothex\r\n",
  8782. &out);
  8783. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8784. }
  8785. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8786. std::string out;
  8787. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8788. "Content-Type: text/plain\r\n"
  8789. "Transfer-Encoding: chunked\r\n"
  8790. "\r\n"
  8791. "3\r\n"
  8792. "xyz\r\n"
  8793. "NaN\r\n",
  8794. &out);
  8795. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8796. }
  8797. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8798. std::string out;
  8799. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8800. "Content-Type: text/plain\r\n"
  8801. "Transfer-Encoding: chunked\r\n"
  8802. "\r\n"
  8803. // Length is too large for 64 bits.
  8804. "1ffffffffffffffff\r\n"
  8805. "xyz\r\n",
  8806. &out);
  8807. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8808. }
  8809. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8810. test_raw_request("GET /hi HTTP/1.1\r\n"
  8811. "Content-Type: text/plain\r\n\r");
  8812. }
  8813. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8814. std::string out;
  8815. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8816. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8817. }
  8818. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8819. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8820. std::string out;
  8821. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8822. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8823. }
  8824. }
  8825. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8826. std::string out;
  8827. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8828. "Connection: close\r\n\r\n",
  8829. &out);
  8830. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8831. }
  8832. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8833. Server svr;
  8834. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8835. EXPECT_TRUE(!req.remote_addr.empty());
  8836. });
  8837. thread t = thread([&] { svr.listen(HOST, PORT); });
  8838. auto se = detail::scope_exit([&] {
  8839. svr.stop();
  8840. t.join();
  8841. ASSERT_FALSE(svr.is_running());
  8842. });
  8843. svr.wait_until_ready();
  8844. // Send an invalid request line to trigger Bad Request
  8845. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8846. std::string out;
  8847. ASSERT_TRUE(send_request(5, bad_req, &out));
  8848. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8849. }
  8850. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8851. // answered right away rather than blocking on a read that waits for EOF.
  8852. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8853. std::string out;
  8854. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8855. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8856. }
  8857. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8858. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8859. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8860. for (const auto *method : methods) {
  8861. Server svr;
  8862. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8863. EXPECT_FALSE(svr.is_valid()) << method;
  8864. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8865. }
  8866. }
  8867. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8868. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8869. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8870. for (const auto *method : methods) {
  8871. Server svr;
  8872. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8873. EXPECT_FALSE(svr.is_valid()) << method;
  8874. }
  8875. }
  8876. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8877. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8878. "COPY", "MOVE", "LOCK",
  8879. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8880. Server svr;
  8881. for (const auto *method : methods) {
  8882. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8883. }
  8884. EXPECT_TRUE(svr.is_valid());
  8885. }
  8886. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8887. Server svr;
  8888. svr.CustomRoute("POST", "/x",
  8889. [](const Request &, Response &, const ContentReader &) {});
  8890. EXPECT_FALSE(svr.is_valid());
  8891. }
  8892. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8893. Server svr;
  8894. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8895. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8896. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8897. EXPECT_FALSE(svr.is_valid());
  8898. }
  8899. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8900. Server svr;
  8901. auto captured = Error::Success;
  8902. svr.set_error_logger(
  8903. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8904. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8905. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8906. }
  8907. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8908. std::string out;
  8909. std::string request(
  8910. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8911. test_raw_request(request, &out);
  8912. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8913. }
  8914. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8915. std::string out;
  8916. std::string request(
  8917. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8918. test_raw_request(request, &out);
  8919. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8920. }
  8921. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8922. std::string out;
  8923. std::string request(
  8924. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8925. test_raw_request(request, &out);
  8926. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8927. }
  8928. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8929. std::string out;
  8930. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8931. "Test: \r\n\r\n",
  8932. &out);
  8933. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8934. }
  8935. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8936. Server svr;
  8937. std::string x_custom;
  8938. std::string cookie;
  8939. std::string xff;
  8940. std::string x_unicode;
  8941. std::string x_iis;
  8942. svr.Get("/check", [&](const Request &req, Response &res) {
  8943. x_custom = req.get_header_value("X-Custom");
  8944. cookie = req.get_header_value("Cookie");
  8945. xff = req.get_header_value("X-Forwarded-For");
  8946. x_unicode = req.get_header_value("X-Unicode");
  8947. x_iis = req.get_header_value("X-IIS");
  8948. res.set_content("ok", "text/plain");
  8949. });
  8950. thread t = thread([&] { svr.listen(HOST, PORT); });
  8951. auto se = detail::scope_exit([&] {
  8952. svr.stop();
  8953. t.join();
  8954. ASSERT_FALSE(svr.is_running());
  8955. });
  8956. svr.wait_until_ready();
  8957. const std::string req = "GET /check HTTP/1.1\r\n"
  8958. "Host: localhost\r\n"
  8959. "X-Custom: a%0D%0AInjected: b\r\n"
  8960. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8961. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8962. "X-Unicode: %E3%81%82\r\n"
  8963. "X-IIS: %u00E9\r\n"
  8964. "Connection: close\r\n"
  8965. "\r\n";
  8966. std::string res;
  8967. ASSERT_TRUE(send_request(5, req, &res));
  8968. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8969. // Every value must be returned verbatim (wire form), with no decoding.
  8970. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8971. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8972. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8973. EXPECT_EQ("%E3%81%82", x_unicode);
  8974. EXPECT_EQ("%u00E9", x_iis);
  8975. }
  8976. // Applications that previously relied on automatic percent-decoding can
  8977. // reproduce the old behavior by explicitly calling decode_path_component()
  8978. // or, for RFC 3986 conformance, decode_uri_component().
  8979. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8980. Server svr;
  8981. std::string decoded;
  8982. svr.Get("/check", [&](const Request &req, Response &res) {
  8983. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8984. res.set_content("ok", "text/plain");
  8985. });
  8986. thread t = thread([&] { svr.listen(HOST, PORT); });
  8987. auto se = detail::scope_exit([&] {
  8988. svr.stop();
  8989. t.join();
  8990. ASSERT_FALSE(svr.is_running());
  8991. });
  8992. svr.wait_until_ready();
  8993. const std::string req = "GET /check HTTP/1.1\r\n"
  8994. "Host: localhost\r\n"
  8995. "X-Custom: hello%20world\r\n"
  8996. "Connection: close\r\n"
  8997. "\r\n";
  8998. std::string res;
  8999. ASSERT_TRUE(send_request(5, req, &res));
  9000. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9001. EXPECT_EQ("hello world", decoded);
  9002. }
  9003. // Regression test for #2033. Browsers send Referer values that include
  9004. // percent-encoded characters such as %0A inside the URL. Decoding the
  9005. // header value would either trip the post-decode CR/LF/NUL guard (the
  9006. // original bug, returning 400) or, after that guard was relaxed, silently
  9007. // store a literal LF — both unacceptable. The wire form must round-trip.
  9008. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9009. Server svr;
  9010. std::string referer;
  9011. svr.Get("/check", [&](const Request &req, Response &res) {
  9012. referer = req.get_header_value("Referer");
  9013. res.set_content("ok", "text/plain");
  9014. });
  9015. thread t = thread([&] { svr.listen(HOST, PORT); });
  9016. auto se = detail::scope_exit([&] {
  9017. svr.stop();
  9018. t.join();
  9019. ASSERT_FALSE(svr.is_running());
  9020. });
  9021. svr.wait_until_ready();
  9022. const std::string req = "GET /check HTTP/1.1\r\n"
  9023. "Host: localhost\r\n"
  9024. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9025. "Connection: close\r\n"
  9026. "\r\n";
  9027. std::string res;
  9028. ASSERT_TRUE(send_request(5, req, &res));
  9029. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9030. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9031. }
  9032. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9033. Server svr;
  9034. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9035. res.set_header("Cache-Control", "no-cache");
  9036. res.set_chunked_content_provider(
  9037. "text/event-stream", [](size_t offset, DataSink &sink) {
  9038. std::string s = "data:";
  9039. s += std::to_string(offset);
  9040. s += "\n\n";
  9041. auto ret = sink.write(s.data(), s.size());
  9042. EXPECT_TRUE(ret);
  9043. std::this_thread::sleep_for(std::chrono::seconds(1));
  9044. return true;
  9045. });
  9046. });
  9047. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9048. svr.wait_until_ready();
  9049. Client client(HOST, PORT);
  9050. const Headers headers = {{"Accept", "text/event-stream"}};
  9051. auto get_thread = std::thread([&client, &headers]() {
  9052. auto res = client.Get(
  9053. "/events", headers,
  9054. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9055. });
  9056. auto se = detail::scope_exit([&] {
  9057. svr.stop();
  9058. get_thread.join();
  9059. listen_thread.join();
  9060. ASSERT_FALSE(svr.is_running());
  9061. });
  9062. // Give GET time to get a few messages.
  9063. std::this_thread::sleep_for(std::chrono::seconds(2));
  9064. }
  9065. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9066. httplib::Server svr;
  9067. svr.Post("/hi",
  9068. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9069. res.status = StatusCode::OK_200;
  9070. });
  9071. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9072. svr.wait_until_ready();
  9073. Client cli(HOST, PORT);
  9074. auto res = cli.Post("/hi", "data", "text/plain");
  9075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9076. EXPECT_EQ(StatusCode::OK_200, res->status);
  9077. svr.stop();
  9078. thread.join();
  9079. ASSERT_FALSE(svr.is_running());
  9080. res = cli.Post("/hi", "data", "text/plain");
  9081. ASSERT_FALSE(res);
  9082. }
  9083. TEST(ServerStopTest, ListenFailure) {
  9084. Server svr;
  9085. auto t = thread([&]() {
  9086. auto ret = svr.listen("????", PORT);
  9087. EXPECT_FALSE(ret);
  9088. });
  9089. svr.wait_until_ready();
  9090. svr.stop();
  9091. t.join();
  9092. }
  9093. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9094. TEST(ServerStopTest, Decommision) {
  9095. Server svr;
  9096. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9097. for (int i = 0; i < 4; i++) {
  9098. auto is_even = !(i % 2);
  9099. std::thread t{[&] {
  9100. try {
  9101. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9102. if (is_even) {
  9103. throw std::runtime_error("Some thing that happens to go wrong.");
  9104. }
  9105. svr.listen(HOST, PORT);
  9106. } catch (...) { svr.decommission(); }
  9107. }};
  9108. svr.wait_until_ready();
  9109. // Server is up
  9110. {
  9111. Client cli(HOST, PORT);
  9112. auto res = cli.Get("/hi");
  9113. if (is_even) {
  9114. EXPECT_FALSE(res);
  9115. } else {
  9116. EXPECT_TRUE(res);
  9117. EXPECT_EQ("hi...", res->body);
  9118. }
  9119. }
  9120. svr.stop();
  9121. t.join();
  9122. // Server is down...
  9123. {
  9124. Client cli(HOST, PORT);
  9125. auto res = cli.Get("/hi");
  9126. EXPECT_FALSE(res);
  9127. }
  9128. }
  9129. }
  9130. #endif
  9131. // Helper function for string body upload progress tests
  9132. template <typename SetupHandler, typename ClientCall>
  9133. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9134. ClientCall &&client_call,
  9135. const string &body) {
  9136. Server svr;
  9137. setup_handler(svr);
  9138. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9139. auto se = detail::scope_exit([&] {
  9140. svr.stop();
  9141. t.join();
  9142. });
  9143. svr.wait_until_ready();
  9144. Client cli(HOST, PORT);
  9145. vector<uint64_t> progress_values;
  9146. bool progress_called = false;
  9147. auto res =
  9148. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9149. progress_values.push_back(current);
  9150. progress_called = true;
  9151. return true;
  9152. });
  9153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9154. EXPECT_EQ(200, res->status);
  9155. EXPECT_TRUE(progress_called);
  9156. }
  9157. TEST(UploadProgressTest, PostStringBodyBasic) {
  9158. TestStringBodyUploadProgress(
  9159. [](Server &svr) {
  9160. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9161. res.set_content("received", "text/plain");
  9162. });
  9163. },
  9164. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9165. return cli.Post("/test", body, "text/plain", progress_callback);
  9166. },
  9167. "test data for upload progress");
  9168. }
  9169. TEST(UploadProgressTest, PutStringBodyBasic) {
  9170. TestStringBodyUploadProgress(
  9171. [](Server &svr) {
  9172. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9173. res.set_content("put received", "text/plain");
  9174. });
  9175. },
  9176. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9177. return cli.Put("/test", body, "text/plain", progress_callback);
  9178. },
  9179. "put test data for upload progress");
  9180. }
  9181. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9182. TestStringBodyUploadProgress(
  9183. [](Server &svr) {
  9184. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9185. res.set_content("patch received", "text/plain");
  9186. });
  9187. },
  9188. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9189. return cli.Patch("/test", body, "text/plain", progress_callback);
  9190. },
  9191. "patch test data for upload progress");
  9192. }
  9193. // Helper function for content provider upload progress tests
  9194. template <typename SetupHandler, typename ClientCall>
  9195. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9196. ClientCall &&client_call) {
  9197. Server svr;
  9198. setup_handler(svr);
  9199. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9200. auto se = detail::scope_exit([&] {
  9201. svr.stop();
  9202. t.join();
  9203. });
  9204. svr.wait_until_ready();
  9205. Client cli(HOST, PORT);
  9206. vector<uint64_t> progress_values;
  9207. auto res =
  9208. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9209. progress_values.push_back(current);
  9210. return true;
  9211. });
  9212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9213. EXPECT_EQ(200, res->status);
  9214. EXPECT_FALSE(progress_values.empty());
  9215. }
  9216. TEST(UploadProgressTest, PostContentProviderProgress) {
  9217. TestContentProviderUploadProgress(
  9218. [](Server &svr) {
  9219. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9220. res.set_content("provider received", "text/plain");
  9221. });
  9222. },
  9223. [](Client &cli, UploadProgress progress_callback) {
  9224. return cli.Post(
  9225. "/test", 10,
  9226. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9227. sink.os << "test data";
  9228. return true;
  9229. },
  9230. "text/plain", progress_callback);
  9231. });
  9232. }
  9233. // Helper function for multipart upload progress tests
  9234. template <typename SetupHandler, typename ClientCall>
  9235. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9236. ClientCall &&client_call,
  9237. const string &endpoint) {
  9238. Server svr;
  9239. setup_handler(svr);
  9240. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9241. auto se = detail::scope_exit([&] {
  9242. svr.stop();
  9243. t.join();
  9244. });
  9245. svr.wait_until_ready();
  9246. Client cli(HOST, PORT);
  9247. vector<uint64_t> progress_values;
  9248. UploadFormDataItems items = {
  9249. {"field1", "value1", "", ""},
  9250. {"field2", "longer value for progress tracking test", "", ""},
  9251. {"file1", "file content data for upload progress", "test.txt",
  9252. "text/plain"}};
  9253. auto res = client_call(cli, endpoint, items,
  9254. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9255. progress_values.push_back(current);
  9256. return true;
  9257. });
  9258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9259. EXPECT_EQ(200, res->status);
  9260. EXPECT_FALSE(progress_values.empty());
  9261. }
  9262. TEST(UploadProgressTest, PostMultipartProgress) {
  9263. TestMultipartUploadProgress(
  9264. [](Server &svr) {
  9265. svr.Post("/multipart", [](const Request &req, Response &res) {
  9266. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9267. res.set_content("multipart received", "text/plain");
  9268. });
  9269. },
  9270. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9271. UploadProgress progress_callback) {
  9272. return cli.Post(endpoint, items, progress_callback);
  9273. },
  9274. "/multipart");
  9275. }
  9276. // Helper function for basic download progress tests
  9277. template <typename SetupHandler, typename ClientCall>
  9278. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9279. ClientCall &&client_call, const string &endpoint,
  9280. size_t expected_content_size) {
  9281. Server svr;
  9282. setup_handler(svr);
  9283. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9284. auto se = detail::scope_exit([&] {
  9285. svr.stop();
  9286. t.join();
  9287. });
  9288. svr.wait_until_ready();
  9289. Client cli(HOST, PORT);
  9290. vector<uint64_t> progress_values;
  9291. auto res = client_call(cli, endpoint,
  9292. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9293. progress_values.push_back(current);
  9294. return true;
  9295. });
  9296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9297. EXPECT_EQ(200, res->status);
  9298. EXPECT_FALSE(progress_values.empty());
  9299. EXPECT_EQ(expected_content_size, res->body.size());
  9300. }
  9301. TEST(DownloadProgressTest, GetBasic) {
  9302. TestBasicDownloadProgress(
  9303. [](Server &svr) {
  9304. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9305. string content(1000, 'D');
  9306. res.set_content(content, "text/plain");
  9307. });
  9308. },
  9309. [](Client &cli, const string &endpoint,
  9310. DownloadProgress progress_callback) {
  9311. return cli.Get(endpoint, progress_callback);
  9312. },
  9313. "/download", 1000u);
  9314. }
  9315. // Helper function for content receiver download progress tests
  9316. template <typename SetupHandler, typename ClientCall>
  9317. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9318. ClientCall &&client_call,
  9319. const string &endpoint,
  9320. size_t expected_content_size) {
  9321. Server svr;
  9322. setup_handler(svr);
  9323. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9324. auto se = detail::scope_exit([&] {
  9325. svr.stop();
  9326. t.join();
  9327. });
  9328. svr.wait_until_ready();
  9329. Client cli(HOST, PORT);
  9330. vector<uint64_t> progress_values;
  9331. string received_body;
  9332. auto res = client_call(
  9333. cli, endpoint,
  9334. [&](const char *data, size_t data_length) -> bool {
  9335. received_body.append(data, data_length);
  9336. return true;
  9337. },
  9338. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9339. progress_values.push_back(current);
  9340. return true;
  9341. });
  9342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9343. EXPECT_EQ(200, res->status);
  9344. EXPECT_FALSE(progress_values.empty());
  9345. EXPECT_EQ(expected_content_size, received_body.size());
  9346. EXPECT_TRUE(res->body.empty());
  9347. }
  9348. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9349. TestContentReceiverDownloadProgress(
  9350. [](Server &svr) {
  9351. svr.Get("/download-receiver",
  9352. [](const Request & /*req*/, Response &res) {
  9353. string content(2000, 'R');
  9354. res.set_content(content, "text/plain");
  9355. });
  9356. },
  9357. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9358. DownloadProgress progress_callback) {
  9359. return cli.Get(endpoint, content_receiver, progress_callback);
  9360. },
  9361. "/download-receiver", 2000u);
  9362. }
  9363. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9364. // A provider reaching a pass with nothing to hand over - an empty buffer
  9365. // popped off a queue, say - must not be taken to mean the body is finished.
  9366. // It used to end the loop with the terminating chunk unwritten while the
  9367. // server still considered the response complete, so the peer waited for an
  9368. // end that never arrived.
  9369. Server svr;
  9370. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9371. auto step = std::make_shared<int>(0);
  9372. res.set_chunked_content_provider("text/plain",
  9373. [step](size_t /*offset*/, DataSink &sink) {
  9374. switch ((*step)++) {
  9375. case 0: sink.write("", 0); break;
  9376. case 1: sink.write("hello", 5); break;
  9377. default: sink.done(); break;
  9378. }
  9379. return true;
  9380. });
  9381. });
  9382. auto port = svr.bind_to_any_port(HOST);
  9383. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9384. auto listen_se = detail::scope_exit([&] {
  9385. svr.stop();
  9386. listen_thread.join();
  9387. ASSERT_FALSE(svr.is_running());
  9388. });
  9389. svr.wait_until_ready();
  9390. Client cli(HOST, port);
  9391. // Without the fix the body is never terminated, so bound the wait rather
  9392. // than letting the test hang on the default read timeout.
  9393. cli.set_read_timeout(5, 0);
  9394. auto res = cli.Get("/stream");
  9395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9396. EXPECT_EQ(StatusCode::OK_200, res->status);
  9397. EXPECT_EQ("hello", res->body);
  9398. }
  9399. TEST(StreamingTest, NoContentLengthStreaming) {
  9400. Server svr;
  9401. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9402. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9403. if (offset < 6) {
  9404. sink.os << (offset < 3 ? "a" : "b");
  9405. } else {
  9406. sink.done();
  9407. }
  9408. return true;
  9409. });
  9410. });
  9411. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9412. auto listen_se = detail::scope_exit([&] {
  9413. svr.stop();
  9414. listen_thread.join();
  9415. ASSERT_FALSE(svr.is_running());
  9416. });
  9417. svr.wait_until_ready();
  9418. Client client(HOST, PORT);
  9419. auto get_thread = std::thread([&client]() {
  9420. std::string s;
  9421. auto res =
  9422. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9423. s += std::string(data, len);
  9424. return true;
  9425. });
  9426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9427. EXPECT_EQ(StatusCode::OK_200, res->status);
  9428. EXPECT_EQ("aaabbb", s);
  9429. });
  9430. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9431. // Give GET time to get a few messages.
  9432. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9433. }
  9434. TEST(MountTest, Unmount) {
  9435. Server svr;
  9436. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9437. auto se = detail::scope_exit([&] {
  9438. svr.stop();
  9439. listen_thread.join();
  9440. ASSERT_FALSE(svr.is_running());
  9441. });
  9442. svr.wait_until_ready();
  9443. Client cli("localhost", PORT);
  9444. svr.set_mount_point("/mount2", "./www2");
  9445. auto res = cli.Get("/");
  9446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9447. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9448. res = cli.Get("/mount2/dir/test.html");
  9449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9450. EXPECT_EQ(StatusCode::OK_200, res->status);
  9451. svr.set_mount_point("/", "./www");
  9452. res = cli.Get("/dir/");
  9453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9454. EXPECT_EQ(StatusCode::OK_200, res->status);
  9455. svr.remove_mount_point("/");
  9456. res = cli.Get("/dir/");
  9457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9459. svr.remove_mount_point("/mount2");
  9460. res = cli.Get("/mount2/dir/test.html");
  9461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9462. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9463. }
  9464. TEST(MountTest, PathSegmentBoundary) {
  9465. Server svr;
  9466. svr.set_mount_point("/mount2", "./www2");
  9467. svr.set_mount_point("/", "./www");
  9468. auto port = svr.bind_to_any_port(HOST);
  9469. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9470. auto se = detail::scope_exit([&] {
  9471. svr.stop();
  9472. listen_thread.join();
  9473. ASSERT_FALSE(svr.is_running());
  9474. });
  9475. svr.wait_until_ready();
  9476. Client cli(HOST, port);
  9477. auto res = cli.Get("/mount2/dir/test.html");
  9478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9479. EXPECT_EQ(StatusCode::OK_200, res->status);
  9480. // "/mount2" must not match part-way through a path segment.
  9481. res = cli.Get("/mount2dir/test.html");
  9482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9483. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9484. // A mount point ending in '/' keeps matching every path below it.
  9485. res = cli.Get("/dir/test.html");
  9486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9487. EXPECT_EQ(StatusCode::OK_200, res->status);
  9488. }
  9489. TEST(MountTest, Redicect) {
  9490. Server svr;
  9491. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9492. auto se = detail::scope_exit([&] {
  9493. svr.stop();
  9494. listen_thread.join();
  9495. ASSERT_FALSE(svr.is_running());
  9496. });
  9497. svr.set_mount_point("/", "./www");
  9498. svr.wait_until_ready();
  9499. Client cli("localhost", PORT);
  9500. auto res = cli.Get("/dir/");
  9501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9502. EXPECT_EQ(StatusCode::OK_200, res->status);
  9503. res = cli.Get("/dir");
  9504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9505. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9506. res = cli.Get("/file");
  9507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9508. EXPECT_EQ(StatusCode::OK_200, res->status);
  9509. res = cli.Get("/file/");
  9510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9511. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9512. cli.set_follow_location(true);
  9513. res = cli.Get("/dir");
  9514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9515. EXPECT_EQ(StatusCode::OK_200, res->status);
  9516. }
  9517. TEST(MountTest, MultibytesPathName) {
  9518. Server svr;
  9519. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9520. auto se = detail::scope_exit([&] {
  9521. svr.stop();
  9522. listen_thread.join();
  9523. ASSERT_FALSE(svr.is_running());
  9524. });
  9525. svr.set_mount_point("/", "./www");
  9526. svr.wait_until_ready();
  9527. Client cli("localhost", PORT);
  9528. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9530. EXPECT_EQ(StatusCode::OK_200, res->status);
  9531. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9532. }
  9533. #ifdef _WIN32
  9534. // Issue #2435: mmap::open() must succeed even when another handle holds
  9535. // the file open for writing (e.g. an active log file).
  9536. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9537. const char *path = "mmap_concurrent_writer_test.txt";
  9538. const char *content = "hello";
  9539. {
  9540. std::ofstream f(path, std::ios::binary);
  9541. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9542. }
  9543. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9544. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9545. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9546. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9547. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9548. detail::mmap m(path);
  9549. ASSERT_TRUE(m.is_open());
  9550. EXPECT_EQ(strlen(content), m.size());
  9551. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9552. }
  9553. #endif
  9554. #ifndef _WIN32
  9555. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9556. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9557. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9558. TEST(MmapTest, FailedMappingIsNotOpen) {
  9559. const char *path = "./mmap_failed_mapping_test_dir";
  9560. ASSERT_EQ(0, ::mkdir(path, 0755));
  9561. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9562. detail::mmap m(path);
  9563. EXPECT_FALSE(m.is_open());
  9564. EXPECT_EQ(0U, m.size());
  9565. EXPECT_NE(static_cast<const void *>(m.data()),
  9566. static_cast<const void *>(MAP_FAILED));
  9567. }
  9568. #endif
  9569. TEST(KeepAliveTest, ReadTimeout) {
  9570. Server svr;
  9571. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9572. std::this_thread::sleep_for(std::chrono::seconds(2));
  9573. res.set_content("a", "text/plain");
  9574. });
  9575. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9576. res.set_content("b", "text/plain");
  9577. });
  9578. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9579. auto se = detail::scope_exit([&] {
  9580. svr.stop();
  9581. listen_thread.join();
  9582. ASSERT_FALSE(svr.is_running());
  9583. });
  9584. svr.wait_until_ready();
  9585. Client cli("localhost", PORT);
  9586. cli.set_keep_alive(true);
  9587. cli.set_read_timeout(std::chrono::seconds(1));
  9588. auto resa = cli.Get("/a");
  9589. ASSERT_FALSE(resa);
  9590. EXPECT_EQ(Error::Read, resa.error());
  9591. auto resb = cli.Get("/b");
  9592. ASSERT_TRUE(resb);
  9593. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9594. EXPECT_EQ("b", resb->body);
  9595. }
  9596. TEST(KeepAliveTest, MaxCount) {
  9597. size_t keep_alive_max_count = 3;
  9598. Server svr;
  9599. svr.set_keep_alive_max_count(keep_alive_max_count);
  9600. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9601. res.set_content("Hello World!", "text/plain");
  9602. });
  9603. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9604. auto se = detail::scope_exit([&] {
  9605. svr.stop();
  9606. listen_thread.join();
  9607. ASSERT_FALSE(svr.is_running());
  9608. });
  9609. svr.wait_until_ready();
  9610. Client cli(HOST, PORT);
  9611. cli.set_keep_alive(true);
  9612. for (size_t i = 0; i < 5; i++) {
  9613. auto result = cli.Get("/hi");
  9614. ASSERT_TRUE(result);
  9615. EXPECT_EQ(StatusCode::OK_200, result->status);
  9616. if (i == keep_alive_max_count - 1) {
  9617. EXPECT_EQ("close", result->get_header_value("Connection"));
  9618. } else {
  9619. EXPECT_FALSE(result->has_header("Connection"));
  9620. }
  9621. }
  9622. }
  9623. TEST(KeepAliveTest, Issue1041) {
  9624. Server svr;
  9625. svr.set_keep_alive_timeout(3);
  9626. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9627. res.set_content("Hello World!", "text/plain");
  9628. });
  9629. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9630. auto se = detail::scope_exit([&] {
  9631. svr.stop();
  9632. listen_thread.join();
  9633. ASSERT_FALSE(svr.is_running());
  9634. });
  9635. svr.wait_until_ready();
  9636. Client cli(HOST, PORT);
  9637. cli.set_keep_alive(true);
  9638. auto result = cli.Get("/hi");
  9639. ASSERT_TRUE(result);
  9640. EXPECT_EQ(StatusCode::OK_200, result->status);
  9641. std::this_thread::sleep_for(std::chrono::seconds(5));
  9642. result = cli.Get("/hi");
  9643. ASSERT_TRUE(result);
  9644. EXPECT_EQ(StatusCode::OK_200, result->status);
  9645. }
  9646. TEST(KeepAliveTest, Issue1959) {
  9647. Server svr;
  9648. svr.set_keep_alive_timeout(5);
  9649. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9650. res.set_content("a", "text/plain");
  9651. });
  9652. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9653. auto se = detail::scope_exit([&] {
  9654. if (!svr.is_running()) return;
  9655. svr.stop();
  9656. listen_thread.join();
  9657. ASSERT_FALSE(svr.is_running());
  9658. });
  9659. svr.wait_until_ready();
  9660. Client cli("localhost", PORT);
  9661. cli.set_keep_alive(true);
  9662. using namespace std::chrono;
  9663. auto start = steady_clock::now();
  9664. cli.Get("/a");
  9665. svr.stop();
  9666. listen_thread.join();
  9667. auto end = steady_clock::now();
  9668. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9669. EXPECT_LT(elapsed, 5000);
  9670. }
  9671. #ifdef CPPHTTPLIB_SSL_ENABLED
  9672. TEST(KeepAliveTest, SSLClientReconnection) {
  9673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9674. ASSERT_TRUE(svr.is_valid());
  9675. svr.set_keep_alive_timeout(1);
  9676. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9677. res.set_content("Hello World!", "text/plain");
  9678. });
  9679. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9680. auto se = detail::scope_exit([&] {
  9681. svr.stop();
  9682. listen_thread.join();
  9683. ASSERT_FALSE(svr.is_running());
  9684. });
  9685. svr.wait_until_ready();
  9686. SSLClient cli(HOST, PORT);
  9687. cli.enable_server_certificate_verification(false);
  9688. cli.set_keep_alive(true);
  9689. auto result = cli.Get("/hi");
  9690. ASSERT_TRUE(result);
  9691. EXPECT_EQ(StatusCode::OK_200, result->status);
  9692. result = cli.Get("/hi");
  9693. ASSERT_TRUE(result);
  9694. EXPECT_EQ(StatusCode::OK_200, result->status);
  9695. std::this_thread::sleep_for(std::chrono::seconds(2));
  9696. // Recoonect
  9697. result = cli.Get("/hi");
  9698. ASSERT_TRUE(result);
  9699. EXPECT_EQ(StatusCode::OK_200, result->status);
  9700. result = cli.Get("/hi");
  9701. ASSERT_TRUE(result);
  9702. EXPECT_EQ(StatusCode::OK_200, result->status);
  9703. }
  9704. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9706. ASSERT_TRUE(svr.is_valid());
  9707. svr.set_keep_alive_timeout(1);
  9708. std::string content = "reconnect";
  9709. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9710. res.set_content("Hello World!", "text/plain");
  9711. });
  9712. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9713. auto se = detail::scope_exit([&] {
  9714. svr.stop();
  9715. listen_thread.join();
  9716. ASSERT_FALSE(svr.is_running());
  9717. });
  9718. svr.wait_until_ready();
  9719. SSLClient cli(HOST, PORT);
  9720. cli.enable_server_certificate_verification(false);
  9721. cli.set_keep_alive(true);
  9722. auto result = cli.Post(
  9723. "/hi", content.size(),
  9724. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9725. sink.write(content.c_str(), content.size());
  9726. return true;
  9727. },
  9728. "text/plain");
  9729. ASSERT_TRUE(result);
  9730. EXPECT_EQ(200, result->status);
  9731. std::this_thread::sleep_for(std::chrono::seconds(2));
  9732. // Recoonect
  9733. result = cli.Post(
  9734. "/hi", content.size(),
  9735. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9736. sink.write(content.c_str(), content.size());
  9737. return true;
  9738. },
  9739. "text/plain");
  9740. ASSERT_TRUE(result);
  9741. EXPECT_EQ(200, result->status);
  9742. result = cli.Post(
  9743. "/hi", content.size(),
  9744. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9745. sink.write(content.c_str(), content.size());
  9746. return true;
  9747. },
  9748. "text/plain");
  9749. ASSERT_TRUE(result);
  9750. EXPECT_EQ(200, result->status);
  9751. }
  9752. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9753. using namespace httplib::tls;
  9754. {
  9755. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9756. ASSERT_TRUE(svr.is_valid());
  9757. svr.Get("/sni", [&](const Request &req, Response &res) {
  9758. std::string expected = req.sni();
  9759. EXPECT_EQ(expected, req.get_param_value("expected"));
  9760. res.set_content("ok", "text/plain");
  9761. });
  9762. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9763. auto se = detail::scope_exit([&] {
  9764. svr.stop();
  9765. listen_thread.join();
  9766. ASSERT_FALSE(svr.is_running());
  9767. });
  9768. svr.wait_until_ready();
  9769. {
  9770. SSLClient cli("localhost", PORT);
  9771. cli.enable_server_certificate_verification(false);
  9772. auto res = cli.Get("/sni?expected=localhost");
  9773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9774. }
  9775. {
  9776. SSLClient cli("::1", PORT);
  9777. cli.enable_server_certificate_verification(false);
  9778. auto res = cli.Get("/sni?expected=");
  9779. // NOTE: This may fail if the server is listening on IPv4 only
  9780. // (e.g., when localhost resolves to 127.0.0.1 only)
  9781. if (res) {
  9782. EXPECT_EQ(StatusCode::OK_200, res->status);
  9783. } else {
  9784. EXPECT_EQ(Error::Connection, res.error());
  9785. }
  9786. }
  9787. }
  9788. }
  9789. #endif
  9790. TEST(ClientProblemDetectionTest, ContentProvider) {
  9791. Server svr;
  9792. size_t content_length = 1024 * 1024;
  9793. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9794. res.set_content_provider(
  9795. content_length, "text/plain",
  9796. [&](size_t offset, size_t length, DataSink &sink) {
  9797. auto out_len = std::min(length, static_cast<size_t>(1024));
  9798. std::string out(out_len, '@');
  9799. sink.write(out.data(), out_len);
  9800. return offset < 4096;
  9801. },
  9802. [](bool success) { ASSERT_FALSE(success); });
  9803. });
  9804. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9805. res.set_content_provider(
  9806. 0, "text/plain",
  9807. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9808. EXPECT_TRUE(false);
  9809. return true;
  9810. },
  9811. [](bool success) { ASSERT_FALSE(success); });
  9812. });
  9813. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9814. auto se = detail::scope_exit([&] {
  9815. svr.stop();
  9816. listen_thread.join();
  9817. ASSERT_FALSE(svr.is_running());
  9818. });
  9819. svr.wait_until_ready();
  9820. Client cli("localhost", PORT);
  9821. {
  9822. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9823. size_t /*data_length*/) { return false; });
  9824. ASSERT_FALSE(res);
  9825. }
  9826. {
  9827. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9828. size_t /*data_length*/) { return false; });
  9829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9830. }
  9831. }
  9832. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9833. // A provider that reports success without writing anything and without
  9834. // calling done() used to be handed the same offset and length again on every
  9835. // pass, so it spun for as long as the peer stayed connected.
  9836. Server svr;
  9837. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9838. res.set_content("ok", "text/plain");
  9839. });
  9840. auto port = svr.bind_to_any_port(HOST);
  9841. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  9842. auto se = detail::scope_exit([&] {
  9843. svr.stop();
  9844. listen_thread.join();
  9845. ASSERT_FALSE(svr.is_running());
  9846. });
  9847. svr.wait_until_ready();
  9848. std::atomic<int> call_count{0};
  9849. Client cli(HOST, port);
  9850. auto res = cli.Post(
  9851. "/", 1024,
  9852. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9853. // Give up after enough passes to show the spin, so that losing the
  9854. // check below fails this test instead of hanging it.
  9855. return ++call_count < 100;
  9856. },
  9857. "text/plain");
  9858. ASSERT_FALSE(res);
  9859. EXPECT_EQ(Error::Write, res.error());
  9860. EXPECT_EQ(1, call_count.load());
  9861. }
  9862. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9863. // A writer only has to assign `write`. The other three used to be left as
  9864. // empty std::functions, so a provider calling one threw
  9865. // std::bad_function_call out of the thread running it and took the whole
  9866. // process down.
  9867. DataSink sink;
  9868. std::string written;
  9869. sink.write = [&](const char *data, size_t data_len) {
  9870. written.append(data, data_len);
  9871. return true;
  9872. };
  9873. EXPECT_TRUE(sink.is_writable());
  9874. sink.done();
  9875. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9876. EXPECT_TRUE(written.empty());
  9877. }
  9878. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9879. // A sink that cannot carry trailers still has to finish.
  9880. DataSink sink;
  9881. auto done_count = 0;
  9882. sink.done = [&]() { done_count++; };
  9883. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9884. EXPECT_EQ(1, done_count);
  9885. }
  9886. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9887. Server svr;
  9888. const std::string body(4096, 'x');
  9889. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9890. res.set_content_provider(body.size(), "text/plain",
  9891. [&](size_t offset, size_t length, DataSink &sink) {
  9892. sink.write(body.data() + offset, length);
  9893. sink.done();
  9894. return true;
  9895. });
  9896. });
  9897. auto port = svr.bind_to_any_port(HOST);
  9898. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9899. auto se = detail::scope_exit([&] {
  9900. svr.stop();
  9901. listen_thread.join();
  9902. ASSERT_FALSE(svr.is_running());
  9903. });
  9904. svr.wait_until_ready();
  9905. Client cli(HOST, port);
  9906. auto res = cli.Get("/");
  9907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9908. EXPECT_EQ(StatusCode::OK_200, res->status);
  9909. EXPECT_EQ(body, res->body);
  9910. }
  9911. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9912. Server svr;
  9913. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9914. res.set_content_provider(
  9915. 1024, "text/plain",
  9916. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9917. sink.write("hello", 5);
  9918. sink.done(); // short of the 1024 bytes the response promised
  9919. return true;
  9920. });
  9921. });
  9922. auto port = svr.bind_to_any_port(HOST);
  9923. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9924. auto se = detail::scope_exit([&] {
  9925. svr.stop();
  9926. listen_thread.join();
  9927. ASSERT_FALSE(svr.is_running());
  9928. });
  9929. svr.wait_until_ready();
  9930. Client cli(HOST, port);
  9931. cli.set_read_timeout(5, 0);
  9932. // The response is short of its Content-Length, so the client cannot read a
  9933. // complete body. What matters is that this returns at all: a no-op done()
  9934. // would leave the writer looping over a provider that never makes progress.
  9935. auto res = cli.Get("/");
  9936. EXPECT_FALSE(res);
  9937. }
  9938. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9939. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9940. // The compressed path builds the whole body before connecting, so this
  9941. // fails client-side and never reaches a server.
  9942. Client cli(HOST, PORT);
  9943. cli.set_compress(true);
  9944. auto res = cli.Post(
  9945. "/", 1024,
  9946. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9947. sink.write("hello", 5);
  9948. sink.done(); // short of the 1024 bytes the request announced
  9949. return true;
  9950. },
  9951. "text/plain");
  9952. ASSERT_FALSE(res);
  9953. EXPECT_EQ(Error::Write, res.error());
  9954. }
  9955. #endif
  9956. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9957. Server svr;
  9958. svr.set_error_handler([](Request const &, Response &res) -> void {
  9959. res.set_chunked_content_provider(
  9960. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9961. sink.os << "hello";
  9962. sink.os << "world";
  9963. sink.done();
  9964. return true;
  9965. });
  9966. });
  9967. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9968. auto se = detail::scope_exit([&] {
  9969. svr.stop();
  9970. listen_thread.join();
  9971. ASSERT_FALSE(svr.is_running());
  9972. });
  9973. svr.wait_until_ready();
  9974. Client cli("localhost", PORT);
  9975. auto res = cli.Get("/");
  9976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9978. EXPECT_EQ("helloworld", res->body);
  9979. }
  9980. TEST(LongPollingTest, ClientCloseDetection) {
  9981. Server svr;
  9982. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9983. res.set_chunked_content_provider(
  9984. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9985. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9986. sink.os << "hello";
  9987. auto count = 10;
  9988. while (count > 0 && sink.is_writable()) {
  9989. this_thread::sleep_for(chrono::milliseconds(10));
  9990. count--;
  9991. }
  9992. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9993. return true;
  9994. });
  9995. });
  9996. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9997. auto se = detail::scope_exit([&] {
  9998. svr.stop();
  9999. listen_thread.join();
  10000. ASSERT_FALSE(svr.is_running());
  10001. });
  10002. svr.wait_until_ready();
  10003. Client cli("localhost", PORT);
  10004. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10005. EXPECT_EQ("hello", string(data, data_length));
  10006. return false; // close the socket immediately.
  10007. });
  10008. ASSERT_FALSE(res);
  10009. }
  10010. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10011. Server svr;
  10012. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10013. res.set_chunked_content_provider(
  10014. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10015. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10016. sink.os << "hello";
  10017. EXPECT_TRUE(sink.os.good());
  10018. // Wait for the client to close the connection
  10019. auto count = 10;
  10020. while (count > 0 && sink.is_writable()) {
  10021. this_thread::sleep_for(chrono::milliseconds(10));
  10022. count--;
  10023. }
  10024. // After client disconnect, write repeatedly until the socket
  10025. // write actually fails (small writes may be absorbed by the
  10026. // kernel buffer)
  10027. std::string chunk(1024, 'x');
  10028. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10029. sink.os << chunk;
  10030. }
  10031. EXPECT_TRUE(sink.os.fail());
  10032. return true;
  10033. });
  10034. });
  10035. auto port = svr.bind_to_any_port("localhost");
  10036. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10037. auto se = detail::scope_exit([&] {
  10038. svr.stop();
  10039. listen_thread.join();
  10040. ASSERT_FALSE(svr.is_running());
  10041. });
  10042. svr.wait_until_ready();
  10043. Client cli("localhost", port);
  10044. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10045. EXPECT_EQ("hello", string(data, data_length));
  10046. return false; // close the socket immediately.
  10047. });
  10048. ASSERT_FALSE(res);
  10049. }
  10050. TEST(GetWithParametersTest, GetWithParameters) {
  10051. Server svr;
  10052. svr.Get("/", [&](const Request &req, Response &) {
  10053. EXPECT_EQ("world", req.get_param_value("hello"));
  10054. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10055. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10056. });
  10057. svr.Get("/params", [&](const Request &req, Response &) {
  10058. EXPECT_EQ("world", req.get_param_value("hello"));
  10059. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10060. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10061. });
  10062. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10063. EXPECT_EQ("resource-id", req.matches[1]);
  10064. EXPECT_EQ("foo", req.get_param_value("param1"));
  10065. EXPECT_EQ("bar", req.get_param_value("param2"));
  10066. });
  10067. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10068. EXPECT_EQ("user-id", req.path_params.at("id"));
  10069. EXPECT_EQ("foo", req.get_param_value("param1"));
  10070. EXPECT_EQ("bar", req.get_param_value("param2"));
  10071. });
  10072. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, 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. {
  10080. Client cli(HOST, PORT);
  10081. Params params;
  10082. params.emplace("hello", "world");
  10083. params.emplace("hello2", "world2");
  10084. params.emplace("hello3", "world3");
  10085. auto res = cli.Get("/", params, Headers{});
  10086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10087. EXPECT_EQ(StatusCode::OK_200, res->status);
  10088. }
  10089. {
  10090. Client cli(HOST, PORT);
  10091. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10093. EXPECT_EQ(StatusCode::OK_200, res->status);
  10094. }
  10095. {
  10096. Client cli(HOST, PORT);
  10097. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10099. EXPECT_EQ(StatusCode::OK_200, res->status);
  10100. }
  10101. {
  10102. Client cli(HOST, PORT);
  10103. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10105. EXPECT_EQ(StatusCode::OK_200, res->status);
  10106. }
  10107. }
  10108. TEST(GetWithParametersTest, GetWithParameters2) {
  10109. Server svr;
  10110. svr.Get("/", [&](const Request &req, Response &res) {
  10111. auto text = req.get_param_value("hello");
  10112. res.set_content(text, "text/plain");
  10113. });
  10114. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10115. auto se = detail::scope_exit([&] {
  10116. svr.stop();
  10117. listen_thread.join();
  10118. ASSERT_FALSE(svr.is_running());
  10119. });
  10120. svr.wait_until_ready();
  10121. Client cli("localhost", PORT);
  10122. Params params;
  10123. params.emplace("hello", "world");
  10124. std::string body;
  10125. auto res = cli.Get("/", params, Headers{},
  10126. [&](const char *data, size_t data_length) {
  10127. body.append(data, data_length);
  10128. return true;
  10129. });
  10130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10131. EXPECT_EQ(StatusCode::OK_200, res->status);
  10132. EXPECT_EQ("world", body);
  10133. }
  10134. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10135. Server svr;
  10136. svr.Get("/search", [&](const Request &req, Response &res) {
  10137. auto q = req.get_param_value("q");
  10138. res.set_content(q, "text/plain");
  10139. });
  10140. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10141. auto se = detail::scope_exit([&] {
  10142. svr.stop();
  10143. listen_thread.join();
  10144. ASSERT_FALSE(svr.is_running());
  10145. });
  10146. svr.wait_until_ready();
  10147. Client cli("localhost", PORT);
  10148. // Verify that Get(path, params) works without requiring Headers argument
  10149. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10151. EXPECT_EQ(StatusCode::OK_200, res->status);
  10152. EXPECT_EQ("cpp-httplib", res->body);
  10153. }
  10154. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10155. auto host = "httpbingo.org";
  10156. auto path = std::string{"/range/32"};
  10157. #ifdef CPPHTTPLIB_SSL_ENABLED
  10158. SSLClient cli(host);
  10159. #else
  10160. Client cli(host);
  10161. #endif
  10162. cli.set_default_headers({make_range_header({{1, 10}})});
  10163. cli.set_connection_timeout(5);
  10164. {
  10165. auto res = cli.Get(path);
  10166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10167. EXPECT_EQ("bcdefghijk", res->body);
  10168. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10169. }
  10170. {
  10171. auto res = cli.Get(path);
  10172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10173. EXPECT_EQ("bcdefghijk", res->body);
  10174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10175. }
  10176. }
  10177. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10178. Server svr;
  10179. svr.set_default_headers({{"Hello", "World"}});
  10180. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10181. res.set_content("ok", "text/plain");
  10182. });
  10183. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10184. auto se = detail::scope_exit([&] {
  10185. svr.stop();
  10186. listen_thread.join();
  10187. ASSERT_FALSE(svr.is_running());
  10188. });
  10189. svr.wait_until_ready();
  10190. Client cli("localhost", PORT);
  10191. auto res = cli.Get("/");
  10192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10193. EXPECT_EQ(StatusCode::OK_200, res->status);
  10194. EXPECT_EQ("ok", res->body);
  10195. EXPECT_EQ("World", res->get_header_value("Hello"));
  10196. }
  10197. #ifdef CPPHTTPLIB_SSL_ENABLED
  10198. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10200. ASSERT_TRUE(svr.is_valid());
  10201. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10202. std::this_thread::sleep_for(std::chrono::seconds(2));
  10203. res.set_content("a", "text/plain");
  10204. });
  10205. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10206. res.set_content("b", "text/plain");
  10207. });
  10208. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10209. auto se = detail::scope_exit([&] {
  10210. svr.stop();
  10211. listen_thread.join();
  10212. ASSERT_FALSE(svr.is_running());
  10213. });
  10214. svr.wait_until_ready();
  10215. SSLClient cli("localhost", PORT);
  10216. cli.enable_server_certificate_verification(false);
  10217. cli.set_keep_alive(true);
  10218. cli.set_read_timeout(std::chrono::seconds(1));
  10219. auto resa = cli.Get("/a");
  10220. ASSERT_TRUE(!resa);
  10221. EXPECT_EQ(Error::Read, resa.error());
  10222. auto resb = cli.Get("/b");
  10223. ASSERT_TRUE(resb);
  10224. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10225. EXPECT_EQ("b", resb->body);
  10226. }
  10227. // Closing an idle keep-alive connection sends close_notify and returns. The
  10228. // server must not wait for the client's close_notify: an idle client never
  10229. // sends one, so the worker would be held until the read timeout expires, and
  10230. // stop() would wait for it.
  10231. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10233. ASSERT_TRUE(svr.is_valid());
  10234. svr.set_keep_alive_timeout(1);
  10235. svr.set_read_timeout(10, 0);
  10236. svr.Get("/", [](const Request &, Response &res) {
  10237. res.set_content("ok", "text/plain");
  10238. });
  10239. auto port = svr.bind_to_any_port(HOST);
  10240. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10241. auto se = detail::scope_exit([&] {
  10242. if (listen_thread.joinable()) {
  10243. svr.stop();
  10244. listen_thread.join();
  10245. }
  10246. });
  10247. svr.wait_until_ready();
  10248. SSLClient cli(HOST, port);
  10249. cli.enable_server_certificate_verification(false);
  10250. cli.set_keep_alive(true);
  10251. auto res = cli.Get("/");
  10252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10253. EXPECT_EQ(StatusCode::OK_200, res->status);
  10254. // Stay idle past the keep-alive timeout so the server closes the connection.
  10255. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10256. auto start = std::chrono::steady_clock::now();
  10257. svr.stop();
  10258. listen_thread.join();
  10259. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10260. std::chrono::steady_clock::now() - start)
  10261. .count();
  10262. EXPECT_LT(elapsed, 3000);
  10263. }
  10264. #endif
  10265. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10266. protected:
  10267. ServerTestWithAI_PASSIVE()
  10268. : cli_(HOST, PORT)
  10269. #ifdef CPPHTTPLIB_SSL_ENABLED
  10270. ,
  10271. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10272. #endif
  10273. {
  10274. #ifdef CPPHTTPLIB_SSL_ENABLED
  10275. cli_.enable_server_certificate_verification(false);
  10276. #endif
  10277. }
  10278. virtual void SetUp() {
  10279. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10280. res.set_content("Hello World!", "text/plain");
  10281. });
  10282. t_ = thread(
  10283. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10284. svr_.wait_until_ready();
  10285. }
  10286. virtual void TearDown() {
  10287. svr_.stop();
  10288. t_.join();
  10289. }
  10290. #ifdef CPPHTTPLIB_SSL_ENABLED
  10291. SSLClient cli_;
  10292. SSLServer svr_;
  10293. #else
  10294. Client cli_;
  10295. Server svr_;
  10296. #endif
  10297. thread t_;
  10298. };
  10299. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10300. auto res = cli_.Get("/hi");
  10301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10302. EXPECT_EQ(StatusCode::OK_200, res->status);
  10303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10304. EXPECT_EQ("Hello World!", res->body);
  10305. }
  10306. class ServerUpDownTest : public ::testing::Test {
  10307. protected:
  10308. ServerUpDownTest() : cli_(HOST, PORT) {}
  10309. virtual void SetUp() {
  10310. t_ = thread([&]() {
  10311. svr_.bind_to_any_port(HOST);
  10312. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10313. ASSERT_TRUE(svr_.listen_after_bind());
  10314. });
  10315. svr_.wait_until_ready();
  10316. }
  10317. virtual void TearDown() {
  10318. svr_.stop();
  10319. t_.join();
  10320. }
  10321. Client cli_;
  10322. Server svr_;
  10323. thread t_;
  10324. };
  10325. TEST_F(ServerUpDownTest, QuickStartStop) {
  10326. // Should not crash, especially when run with
  10327. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10328. }
  10329. class PayloadMaxLengthTest : public ::testing::Test {
  10330. protected:
  10331. PayloadMaxLengthTest()
  10332. : cli_(HOST, PORT)
  10333. #ifdef CPPHTTPLIB_SSL_ENABLED
  10334. ,
  10335. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10336. #endif
  10337. {
  10338. #ifdef CPPHTTPLIB_SSL_ENABLED
  10339. cli_.enable_server_certificate_verification(false);
  10340. #endif
  10341. }
  10342. virtual void SetUp() {
  10343. svr_.set_payload_max_length(8);
  10344. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10345. res.set_content("test", "text/plain");
  10346. });
  10347. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10348. svr_.wait_until_ready();
  10349. }
  10350. virtual void TearDown() {
  10351. svr_.stop();
  10352. t_.join();
  10353. }
  10354. #ifdef CPPHTTPLIB_SSL_ENABLED
  10355. SSLClient cli_;
  10356. SSLServer svr_;
  10357. #else
  10358. Client cli_;
  10359. Server svr_;
  10360. #endif
  10361. thread t_;
  10362. };
  10363. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10364. auto res = cli_.Post("/test", "123456789", "text/plain");
  10365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10366. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10367. res = cli_.Post("/test", "12345678", "text/plain");
  10368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10369. EXPECT_EQ(StatusCode::OK_200, res->status);
  10370. }
  10371. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10372. // Test chunked encoding with payload exceeding the 8-byte limit
  10373. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10374. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10376. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10377. }
  10378. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10379. // Test chunked encoding with payload within the 8-byte limit
  10380. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10381. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10383. EXPECT_EQ(StatusCode::OK_200, res->status);
  10384. }
  10385. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10386. // Test using send_request to send chunked data exceeding payload limit
  10387. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10388. "Host: " +
  10389. std::string(HOST) + ":" + std::to_string(PORT) +
  10390. "\r\n"
  10391. "Transfer-Encoding: chunked\r\n"
  10392. "Connection: close\r\n"
  10393. "\r\n"
  10394. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10395. "0123456789\r\n"
  10396. "0\r\n" // End chunk
  10397. "\r\n";
  10398. std::string response;
  10399. bool result = send_request(1, chunked_request, &response);
  10400. if (!result) {
  10401. // If send_request fails, it might be because the server closed the
  10402. // connection due to payload limit enforcement, which is acceptable
  10403. SUCCEED()
  10404. << "Server rejected oversized chunked request (connection closed)";
  10405. } else {
  10406. // If we got a response, check if it's an error response or connection was
  10407. // closed early Short response length indicates connection was closed due to
  10408. // payload limit
  10409. if (response.length() <= 10) {
  10410. SUCCEED() << "Server closed connection for oversized chunked request";
  10411. } else {
  10412. // Check for error status codes
  10413. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10414. response.find("Payload Too Large") != std::string::npos ||
  10415. response.find("400") != std::string::npos);
  10416. }
  10417. }
  10418. }
  10419. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10420. // Test request without Content-Length header exceeding payload limit
  10421. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10422. "Host: " +
  10423. std::string(HOST) + ":" +
  10424. std::to_string(PORT) +
  10425. "\r\n"
  10426. "Connection: close\r\n"
  10427. "\r\n";
  10428. // Add payload exceeding the 8-byte limit
  10429. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10430. request_without_content_length += large_payload;
  10431. std::string response;
  10432. bool result = send_request(1, request_without_content_length, &response);
  10433. if (!result) {
  10434. // If send_request fails, server likely closed connection due to payload
  10435. // limit
  10436. SUCCEED() << "Server rejected oversized request without Content-Length "
  10437. "(connection closed)";
  10438. } else {
  10439. // Check if server responded with error or closed connection early
  10440. if (response.length() <= 10) {
  10441. SUCCEED() << "Server closed connection for oversized request without "
  10442. "Content-Length";
  10443. } else {
  10444. // Check for error status codes
  10445. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10446. response.find("Payload Too Large") != std::string::npos ||
  10447. response.find("400") != std::string::npos);
  10448. }
  10449. }
  10450. }
  10451. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10452. // Test request without Content-Length header within payload limit
  10453. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10454. "Host: " +
  10455. std::string(HOST) + ":" +
  10456. std::to_string(PORT) +
  10457. "\r\n"
  10458. "Connection: close\r\n"
  10459. "\r\n";
  10460. // Add payload within the 8-byte limit
  10461. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10462. request_without_content_length += small_payload;
  10463. std::string response;
  10464. bool result = send_request(1, request_without_content_length, &response);
  10465. // For requests without Content-Length, the server may have different behavior
  10466. // The key is that it should not reject due to payload limit for small
  10467. // payloads
  10468. if (result) {
  10469. // Check for any HTTP response (success or error, but not connection closed)
  10470. if (response.length() > 10) {
  10471. SUCCEED()
  10472. << "Server processed request without Content-Length within limit";
  10473. } else {
  10474. // Short response might indicate connection closed, which is acceptable
  10475. SUCCEED() << "Server closed connection for request without "
  10476. "Content-Length (acceptable behavior)";
  10477. }
  10478. } else {
  10479. // Connection failure might be due to protocol requirements
  10480. SUCCEED() << "Connection issue with request without Content-Length "
  10481. "(environment-specific)";
  10482. }
  10483. }
  10484. class LargePayloadMaxLengthTest : public ::testing::Test {
  10485. protected:
  10486. LargePayloadMaxLengthTest()
  10487. : cli_(HOST, PORT)
  10488. #ifdef CPPHTTPLIB_SSL_ENABLED
  10489. ,
  10490. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10491. #endif
  10492. {
  10493. #ifdef CPPHTTPLIB_SSL_ENABLED
  10494. cli_.enable_server_certificate_verification(false);
  10495. #endif
  10496. }
  10497. virtual void SetUp() {
  10498. // Set 10MB payload limit
  10499. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10500. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10501. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10502. res.set_content("Large payload test", "text/plain");
  10503. });
  10504. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10505. svr_.wait_until_ready();
  10506. }
  10507. virtual void TearDown() {
  10508. svr_.stop();
  10509. t_.join();
  10510. }
  10511. #ifdef CPPHTTPLIB_SSL_ENABLED
  10512. SSLClient cli_;
  10513. SSLServer svr_;
  10514. #else
  10515. Client cli_;
  10516. Server svr_;
  10517. #endif
  10518. thread t_;
  10519. };
  10520. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10521. // Test chunked encoding with payload within 10MB limit
  10522. std::string medium_payload(5 * 1024 * 1024,
  10523. 'A'); // 5MB payload, within 10MB limit
  10524. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10526. EXPECT_EQ(StatusCode::OK_200, res->status);
  10527. }
  10528. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10529. // Test chunked encoding with payload exceeding 10MB limit
  10530. std::string large_payload(12 * 1024 * 1024,
  10531. 'B'); // 12MB payload, exceeds 10MB limit
  10532. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10533. // Server may either return 413 or close the connection
  10534. if (res) {
  10535. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10536. } else {
  10537. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10538. }
  10539. }
  10540. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10541. // Test request without Content-Length header within 10MB limit
  10542. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10543. "Host: " +
  10544. std::string(HOST) + ":" +
  10545. std::to_string(PORT) +
  10546. "\r\n"
  10547. "Connection: close\r\n"
  10548. "\r\n";
  10549. // Add 1MB payload (within 10MB limit)
  10550. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10551. request_without_content_length += medium_payload;
  10552. std::string response;
  10553. bool result = send_request(5, request_without_content_length, &response);
  10554. if (result) {
  10555. // Should get a proper HTTP response for payloads within limit
  10556. if (response.length() > 10) {
  10557. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10558. "10MB limit";
  10559. } else {
  10560. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10561. "Content-Length)";
  10562. }
  10563. } else {
  10564. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10565. }
  10566. }
  10567. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10568. // Test request without Content-Length header exceeding 10MB limit
  10569. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10570. "Host: " +
  10571. std::string(HOST) + ":" +
  10572. std::to_string(PORT) +
  10573. "\r\n"
  10574. "Connection: close\r\n"
  10575. "\r\n";
  10576. // Add 12MB payload (exceeds 10MB limit)
  10577. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10578. request_without_content_length += large_payload;
  10579. std::string response;
  10580. bool result = send_request(10, request_without_content_length, &response);
  10581. if (!result) {
  10582. // Server should close connection due to payload limit
  10583. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10584. "(connection closed)";
  10585. } else {
  10586. // Check for error response
  10587. if (response.length() <= 10) {
  10588. SUCCEED()
  10589. << "Server closed connection for 12MB request exceeding 10MB limit";
  10590. } else {
  10591. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10592. response.find("Payload Too Large") != std::string::npos ||
  10593. response.find("400") != std::string::npos);
  10594. }
  10595. }
  10596. }
  10597. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10598. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10599. // path.
  10600. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10601. Server svr;
  10602. const size_t LIMIT = 64 * 1024; // 64KB
  10603. svr.set_payload_max_length(LIMIT);
  10604. size_t total = 0;
  10605. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10606. const ContentReader &content_reader) {
  10607. content_reader([&](const char * /*data*/, size_t len) {
  10608. total += len;
  10609. return true;
  10610. });
  10611. res.status = 200;
  10612. res.set_content("stream_ok", "text/plain");
  10613. });
  10614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10615. auto se = detail::scope_exit([&] {
  10616. svr.stop();
  10617. thread.join();
  10618. ASSERT_FALSE(svr.is_running());
  10619. });
  10620. svr.wait_until_ready();
  10621. // Prepare 256KB raw data and gzip-compress it
  10622. std::string raw(256 * 1024, 'A');
  10623. std::string gz;
  10624. {
  10625. z_stream zs{};
  10626. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10627. Z_DEFAULT_STRATEGY);
  10628. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10629. zs.avail_in = static_cast<uInt>(raw.size());
  10630. char outbuf[4096];
  10631. int ret;
  10632. do {
  10633. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10634. zs.avail_out = sizeof(outbuf);
  10635. ret = deflate(&zs, Z_FINISH);
  10636. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10637. } while (ret != Z_STREAM_END);
  10638. deflateEnd(&zs);
  10639. }
  10640. Client cli(HOST, PORT);
  10641. cli.set_connection_timeout(std::chrono::seconds(5));
  10642. Headers headers = {{"Content-Encoding", "gzip"}};
  10643. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10644. "application/octet-stream");
  10645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10646. // Server must reject oversized decompressed payloads with 413.
  10647. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10648. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10649. EXPECT_LE(total, LIMIT);
  10650. }
  10651. #ifndef CPPHTTPLIB_SSL_ENABLED
  10652. // For a request with neither Content-Length nor Transfer-Encoding, the
  10653. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10654. // compressed wire bytes straight to the ContentReader without ever routing
  10655. // them through the decompressor, so payload_max_length_ only bounded the
  10656. // compressed size on the wire, not the decompressed size.
  10657. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10658. Server svr;
  10659. const size_t LIMIT = 64 * 1024; // 64KB
  10660. svr.set_payload_max_length(LIMIT);
  10661. size_t total = 0;
  10662. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10663. const ContentReader &content_reader) {
  10664. content_reader([&](const char * /*data*/, size_t len) {
  10665. total += len;
  10666. return true;
  10667. });
  10668. res.status = 200;
  10669. res.set_content("stream_ok", "text/plain");
  10670. });
  10671. auto port = svr.bind_to_any_port(HOST);
  10672. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10673. auto se = detail::scope_exit([&] {
  10674. svr.stop();
  10675. thread.join();
  10676. ASSERT_FALSE(svr.is_running());
  10677. });
  10678. svr.wait_until_ready();
  10679. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10680. // StreamingGzipDecompression test above.
  10681. std::string raw(256 * 1024, 'A');
  10682. std::string gz;
  10683. {
  10684. httplib::detail::gzip_compressor compressor;
  10685. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10686. [&](const char *chunk, size_t len) {
  10687. gz.append(chunk, len);
  10688. return true;
  10689. });
  10690. ASSERT_TRUE(result);
  10691. }
  10692. // Send the gzip body over raw TCP with neither Content-Length nor
  10693. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10694. // kicks in.
  10695. std::string req = "POST /stream HTTP/1.1\r\n"
  10696. "Host: " +
  10697. std::string(HOST) + ":" + std::to_string(port) +
  10698. "\r\n"
  10699. "Content-Encoding: gzip\r\n"
  10700. "Connection: close\r\n"
  10701. "\r\n" +
  10702. gz;
  10703. std::string response;
  10704. ASSERT_TRUE(send_request(5, req, &response, port));
  10705. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10706. EXPECT_LE(total, LIMIT);
  10707. }
  10708. #endif
  10709. #endif
  10710. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10711. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10712. // the payload must be passed through untouched instead of being rejected.
  10713. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10714. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10715. Server svr;
  10716. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10717. res.set_content(body, "image/jpeg");
  10718. res.set_header("Content-Encoding", "UTF-8");
  10719. });
  10720. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10721. res.set_content(body, "image/jpeg");
  10722. res.set_header("Content-Encoding", "identity");
  10723. });
  10724. svr.Post("/echo", [](const Request &req, Response &res) {
  10725. res.set_content(req.body, "image/jpeg");
  10726. });
  10727. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10728. auto se = detail::scope_exit([&] {
  10729. svr.stop();
  10730. t.join();
  10731. ASSERT_FALSE(svr.is_running());
  10732. });
  10733. svr.wait_until_ready();
  10734. Client cli(HOST, PORT);
  10735. {
  10736. auto res = cli.Get("/image");
  10737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10738. EXPECT_EQ(StatusCode::OK_200, res->status);
  10739. EXPECT_EQ(body, res->body);
  10740. }
  10741. {
  10742. auto res = cli.Get("/identity");
  10743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10744. EXPECT_EQ(StatusCode::OK_200, res->status);
  10745. EXPECT_EQ(body, res->body);
  10746. }
  10747. {
  10748. // The same applies to a request body reaching the server.
  10749. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10750. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10752. EXPECT_EQ(StatusCode::OK_200, res->status);
  10753. EXPECT_EQ(body, res->body);
  10754. }
  10755. }
  10756. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10757. // gzip-encoded response even when the build has no zlib support.
  10758. static const char GZIPPED_HELLO_WORLD[] = {
  10759. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10760. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10761. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10762. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10763. // A content coding is a whole token, not something the field value merely
  10764. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10765. // as "fibre" look like Brotli, and turned a multi-coding value like
  10766. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10767. // it was never meant to see.
  10768. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10769. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10770. Server svr;
  10771. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10772. res.set_content(body, "image/jpeg");
  10773. res.set_header("Content-Encoding", "fibre");
  10774. });
  10775. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10776. res.set_content(body, "image/jpeg");
  10777. res.set_header("Content-Encoding", "gzip, br");
  10778. });
  10779. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10780. res.set_content(body, "image/jpeg");
  10781. res.set_header("Content-Encoding", "x-zstd-ish");
  10782. });
  10783. auto port = svr.bind_to_any_port(HOST);
  10784. thread t = thread([&]() { svr.listen_after_bind(); });
  10785. auto se = detail::scope_exit([&] {
  10786. svr.stop();
  10787. t.join();
  10788. ASSERT_FALSE(svr.is_running());
  10789. });
  10790. svr.wait_until_ready();
  10791. Client cli(HOST, port);
  10792. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10793. auto res = cli.Get(path);
  10794. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10795. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10796. // Not a coding we recognize, so the payload comes back untouched
  10797. EXPECT_EQ(body, res->body) << path;
  10798. }
  10799. }
  10800. // A content coding cpp-httplib recognizes but was not built with must be
  10801. // reported as such. Handing the still-compressed payload back to the caller
  10802. // would silently corrupt it.
  10803. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10804. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10805. Server svr;
  10806. // "image/jpeg" keeps the server from applying a content coding of its own,
  10807. // so the hand-crafted Content-Encoding below survives.
  10808. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10809. res.set_content(gzipped, "image/jpeg");
  10810. res.set_header("Content-Encoding", "gzip");
  10811. });
  10812. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10813. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10814. res.set_content(gzipped, "image/jpeg");
  10815. res.set_header("Content-Encoding", "GZIP");
  10816. });
  10817. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10818. auto se = detail::scope_exit([&] {
  10819. svr.stop();
  10820. t.join();
  10821. ASSERT_FALSE(svr.is_running());
  10822. });
  10823. svr.wait_until_ready();
  10824. Client cli(HOST, PORT);
  10825. {
  10826. auto res = cli.Get("/gzipped");
  10827. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10829. EXPECT_EQ("Hello World!", res->body);
  10830. #else
  10831. ASSERT_FALSE(res);
  10832. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10833. #endif
  10834. }
  10835. {
  10836. // open_stream() must behave the same way.
  10837. auto handle = cli.open_stream("GET", "/gzipped");
  10838. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10839. ASSERT_TRUE(handle.is_valid());
  10840. std::string received;
  10841. char buf[256];
  10842. ssize_t n;
  10843. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10844. received.append(buf, static_cast<size_t>(n));
  10845. }
  10846. EXPECT_EQ("Hello World!", received);
  10847. #else
  10848. EXPECT_FALSE(handle.is_valid());
  10849. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10850. #endif
  10851. }
  10852. {
  10853. // A differently-cased coding must not be mistaken for an unknown one, or
  10854. // the body would be handed back still compressed.
  10855. auto res = cli.Get("/gzipped-uppercase");
  10856. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10858. EXPECT_EQ("Hello World!", res->body);
  10859. #else
  10860. ASSERT_FALSE(res);
  10861. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10862. #endif
  10863. }
  10864. }
  10865. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10866. // A handler serving pre-compressed content (e.g. build-time gzipped static
  10867. // assets) sets Content-Encoding itself. The server used to pick a coding from
  10868. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  10869. // body a second time and appending a second Content-Encoding field line, so
  10870. // clients that decode one coding per listed value handed back raw gzip bytes.
  10871. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  10872. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10873. Server svr;
  10874. // text/plain is a compressible type, so only the pre-set Content-Encoding
  10875. // keeps the server from applying a coding of its own.
  10876. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10877. res.set_content(gzipped, "text/plain");
  10878. res.set_header("Content-Encoding", "gzip");
  10879. });
  10880. auto port = svr.bind_to_any_port(HOST);
  10881. thread t = thread([&]() { svr.listen_after_bind(); });
  10882. auto se = detail::scope_exit([&] {
  10883. svr.stop();
  10884. t.join();
  10885. ASSERT_FALSE(svr.is_running());
  10886. });
  10887. svr.wait_until_ready();
  10888. Client cli(HOST, port);
  10889. Headers headers = {{"Accept-Encoding", "gzip"}};
  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. // A chunked provider settles its coding where the headers are written and
  10897. // reuses it at write time. Both ends of that have to hold: a handler's own
  10898. // Content-Encoding suppresses the coding, and a response without one is still
  10899. // compressed as it always was.
  10900. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  10901. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10902. const std::string plain = "Hello World! Hello World! Hello World!";
  10903. Server svr;
  10904. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10905. res.set_header("Content-Encoding", "gzip");
  10906. res.set_chunked_content_provider(
  10907. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  10908. sink.write(gzipped.data(), gzipped.size());
  10909. sink.done();
  10910. return true;
  10911. });
  10912. });
  10913. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  10914. res.set_chunked_content_provider(
  10915. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  10916. sink.write(plain.data(), plain.size());
  10917. sink.done();
  10918. return true;
  10919. });
  10920. });
  10921. auto port = svr.bind_to_any_port(HOST);
  10922. thread t = thread([&]() { svr.listen_after_bind(); });
  10923. auto se = detail::scope_exit([&] {
  10924. svr.stop();
  10925. t.join();
  10926. ASSERT_FALSE(svr.is_running());
  10927. });
  10928. svr.wait_until_ready();
  10929. Client cli(HOST, port);
  10930. Headers headers = {{"Accept-Encoding", "gzip"}};
  10931. {
  10932. auto res = cli.Get("/pre-gzipped", headers);
  10933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10934. EXPECT_EQ(StatusCode::OK_200, res->status);
  10935. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10936. EXPECT_EQ("Hello World!", res->body);
  10937. }
  10938. {
  10939. auto res = cli.Get("/negotiated", headers);
  10940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10941. EXPECT_EQ(StatusCode::OK_200, res->status);
  10942. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  10943. EXPECT_EQ(plain, res->body);
  10944. }
  10945. }
  10946. #endif
  10947. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10948. // the same message as the comma-joined one, so both have to be read the same
  10949. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10950. // single gzip coding, and a body the sender says was encoded twice was handed
  10951. // back after one pass, still compressed but presented as decoded.
  10952. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10953. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10954. Server svr;
  10955. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10956. res.set_content(body, "image/jpeg");
  10957. res.headers.emplace("Content-Encoding", "gzip");
  10958. res.headers.emplace("Content-Encoding", "gzip");
  10959. });
  10960. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10961. res.set_content(body, "image/jpeg");
  10962. res.set_header("Content-Encoding", "gzip, gzip");
  10963. });
  10964. auto port = svr.bind_to_any_port(HOST);
  10965. thread t = thread([&]() { svr.listen_after_bind(); });
  10966. auto se = detail::scope_exit([&] {
  10967. svr.stop();
  10968. t.join();
  10969. ASSERT_FALSE(svr.is_running());
  10970. });
  10971. svr.wait_until_ready();
  10972. Client cli(HOST, port);
  10973. // Two codings is not something cpp-httplib decodes, so both representations
  10974. // take the pass-through path rather than one of them being gunzipped once.
  10975. for (const char *path : {"/split", "/joined"}) {
  10976. auto res = cli.Get(path);
  10977. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10978. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10979. EXPECT_EQ(body, res->body) << path;
  10980. }
  10981. }
  10982. // Regression test for DoS vulnerability: a malicious server sending a response
  10983. // without Content-Length header must not cause unbounded memory consumption on
  10984. // the client side. The client should stop reading after a reasonable limit,
  10985. // similar to the server-side set_payload_max_length protection.
  10986. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10987. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10988. #ifndef _WIN32
  10989. signal(SIGPIPE, SIG_IGN);
  10990. #endif
  10991. auto server_thread = std::thread([] {
  10992. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10993. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10994. default_socket_options(srv);
  10995. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10996. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10997. sockaddr_in addr{};
  10998. addr.sin_family = AF_INET;
  10999. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11000. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11001. int opt = 1;
  11002. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11003. #ifdef _WIN32
  11004. reinterpret_cast<const char *>(&opt),
  11005. #else
  11006. &opt,
  11007. #endif
  11008. sizeof(opt));
  11009. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11010. ::listen(srv, 1);
  11011. sockaddr_in cli_addr{};
  11012. socklen_t cli_len = sizeof(cli_addr);
  11013. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11014. if (cli != INVALID_SOCKET) {
  11015. char buf[4096];
  11016. ::recv(cli, buf, sizeof(buf), 0);
  11017. // Malicious response: no Content-Length, no chunked encoding
  11018. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11019. "Connection: close\r\n"
  11020. "\r\n";
  11021. ::send(cli,
  11022. #ifdef _WIN32
  11023. static_cast<const char *>(response_header.c_str()),
  11024. static_cast<int>(response_header.size()),
  11025. #else
  11026. response_header.c_str(), response_header.size(),
  11027. #endif
  11028. 0);
  11029. // Send 10MB of data
  11030. std::string chunk(64 * 1024, 'A');
  11031. size_t total_sent = 0;
  11032. while (total_sent < MALICIOUS_DATA_SIZE) {
  11033. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11034. auto sent = ::send(cli,
  11035. #ifdef _WIN32
  11036. static_cast<const char *>(chunk.c_str()),
  11037. static_cast<int>(to_send),
  11038. #else
  11039. chunk.c_str(), to_send,
  11040. #endif
  11041. 0);
  11042. if (sent <= 0) break;
  11043. total_sent += static_cast<size_t>(sent);
  11044. }
  11045. detail::close_socket(cli);
  11046. }
  11047. detail::close_socket(srv);
  11048. });
  11049. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11050. size_t total_read = 0;
  11051. {
  11052. Client cli("127.0.0.1", PORT + 2);
  11053. cli.set_read_timeout(5, 0);
  11054. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11055. auto stream = cli.open_stream("GET", "/malicious");
  11056. ASSERT_TRUE(stream.is_valid());
  11057. char buffer[64 * 1024];
  11058. ssize_t n;
  11059. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11060. total_read += static_cast<size_t>(n);
  11061. }
  11062. } // StreamHandle and Client destroyed here, closing the socket
  11063. server_thread.join();
  11064. // With set_payload_max_length, the client must stop reading before consuming
  11065. // all 10MB. The read loop should be cut off at or near the configured limit.
  11066. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11067. << "Client read " << total_read << " bytes, exceeding the configured "
  11068. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11069. }
  11070. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11071. // the entire response body without truncation.
  11072. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11073. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11074. #ifndef _WIN32
  11075. signal(SIGPIPE, SIG_IGN);
  11076. #endif
  11077. auto server_thread = std::thread([] {
  11078. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11079. default_socket_options(srv);
  11080. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11081. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11082. sockaddr_in addr{};
  11083. addr.sin_family = AF_INET;
  11084. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11085. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11086. int opt = 1;
  11087. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11088. #ifdef _WIN32
  11089. reinterpret_cast<const char *>(&opt),
  11090. #else
  11091. &opt,
  11092. #endif
  11093. sizeof(opt));
  11094. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11095. ::listen(srv, 1);
  11096. sockaddr_in cli_addr{};
  11097. socklen_t cli_len = sizeof(cli_addr);
  11098. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11099. if (cli != INVALID_SOCKET) {
  11100. char buf[4096];
  11101. ::recv(cli, buf, sizeof(buf), 0);
  11102. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11103. "Connection: close\r\n"
  11104. "\r\n";
  11105. ::send(cli,
  11106. #ifdef _WIN32
  11107. static_cast<const char *>(response_header.c_str()),
  11108. static_cast<int>(response_header.size()),
  11109. #else
  11110. response_header.c_str(), response_header.size(),
  11111. #endif
  11112. 0);
  11113. std::string chunk(64 * 1024, 'A');
  11114. size_t total_sent = 0;
  11115. while (total_sent < DATA_SIZE) {
  11116. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11117. auto sent = ::send(cli,
  11118. #ifdef _WIN32
  11119. static_cast<const char *>(chunk.c_str()),
  11120. static_cast<int>(to_send),
  11121. #else
  11122. chunk.c_str(), to_send,
  11123. #endif
  11124. 0);
  11125. if (sent <= 0) break;
  11126. total_sent += static_cast<size_t>(sent);
  11127. }
  11128. #ifdef _WIN32
  11129. ::shutdown(cli, SD_SEND);
  11130. #else
  11131. ::shutdown(cli, SHUT_WR);
  11132. #endif
  11133. // Drain until the client closes its end, ensuring all data is delivered
  11134. char drain[1024];
  11135. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11136. detail::close_socket(cli);
  11137. }
  11138. detail::close_socket(srv);
  11139. });
  11140. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11141. size_t total_read = 0;
  11142. {
  11143. Client cli("127.0.0.1", PORT + 2);
  11144. cli.set_read_timeout(5, 0);
  11145. cli.set_payload_max_length(0); // 0 means no limit
  11146. auto stream = cli.open_stream("GET", "/data");
  11147. ASSERT_TRUE(stream.is_valid());
  11148. char buffer[64 * 1024];
  11149. ssize_t n;
  11150. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11151. total_read += static_cast<size_t>(n);
  11152. }
  11153. }
  11154. server_thread.join();
  11155. EXPECT_EQ(total_read, DATA_SIZE)
  11156. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11157. << " bytes without truncation, but only read " << total_read << " bytes.";
  11158. }
  11159. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11160. // enormous Content-Length must not cause the client to pre-allocate a huge
  11161. // response body buffer. The reservation is capped at payload_max_length_, and
  11162. // the read itself fails when the body exceeds the limit.
  11163. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11164. #ifndef _WIN32
  11165. signal(SIGPIPE, SIG_IGN);
  11166. #endif
  11167. auto server_thread = std::thread([] {
  11168. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11169. default_socket_options(srv);
  11170. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11171. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11172. sockaddr_in addr{};
  11173. addr.sin_family = AF_INET;
  11174. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11175. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11176. int opt = 1;
  11177. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11178. #ifdef _WIN32
  11179. reinterpret_cast<const char *>(&opt),
  11180. #else
  11181. &opt,
  11182. #endif
  11183. sizeof(opt));
  11184. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11185. ::listen(srv, 1);
  11186. sockaddr_in cli_addr{};
  11187. socklen_t cli_len = sizeof(cli_addr);
  11188. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11189. if (cli != INVALID_SOCKET) {
  11190. char buf[4096];
  11191. ::recv(cli, buf, sizeof(buf), 0);
  11192. // Malicious response: claim a 20GB body but send only a tiny payload.
  11193. std::string response = "HTTP/1.1 200 OK\r\n"
  11194. "Content-Length: 20000000000\r\n"
  11195. "\r\n"
  11196. "abc";
  11197. ::send(cli,
  11198. #ifdef _WIN32
  11199. static_cast<const char *>(response.c_str()),
  11200. static_cast<int>(response.size()),
  11201. #else
  11202. response.c_str(), response.size(),
  11203. #endif
  11204. 0);
  11205. detail::close_socket(cli);
  11206. }
  11207. detail::close_socket(srv);
  11208. });
  11209. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11210. {
  11211. Client cli("127.0.0.1", PORT + 2);
  11212. cli.set_read_timeout(5, 0);
  11213. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11214. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11215. // (server claims more bytes than payload_max_length permits), but it must
  11216. // not exhaust memory before getting there.
  11217. auto res = cli.Get("/malicious");
  11218. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11219. }
  11220. server_thread.join();
  11221. }
  11222. // Verify that content_receiver bypasses the default payload_max_length,
  11223. // allowing streaming downloads larger than 100MB without requiring an explicit
  11224. // set_payload_max_length call.
  11225. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11226. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11227. #ifndef _WIN32
  11228. signal(SIGPIPE, SIG_IGN);
  11229. #endif
  11230. auto server_thread = std::thread([] {
  11231. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11232. default_socket_options(srv);
  11233. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11234. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11235. sockaddr_in addr{};
  11236. addr.sin_family = AF_INET;
  11237. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11238. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11239. int opt = 1;
  11240. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11241. #ifdef _WIN32
  11242. reinterpret_cast<const char *>(&opt),
  11243. #else
  11244. &opt,
  11245. #endif
  11246. sizeof(opt));
  11247. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11248. ::listen(srv, 1);
  11249. sockaddr_in cli_addr{};
  11250. socklen_t cli_len = sizeof(cli_addr);
  11251. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11252. if (cli != INVALID_SOCKET) {
  11253. char buf[4096];
  11254. ::recv(cli, buf, sizeof(buf), 0);
  11255. // Response with Content-Length larger than default 100MB limit
  11256. auto content_length = std::to_string(DATA_SIZE);
  11257. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11258. "Content-Length: " +
  11259. content_length +
  11260. "\r\n"
  11261. "Connection: close\r\n"
  11262. "\r\n";
  11263. ::send(cli,
  11264. #ifdef _WIN32
  11265. static_cast<const char *>(response_header.c_str()),
  11266. static_cast<int>(response_header.size()),
  11267. #else
  11268. response_header.c_str(), response_header.size(),
  11269. #endif
  11270. 0);
  11271. std::string chunk(64 * 1024, 'A');
  11272. size_t total_sent = 0;
  11273. while (total_sent < DATA_SIZE) {
  11274. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11275. auto sent = ::send(cli,
  11276. #ifdef _WIN32
  11277. static_cast<const char *>(chunk.c_str()),
  11278. static_cast<int>(to_send),
  11279. #else
  11280. chunk.c_str(), to_send,
  11281. #endif
  11282. 0);
  11283. if (sent <= 0) break;
  11284. total_sent += static_cast<size_t>(sent);
  11285. }
  11286. detail::close_socket(cli);
  11287. }
  11288. detail::close_socket(srv);
  11289. });
  11290. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11291. size_t total_received = 0;
  11292. {
  11293. Client cli("127.0.0.1", PORT + 2);
  11294. cli.set_read_timeout(10, 0);
  11295. // Do NOT call set_payload_max_length — use the default 100MB limit
  11296. auto res =
  11297. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11298. total_received += data_length;
  11299. return true;
  11300. });
  11301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11302. EXPECT_EQ(StatusCode::OK_200, res->status);
  11303. }
  11304. server_thread.join();
  11305. EXPECT_EQ(total_received, DATA_SIZE)
  11306. << "With content_receiver, the client should read all " << DATA_SIZE
  11307. << " bytes despite the default 100MB payload_max_length, but only read "
  11308. << total_received << " bytes.";
  11309. }
  11310. // Verify that an explicit set_payload_max_length smaller than the response is
  11311. // enforced even when a content_receiver is used.
  11312. TEST(ClientVulnerabilityTest,
  11313. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11314. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11315. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11316. #ifndef _WIN32
  11317. signal(SIGPIPE, SIG_IGN);
  11318. #endif
  11319. auto server_thread = std::thread([] {
  11320. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11321. default_socket_options(srv);
  11322. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11323. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11324. sockaddr_in addr{};
  11325. addr.sin_family = AF_INET;
  11326. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11327. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11328. int opt = 1;
  11329. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11330. #ifdef _WIN32
  11331. reinterpret_cast<const char *>(&opt),
  11332. #else
  11333. &opt,
  11334. #endif
  11335. sizeof(opt));
  11336. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11337. ::listen(srv, 1);
  11338. sockaddr_in cli_addr{};
  11339. socklen_t cli_len = sizeof(cli_addr);
  11340. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11341. if (cli != INVALID_SOCKET) {
  11342. char buf[4096];
  11343. ::recv(cli, buf, sizeof(buf), 0);
  11344. auto content_length = std::to_string(DATA_SIZE);
  11345. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11346. "Content-Length: " +
  11347. content_length +
  11348. "\r\n"
  11349. "Connection: close\r\n"
  11350. "\r\n";
  11351. ::send(cli,
  11352. #ifdef _WIN32
  11353. static_cast<const char *>(response_header.c_str()),
  11354. static_cast<int>(response_header.size()),
  11355. #else
  11356. response_header.c_str(), response_header.size(),
  11357. #endif
  11358. 0);
  11359. std::string chunk(64 * 1024, 'A');
  11360. size_t total_sent = 0;
  11361. while (total_sent < DATA_SIZE) {
  11362. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11363. auto sent = ::send(cli,
  11364. #ifdef _WIN32
  11365. static_cast<const char *>(chunk.c_str()),
  11366. static_cast<int>(to_send),
  11367. #else
  11368. chunk.c_str(), to_send,
  11369. #endif
  11370. 0);
  11371. if (sent <= 0) break;
  11372. total_sent += static_cast<size_t>(sent);
  11373. }
  11374. detail::close_socket(cli);
  11375. }
  11376. detail::close_socket(srv);
  11377. });
  11378. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11379. size_t total_received = 0;
  11380. {
  11381. Client cli("127.0.0.1", PORT + 2);
  11382. cli.set_read_timeout(10, 0);
  11383. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11384. auto res =
  11385. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11386. total_received += data_length;
  11387. return true;
  11388. });
  11389. // Should fail because 200MB exceeds the explicit 150MB limit
  11390. EXPECT_FALSE(res);
  11391. }
  11392. server_thread.join();
  11393. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11394. << "Client with content_receiver should respect the explicit "
  11395. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11396. << total_received << " bytes.";
  11397. }
  11398. // Verify that an explicit set_payload_max_length larger than the response
  11399. // allows the content_receiver to read all data successfully.
  11400. TEST(ClientVulnerabilityTest,
  11401. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11402. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11403. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11404. #ifndef _WIN32
  11405. signal(SIGPIPE, SIG_IGN);
  11406. #endif
  11407. auto server_thread = std::thread([] {
  11408. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11409. default_socket_options(srv);
  11410. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11411. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11412. sockaddr_in addr{};
  11413. addr.sin_family = AF_INET;
  11414. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11415. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11416. int opt = 1;
  11417. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11418. #ifdef _WIN32
  11419. reinterpret_cast<const char *>(&opt),
  11420. #else
  11421. &opt,
  11422. #endif
  11423. sizeof(opt));
  11424. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11425. ::listen(srv, 1);
  11426. sockaddr_in cli_addr{};
  11427. socklen_t cli_len = sizeof(cli_addr);
  11428. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11429. if (cli != INVALID_SOCKET) {
  11430. char buf[4096];
  11431. ::recv(cli, buf, sizeof(buf), 0);
  11432. auto content_length = std::to_string(DATA_SIZE);
  11433. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11434. "Content-Length: " +
  11435. content_length +
  11436. "\r\n"
  11437. "Connection: close\r\n"
  11438. "\r\n";
  11439. ::send(cli,
  11440. #ifdef _WIN32
  11441. static_cast<const char *>(response_header.c_str()),
  11442. static_cast<int>(response_header.size()),
  11443. #else
  11444. response_header.c_str(), response_header.size(),
  11445. #endif
  11446. 0);
  11447. std::string chunk(64 * 1024, 'A');
  11448. size_t total_sent = 0;
  11449. while (total_sent < DATA_SIZE) {
  11450. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11451. auto sent = ::send(cli,
  11452. #ifdef _WIN32
  11453. static_cast<const char *>(chunk.c_str()),
  11454. static_cast<int>(to_send),
  11455. #else
  11456. chunk.c_str(), to_send,
  11457. #endif
  11458. 0);
  11459. if (sent <= 0) break;
  11460. total_sent += static_cast<size_t>(sent);
  11461. }
  11462. #ifdef _WIN32
  11463. ::shutdown(cli, SD_SEND);
  11464. #else
  11465. ::shutdown(cli, SHUT_WR);
  11466. #endif
  11467. char drain[1024];
  11468. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11469. detail::close_socket(cli);
  11470. }
  11471. detail::close_socket(srv);
  11472. });
  11473. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11474. size_t total_received = 0;
  11475. {
  11476. Client cli("127.0.0.1", PORT + 2);
  11477. cli.set_read_timeout(10, 0);
  11478. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11479. auto res =
  11480. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11481. total_received += data_length;
  11482. return true;
  11483. });
  11484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11485. EXPECT_EQ(StatusCode::OK_200, res->status);
  11486. }
  11487. server_thread.join();
  11488. EXPECT_EQ(total_received, DATA_SIZE)
  11489. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11490. << " bytes (larger than " << DATA_SIZE
  11491. << " bytes response), content_receiver should read all data, but only "
  11492. "read "
  11493. << total_received << " bytes.";
  11494. }
  11495. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11496. // Regression test for "zip bomb" attack on the client side: a malicious server
  11497. // sends a small gzip-compressed response that decompresses to a huge payload.
  11498. // The client must enforce payload_max_length on the decompressed size.
  11499. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11500. constexpr size_t DECOMPRESSED_SIZE =
  11501. 10 * 1024 * 1024; // 10MB after decompression
  11502. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11503. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11504. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11505. std::string compressed;
  11506. {
  11507. httplib::detail::gzip_compressor compressor;
  11508. bool ok =
  11509. compressor.compress(uncompressed.data(), uncompressed.size(),
  11510. /*last=*/true, [&](const char *buf, size_t len) {
  11511. compressed.append(buf, len);
  11512. return true;
  11513. });
  11514. ASSERT_TRUE(ok);
  11515. }
  11516. // Sanity: compressed data should be much smaller than the decompressed size
  11517. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11518. #ifndef _WIN32
  11519. signal(SIGPIPE, SIG_IGN);
  11520. #endif
  11521. // Set up the listening socket in the main thread so the server is guaranteed
  11522. // to be ready before the client connects (eliminates race condition).
  11523. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11524. default_socket_options(srv);
  11525. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11526. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11527. sockaddr_in addr{};
  11528. addr.sin_family = AF_INET;
  11529. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11530. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11531. int opt = 1;
  11532. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11533. #ifdef _WIN32
  11534. reinterpret_cast<const char *>(&opt),
  11535. #else
  11536. &opt,
  11537. #endif
  11538. sizeof(opt));
  11539. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11540. ASSERT_EQ(0, ::listen(srv, 1));
  11541. auto server_thread = std::thread([&compressed, srv] {
  11542. sockaddr_in cli_addr{};
  11543. socklen_t cli_len = sizeof(cli_addr);
  11544. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11545. if (cli != INVALID_SOCKET) {
  11546. // Read the full HTTP request (until \r\n\r\n)
  11547. char buf[4096];
  11548. size_t total = 0;
  11549. while (total < sizeof(buf)) {
  11550. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11551. if (n <= 0) break;
  11552. total += static_cast<size_t>(n);
  11553. // Check for end of headers
  11554. if (total >= 4) {
  11555. std::string req(buf, total);
  11556. if (req.find("\r\n\r\n") != std::string::npos) break;
  11557. }
  11558. }
  11559. // Malicious response: gzip-compressed body, no Content-Length
  11560. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11561. "Content-Encoding: gzip\r\n"
  11562. "Connection: close\r\n"
  11563. "\r\n";
  11564. ::send(cli,
  11565. #ifdef _WIN32
  11566. static_cast<const char *>(response_header.c_str()),
  11567. static_cast<int>(response_header.size()),
  11568. #else
  11569. response_header.c_str(), response_header.size(),
  11570. #endif
  11571. 0);
  11572. // Send the compressed payload (small on the wire, huge when decompressed)
  11573. size_t total_sent = 0;
  11574. while (total_sent < compressed.size()) {
  11575. auto to_send = std::min(compressed.size() - total_sent,
  11576. static_cast<size_t>(64 * 1024));
  11577. auto sent =
  11578. ::send(cli,
  11579. #ifdef _WIN32
  11580. static_cast<const char *>(compressed.c_str() + total_sent),
  11581. static_cast<int>(to_send),
  11582. #else
  11583. compressed.c_str() + total_sent, to_send,
  11584. #endif
  11585. 0);
  11586. if (sent <= 0) break;
  11587. total_sent += static_cast<size_t>(sent);
  11588. }
  11589. detail::close_socket(cli);
  11590. }
  11591. });
  11592. auto se = detail::scope_exit([&] {
  11593. detail::close_socket(srv);
  11594. server_thread.join();
  11595. });
  11596. size_t total_decompressed = 0;
  11597. {
  11598. Client cli("127.0.0.1", PORT + 3);
  11599. cli.set_read_timeout(5, 0);
  11600. cli.set_decompress(true);
  11601. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11602. auto stream = cli.open_stream("GET", "/zipbomb");
  11603. ASSERT_TRUE(stream.is_valid());
  11604. char buffer[64 * 1024];
  11605. ssize_t n;
  11606. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11607. total_decompressed += static_cast<size_t>(n);
  11608. }
  11609. }
  11610. // The decompressed size must be capped by payload_max_length. Without
  11611. // protection, the client would decompress the full 10MB from a tiny
  11612. // compressed payload, enabling a zip bomb DoS attack.
  11613. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11614. << "Client decompressed " << total_decompressed
  11615. << " bytes from a gzip response. The decompressed size should be "
  11616. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11617. }
  11618. #endif
  11619. TEST(HostAndPortPropertiesTest, NoSSL) {
  11620. httplib::Client cli("www.google.com", 1234);
  11621. ASSERT_EQ("www.google.com", cli.host());
  11622. ASSERT_EQ(1234, cli.port());
  11623. }
  11624. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11625. httplib::Client cli("www.google.com:1234");
  11626. ASSERT_EQ("www.google.com", cli.host());
  11627. ASSERT_EQ(1234, cli.port());
  11628. }
  11629. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11630. // Port number that overflows int — should not crash, client becomes invalid
  11631. httplib::Client cli("http://www.google.com:99999999999999999999");
  11632. ASSERT_FALSE(cli.is_valid());
  11633. }
  11634. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11635. // Port 99999 exceeds valid range (1-65535) — should not crash
  11636. httplib::Client cli("http://www.google.com:99999");
  11637. ASSERT_FALSE(cli.is_valid());
  11638. }
  11639. #ifdef CPPHTTPLIB_SSL_ENABLED
  11640. TEST(HostAndPortPropertiesTest, SSL) {
  11641. httplib::SSLClient cli("www.google.com");
  11642. ASSERT_EQ("www.google.com", cli.host());
  11643. ASSERT_EQ(443, cli.port());
  11644. }
  11645. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11646. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11647. std::string cert;
  11648. read_file(CA_CERT_FILE, cert);
  11649. httplib::SSLClient httplib_client("www.google.com");
  11650. // Load CA store first time
  11651. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11652. // Load CA store second time (update)
  11653. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11654. // Verify client is still valid and can make connections
  11655. httplib_client.enable_server_certificate_verification(true);
  11656. auto res = httplib_client.Get("/");
  11657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11658. // Google may return 200 or 301 depending on various factors
  11659. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11660. res->status == StatusCode::MovedPermanently_301);
  11661. }
  11662. TEST(SSLClientTest, ServerNameIndication_Online) {
  11663. auto host = "httpbingo.org";
  11664. auto path = std::string{"/get"};
  11665. SSLClient cli(host, 443);
  11666. auto res = cli.Get(path);
  11667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11668. ASSERT_EQ(StatusCode::OK_200, res->status);
  11669. }
  11670. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11671. // Use a site that will cause SSL verification failure due to self-signed cert
  11672. SSLClient cli("self-signed.badssl.com", 443);
  11673. cli.enable_server_certificate_verification(true);
  11674. auto res = cli.Get("/");
  11675. ASSERT_TRUE(!res);
  11676. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11677. // Verify backend error is captured for SSLServerVerification
  11678. // This occurs when certificate verification fails
  11679. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11680. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11681. EXPECT_NE(0UL, res.ssl_backend_error());
  11682. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11683. // For OpenSSL, ssl_error is 0 for verification errors
  11684. EXPECT_EQ(0, res.ssl_error());
  11685. #if !defined(_WIN32) || \
  11686. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11687. // On non-Windows or when Windows Schannel is disabled, the error comes
  11688. // from OpenSSL's verification
  11689. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11690. res.ssl_backend_error());
  11691. #endif
  11692. #endif
  11693. }
  11694. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11695. // Use a site where hostname doesn't match the certificate
  11696. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11697. SSLClient cli("wrong.host.badssl.com", 443);
  11698. cli.enable_server_certificate_verification(true);
  11699. cli.enable_server_hostname_verification(true);
  11700. auto res = cli.Get("/");
  11701. ASSERT_TRUE(!res);
  11702. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11703. // Verify backend error is captured for hostname verification failure
  11704. EXPECT_NE(0UL, res.ssl_backend_error());
  11705. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11706. // For OpenSSL, ssl_error is 0 for verification errors
  11707. EXPECT_EQ(0, res.ssl_error());
  11708. #if !defined(_WIN32) || \
  11709. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11710. // On non-Windows or when Windows Schannel is disabled, the error comes
  11711. // from OpenSSL's hostname verification
  11712. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11713. res.ssl_backend_error());
  11714. #endif
  11715. #endif
  11716. }
  11717. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11718. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11719. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11720. SSLClient cli("www.google.com", 443);
  11721. cli.enable_server_certificate_verification(true);
  11722. auto res = cli.Get("/");
  11723. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11724. }
  11725. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11726. SSLClient cli("www.google.com", 443);
  11727. cli.enable_server_certificate_verification(true);
  11728. cli.enable_windows_certificate_verification(false);
  11729. auto res = cli.Get("/");
  11730. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11731. }
  11732. // The server sends an intermediate cross-signed by a root Windows trusts,
  11733. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  11734. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  11735. SSLClient cli("accounts.spotify.com", 443);
  11736. auto res = cli.Get("/");
  11737. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  11738. << " ssl_backend_error=" << res.ssl_backend_error();
  11739. }
  11740. #endif
  11741. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11742. Client cli("https://google.com");
  11743. auto res = cli.Get("/");
  11744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11745. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11746. }
  11747. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11748. SSLClient cli("google.com");
  11749. cli.set_ca_cert_path(CA_CERT_FILE);
  11750. auto res = cli.Get("/");
  11751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11752. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11753. }
  11754. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11755. SSLClient cli("google.com");
  11756. cli.enable_server_certificate_verification(true);
  11757. cli.set_ca_cert_path("hello");
  11758. auto res = cli.Get("/");
  11759. ASSERT_TRUE(!res);
  11760. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11761. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11762. // should be set
  11763. EXPECT_EQ(0, res.ssl_error());
  11764. // Verify backend error is captured for SSLLoadingCerts
  11765. // This error occurs when loading CA certificates fails
  11766. EXPECT_NE(0UL, res.ssl_backend_error());
  11767. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11768. // OpenSSL specific error codes:
  11769. // > openssl errstr 0x80000002
  11770. // error:80000002:system library::No such file or directory
  11771. // > openssl errstr 0xA000126
  11772. // error:0A000126:SSL routines::unexpected eof while reading
  11773. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11774. res.ssl_backend_error() == 0xA000126);
  11775. #endif
  11776. }
  11777. TEST(SSLClientTest, ServerCertificateVerification4) {
  11778. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11779. ASSERT_TRUE(svr.is_valid());
  11780. svr.Get("/test", [&](const Request &, Response &res) {
  11781. res.set_content("test", "text/plain");
  11782. svr.stop();
  11783. ASSERT_TRUE(true);
  11784. });
  11785. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11786. auto se = detail::scope_exit([&] {
  11787. t.join();
  11788. ASSERT_FALSE(svr.is_running());
  11789. });
  11790. svr.wait_until_ready();
  11791. SSLClient cli("127.0.0.1", PORT);
  11792. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11793. cli.enable_server_certificate_verification(true);
  11794. cli.set_connection_timeout(30);
  11795. auto res = cli.Get("/test");
  11796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11797. ASSERT_EQ(StatusCode::OK_200, res->status);
  11798. }
  11799. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11800. std::string cert;
  11801. read_file(CA_CERT_FILE, cert);
  11802. SSLClient cli("google.com");
  11803. cli.load_ca_cert_store(cert.data(), cert.size());
  11804. const auto res = cli.Get("/");
  11805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11806. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11807. }
  11808. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11809. // clang-format off
  11810. static constexpr char cert[] =
  11811. "GlobalSign Root CA\n"
  11812. "==================\n"
  11813. "-----BEGIN CERTIFICATE-----\n"
  11814. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11815. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11816. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11817. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11818. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11819. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11820. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11821. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11822. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11823. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11824. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11825. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11826. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11827. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11828. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11829. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11830. "-----END CERTIFICATE-----\n";
  11831. // clang-format on
  11832. SSLClient cli("google.com");
  11833. cli.load_ca_cert_store(cert, sizeof(cert));
  11834. const auto res = cli.Get("/");
  11835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11836. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11837. }
  11838. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11839. SSLClient cli("www.youtube.com");
  11840. cli.set_ca_cert_path(CA_CERT_FILE);
  11841. cli.enable_server_certificate_verification(true);
  11842. cli.set_follow_location(true);
  11843. auto res = cli.Get("/");
  11844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11845. ASSERT_EQ(StatusCode::OK_200, res->status);
  11846. }
  11847. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11848. SSLClient cli("wWw.YouTube.Com");
  11849. cli.set_ca_cert_path(CA_CERT_FILE);
  11850. cli.enable_server_certificate_verification(true);
  11851. cli.enable_server_hostname_verification(true);
  11852. cli.set_follow_location(true);
  11853. auto res = cli.Get("/");
  11854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11855. ASSERT_EQ(StatusCode::OK_200, res->status);
  11856. }
  11857. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11858. SSLClient cli("gOoGlE.COm");
  11859. cli.enable_server_certificate_verification(true);
  11860. cli.enable_server_hostname_verification(true);
  11861. cli.set_follow_location(true);
  11862. auto res = cli.Get("/");
  11863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11864. ASSERT_EQ(StatusCode::OK_200, res->status);
  11865. }
  11866. TEST(SSLClientTest, Issue2004_Online) {
  11867. Client client("https://google.com");
  11868. client.set_follow_location(true);
  11869. auto res = client.Get("/");
  11870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11871. ASSERT_EQ(StatusCode::OK_200, res->status);
  11872. auto body = res->body;
  11873. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11874. }
  11875. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11876. // Create SSLClient with invalid cert/key to make is_valid() return false
  11877. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11878. "nonexistent_key.pem");
  11879. // is_valid() should be false due to cert loading failure
  11880. ASSERT_FALSE(cli.is_valid());
  11881. auto res = cli.Get("/");
  11882. ASSERT_FALSE(res);
  11883. EXPECT_EQ(Error::SSLConnection, res.error());
  11884. }
  11885. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11886. // Test for Issue #2251: SSL error not properly reported when client cert
  11887. // and key paths are swapped or mismatched
  11888. // This simulates the scenario where user accidentally swaps the cert and key
  11889. // files
  11890. // Using client cert file as private key and vice versa (completely wrong)
  11891. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11892. // Should fail validation due to cert/key mismatch
  11893. ASSERT_FALSE(cli.is_valid());
  11894. // Attempt to make a request should fail with proper error
  11895. auto res = cli.Get("/");
  11896. ASSERT_FALSE(res);
  11897. EXPECT_EQ(Error::SSLConnection, res.error());
  11898. // SSL error should be recorded in the Result object (this is the key fix for
  11899. // Issue #2251)
  11900. auto backend_error = res.ssl_backend_error();
  11901. EXPECT_NE(0u, backend_error);
  11902. }
  11903. // Tests cert/key mismatch detection at the TLS context level
  11904. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11905. // Test that using mismatched cert/key causes connection failure.
  11906. // We verify this at the SSLClient level rather than through internal
  11907. // TLS API functions.
  11908. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11909. cli.enable_server_certificate_verification(false);
  11910. cli.set_connection_timeout(2);
  11911. // The mismatch should cause a connection or handshake error
  11912. auto res = cli.Get("/test");
  11913. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11914. // Either way, the request should fail
  11915. EXPECT_FALSE(res);
  11916. }
  11917. #endif
  11918. #if 0
  11919. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11920. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11921. ASSERT_TRUE(cli != nullptr);
  11922. cli->set_address_family(AF_INET6);
  11923. cli->set_interface("en0");
  11924. auto res = cli->Get("/get");
  11925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11926. ASSERT_EQ(StatusCode::OK_200, res->status);
  11927. }
  11928. #endif
  11929. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11930. #ifdef CPPHTTPLIB_SSL_ENABLED
  11931. void ClientCertPresent(
  11932. const std::string &client_cert_file,
  11933. const std::string &client_private_key_file,
  11934. const std::string &client_encrypted_private_key_pass = std::string()) {
  11935. using namespace httplib::tls;
  11936. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11937. CLIENT_CA_CERT_DIR);
  11938. ASSERT_TRUE(svr.is_valid());
  11939. svr.Get("/test", [&](const Request &req, Response &res) {
  11940. res.set_content("test", "text/plain");
  11941. auto cert = req.peer_cert();
  11942. ASSERT_TRUE(static_cast<bool>(cert));
  11943. std::string common_name = cert.subject_cn();
  11944. EXPECT_EQ("Common Name", common_name);
  11945. });
  11946. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11947. auto se = detail::scope_exit([&] {
  11948. svr.stop();
  11949. t.join();
  11950. ASSERT_FALSE(svr.is_running());
  11951. });
  11952. svr.wait_until_ready();
  11953. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11954. client_encrypted_private_key_pass);
  11955. cli.enable_server_certificate_verification(false);
  11956. cli.set_connection_timeout(30);
  11957. auto res = cli.Get("/test");
  11958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11959. ASSERT_EQ(StatusCode::OK_200, res->status);
  11960. }
  11961. TEST(SSLClientServerTest, ClientCertPresent) {
  11962. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11963. }
  11964. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11965. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11966. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11967. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11968. }
  11969. // PEM memory-based constructor tests (works with all TLS backends)
  11970. void PemMemoryClientCertPresent(
  11971. const std::string &client_cert_file,
  11972. const std::string &client_private_key_file,
  11973. const std::string &client_encrypted_private_key_pass = std::string()) {
  11974. // Read PEM files into memory
  11975. std::string server_cert_pem, server_key_pem;
  11976. std::string client_ca_pem;
  11977. std::string client_cert_pem, client_key_pem;
  11978. read_file(SERVER_CERT_FILE, server_cert_pem);
  11979. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11980. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11981. read_file(client_cert_file, client_cert_pem);
  11982. read_file(client_private_key_file, client_key_pem);
  11983. // Create server with PEM memory
  11984. SSLServer::PemMemory server_pem = {
  11985. server_cert_pem.c_str(),
  11986. server_cert_pem.size(),
  11987. server_key_pem.c_str(),
  11988. server_key_pem.size(),
  11989. client_ca_pem.c_str(),
  11990. client_ca_pem.size(),
  11991. nullptr // no password for server key
  11992. };
  11993. SSLServer svr(server_pem);
  11994. ASSERT_TRUE(svr.is_valid());
  11995. svr.Get("/test", [&](const Request &, Response &res) {
  11996. res.set_content("test", "text/plain");
  11997. });
  11998. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11999. auto se = detail::scope_exit([&] {
  12000. svr.stop();
  12001. t.join();
  12002. ASSERT_FALSE(svr.is_running());
  12003. });
  12004. svr.wait_until_ready();
  12005. // Create client with PEM memory
  12006. const char *password = client_encrypted_private_key_pass.empty()
  12007. ? nullptr
  12008. : client_encrypted_private_key_pass.c_str();
  12009. SSLClient::PemMemory client_pem = {
  12010. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12011. client_key_pem.size(), password};
  12012. SSLClient cli(HOST, PORT, client_pem);
  12013. cli.enable_server_certificate_verification(false);
  12014. cli.set_connection_timeout(30);
  12015. auto res = cli.Get("/test");
  12016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12017. ASSERT_EQ(StatusCode::OK_200, res->status);
  12018. }
  12019. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12020. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12021. }
  12022. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12023. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12024. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12025. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12026. }
  12027. TEST(SSLClientServerTest, ClientCertMissing) {
  12028. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12029. CLIENT_CA_CERT_DIR);
  12030. ASSERT_TRUE(svr.is_valid());
  12031. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12032. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12033. auto se = detail::scope_exit([&] {
  12034. svr.stop();
  12035. t.join();
  12036. ASSERT_FALSE(svr.is_running());
  12037. });
  12038. svr.wait_until_ready();
  12039. SSLClient cli(HOST, PORT);
  12040. cli.set_connection_timeout(30);
  12041. auto res = cli.Get("/test");
  12042. ASSERT_TRUE(!res);
  12043. // When client cert is missing and server requires it, connection fails
  12044. // Error type depends on backend implementation
  12045. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12046. res.error() == Error::SSLConnection);
  12047. // Verify backend error is captured
  12048. // Note: This test may have different error codes depending on the exact
  12049. // verification failure
  12050. EXPECT_NE(0UL, res.ssl_backend_error());
  12051. }
  12052. TEST(SSLClientServerTest, TrustDirOptional) {
  12053. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12054. ASSERT_TRUE(svr.is_valid());
  12055. svr.Get("/test", [&](const Request &, Response &res) {
  12056. res.set_content("test", "text/plain");
  12057. });
  12058. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12059. auto se = detail::scope_exit([&] {
  12060. svr.stop();
  12061. t.join();
  12062. ASSERT_FALSE(svr.is_running());
  12063. });
  12064. svr.wait_until_ready();
  12065. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12066. cli.enable_server_certificate_verification(false);
  12067. cli.set_connection_timeout(30);
  12068. auto res = cli.Get("/test");
  12069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12070. ASSERT_EQ(StatusCode::OK_200, res->status);
  12071. }
  12072. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12073. class NoListenSSLServer : public SSLServer {
  12074. public:
  12075. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12076. const char *client_ca_cert_file_path,
  12077. const char *client_ca_cert_dir_path = nullptr)
  12078. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12079. client_ca_cert_dir_path),
  12080. stop_(false) {}
  12081. std::atomic_bool stop_;
  12082. private:
  12083. bool process_and_close_socket(socket_t /*sock*/) override {
  12084. // Don't create SSL context
  12085. while (!stop_.load()) {
  12086. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12087. }
  12088. return true;
  12089. }
  12090. };
  12091. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12092. CLIENT_CA_CERT_FILE);
  12093. ASSERT_TRUE(svr.is_valid());
  12094. svr.Get("/test", [&](const Request &, Response &res) {
  12095. res.set_content("test", "text/plain");
  12096. });
  12097. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12098. auto se = detail::scope_exit([&] {
  12099. svr.stop_ = true;
  12100. svr.stop();
  12101. t.join();
  12102. ASSERT_FALSE(svr.is_running());
  12103. });
  12104. svr.wait_until_ready();
  12105. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12106. cli.enable_server_certificate_verification(false);
  12107. cli.set_connection_timeout(1);
  12108. auto res = cli.Get("/test");
  12109. ASSERT_TRUE(!res);
  12110. EXPECT_EQ(Error::SSLConnection, res.error());
  12111. // Timeout results in WantRead error code (maps to backend-specific value)
  12112. EXPECT_NE(0, res.ssl_error());
  12113. }
  12114. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12115. // Test SSLServer with client certificate verification using the standard
  12116. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12118. CLIENT_CA_CERT_DIR);
  12119. ASSERT_TRUE(svr.is_valid());
  12120. svr.Get("/test", [&](const Request &req, Response &res) {
  12121. res.set_content("test", "text/plain");
  12122. auto cert = req.peer_cert();
  12123. ASSERT_TRUE(static_cast<bool>(cert));
  12124. auto common_name = cert.subject_cn();
  12125. EXPECT_EQ("Common Name", common_name);
  12126. });
  12127. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12128. auto se = detail::scope_exit([&] {
  12129. svr.stop();
  12130. t.join();
  12131. ASSERT_FALSE(svr.is_running());
  12132. });
  12133. svr.wait_until_ready();
  12134. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12135. cli.enable_server_certificate_verification(false);
  12136. cli.set_connection_timeout(30);
  12137. auto res = cli.Get("/test");
  12138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12139. ASSERT_EQ(StatusCode::OK_200, res->status);
  12140. }
  12141. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12142. // Verifies that wildcard matching and exact matching work consistently
  12143. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12144. using namespace httplib::tls;
  12145. // We need a running server to test against
  12146. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12147. ASSERT_TRUE(svr.is_valid());
  12148. svr.Get("/test", [](const Request &, Response &res) {
  12149. res.set_content("ok", "text/plain");
  12150. });
  12151. thread t([&]() { svr.listen(HOST, PORT); });
  12152. auto se = detail::scope_exit([&] {
  12153. svr.stop();
  12154. t.join();
  12155. });
  12156. svr.wait_until_ready();
  12157. bool verify_callback_called = false;
  12158. bool verify_result_wrong = false;
  12159. SSLClient cli(HOST, PORT);
  12160. cli.enable_server_certificate_verification(true);
  12161. cli.set_ca_cert_path(CA_CERT_FILE);
  12162. cli.set_connection_timeout(5);
  12163. // Note: Test certificate has CN="Common Name", not "localhost"
  12164. bool verify_result_cn = false;
  12165. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12166. verify_callback_called = true;
  12167. if (!ctx.cert) return false;
  12168. // Test 1: "Common Name" should match (our test server cert CN)
  12169. verify_result_cn = ctx.check_hostname("Common Name");
  12170. // Test 2: wrong hostname should not match
  12171. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12172. return true; // Accept for the purpose of this test
  12173. });
  12174. auto res = cli.Get("/test");
  12175. // The request may succeed or fail depending on cert configuration
  12176. // but the callback should have been called
  12177. ASSERT_TRUE(verify_callback_called)
  12178. << "Verify callback should have been called";
  12179. // CN="Common Name" should match our test certificate
  12180. //
  12181. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12182. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12183. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12184. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12185. // <openssl/base.h>, which is included transitively when
  12186. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12187. #if defined(OPENSSL_IS_BORINGSSL)
  12188. EXPECT_FALSE(verify_result_cn)
  12189. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12190. #else
  12191. EXPECT_TRUE(verify_result_cn)
  12192. << "verify_hostname should match 'Common Name' (certificate CN)";
  12193. #endif
  12194. // Wrong hostname should not match
  12195. EXPECT_FALSE(verify_result_wrong)
  12196. << "verify_hostname should not match 'wronghost.example.com'";
  12197. }
  12198. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12199. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12200. // X509_check_ip behavior and must hold for every backend.
  12201. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12202. using namespace httplib::tls;
  12203. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12204. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12205. ASSERT_TRUE(svr.is_valid());
  12206. svr.Get("/test", [](const Request &, Response &res) {
  12207. res.set_content("ok", "text/plain");
  12208. });
  12209. thread t([&]() { svr.listen(HOST, PORT); });
  12210. auto se = detail::scope_exit([&] {
  12211. svr.stop();
  12212. t.join();
  12213. });
  12214. svr.wait_until_ready();
  12215. bool verify_callback_called = false;
  12216. bool ip_matched_via_cn = true;
  12217. SSLClient cli(HOST, PORT);
  12218. cli.enable_server_certificate_verification(true);
  12219. cli.set_ca_cert_path(CA_CERT_FILE);
  12220. cli.set_connection_timeout(5);
  12221. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12222. verify_callback_called = true;
  12223. if (!ctx.cert) return false;
  12224. // The IP appears only in the CN, so it must NOT be accepted.
  12225. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12226. return true; // Accept for the purpose of this test
  12227. });
  12228. cli.Get("/test");
  12229. ASSERT_TRUE(verify_callback_called)
  12230. << "Verify callback should have been called";
  12231. EXPECT_FALSE(ip_matched_via_cn)
  12232. << "An IP host must not be authenticated via the certificate CN";
  12233. }
  12234. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12235. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12236. using namespace httplib::tls;
  12237. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12238. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12239. ASSERT_TRUE(svr.is_valid());
  12240. svr.Get("/test", [](const Request &, Response &res) {
  12241. res.set_content("ok", "text/plain");
  12242. });
  12243. thread t([&]() { svr.listen(HOST, PORT); });
  12244. auto se = detail::scope_exit([&] {
  12245. svr.stop();
  12246. t.join();
  12247. });
  12248. svr.wait_until_ready();
  12249. bool verify_callback_called = false;
  12250. bool san_matched = false;
  12251. bool wrong_ipv6_matched = true;
  12252. bool cn_ipv6_matched = true;
  12253. SSLClient cli(HOST, PORT);
  12254. cli.enable_server_certificate_verification(true);
  12255. cli.set_ca_cert_path(CA_CERT_FILE);
  12256. cli.set_connection_timeout(5);
  12257. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12258. verify_callback_called = true;
  12259. if (!ctx.cert) return false;
  12260. // Matches the IPv6 iPAddress SAN.
  12261. san_matched = ctx.check_hostname("2001:db8::1");
  12262. // A different IPv6 address must not match.
  12263. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12264. // "::1" lives only in the CN, so it must not be accepted.
  12265. cn_ipv6_matched = ctx.check_hostname("::1");
  12266. return true; // Accept for the purpose of this test
  12267. });
  12268. cli.Get("/test");
  12269. ASSERT_TRUE(verify_callback_called)
  12270. << "Verify callback should have been called";
  12271. EXPECT_TRUE(san_matched)
  12272. << "verify_hostname should match an IPv6 iPAddress SAN";
  12273. EXPECT_FALSE(wrong_ipv6_matched)
  12274. << "verify_hostname should not match a non-matching IPv6 address";
  12275. EXPECT_FALSE(cn_ipv6_matched)
  12276. << "An IPv6 host must not be authenticated via the certificate CN";
  12277. }
  12278. #endif
  12279. // mbedTLS-specific callback constructor test
  12280. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12281. #ifdef CPPHTTPLIB_SSL_ENABLED
  12282. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12283. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12284. ASSERT_TRUE(svr.is_valid());
  12285. // Set up a handler to verify client certificate is present
  12286. bool client_cert_verified = false;
  12287. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12288. // Verify that client certificate was provided
  12289. client_cert_verified = true;
  12290. res.set_content("success", "text/plain");
  12291. });
  12292. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12293. auto se = detail::scope_exit([&] {
  12294. svr.stop();
  12295. t.join();
  12296. ASSERT_FALSE(svr.is_running());
  12297. });
  12298. svr.wait_until_ready();
  12299. // Client with certificate
  12300. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12301. cli.enable_server_certificate_verification(false);
  12302. cli.set_connection_timeout(30);
  12303. auto res = cli.Get("/test");
  12304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12305. ASSERT_EQ(StatusCode::OK_200, res->status);
  12306. ASSERT_TRUE(client_cert_verified);
  12307. EXPECT_EQ("success", res->body);
  12308. }
  12309. #endif
  12310. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12311. // backends
  12312. #ifdef CPPHTTPLIB_SSL_ENABLED
  12313. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12314. using namespace httplib::tls;
  12315. // Test that when client CA cert file is provided,
  12316. // the server properly requests and validates client certificates
  12317. // Create a server with client authentication
  12318. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12319. ASSERT_TRUE(svr.is_valid());
  12320. bool handler_called = false;
  12321. svr.Get("/test", [&](const Request &req, Response &res) {
  12322. handler_called = true;
  12323. // Verify that a client certificate was provided
  12324. auto cert = req.peer_cert();
  12325. ASSERT_TRUE(static_cast<bool>(cert));
  12326. // Get the issuer name
  12327. std::string issuer_str = cert.issuer_name();
  12328. ASSERT_FALSE(issuer_str.empty());
  12329. // The client certificate should be issued by our test CA
  12330. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12331. res.set_content("authenticated", "text/plain");
  12332. });
  12333. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12334. auto se = detail::scope_exit([&] {
  12335. svr.stop();
  12336. t.join();
  12337. ASSERT_FALSE(svr.is_running());
  12338. });
  12339. svr.wait_until_ready();
  12340. // Connect with a client certificate issued by the CA
  12341. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12342. cli.enable_server_certificate_verification(false);
  12343. cli.set_connection_timeout(30);
  12344. auto res = cli.Get("/test");
  12345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12346. ASSERT_EQ(StatusCode::OK_200, res->status);
  12347. ASSERT_TRUE(handler_called);
  12348. EXPECT_EQ("authenticated", res->body);
  12349. }
  12350. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12351. using namespace httplib::tls;
  12352. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12353. ASSERT_TRUE(svr.is_valid());
  12354. svr.Get("/test", [](const Request &, Response &res) {
  12355. res.set_content("ok", "text/plain");
  12356. });
  12357. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12358. auto se = detail::scope_exit([&] {
  12359. svr.stop();
  12360. t.join();
  12361. });
  12362. svr.wait_until_ready();
  12363. SSLClient cli(HOST, PORT);
  12364. cli.enable_server_certificate_verification(false);
  12365. cli.set_connection_timeout(30);
  12366. bool cert_checked = false;
  12367. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12368. if (ctx.cert) {
  12369. auto sans = ctx.sans();
  12370. // Test certificate may or may not have SANs - just verify the API
  12371. // works If SANs exist, verify the types are valid
  12372. for (const auto &san : sans) {
  12373. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12374. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12375. san.type == SanType::OTHER);
  12376. EXPECT_FALSE(san.value.empty());
  12377. }
  12378. cert_checked = true;
  12379. }
  12380. return true;
  12381. });
  12382. auto res = cli.Get("/test");
  12383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12384. EXPECT_TRUE(cert_checked);
  12385. }
  12386. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12387. using namespace httplib::tls;
  12388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12389. ASSERT_TRUE(svr.is_valid());
  12390. svr.Get("/test", [](const Request &, Response &res) {
  12391. res.set_content("ok", "text/plain");
  12392. });
  12393. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12394. auto se = detail::scope_exit([&] {
  12395. svr.stop();
  12396. t.join();
  12397. });
  12398. svr.wait_until_ready();
  12399. SSLClient cli(HOST, PORT);
  12400. cli.enable_server_certificate_verification(false);
  12401. cli.set_connection_timeout(30);
  12402. bool validity_checked = false;
  12403. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12404. if (ctx.cert) {
  12405. time_t not_before = 0, not_after = 0;
  12406. bool result = ctx.validity(not_before, not_after);
  12407. EXPECT_TRUE(result);
  12408. // Verify that not_before < now < not_after for a valid cert
  12409. time_t now = time(nullptr);
  12410. EXPECT_LT(not_before, now);
  12411. EXPECT_GT(not_after, now);
  12412. validity_checked = true;
  12413. }
  12414. return true;
  12415. });
  12416. auto res = cli.Get("/test");
  12417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12418. EXPECT_TRUE(validity_checked);
  12419. }
  12420. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12421. using namespace httplib::tls;
  12422. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12423. ASSERT_TRUE(svr.is_valid());
  12424. svr.Get("/test", [](const Request &, Response &res) {
  12425. res.set_content("ok", "text/plain");
  12426. });
  12427. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12428. auto se = detail::scope_exit([&] {
  12429. svr.stop();
  12430. t.join();
  12431. });
  12432. svr.wait_until_ready();
  12433. SSLClient cli(HOST, PORT);
  12434. cli.enable_server_certificate_verification(false);
  12435. cli.set_connection_timeout(30);
  12436. bool serial_checked = false;
  12437. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12438. if (ctx.cert) {
  12439. std::string serial = ctx.serial();
  12440. EXPECT_FALSE(serial.empty());
  12441. // Serial should be a hex string
  12442. for (char c : serial) {
  12443. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12444. (c >= 'a' && c <= 'f'));
  12445. }
  12446. serial_checked = true;
  12447. }
  12448. return true;
  12449. });
  12450. auto res = cli.Get("/test");
  12451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12452. EXPECT_TRUE(serial_checked);
  12453. }
  12454. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12455. // Test 1: Valid CA file - no error should be recorded
  12456. {
  12457. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12458. CLIENT_CA_CERT_FILE);
  12459. ASSERT_TRUE(svr.is_valid());
  12460. // With valid setup, last_ssl_error should be 0
  12461. EXPECT_EQ(0, svr.ssl_last_error());
  12462. }
  12463. // Test 2: Invalid CA file content
  12464. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12465. {
  12466. // Create a temporary file with completely invalid content
  12467. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12468. {
  12469. std::ofstream ofs(temp_invalid_ca);
  12470. ofs << "This is not a certificate file at all\n";
  12471. ofs << "Just plain text content\n";
  12472. }
  12473. // Create server with invalid CA file
  12474. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12475. // Clean up temporary file
  12476. std::remove(temp_invalid_ca);
  12477. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12478. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12479. // Note: SSL_CTX_load_verify_locations typically fails first,
  12480. // but our error handling code path is still exercised
  12481. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12482. }
  12483. }
  12484. TEST(VerifyCallbackTest, VerifyContextFields) {
  12485. using namespace httplib::tls;
  12486. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12487. ASSERT_TRUE(svr.is_valid());
  12488. svr.Get("/test", [](const Request &, Response &res) {
  12489. res.set_content("ok", "text/plain");
  12490. });
  12491. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12492. auto se = detail::scope_exit([&] {
  12493. svr.stop();
  12494. t.join();
  12495. });
  12496. svr.wait_until_ready();
  12497. SSLClient cli(HOST, PORT);
  12498. cli.enable_server_certificate_verification(false);
  12499. cli.set_connection_timeout(30);
  12500. int callback_count = 0;
  12501. bool saw_leaf_cert = false;
  12502. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12503. if (ctx.cert) {
  12504. callback_count++;
  12505. // We should see at least one certificate (the leaf)
  12506. std::string cn = ctx.subject_cn();
  12507. if (!cn.empty()) { saw_leaf_cert = true; }
  12508. // Verify context fields are populated
  12509. EXPECT_NE(ctx.session, nullptr);
  12510. EXPECT_GE(ctx.depth, 0);
  12511. }
  12512. return true;
  12513. });
  12514. auto res = cli.Get("/test");
  12515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12516. EXPECT_GT(callback_count, 0);
  12517. EXPECT_TRUE(saw_leaf_cert);
  12518. }
  12519. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12520. using httplib::tls::TlsError;
  12521. // Test that verify_error_to_string returns empty for success
  12522. std::string success_str = TlsError::verify_error_to_string(0);
  12523. EXPECT_TRUE(success_str.empty());
  12524. // Test that verify_error_to_string returns non-empty for error codes
  12525. // Using a common error code (certificate expired)
  12526. std::string error_str =
  12527. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12528. EXPECT_FALSE(error_str.empty());
  12529. }
  12530. TEST(SessionVerifierTest, CertificateAccepted) {
  12531. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12532. ASSERT_TRUE(svr.is_valid());
  12533. svr.Get("/test", [](const Request &, Response &res) {
  12534. res.set_content("ok", "text/plain");
  12535. });
  12536. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12537. auto se = detail::scope_exit([&] {
  12538. svr.stop();
  12539. t.join();
  12540. });
  12541. svr.wait_until_ready();
  12542. SSLClient cli(HOST, PORT);
  12543. cli.enable_server_certificate_verification(false);
  12544. cli.set_connection_timeout(30);
  12545. bool callback_called = false;
  12546. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12547. EXPECT_NE(session, nullptr);
  12548. callback_called = true;
  12549. return SSLVerifierResponse::CertificateAccepted;
  12550. });
  12551. auto res = cli.Get("/test");
  12552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12553. EXPECT_EQ(200, res->status);
  12554. EXPECT_TRUE(callback_called);
  12555. }
  12556. TEST(SessionVerifierTest, CertificateRejected) {
  12557. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12558. ASSERT_TRUE(svr.is_valid());
  12559. svr.Get("/test", [](const Request &, Response &res) {
  12560. res.set_content("ok", "text/plain");
  12561. });
  12562. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12563. auto se = detail::scope_exit([&] {
  12564. svr.stop();
  12565. t.join();
  12566. });
  12567. svr.wait_until_ready();
  12568. SSLClient cli(HOST, PORT);
  12569. cli.enable_server_certificate_verification(false);
  12570. cli.set_connection_timeout(30);
  12571. bool callback_called = false;
  12572. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12573. EXPECT_NE(session, nullptr);
  12574. callback_called = true;
  12575. return SSLVerifierResponse::CertificateRejected;
  12576. });
  12577. auto res = cli.Get("/test");
  12578. EXPECT_FALSE(res);
  12579. EXPECT_TRUE(callback_called);
  12580. }
  12581. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12583. ASSERT_TRUE(svr.is_valid());
  12584. svr.Get("/test", [](const Request &, Response &res) {
  12585. res.set_content("ok", "text/plain");
  12586. });
  12587. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12588. auto se = detail::scope_exit([&] {
  12589. svr.stop();
  12590. t.join();
  12591. });
  12592. svr.wait_until_ready();
  12593. // NoDecisionMade with verification disabled should succeed (no default check)
  12594. SSLClient cli(HOST, PORT);
  12595. cli.enable_server_certificate_verification(false);
  12596. cli.set_connection_timeout(30);
  12597. bool callback_called = false;
  12598. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12599. EXPECT_NE(session, nullptr);
  12600. callback_called = true;
  12601. return SSLVerifierResponse::NoDecisionMade;
  12602. });
  12603. auto res = cli.Get("/test");
  12604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12605. EXPECT_EQ(200, res->status);
  12606. EXPECT_TRUE(callback_called);
  12607. }
  12608. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12609. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12610. ASSERT_TRUE(svr.is_valid());
  12611. svr.Get("/test", [](const Request &, Response &res) {
  12612. res.set_content("ok", "text/plain");
  12613. });
  12614. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12615. auto se = detail::scope_exit([&] {
  12616. svr.stop();
  12617. t.join();
  12618. });
  12619. svr.wait_until_ready();
  12620. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12621. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12622. // so we only check that the request fails, not whether the callback was
  12623. // called.
  12624. SSLClient cli(HOST, PORT);
  12625. cli.enable_server_certificate_verification(true);
  12626. cli.set_connection_timeout(30);
  12627. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12628. EXPECT_NE(session, nullptr);
  12629. return SSLVerifierResponse::NoDecisionMade;
  12630. });
  12631. auto res = cli.Get("/test");
  12632. EXPECT_FALSE(res);
  12633. }
  12634. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12635. // Test SSL server using PemMemory constructor with client CA certificates
  12636. // Read PEM files
  12637. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12638. read_file(SERVER_CERT_FILE, server_cert_pem);
  12639. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12640. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12641. // Create SSLServer with PemMemory constructor including client CA
  12642. SSLServer::PemMemory server_pem = {
  12643. server_cert_pem.c_str(),
  12644. server_cert_pem.size(),
  12645. server_key_pem.c_str(),
  12646. server_key_pem.size(),
  12647. client_ca_pem.c_str(),
  12648. client_ca_pem.size(),
  12649. nullptr // no password for server key
  12650. };
  12651. SSLServer svr(server_pem);
  12652. ASSERT_TRUE(svr.is_valid());
  12653. // No SSL error should be recorded for valid setup
  12654. EXPECT_EQ(0, svr.ssl_last_error());
  12655. // Set up server endpoints
  12656. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12657. res.set_content("ok", "text/plain");
  12658. });
  12659. // Start server in a thread
  12660. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12661. svr.wait_until_ready();
  12662. // Connect with client certificate (using constructor with paths)
  12663. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12664. cli.enable_server_certificate_verification(false);
  12665. auto res = cli.Get("/test-pem-ca");
  12666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12667. EXPECT_EQ(200, res->status);
  12668. EXPECT_EQ("ok", res->body);
  12669. svr.stop();
  12670. server_thread.join();
  12671. }
  12672. #endif
  12673. #ifdef _WIN32
  12674. TEST(CleanupTest, WSACleanup) {
  12675. int ret = WSACleanup();
  12676. ASSERT_EQ(0, ret);
  12677. }
  12678. #endif
  12679. #ifndef CPPHTTPLIB_SSL_ENABLED
  12680. TEST(NoSSLSupport, SimpleInterface) {
  12681. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12682. }
  12683. #endif
  12684. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12685. TEST(InvalidScheme, SimpleInterface) {
  12686. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12687. }
  12688. #endif
  12689. TEST(NoScheme, SimpleInterface) {
  12690. Client cli("yahoo.com:80");
  12691. ASSERT_TRUE(cli.is_valid());
  12692. }
  12693. TEST(SendAPI, SimpleInterface_Online) {
  12694. Client cli("http://yahoo.com");
  12695. Request req;
  12696. req.method = "GET";
  12697. req.path = "/";
  12698. auto res = cli.send(req);
  12699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12700. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12701. }
  12702. TEST(SendAPI, WithParamsInRequest) {
  12703. Server svr;
  12704. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12705. EXPECT_TRUE(req.has_param("test"));
  12706. EXPECT_EQ("test_value", req.get_param_value("test"));
  12707. });
  12708. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12709. auto se = detail::scope_exit([&] {
  12710. svr.stop();
  12711. t.join();
  12712. ASSERT_FALSE(svr.is_running());
  12713. });
  12714. svr.wait_until_ready();
  12715. Client cli(HOST, PORT);
  12716. {
  12717. Request req;
  12718. req.method = "GET";
  12719. req.path = "/";
  12720. req.params.emplace("test", "test_value");
  12721. auto res = cli.send(req);
  12722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12723. }
  12724. {
  12725. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12727. }
  12728. }
  12729. TEST(ClientImplMethods, GetSocketTest) {
  12730. httplib::Server svr;
  12731. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12732. res.status = StatusCode::OK_200;
  12733. });
  12734. auto port = svr.bind_to_any_port("127.0.0.1");
  12735. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12736. auto se = detail::scope_exit([&] {
  12737. svr.stop();
  12738. thread.join();
  12739. ASSERT_FALSE(svr.is_running());
  12740. });
  12741. svr.wait_until_ready();
  12742. {
  12743. httplib::Client cli("127.0.0.1", port);
  12744. cli.set_keep_alive(true);
  12745. // Use the behavior of cpp-httplib of opening the connection
  12746. // only when the first request happens. If that changes,
  12747. // this test would be obsolete.
  12748. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12749. // This also implicitly tests the server. But other tests would fail much
  12750. // earlier than this one to be considered.
  12751. auto res = cli.Get("/");
  12752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12753. EXPECT_EQ(StatusCode::OK_200, res->status);
  12754. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12755. }
  12756. }
  12757. #ifdef CPPHTTPLIB_SSL_ENABLED
  12758. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12759. Client cli("http://yahoo.com");
  12760. auto res = cli.Get("/");
  12761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12762. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12763. cli.set_follow_location(true);
  12764. res = cli.Get("/");
  12765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12766. EXPECT_EQ(StatusCode::OK_200, res->status);
  12767. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12768. }
  12769. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12770. Client cli("https://yahoo.com");
  12771. auto res = cli.Get("/");
  12772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12773. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12774. cli.set_follow_location(true);
  12775. res = cli.Get("/");
  12776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12777. EXPECT_EQ(StatusCode::OK_200, res->status);
  12778. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12779. }
  12780. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12781. Client cli("https://yahoo.com");
  12782. auto res = cli.Get("/");
  12783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12784. ASSERT_FALSE(!res);
  12785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12786. ASSERT_FALSE(res == nullptr);
  12787. ASSERT_TRUE(res != nullptr);
  12788. EXPECT_EQ(Error::Success, res.error());
  12789. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12790. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12791. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12792. cli.set_follow_location(true);
  12793. res = cli.Get("/");
  12794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12795. EXPECT_EQ(Error::Success, res.error());
  12796. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12797. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12798. EXPECT_EQ(StatusCode::OK_200, res->status);
  12799. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12800. }
  12801. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12802. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12803. Client cli("https://cdnjs.cloudflare.com");
  12804. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12805. Headers{{"Accept-Encoding", "br"}});
  12806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12807. EXPECT_EQ(StatusCode::OK_200, res->status);
  12808. EXPECT_EQ(287630U, res->body.size());
  12809. EXPECT_EQ("application/javascript; charset=utf-8",
  12810. res->get_header_value("Content-Type"));
  12811. }
  12812. #endif
  12813. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12814. #undef REDIR_HOST // Silence compiler warning
  12815. #define REDIR_HOST "https://httpbingo.org"
  12816. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12817. Client cli(REDIR_HOST);
  12818. cli.set_follow_location(true);
  12819. auto res =
  12820. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12822. EXPECT_EQ(StatusCode::OK_200, res->status);
  12823. }
  12824. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12825. Client cli(REDIR_HOST);
  12826. cli.set_follow_location(true);
  12827. Params params;
  12828. params.emplace("url", "http://example.com");
  12829. params.emplace("status_code", "302");
  12830. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12832. EXPECT_EQ(StatusCode::OK_200, res->status);
  12833. }
  12834. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12835. Client cli(REDIR_HOST);
  12836. cli.set_follow_location(true);
  12837. Params params;
  12838. params.emplace("url", "http://example.com");
  12839. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12841. EXPECT_EQ(StatusCode::OK_200, res->status);
  12842. }
  12843. TEST(HttpToHttpsRedirectTest, CertFile) {
  12844. auto ssl_port = PORT + 1;
  12845. Server svr;
  12846. ASSERT_TRUE(svr.is_valid());
  12847. svr.Get("/index", [&](const Request &, Response &res) {
  12848. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12849. "/index");
  12850. svr.stop();
  12851. });
  12852. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12853. ASSERT_TRUE(ssl_svr.is_valid());
  12854. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12855. res.set_content("test", "text/plain");
  12856. ssl_svr.stop();
  12857. });
  12858. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12859. thread t2 =
  12860. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12861. auto se = detail::scope_exit([&] {
  12862. t2.join();
  12863. t.join();
  12864. ASSERT_FALSE(svr.is_running());
  12865. });
  12866. svr.wait_until_ready();
  12867. ssl_svr.wait_until_ready();
  12868. Client cli("127.0.0.1", PORT);
  12869. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12870. cli.enable_server_certificate_verification(true);
  12871. cli.set_follow_location(true);
  12872. cli.set_connection_timeout(30);
  12873. auto res = cli.Get("/index");
  12874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12875. ASSERT_EQ(StatusCode::OK_200, res->status);
  12876. }
  12877. TEST(SSLClientRedirectTest, CertFile) {
  12878. auto ssl_port = PORT + 1;
  12879. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12880. ASSERT_TRUE(ssl_svr1.is_valid());
  12881. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12882. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12883. "/index");
  12884. ssl_svr1.stop();
  12885. });
  12886. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12887. ASSERT_TRUE(ssl_svr2.is_valid());
  12888. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12889. res.set_content("test", "text/plain");
  12890. ssl_svr2.stop();
  12891. });
  12892. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12893. thread t2 =
  12894. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12895. auto se = detail::scope_exit([&] {
  12896. t2.join();
  12897. t.join();
  12898. ASSERT_FALSE(ssl_svr1.is_running());
  12899. });
  12900. ssl_svr1.wait_until_ready();
  12901. ssl_svr2.wait_until_ready();
  12902. SSLClient cli("127.0.0.1", PORT);
  12903. std::string cert;
  12904. read_file(SERVER_CERT2_FILE, cert);
  12905. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12906. cli.enable_server_certificate_verification(true);
  12907. cli.set_follow_location(true);
  12908. cli.set_connection_timeout(30);
  12909. auto res = cli.Get("/index");
  12910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12911. ASSERT_EQ(StatusCode::OK_200, res->status);
  12912. }
  12913. #endif
  12914. #ifdef CPPHTTPLIB_SSL_ENABLED
  12915. // Test that set_ca_cert_store() skips system certs (consistent with
  12916. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12917. // should be trusted - system certs should NOT be loaded.
  12918. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12919. // Load a specific cert that is NOT a system CA cert
  12920. std::string cert;
  12921. read_file(SERVER_CERT2_FILE, cert);
  12922. SSLClient cli("google.com");
  12923. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12924. cli.enable_server_certificate_verification(true);
  12925. // This should FAIL because:
  12926. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12927. // 2. System certs should NOT be loaded when custom store is set
  12928. // If system certs WERE loaded, this would succeed
  12929. auto res = cli.Get("/");
  12930. ASSERT_FALSE(res);
  12931. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12932. }
  12933. // Same as above, but through the native store handle path. Regression test:
  12934. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12935. // merged system certs into the user-provided store.
  12936. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12937. std::string cert;
  12938. read_file(SERVER_CERT2_FILE, cert);
  12939. SSLClient cli("google.com");
  12940. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12941. cli.enable_server_certificate_verification(true);
  12942. auto res = cli.Get("/");
  12943. ASSERT_FALSE(res);
  12944. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12945. }
  12946. // A custom store set via the native handle must still verify a server whose
  12947. // cert it does contain.
  12948. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12949. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12950. ASSERT_TRUE(svr.is_valid());
  12951. svr.Get("/test", [&](const Request &, Response &res) {
  12952. res.set_content("test", "text/plain");
  12953. });
  12954. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12955. auto se = detail::scope_exit([&] {
  12956. svr.stop();
  12957. t.join();
  12958. ASSERT_FALSE(svr.is_running());
  12959. });
  12960. svr.wait_until_ready();
  12961. SSLClient cli("127.0.0.1", PORT);
  12962. std::string cert;
  12963. read_file(SERVER_CERT2_FILE, cert);
  12964. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12965. cli.enable_server_certificate_verification(true);
  12966. cli.set_connection_timeout(30);
  12967. auto res = cli.Get("/test");
  12968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12969. ASSERT_EQ(StatusCode::OK_200, res->status);
  12970. }
  12971. // CA certs loaded through the universal Client must be transferred to the
  12972. // client created internally for following an HTTPS redirect. Regression test:
  12973. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12974. // the CA data for redirect transfer.
  12975. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12976. auto ssl_port = PORT + 1;
  12977. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12978. ASSERT_TRUE(ssl_svr1.is_valid());
  12979. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12980. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12981. "/index");
  12982. });
  12983. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12984. ASSERT_TRUE(ssl_svr2.is_valid());
  12985. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12986. res.set_content("test", "text/plain");
  12987. });
  12988. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12989. thread t2 =
  12990. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12991. auto se = detail::scope_exit([&] {
  12992. ssl_svr2.stop();
  12993. ssl_svr1.stop();
  12994. t2.join();
  12995. t.join();
  12996. ASSERT_FALSE(ssl_svr1.is_running());
  12997. });
  12998. ssl_svr1.wait_until_ready();
  12999. ssl_svr2.wait_until_ready();
  13000. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13001. std::string cert;
  13002. read_file(SERVER_CERT2_FILE, cert);
  13003. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13004. cli.enable_server_certificate_verification(true);
  13005. cli.set_follow_location(true);
  13006. cli.set_connection_timeout(30);
  13007. auto res = cli.Get("/index");
  13008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13009. ASSERT_EQ(StatusCode::OK_200, res->status);
  13010. }
  13011. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13012. // so a host signed by a system CA verifies even though a custom CA is set
  13013. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13014. std::string cert;
  13015. read_file(SERVER_CERT2_FILE, cert);
  13016. SSLClient cli("google.com");
  13017. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13018. cli.enable_system_ca(true);
  13019. cli.enable_server_certificate_verification(true);
  13020. auto res = cli.Get("/");
  13021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13022. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13023. }
  13024. // The custom CA remains effective when combined with the system CA
  13025. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13026. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13027. ASSERT_TRUE(svr.is_valid());
  13028. svr.Get("/test", [&](const Request &, Response &res) {
  13029. res.set_content("test", "text/plain");
  13030. });
  13031. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13032. auto se = detail::scope_exit([&] {
  13033. svr.stop();
  13034. t.join();
  13035. ASSERT_FALSE(svr.is_running());
  13036. });
  13037. svr.wait_until_ready();
  13038. SSLClient cli("127.0.0.1", PORT);
  13039. std::string cert;
  13040. read_file(SERVER_CERT2_FILE, cert);
  13041. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13042. cli.enable_system_ca(true);
  13043. cli.enable_server_certificate_verification(true);
  13044. cli.set_connection_timeout(30);
  13045. auto res = cli.Get("/test");
  13046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13047. ASSERT_EQ(StatusCode::OK_200, res->status);
  13048. }
  13049. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13050. // skip chain verification entirely (only the certificate identity was
  13051. // checked), so a server presenting an untrusted certificate with a matching
  13052. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13053. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13054. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13055. ASSERT_TRUE(svr.is_valid());
  13056. svr.Get("/test", [&](const Request &, Response &res) {
  13057. res.set_content("test", "text/plain");
  13058. });
  13059. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13060. auto se = detail::scope_exit([&] {
  13061. svr.stop();
  13062. t.join();
  13063. ASSERT_FALSE(svr.is_running());
  13064. });
  13065. svr.wait_until_ready();
  13066. SSLClient cli("127.0.0.1", PORT);
  13067. std::string cert;
  13068. // A trusted CA that did not sign the server certificate. The server cert
  13069. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13070. // this connection.
  13071. read_file(CLIENT_CA_CERT_FILE, cert);
  13072. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13073. cli.enable_server_certificate_verification(true);
  13074. cli.set_connection_timeout(30);
  13075. auto res = cli.Get("/test");
  13076. ASSERT_FALSE(res);
  13077. }
  13078. // enable_system_ca(false) prevents system CA loading entirely
  13079. TEST(SSLClientTest, DisableSystemCa_Online) {
  13080. SSLClient cli("google.com");
  13081. cli.enable_system_ca(false);
  13082. cli.enable_server_certificate_verification(true);
  13083. auto res = cli.Get("/");
  13084. ASSERT_FALSE(res);
  13085. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13086. // itself when the CA chain is empty
  13087. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13088. res.error() == Error::SSLConnection);
  13089. }
  13090. // The universal Client forwards enable_system_ca()
  13091. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13092. std::string cert;
  13093. read_file(SERVER_CERT2_FILE, cert);
  13094. Client cli("https://google.com");
  13095. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13096. cli.enable_system_ca(true);
  13097. cli.enable_server_certificate_verification(true);
  13098. auto res = cli.Get("/");
  13099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13100. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13101. }
  13102. // The system CA policy must carry over to the client created internally for
  13103. // following a cross-host HTTPS redirect
  13104. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13105. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13106. ASSERT_TRUE(svr.is_valid());
  13107. svr.Get("/index", [&](const Request &, Response &res) {
  13108. res.set_redirect("https://www.google.com/");
  13109. });
  13110. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13111. auto se = detail::scope_exit([&] {
  13112. svr.stop();
  13113. t.join();
  13114. ASSERT_FALSE(svr.is_running());
  13115. });
  13116. svr.wait_until_ready();
  13117. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13118. std::string cert;
  13119. read_file(SERVER_CERT2_FILE, cert);
  13120. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13121. cli.enable_system_ca(true);
  13122. cli.enable_server_certificate_verification(true);
  13123. cli.set_follow_location(true);
  13124. cli.set_connection_timeout(30);
  13125. // Receiving any response proves the redirect client completed the TLS
  13126. // handshake with a system-CA-signed host
  13127. auto res = cli.Get("/index");
  13128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13129. }
  13130. TEST(MultipartFormDataTest, LargeData) {
  13131. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13132. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13133. const ContentReader &content_reader) {
  13134. if (req.is_multipart_form_data()) {
  13135. std::vector<FormData> items;
  13136. content_reader(
  13137. [&](const FormData &file) {
  13138. items.push_back(file);
  13139. return true;
  13140. },
  13141. [&](const char *data, size_t data_length) {
  13142. items.back().content.append(data, data_length);
  13143. return true;
  13144. });
  13145. EXPECT_TRUE(std::string(items[0].name) == "document");
  13146. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13147. EXPECT_TRUE(items[0].filename == "2MB_data");
  13148. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13149. EXPECT_TRUE(items[1].name == "hello");
  13150. EXPECT_TRUE(items[1].content == "world");
  13151. EXPECT_TRUE(items[1].filename == "");
  13152. EXPECT_TRUE(items[1].content_type == "");
  13153. } else {
  13154. std::string body;
  13155. content_reader([&](const char *data, size_t data_length) {
  13156. body.append(data, data_length);
  13157. return true;
  13158. });
  13159. }
  13160. });
  13161. auto port = svr.bind_to_any_port(HOST);
  13162. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13163. auto se = detail::scope_exit([&] {
  13164. svr.stop();
  13165. t.join();
  13166. ASSERT_FALSE(svr.is_running());
  13167. });
  13168. svr.wait_until_ready();
  13169. {
  13170. std::string data(1024 * 1024 * 2, '.');
  13171. std::stringstream buffer;
  13172. buffer << data;
  13173. SSLClient cli(HOST, port);
  13174. cli.enable_server_certificate_verification(false);
  13175. UploadFormDataItems items{
  13176. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13177. {"hello", "world", "", ""},
  13178. };
  13179. auto res = cli.Post("/post", items);
  13180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13181. ASSERT_EQ(StatusCode::OK_200, res->status);
  13182. }
  13183. }
  13184. TEST(MultipartFormDataTest, DataProviderItems) {
  13185. std::random_device seed_gen;
  13186. std::mt19937 random(seed_gen());
  13187. std::string rand1;
  13188. rand1.resize(1000);
  13189. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13190. std::string rand2;
  13191. rand2.resize(3000);
  13192. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13193. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13194. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13195. const ContentReader &content_reader) {
  13196. ASSERT_FALSE(req.is_multipart_form_data());
  13197. std::string body;
  13198. content_reader([&](const char *data, size_t data_length) {
  13199. body.append(data, data_length);
  13200. return true;
  13201. });
  13202. EXPECT_EQ(body, "");
  13203. });
  13204. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13205. const ContentReader &content_reader) {
  13206. ASSERT_TRUE(req.is_multipart_form_data());
  13207. std::vector<FormData> items;
  13208. content_reader(
  13209. [&](const FormData &file) {
  13210. items.push_back(file);
  13211. return true;
  13212. },
  13213. [&](const char *data, size_t data_length) {
  13214. items.back().content.append(data, data_length);
  13215. return true;
  13216. });
  13217. ASSERT_TRUE(items.size() == 2);
  13218. EXPECT_EQ(std::string(items[0].name), "name1");
  13219. EXPECT_EQ(items[0].content, "Testing123");
  13220. EXPECT_EQ(items[0].filename, "filename1");
  13221. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13222. EXPECT_EQ(items[1].name, "name2");
  13223. EXPECT_EQ(items[1].content, "Testing456");
  13224. EXPECT_EQ(items[1].filename, "");
  13225. EXPECT_EQ(items[1].content_type, "");
  13226. });
  13227. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13228. const ContentReader &content_reader) {
  13229. ASSERT_TRUE(req.is_multipart_form_data());
  13230. std::vector<FormData> items;
  13231. content_reader(
  13232. [&](const FormData &file) {
  13233. items.push_back(file);
  13234. return true;
  13235. },
  13236. [&](const char *data, size_t data_length) {
  13237. items.back().content.append(data, data_length);
  13238. return true;
  13239. });
  13240. ASSERT_TRUE(items.size() == 2);
  13241. EXPECT_EQ(items[0].name, "name3");
  13242. EXPECT_EQ(items[0].content, rand1);
  13243. EXPECT_EQ(items[0].filename, "filename3");
  13244. EXPECT_EQ(items[0].content_type, "");
  13245. EXPECT_EQ(items[1].name, "name4");
  13246. EXPECT_EQ(items[1].content, rand2);
  13247. EXPECT_EQ(items[1].filename, "filename4");
  13248. EXPECT_EQ(items[1].content_type, "");
  13249. });
  13250. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13251. const ContentReader &content_reader) {
  13252. ASSERT_TRUE(req.is_multipart_form_data());
  13253. std::vector<FormData> items;
  13254. content_reader(
  13255. [&](const FormData &file) {
  13256. items.push_back(file);
  13257. return true;
  13258. },
  13259. [&](const char *data, size_t data_length) {
  13260. items.back().content.append(data, data_length);
  13261. return true;
  13262. });
  13263. ASSERT_TRUE(items.size() == 4);
  13264. EXPECT_EQ(std::string(items[0].name), "name1");
  13265. EXPECT_EQ(items[0].content, "Testing123");
  13266. EXPECT_EQ(items[0].filename, "filename1");
  13267. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13268. EXPECT_EQ(items[1].name, "name2");
  13269. EXPECT_EQ(items[1].content, "Testing456");
  13270. EXPECT_EQ(items[1].filename, "");
  13271. EXPECT_EQ(items[1].content_type, "");
  13272. EXPECT_EQ(items[2].name, "name3");
  13273. EXPECT_EQ(items[2].content, rand1);
  13274. EXPECT_EQ(items[2].filename, "filename3");
  13275. EXPECT_EQ(items[2].content_type, "");
  13276. EXPECT_EQ(items[3].name, "name4");
  13277. EXPECT_EQ(items[3].content, rand2);
  13278. EXPECT_EQ(items[3].filename, "filename4");
  13279. EXPECT_EQ(items[3].content_type, "");
  13280. });
  13281. auto port = svr.bind_to_any_port("localhost");
  13282. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13283. auto se = detail::scope_exit([&] {
  13284. svr.stop();
  13285. t.join();
  13286. ASSERT_FALSE(svr.is_running());
  13287. });
  13288. svr.wait_until_ready();
  13289. {
  13290. SSLClient cli("localhost", port);
  13291. cli.enable_server_certificate_verification(false);
  13292. UploadFormDataItems items{
  13293. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13294. {"name2", "Testing456", "", ""}, // not a file
  13295. };
  13296. {
  13297. auto res = cli.Post("/post-none", {}, {}, {});
  13298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13299. ASSERT_EQ(StatusCode::OK_200, res->status);
  13300. }
  13301. FormDataProviderItems providers;
  13302. {
  13303. auto res =
  13304. cli.Post("/post-items", {}, items, providers); // empty providers
  13305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13306. ASSERT_EQ(StatusCode::OK_200, res->status);
  13307. }
  13308. providers.push_back({"name3",
  13309. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13310. // test the offset is given correctly at each step
  13311. if (!offset)
  13312. sink.os.write(rand1.data(), 30);
  13313. else if (offset == 30)
  13314. sink.os.write(rand1.data() + 30, 300);
  13315. else if (offset == 330)
  13316. sink.os.write(rand1.data() + 330, 670);
  13317. else if (offset == rand1.size())
  13318. sink.done();
  13319. return true;
  13320. },
  13321. "filename3",
  13322. {}});
  13323. providers.push_back({"name4",
  13324. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13325. // test the offset is given correctly at each step
  13326. if (!offset)
  13327. sink.os.write(rand2.data(), 2000);
  13328. else if (offset == 2000)
  13329. sink.os.write(rand2.data() + 2000, 1);
  13330. else if (offset == 2001)
  13331. sink.os.write(rand2.data() + 2001, 999);
  13332. else if (offset == rand2.size())
  13333. sink.done();
  13334. return true;
  13335. },
  13336. "filename4",
  13337. {}});
  13338. {
  13339. auto res = cli.Post("/post-providers", {}, {}, providers);
  13340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13341. ASSERT_EQ(StatusCode::OK_200, res->status);
  13342. }
  13343. {
  13344. auto res = cli.Post("/post-both", {}, items, providers);
  13345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13346. ASSERT_EQ(StatusCode::OK_200, res->status);
  13347. }
  13348. }
  13349. }
  13350. TEST(MultipartFormDataTest, BadHeader) {
  13351. Server svr;
  13352. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13353. res.set_content("ok", "text/plain");
  13354. });
  13355. thread t = thread([&] { svr.listen(HOST, PORT); });
  13356. auto se = detail::scope_exit([&] {
  13357. svr.stop();
  13358. t.join();
  13359. ASSERT_FALSE(svr.is_running());
  13360. });
  13361. svr.wait_until_ready();
  13362. const std::string body =
  13363. "This is the preamble. It is to be ignored, though it\r\n"
  13364. "is a handy place for composition agents to include an\r\n"
  13365. "explanatory note to non-MIME conformant readers.\r\n"
  13366. "\r\n"
  13367. "\r\n"
  13368. "--simple boundary\r\n"
  13369. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13370. ": BAD...\r\n"
  13371. "\r\n"
  13372. "value1\r\n"
  13373. "--simple boundary\r\n"
  13374. "Content-Disposition: form-data; name=\"field2\"; "
  13375. "filename=\"example.txt\"\r\n"
  13376. "\r\n"
  13377. "value2\r\n"
  13378. "--simple boundary--\r\n"
  13379. "This is the epilogue. It is also to be ignored.\r\n";
  13380. std::string content_type =
  13381. R"(multipart/form-data; boundary="simple boundary")";
  13382. Client cli(HOST, PORT);
  13383. auto res = cli.Post("/post", body, content_type.c_str());
  13384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13385. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13386. }
  13387. TEST(MultipartFormDataTest, WithPreamble) {
  13388. Server svr;
  13389. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13390. res.set_content("ok", "text/plain");
  13391. });
  13392. thread t = thread([&] { svr.listen(HOST, PORT); });
  13393. auto se = detail::scope_exit([&] {
  13394. svr.stop();
  13395. t.join();
  13396. ASSERT_FALSE(svr.is_running());
  13397. });
  13398. svr.wait_until_ready();
  13399. const std::string body =
  13400. "This is the preamble. It is to be ignored, though it\r\n"
  13401. "is a handy place for composition agents to include an\r\n"
  13402. "explanatory note to non-MIME conformant readers.\r\n"
  13403. "\r\n"
  13404. "\r\n"
  13405. "--simple boundary\r\n"
  13406. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13407. "\r\n"
  13408. "value1\r\n"
  13409. "--simple boundary\r\n"
  13410. "Content-Disposition: form-data; name=\"field2\"; "
  13411. "filename=\"example.txt\"\r\n"
  13412. "\r\n"
  13413. "value2\r\n"
  13414. "--simple boundary--\r\n"
  13415. "This is the epilogue. It is also to be ignored.\r\n";
  13416. std::string content_type =
  13417. R"(multipart/form-data; boundary="simple boundary")";
  13418. Client cli(HOST, PORT);
  13419. auto res = cli.Post("/post", body, content_type.c_str());
  13420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13421. EXPECT_EQ(StatusCode::OK_200, res->status);
  13422. }
  13423. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13424. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13425. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13426. const ContentReader &content_reader) {
  13427. if (req.is_multipart_form_data()) {
  13428. std::vector<FormData> items;
  13429. content_reader(
  13430. [&](const FormData &file) {
  13431. items.push_back(file);
  13432. return true;
  13433. },
  13434. [&](const char *data, size_t data_length) {
  13435. items.back().content.append(data, data_length);
  13436. return true;
  13437. });
  13438. EXPECT_TRUE(std::string(items[0].name) == "document");
  13439. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13440. EXPECT_TRUE(items[0].filename == "2MB_data");
  13441. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13442. EXPECT_TRUE(items[1].name == "hello");
  13443. EXPECT_TRUE(items[1].content == "world");
  13444. EXPECT_TRUE(items[1].filename == "");
  13445. EXPECT_TRUE(items[1].content_type == "");
  13446. } else {
  13447. std::string body;
  13448. content_reader([&](const char *data, size_t data_length) {
  13449. body.append(data, data_length);
  13450. return true;
  13451. });
  13452. }
  13453. });
  13454. auto port = svr.bind_to_any_port("localhost");
  13455. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13456. auto se = detail::scope_exit([&] {
  13457. svr.stop();
  13458. t.join();
  13459. ASSERT_FALSE(svr.is_running());
  13460. });
  13461. svr.wait_until_ready();
  13462. {
  13463. std::string data(1024 * 1024 * 2, '.');
  13464. std::stringstream buffer;
  13465. buffer << data;
  13466. SSLClient cli("localhost", port);
  13467. cli.enable_server_certificate_verification(false);
  13468. UploadFormDataItems items{
  13469. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13470. {"hello", "world", "", ""},
  13471. };
  13472. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13474. ASSERT_EQ(StatusCode::OK_200, res->status);
  13475. }
  13476. }
  13477. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13478. std::string data(1024 * 1024 * 2, '&');
  13479. std::stringstream buffer;
  13480. buffer << data;
  13481. Client cli("https://localhost:8080");
  13482. UploadFormDataItems items{
  13483. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13484. {"hello", "world", "", ""},
  13485. };
  13486. for (const char &c : " \t\r\n") {
  13487. auto res =
  13488. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13489. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13490. ASSERT_FALSE(res);
  13491. }
  13492. }
  13493. TEST(MultipartFormDataTest, PutFormData) {
  13494. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13495. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13496. const ContentReader &content_reader) {
  13497. if (req.is_multipart_form_data()) {
  13498. std::vector<FormData> items;
  13499. content_reader(
  13500. [&](const FormData &file) {
  13501. items.push_back(file);
  13502. return true;
  13503. },
  13504. [&](const char *data, size_t data_length) {
  13505. items.back().content.append(data, data_length);
  13506. return true;
  13507. });
  13508. EXPECT_TRUE(std::string(items[0].name) == "document");
  13509. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13510. EXPECT_TRUE(items[0].filename == "2MB_data");
  13511. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13512. EXPECT_TRUE(items[1].name == "hello");
  13513. EXPECT_TRUE(items[1].content == "world");
  13514. EXPECT_TRUE(items[1].filename == "");
  13515. EXPECT_TRUE(items[1].content_type == "");
  13516. } else {
  13517. std::string body;
  13518. content_reader([&](const char *data, size_t data_length) {
  13519. body.append(data, data_length);
  13520. return true;
  13521. });
  13522. }
  13523. });
  13524. auto port = svr.bind_to_any_port("localhost");
  13525. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13526. auto se = detail::scope_exit([&] {
  13527. svr.stop();
  13528. t.join();
  13529. ASSERT_FALSE(svr.is_running());
  13530. });
  13531. svr.wait_until_ready();
  13532. {
  13533. std::string data(1024 * 1024 * 2, '&');
  13534. std::stringstream buffer;
  13535. buffer << data;
  13536. SSLClient cli("localhost", port);
  13537. cli.enable_server_certificate_verification(false);
  13538. UploadFormDataItems items{
  13539. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13540. {"hello", "world", "", ""},
  13541. };
  13542. auto res = cli.Put("/put", items);
  13543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13544. ASSERT_EQ(StatusCode::OK_200, res->status);
  13545. }
  13546. }
  13547. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13549. svr.Put("/put_customboundary",
  13550. [&](const Request &req, const Response & /*res*/,
  13551. const ContentReader &content_reader) {
  13552. if (req.is_multipart_form_data()) {
  13553. std::vector<FormData> items;
  13554. content_reader(
  13555. [&](const FormData &file) {
  13556. items.push_back(file);
  13557. return true;
  13558. },
  13559. [&](const char *data, size_t data_length) {
  13560. items.back().content.append(data, data_length);
  13561. return true;
  13562. });
  13563. EXPECT_TRUE(std::string(items[0].name) == "document");
  13564. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13565. EXPECT_TRUE(items[0].filename == "2MB_data");
  13566. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13567. EXPECT_TRUE(items[1].name == "hello");
  13568. EXPECT_TRUE(items[1].content == "world");
  13569. EXPECT_TRUE(items[1].filename == "");
  13570. EXPECT_TRUE(items[1].content_type == "");
  13571. } else {
  13572. std::string body;
  13573. content_reader([&](const char *data, size_t data_length) {
  13574. body.append(data, data_length);
  13575. return true;
  13576. });
  13577. }
  13578. });
  13579. auto port = svr.bind_to_any_port("localhost");
  13580. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13581. auto se = detail::scope_exit([&] {
  13582. svr.stop();
  13583. t.join();
  13584. ASSERT_FALSE(svr.is_running());
  13585. });
  13586. svr.wait_until_ready();
  13587. {
  13588. std::string data(1024 * 1024 * 2, '&');
  13589. std::stringstream buffer;
  13590. buffer << data;
  13591. SSLClient cli("localhost", port);
  13592. cli.enable_server_certificate_verification(false);
  13593. UploadFormDataItems items{
  13594. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13595. {"hello", "world", "", ""},
  13596. };
  13597. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13599. ASSERT_EQ(StatusCode::OK_200, res->status);
  13600. }
  13601. }
  13602. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13603. std::string data(1024 * 1024 * 2, '&');
  13604. std::stringstream buffer;
  13605. buffer << data;
  13606. Client cli("https://localhost:8080");
  13607. cli.enable_server_certificate_verification(false);
  13608. UploadFormDataItems items{
  13609. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13610. {"hello", "world", "", ""},
  13611. };
  13612. for (const char &c : " \t\r\n") {
  13613. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13614. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13615. ASSERT_FALSE(res);
  13616. }
  13617. }
  13618. TEST(MultipartFormDataTest, AlternateFilename) {
  13619. auto handled = false;
  13620. Server svr;
  13621. svr.Post("/test", [&](const Request &req, Response &res) {
  13622. ASSERT_EQ(2u, req.form.files.size());
  13623. ASSERT_EQ(1u, req.form.fields.size());
  13624. // Test files
  13625. const auto &file1 = req.form.get_file("file1");
  13626. ASSERT_EQ("file1", file1.name);
  13627. ASSERT_EQ("A.txt", file1.filename);
  13628. ASSERT_EQ("text/plain", file1.content_type);
  13629. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13630. const auto &file2 = req.form.get_file("file2");
  13631. ASSERT_EQ("file2", file2.name);
  13632. ASSERT_EQ("a.html", file2.filename);
  13633. ASSERT_EQ("text/html", file2.content_type);
  13634. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13635. file2.content);
  13636. // Test text field
  13637. const auto &text = req.form.get_field("text");
  13638. ASSERT_EQ("text default", text);
  13639. res.set_content("ok", "text/plain");
  13640. handled = true;
  13641. });
  13642. thread t = thread([&] { svr.listen(HOST, PORT); });
  13643. auto se = detail::scope_exit([&] {
  13644. svr.stop();
  13645. t.join();
  13646. ASSERT_FALSE(svr.is_running());
  13647. ASSERT_TRUE(handled);
  13648. });
  13649. svr.wait_until_ready();
  13650. auto req = "POST /test HTTP/1.1\r\n"
  13651. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13652. "Content-Length: 399\r\n"
  13653. "\r\n"
  13654. "----------\r\n"
  13655. "Content-Disposition: form-data; name=\"text\"\r\n"
  13656. "\r\n"
  13657. "text default\r\n"
  13658. "----------\r\n"
  13659. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13660. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13661. "Content-Type: text/plain\r\n"
  13662. "\r\n"
  13663. "Content of a.txt.\r\n"
  13664. "\r\n"
  13665. "----------\r\n"
  13666. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13667. "\"a.html\"\r\n"
  13668. "Content-Type: text/html\r\n"
  13669. "\r\n"
  13670. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13671. "\r\n"
  13672. "------------\r\n";
  13673. ASSERT_TRUE(send_request(1, req));
  13674. }
  13675. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13676. auto handled = false;
  13677. Server svr;
  13678. svr.Post("/test", [&](const Request &req, Response &res) {
  13679. // Case-insensitive "utf-8''" prefix with a long value
  13680. const auto &file = req.form.get_file("file1");
  13681. ASSERT_EQ("file1", file.name);
  13682. // 8000 chars exercises both the Content-Disposition parser and the
  13683. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13684. // Prior to the fix, std::regex_match on this header would cause O(N)
  13685. // stack recursion in libstdc++, leading to SIGSEGV.
  13686. std::string expected_filename(8000, 'A');
  13687. ASSERT_EQ(expected_filename, file.filename);
  13688. res.set_content("ok", "text/plain");
  13689. handled = true;
  13690. });
  13691. thread t = thread([&] { svr.listen(HOST, PORT); });
  13692. auto se = detail::scope_exit([&] {
  13693. svr.stop();
  13694. t.join();
  13695. ASSERT_FALSE(svr.is_running());
  13696. ASSERT_TRUE(handled);
  13697. });
  13698. svr.wait_until_ready();
  13699. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13700. // Regression test for GHSA-qq6v-r583-3h69
  13701. std::string long_filename(8000, 'A');
  13702. std::string body = "----------\r\n"
  13703. "Content-Disposition: form-data; name=\"file1\"; "
  13704. "filename*=\"Utf-8''" +
  13705. long_filename +
  13706. "\"\r\n"
  13707. "\r\n"
  13708. "hello\r\n"
  13709. "------------\r\n";
  13710. auto req = "POST /test HTTP/1.1\r\n"
  13711. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13712. "Content-Length: " +
  13713. std::to_string(body.size()) + "\r\n\r\n" + body;
  13714. ASSERT_TRUE(send_request(1, req));
  13715. }
  13716. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13717. auto handled = false;
  13718. Server svr;
  13719. svr.Post("/test", [&](const Request &req, Response &) {
  13720. ASSERT_EQ(2u, req.form.fields.size());
  13721. const auto &text1 = req.form.get_field("text1");
  13722. ASSERT_EQ("text1", text1);
  13723. const auto &text2 = req.form.get_field("text2");
  13724. ASSERT_EQ("text2", text2);
  13725. handled = true;
  13726. });
  13727. thread t = thread([&] { svr.listen(HOST, PORT); });
  13728. auto se = detail::scope_exit([&] {
  13729. svr.stop();
  13730. t.join();
  13731. ASSERT_FALSE(svr.is_running());
  13732. ASSERT_TRUE(handled);
  13733. });
  13734. svr.wait_until_ready();
  13735. auto req = "POST /test HTTP/1.1\r\n"
  13736. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13737. "Content-Length: 146\r\n"
  13738. "\r\n----------\r\n"
  13739. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13740. "\r\n"
  13741. "text1"
  13742. "\r\n----------\r\n"
  13743. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13744. "\r\n"
  13745. "text2"
  13746. "\r\n------------";
  13747. std::string response;
  13748. ASSERT_TRUE(send_request(1, req, &response));
  13749. ASSERT_EQ("200", response.substr(9, 3));
  13750. }
  13751. TEST(MultipartFormDataTest, ContentLength) {
  13752. auto handled = false;
  13753. Server svr;
  13754. svr.Post("/test", [&](const Request &req, Response &) {
  13755. ASSERT_EQ(2u, req.form.fields.size());
  13756. const auto &text1 = req.form.get_field("text1");
  13757. ASSERT_EQ("text1", text1);
  13758. const auto &text2 = req.form.get_field("text2");
  13759. ASSERT_EQ("text2", text2);
  13760. handled = true;
  13761. });
  13762. thread t = thread([&] { svr.listen(HOST, PORT); });
  13763. auto se = detail::scope_exit([&] {
  13764. svr.stop();
  13765. t.join();
  13766. ASSERT_FALSE(svr.is_running());
  13767. ASSERT_TRUE(handled);
  13768. });
  13769. svr.wait_until_ready();
  13770. auto req = "POST /test HTTP/1.1\r\n"
  13771. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13772. "Content-Length: 167\r\n"
  13773. "\r\n----------\r\n"
  13774. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13775. "Content-Length: 5\r\n"
  13776. "\r\n"
  13777. "text1"
  13778. "\r\n----------\r\n"
  13779. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13780. "\r\n"
  13781. "text2"
  13782. "\r\n------------\r\n";
  13783. std::string response;
  13784. ASSERT_TRUE(send_request(1, req, &response));
  13785. ASSERT_EQ("200", response.substr(9, 3));
  13786. }
  13787. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13788. auto handled = false;
  13789. Server svr;
  13790. svr.Post("/test", [&](const Request &req, Response &) {
  13791. ASSERT_EQ(2u, req.form.fields.size());
  13792. const auto &text1 = req.form.get_field("text1");
  13793. ASSERT_EQ("text1", text1);
  13794. // TODO: Add header access for text fields if needed
  13795. const auto &text2 = req.form.get_field("text2");
  13796. ASSERT_EQ("text2", text2);
  13797. // TODO: Header access for text fields needs to be implemented
  13798. // auto &headers = it->second.headers;
  13799. // ASSERT_EQ(3U, headers.size());
  13800. // auto custom_header = headers.find("x-whatever");
  13801. // ASSERT_TRUE(custom_header != headers.end());
  13802. // ASSERT_NE("customvalue", custom_header->second);
  13803. // ASSERT_EQ("CustomValue", custom_header->second);
  13804. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13805. handled = true;
  13806. });
  13807. thread t = thread([&] { svr.listen(HOST, PORT); });
  13808. auto se = detail::scope_exit([&] {
  13809. svr.stop();
  13810. t.join();
  13811. ASSERT_FALSE(svr.is_running());
  13812. ASSERT_TRUE(handled);
  13813. });
  13814. svr.wait_until_ready();
  13815. auto req = "POST /test HTTP/1.1\r\n"
  13816. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13817. "Content-Length: 232\r\n"
  13818. "\r\n----------\r\n"
  13819. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13820. "Content-Length: 5\r\n"
  13821. "X-Test: 1\r\n"
  13822. "\r\n"
  13823. "text1"
  13824. "\r\n----------\r\n"
  13825. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13826. "Content-Type: text/plain\r\n"
  13827. "X-Whatever: CustomValue\r\n"
  13828. "\r\n"
  13829. "text2"
  13830. "\r\n------------\r\n"
  13831. "That should be disregarded. Not even read";
  13832. std::string response;
  13833. ASSERT_TRUE(send_request(1, req, &response));
  13834. ASSERT_EQ("200", response.substr(9, 3));
  13835. }
  13836. TEST(MultipartFormDataTest, LargeHeader) {
  13837. auto handled = false;
  13838. Server svr;
  13839. svr.Post("/test", [&](const Request &req, Response &) {
  13840. ASSERT_EQ(1u, req.form.fields.size());
  13841. const auto &text = req.form.get_field("name1");
  13842. ASSERT_EQ("text1", text);
  13843. handled = true;
  13844. });
  13845. thread t = thread([&] { svr.listen(HOST, PORT); });
  13846. auto se = detail::scope_exit([&] {
  13847. svr.stop();
  13848. t.join();
  13849. ASSERT_FALSE(svr.is_running());
  13850. ASSERT_TRUE(handled);
  13851. });
  13852. svr.wait_until_ready();
  13853. auto boundary = std::string("cpp-httplib-multipart-data");
  13854. std::string content = "--" + boundary +
  13855. "\r\n"
  13856. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13857. "\r\n"
  13858. "text1\r\n"
  13859. "--" +
  13860. boundary + "--\r\n";
  13861. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13862. "Content-Type: multipart/form-data;boundary=" +
  13863. boundary +
  13864. "\r\n"
  13865. "Content-Length: " +
  13866. std::to_string(content.size()) +
  13867. "\r\n"
  13868. "Dummy-Header: ";
  13869. std::string header_suffix = "\r\n"
  13870. "\r\n";
  13871. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13872. size_t header_dummy_size =
  13873. read_buff_size -
  13874. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13875. auto header_dummy = std::string(header_dummy_size, '@');
  13876. auto req = header_prefix + header_dummy + header_suffix + content;
  13877. std::string response;
  13878. ASSERT_TRUE(send_request(1, req, &response));
  13879. ASSERT_EQ("200", response.substr(9, 3));
  13880. }
  13881. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13882. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13883. // (not chunked Transfer-Encoding) after the streaming refactor.
  13884. auto handled = false;
  13885. Server svr;
  13886. svr.Post("/upload", [&](const Request &req, Response &res) {
  13887. auto cl_it = req.headers.find("Content-Length");
  13888. EXPECT_TRUE(cl_it != req.headers.end());
  13889. auto te_it = req.headers.find("Transfer-Encoding");
  13890. EXPECT_TRUE(te_it == req.headers.end());
  13891. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13892. res.set_content("ok", "text/plain");
  13893. handled = true;
  13894. });
  13895. auto port = svr.bind_to_any_port(HOST);
  13896. auto t = thread([&] { svr.listen_after_bind(); });
  13897. auto se = detail::scope_exit([&] {
  13898. svr.stop();
  13899. t.join();
  13900. ASSERT_FALSE(svr.is_running());
  13901. ASSERT_TRUE(handled);
  13902. });
  13903. svr.wait_until_ready();
  13904. UploadFormDataItems items = {
  13905. {"field1", "hello", "", "text/plain"},
  13906. {"file1", "world", "test.txt", "application/octet-stream"},
  13907. };
  13908. Client cli(HOST, port);
  13909. auto res = cli.Post("/upload", {}, items);
  13910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13911. EXPECT_EQ(StatusCode::OK_200, res->status);
  13912. }
  13913. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13914. // Verify that make_multipart_content_provider coalesces many small segments
  13915. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13916. constexpr size_t kItemCount = 1000;
  13917. UploadFormDataItems items;
  13918. items.reserve(kItemCount);
  13919. for (size_t i = 0; i < kItemCount; i++) {
  13920. items.push_back(
  13921. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13922. }
  13923. const std::string boundary = "----test-boundary";
  13924. auto content_length = detail::get_multipart_content_length(items, boundary);
  13925. auto provider = detail::make_multipart_content_provider(items, boundary);
  13926. // Drive the provider the same way write_content_with_progress does
  13927. size_t write_count = 0;
  13928. size_t total_bytes = 0;
  13929. DataSink sink;
  13930. size_t offset = 0;
  13931. sink.write = [&](const char *d, size_t l) -> bool {
  13932. (void)d;
  13933. write_count++;
  13934. total_bytes += l;
  13935. offset += l;
  13936. return true;
  13937. };
  13938. sink.is_writable = []() -> bool { return true; };
  13939. while (offset < content_length) {
  13940. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13941. }
  13942. EXPECT_EQ(content_length, total_bytes);
  13943. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13944. // With buffering into 64KB blocks, write_count should be much smaller.
  13945. auto segment_count = 3 * kItemCount + 1;
  13946. EXPECT_LT(write_count, segment_count / 10);
  13947. }
  13948. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13949. // Integration test: send many UploadFormDataItems and verify the server
  13950. // receives all of them correctly (#2410).
  13951. constexpr size_t kItemCount = 500;
  13952. auto handled = false;
  13953. Server svr;
  13954. svr.Post("/upload", [&](const Request &req, Response &res) {
  13955. EXPECT_EQ(kItemCount, req.form.fields.size());
  13956. for (size_t i = 0; i < kItemCount; i++) {
  13957. auto key = "field" + std::to_string(i);
  13958. auto val = "value" + std::to_string(i);
  13959. auto it = req.form.fields.find(key);
  13960. if (it != req.form.fields.end()) {
  13961. EXPECT_EQ(val, it->second.content);
  13962. } else {
  13963. ADD_FAILURE() << "Missing field: " << key;
  13964. }
  13965. }
  13966. res.set_content("ok", "text/plain");
  13967. handled = true;
  13968. });
  13969. auto port = svr.bind_to_any_port(HOST);
  13970. auto t = thread([&] { svr.listen_after_bind(); });
  13971. auto se = detail::scope_exit([&] {
  13972. svr.stop();
  13973. t.join();
  13974. ASSERT_FALSE(svr.is_running());
  13975. ASSERT_TRUE(handled);
  13976. });
  13977. svr.wait_until_ready();
  13978. UploadFormDataItems items;
  13979. items.reserve(kItemCount);
  13980. for (size_t i = 0; i < kItemCount; i++) {
  13981. items.push_back(
  13982. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13983. }
  13984. Client cli(HOST, port);
  13985. auto res = cli.Post("/upload", items);
  13986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13987. EXPECT_EQ(StatusCode::OK_200, res->status);
  13988. }
  13989. TEST(MultipartFormDataTest, MakeFileProvider) {
  13990. // Verify make_file_provider sends a file's contents correctly.
  13991. const std::string file_content(4096, 'Z');
  13992. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13993. {
  13994. std::ofstream ofs(tmp_path, std::ios::binary);
  13995. ofs.write(file_content.data(),
  13996. static_cast<std::streamsize>(file_content.size()));
  13997. }
  13998. auto handled = false;
  13999. Server svr;
  14000. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14001. const ContentReader &content_reader) {
  14002. ASSERT_TRUE(req.is_multipart_form_data());
  14003. std::vector<FormData> items;
  14004. content_reader(
  14005. [&](const FormData &file) {
  14006. items.push_back(file);
  14007. return true;
  14008. },
  14009. [&](const char *data, size_t data_length) {
  14010. items.back().content.append(data, data_length);
  14011. return true;
  14012. });
  14013. ASSERT_EQ(1u, items.size());
  14014. EXPECT_EQ("myfile", items[0].name);
  14015. EXPECT_EQ("data.bin", items[0].filename);
  14016. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14017. EXPECT_EQ(file_content, items[0].content);
  14018. handled = true;
  14019. });
  14020. auto port = svr.bind_to_any_port(HOST);
  14021. auto t = thread([&] { svr.listen_after_bind(); });
  14022. auto se = detail::scope_exit([&] {
  14023. svr.stop();
  14024. t.join();
  14025. ASSERT_FALSE(svr.is_running());
  14026. ASSERT_TRUE(handled);
  14027. std::remove(tmp_path.c_str());
  14028. });
  14029. svr.wait_until_ready();
  14030. FormDataProviderItems providers;
  14031. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14032. "application/octet-stream"));
  14033. Client cli(HOST, port);
  14034. auto res = cli.Post("/upload", {}, {}, providers);
  14035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14036. EXPECT_EQ(StatusCode::OK_200, res->status);
  14037. }
  14038. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14039. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14040. // (100) headers is rejected with a 400 Bad Request response.
  14041. Server svr;
  14042. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14043. res.set_content("ok", "text/plain");
  14044. });
  14045. thread t = thread([&] { svr.listen(HOST, PORT); });
  14046. auto se = detail::scope_exit([&] {
  14047. svr.stop();
  14048. t.join();
  14049. ASSERT_FALSE(svr.is_running());
  14050. });
  14051. svr.wait_until_ready();
  14052. // Build a multipart part with 101 custom headers (exceeding
  14053. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14054. std::stringstream body;
  14055. body << "--simpleboundary\r\n"
  14056. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14057. for (int i = 0; i < 101; i++) {
  14058. body << "X-Custom-Header-" << i << ": value\r\n";
  14059. }
  14060. body << "\r\n"
  14061. << "value1\r\n"
  14062. << "--simpleboundary--\r\n";
  14063. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14064. Client cli(HOST, PORT);
  14065. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14067. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14068. }
  14069. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14070. // A body that never contains the declared boundary must not be accumulated
  14071. // while the parser waits for it. Buffering it would also make every read
  14072. // rescan everything seen so far, which is quadratic in the body size.
  14073. Server svr;
  14074. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14075. res.set_content("ok", "text/plain");
  14076. });
  14077. auto port = svr.bind_to_any_port(HOST);
  14078. thread t = thread([&] { svr.listen_after_bind(); });
  14079. auto se = detail::scope_exit([&] {
  14080. svr.stop();
  14081. t.join();
  14082. ASSERT_FALSE(svr.is_running());
  14083. });
  14084. svr.wait_until_ready();
  14085. Client cli(HOST, port);
  14086. cli.set_read_timeout(60, 0);
  14087. cli.set_write_timeout(60, 0);
  14088. // '-' is the worst case: it matches the first character of the boundary, so
  14089. // every position has to be checked against it.
  14090. auto post_dashes = [&](size_t size) {
  14091. const std::string body(size, '-');
  14092. auto start = std::chrono::steady_clock::now();
  14093. auto res =
  14094. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14095. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14096. std::chrono::steady_clock::now() - start)
  14097. .count();
  14098. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14099. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14100. return ms;
  14101. };
  14102. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14103. // Windows.
  14104. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14105. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14106. // Comparing the two sizes rather than checking an absolute duration keeps
  14107. // this meaningful across build types and CI load, both of which move the
  14108. // absolute numbers by more than an order of magnitude. Four times the bytes
  14109. // costs about four times the time when parsing is linear, and about sixteen
  14110. // times when the body is buffered and rescanned.
  14111. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14112. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14113. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14114. << "ms, which suggests the body is being buffered and rescanned";
  14115. }
  14116. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14117. // A boundary can only be followed by CRLF or by "--", so anything else is
  14118. // malformed no matter what comes next. The parser must say so right away
  14119. // instead of buffering the rest of the declared body.
  14120. Server svr;
  14121. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14122. res.set_content("ok", "text/plain");
  14123. });
  14124. auto port = svr.bind_to_any_port(HOST);
  14125. thread t = thread([&] { svr.listen_after_bind(); });
  14126. auto se = detail::scope_exit([&] {
  14127. svr.stop();
  14128. t.join();
  14129. ASSERT_FALSE(svr.is_running());
  14130. });
  14131. svr.wait_until_ready();
  14132. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14133. // buffers instead of failing would still be waiting for the remaining bytes.
  14134. const std::string body = "--zzzz\r\n"
  14135. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14136. "\r\n"
  14137. "text1"
  14138. "\r\n--zzzzXX";
  14139. const std::string req = "POST /post HTTP/1.1\r\n"
  14140. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14141. "Content-Length: 1048576\r\n"
  14142. "\r\n" +
  14143. body;
  14144. std::string response;
  14145. ASSERT_TRUE(send_request(3, req, &response, port));
  14146. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14147. EXPECT_EQ("400", response.substr(9, 3));
  14148. }
  14149. // Posts a multipart body split into two writes, so that the server sees the
  14150. // split at whatever offset the caller chose, and expects the single "text1"
  14151. // field to come through.
  14152. static void expect_split_multipart_ok(const std::string &body1,
  14153. const std::string &body2) {
  14154. auto handled = false;
  14155. Server svr;
  14156. svr.Post("/post", [&](const Request &req, Response &) {
  14157. EXPECT_EQ(1u, req.form.fields.size());
  14158. EXPECT_EQ("text1", req.form.get_field("text1"));
  14159. handled = true;
  14160. });
  14161. auto port = svr.bind_to_any_port(HOST);
  14162. thread t = thread([&] { svr.listen_after_bind(); });
  14163. auto se = detail::scope_exit([&] {
  14164. svr.stop();
  14165. t.join();
  14166. ASSERT_FALSE(svr.is_running());
  14167. ASSERT_TRUE(handled);
  14168. });
  14169. svr.wait_until_ready();
  14170. // "Connection: close" makes the server close once it has answered, so the
  14171. // response drain ends immediately instead of idling until the read timeout.
  14172. const std::string head =
  14173. "POST /post HTTP/1.1\r\n"
  14174. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14175. "Connection: close\r\n"
  14176. "Content-Length: " +
  14177. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14178. std::string response;
  14179. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14180. ASSERT_GE(response.size(), 12u) << "no response";
  14181. EXPECT_EQ("200", response.substr(9, 3));
  14182. }
  14183. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14184. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14185. // ignored, including when it does not arrive in the same read as the
  14186. // close-delimiter itself.
  14187. expect_split_multipart_ok("--zzzz\r\n"
  14188. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14189. "\r\n"
  14190. "text1"
  14191. "\r\n--zzzz--",
  14192. "\r\nthis epilogue must be ignored\r\n");
  14193. }
  14194. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14195. // The initial boundary may be preceded by a preamble of any length and may
  14196. // straddle a read boundary. Discarding data while waiting for it must not
  14197. // throw away a partial boundary sitting at the end of the buffer.
  14198. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14199. "zz\r\n"
  14200. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14201. "\r\n"
  14202. "text1"
  14203. "\r\n--zzzz--\r\n");
  14204. }
  14205. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14206. // The received boundary was only checked for being non-empty, so it could be
  14207. // as long as a header is allowed to be. The parser scans the body for
  14208. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14209. // costs a nearly full comparison at nearly every position, making the
  14210. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14211. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14212. Server svr;
  14213. svr.Post("/post", [](const Request &req, Response &res) {
  14214. EXPECT_EQ(1u, req.form.fields.size());
  14215. EXPECT_EQ("text1", req.form.get_field("text1"));
  14216. res.set_content("ok", "text/plain");
  14217. });
  14218. auto port = svr.bind_to_any_port(HOST);
  14219. thread t = thread([&] { svr.listen_after_bind(); });
  14220. auto se = detail::scope_exit([&] {
  14221. svr.stop();
  14222. t.join();
  14223. ASSERT_FALSE(svr.is_running());
  14224. });
  14225. svr.wait_until_ready();
  14226. Client cli(HOST, port);
  14227. auto post_with_boundary_of_length = [&](size_t len) {
  14228. const std::string boundary(len, 'a');
  14229. const std::string body =
  14230. "--" + boundary +
  14231. "\r\n"
  14232. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14233. "\r\n"
  14234. "text1"
  14235. "\r\n--" +
  14236. boundary + "--\r\n";
  14237. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14238. };
  14239. auto res = post_with_boundary_of_length(70);
  14240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14241. EXPECT_EQ(StatusCode::OK_200, res->status);
  14242. res = post_with_boundary_of_length(71);
  14243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14244. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14245. }
  14246. TEST(MakeFileBodyTest, Basic) {
  14247. const std::string file_content(4096, 'Z');
  14248. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14249. {
  14250. std::ofstream ofs(tmp_path, std::ios::binary);
  14251. ofs.write(file_content.data(),
  14252. static_cast<std::streamsize>(file_content.size()));
  14253. }
  14254. auto handled = false;
  14255. Server svr;
  14256. svr.Post("/upload", [&](const Request &req, Response &res) {
  14257. EXPECT_EQ(file_content, req.body);
  14258. handled = true;
  14259. res.status = StatusCode::OK_200;
  14260. });
  14261. auto port = svr.bind_to_any_port(HOST);
  14262. auto t = thread([&] { svr.listen_after_bind(); });
  14263. auto se = detail::scope_exit([&] {
  14264. svr.stop();
  14265. t.join();
  14266. ASSERT_FALSE(svr.is_running());
  14267. ASSERT_TRUE(handled);
  14268. std::remove(tmp_path.c_str());
  14269. });
  14270. svr.wait_until_ready();
  14271. auto fb = make_file_body(tmp_path);
  14272. ASSERT_GT(fb.first, 0u);
  14273. Client cli(HOST, port);
  14274. auto res =
  14275. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14277. EXPECT_EQ(StatusCode::OK_200, res->status);
  14278. }
  14279. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14280. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14281. {
  14282. std::ofstream ofs(path, std::ios::binary);
  14283. const std::string content(100, 'A');
  14284. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14285. }
  14286. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14287. auto body = make_file_body(path);
  14288. ASSERT_EQ(100u, body.first);
  14289. ASSERT_TRUE(static_cast<bool>(body.second));
  14290. // Rewritten shorter after its length was measured - and, on a server, after
  14291. // that length has already gone out as Content-Length.
  14292. {
  14293. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14294. const std::string content(10, 'A');
  14295. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14296. }
  14297. std::string written;
  14298. DataSink sink;
  14299. sink.write = [&](const char *d, size_t l) {
  14300. written.append(d, l);
  14301. return true;
  14302. };
  14303. // The provider has to report failure. write_content_with_progress() advances
  14304. // its offset only by what was written, so a provider that returns true
  14305. // without completing the length it promised is called again straight away,
  14306. // and again.
  14307. EXPECT_FALSE(body.second(0, body.first, sink));
  14308. EXPECT_EQ(std::string(10, 'A'), written);
  14309. }
  14310. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14311. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14312. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14313. {
  14314. std::ofstream ofs(path, std::ios::binary);
  14315. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14316. }
  14317. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14318. auto body = make_file_body(path);
  14319. ASSERT_EQ(content.size(), body.first);
  14320. ASSERT_TRUE(static_cast<bool>(body.second));
  14321. std::string written;
  14322. DataSink sink;
  14323. sink.write = [&](const char *d, size_t l) {
  14324. written.append(d, l);
  14325. return true;
  14326. };
  14327. EXPECT_TRUE(body.second(0, body.first, sink));
  14328. EXPECT_EQ(content, written);
  14329. }
  14330. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14331. static constexpr unsigned int number_of_tasks{1000000};
  14332. std::atomic_uint count{0};
  14333. std::unique_ptr<TaskQueue> task_queue{
  14334. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14335. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14336. auto queued = task_queue->enqueue(
  14337. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14338. EXPECT_TRUE(queued);
  14339. }
  14340. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14341. task_queue->shutdown();
  14342. #else
  14343. EXPECT_NO_THROW(task_queue->shutdown());
  14344. #endif
  14345. EXPECT_EQ(number_of_tasks, count.load());
  14346. }
  14347. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14348. static constexpr unsigned int number_of_tasks{1000000};
  14349. static constexpr unsigned int qlimit{2};
  14350. unsigned int queued_count{0};
  14351. std::atomic_uint count{0};
  14352. std::unique_ptr<TaskQueue> task_queue{
  14353. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14354. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14355. if (task_queue->enqueue(
  14356. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14357. queued_count++;
  14358. }
  14359. }
  14360. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14361. task_queue->shutdown();
  14362. #else
  14363. EXPECT_NO_THROW(task_queue->shutdown());
  14364. #endif
  14365. EXPECT_EQ(queued_count, count.load());
  14366. EXPECT_TRUE(queued_count <= number_of_tasks);
  14367. EXPECT_TRUE(queued_count >= qlimit);
  14368. }
  14369. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14370. // Use a short idle timeout so a dynamic thread spawns, times out and
  14371. // exits during the test, and the pool keeps working afterwards.
  14372. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14373. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14374. /*idle_timeout_sec=*/1}};
  14375. std::atomic_uint count{0};
  14376. std::condition_variable cv;
  14377. std::mutex mtx;
  14378. bool release = false;
  14379. // Block the base thread so the second task spawns a dynamic thread.
  14380. EXPECT_TRUE(task_queue->enqueue([&] {
  14381. std::unique_lock<std::mutex> lock(mtx);
  14382. while (!release) {
  14383. cv.wait(lock);
  14384. }
  14385. count++;
  14386. }));
  14387. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14388. // Let the dynamic thread finish its task and exceed the idle timeout.
  14389. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14390. {
  14391. std::unique_lock<std::mutex> lock(mtx);
  14392. release = true;
  14393. }
  14394. cv.notify_all();
  14395. // The pool must still accept and run tasks after the dynamic thread exited.
  14396. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14397. task_queue->shutdown();
  14398. EXPECT_EQ(3u, count.load());
  14399. }
  14400. TEST(TaskQueueTest, MaxQueuedRequests) {
  14401. static constexpr unsigned int qlimit{3};
  14402. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14403. std::condition_variable sem_cv;
  14404. std::mutex sem_mtx;
  14405. int credits = 0;
  14406. bool queued;
  14407. /* Fill up the queue with tasks that will block until we give them credits to
  14408. * complete. */
  14409. for (unsigned int n = 0; n <= qlimit;) {
  14410. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14411. std::unique_lock<std::mutex> lock(sem_mtx);
  14412. while (credits <= 0) {
  14413. sem_cv.wait(lock);
  14414. }
  14415. /* Consume the credit and signal the test code if they are all gone. */
  14416. if (--credits == 0) { sem_cv.notify_one(); }
  14417. });
  14418. if (n < qlimit) {
  14419. /* The first qlimit enqueues must succeed. */
  14420. EXPECT_TRUE(queued);
  14421. } else {
  14422. /* The last one will succeed only when the worker thread
  14423. * starts and dequeues the first blocking task. Although
  14424. * not necessary for the correctness of this test, we sleep for
  14425. * a short while to avoid busy waiting. */
  14426. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14427. }
  14428. if (queued) { n++; }
  14429. }
  14430. /* Further enqueues must fail since the queue is full. */
  14431. for (auto i = 0; i < 4; i++) {
  14432. queued = task_queue->enqueue([] {});
  14433. EXPECT_FALSE(queued);
  14434. }
  14435. /* Give the credits to allow the previous tasks to complete. */
  14436. {
  14437. std::unique_lock<std::mutex> lock(sem_mtx);
  14438. credits += qlimit + 1;
  14439. }
  14440. sem_cv.notify_all();
  14441. /* Wait for all the credits to be consumed. */
  14442. {
  14443. std::unique_lock<std::mutex> lock(sem_mtx);
  14444. while (credits > 0) {
  14445. sem_cv.wait(lock);
  14446. }
  14447. }
  14448. /* Check that we are able again to enqueue at least qlimit tasks. */
  14449. for (unsigned int i = 0; i < qlimit; i++) {
  14450. queued = task_queue->enqueue([] {});
  14451. EXPECT_TRUE(queued);
  14452. }
  14453. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14454. task_queue->shutdown();
  14455. #else
  14456. EXPECT_NO_THROW(task_queue->shutdown());
  14457. #endif
  14458. }
  14459. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14460. Server svr;
  14461. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14462. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14463. });
  14464. svr.Get("/hello", [](const Request &req, Response &res) {
  14465. res.set_content(req.get_param_value("key"), "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("val&key2=val2", res->body);
  14481. }
  14482. }
  14483. #endif
  14484. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14485. Server svr;
  14486. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14487. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14488. });
  14489. svr.Get("/hello", [](const Request &req, Response &res) {
  14490. res.set_content(req.get_param_value("key"), "text/plain");
  14491. });
  14492. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14493. auto se = detail::scope_exit([&] {
  14494. svr.stop();
  14495. thread.join();
  14496. ASSERT_FALSE(svr.is_running());
  14497. });
  14498. svr.wait_until_ready();
  14499. {
  14500. Client cli(HOST, PORT);
  14501. cli.set_follow_location(true);
  14502. auto res = cli.Get("/");
  14503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14504. EXPECT_EQ(StatusCode::OK_200, res->status);
  14505. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14506. }
  14507. }
  14508. TEST(RedirectTest, RedirectWithPlusInPath) {
  14509. Server svr;
  14510. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14511. res.set_redirect("/a+b");
  14512. });
  14513. // Route pattern uses regex; escape + as \\+
  14514. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14515. res.set_content(req.path, "text/plain");
  14516. });
  14517. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14518. auto se = detail::scope_exit([&] {
  14519. svr.stop();
  14520. thread.join();
  14521. ASSERT_FALSE(svr.is_running());
  14522. });
  14523. svr.wait_until_ready();
  14524. {
  14525. Client cli(HOST, PORT);
  14526. cli.set_follow_location(true);
  14527. auto res = cli.Get("/");
  14528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14529. EXPECT_EQ(StatusCode::OK_200, res->status);
  14530. EXPECT_EQ("/a+b", res->body);
  14531. }
  14532. }
  14533. TEST(RedirectTest, ResolveRelativeLocation) {
  14534. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14535. const std::vector<std::pair<std::string, std::string>> cases = {
  14536. {"g", "/b/c/g"},
  14537. {"./g", "/b/c/g"},
  14538. {"g/", "/b/c/g/"},
  14539. {"?y", "/b/c/d;p?y"},
  14540. {"g?y", "/b/c/g?y"},
  14541. {"#s", "/b/c/d;p?q#s"},
  14542. {"g#s", "/b/c/g#s"},
  14543. {"g?y#s", "/b/c/g?y#s"},
  14544. {";x", "/b/c/;x"},
  14545. {"g;x", "/b/c/g;x"},
  14546. {".", "/b/c/"},
  14547. {"./", "/b/c/"},
  14548. {"..", "/b/"},
  14549. {"../", "/b/"},
  14550. {"../g", "/b/g"},
  14551. {"../..", "/"},
  14552. {"../../", "/"},
  14553. {"../../g", "/g"},
  14554. {"../../../g", "/g"},
  14555. {"g.", "/b/c/g."},
  14556. {".g", "/b/c/.g"},
  14557. {"g..", "/b/c/g.."},
  14558. {"..g", "/b/c/..g"},
  14559. {"./../g", "/b/g"},
  14560. {"./g/.", "/b/c/g/"},
  14561. {"g/./h", "/b/c/g/h"},
  14562. {"g/../h", "/b/c/h"},
  14563. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14564. {"g;x=1/../y", "/b/c/y"},
  14565. {"g?y/./x", "/b/c/g?y/./x"},
  14566. {"g#s/../x", "/b/c/g#s/../x"},
  14567. // Not relative-path references, so left for parse_url.
  14568. {"/g", "/g"},
  14569. {"//g", "//g"},
  14570. {"http://g/x", "http://g/x"},
  14571. {"g:h", "g:h"},
  14572. };
  14573. for (const auto &c : cases) {
  14574. EXPECT_EQ(c.second,
  14575. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  14576. << c.first;
  14577. }
  14578. }
  14579. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  14580. Server svr;
  14581. svr.Get("/dir/page", [](const Request &req, Response &res) {
  14582. res.set_redirect(req.get_param_value("to"));
  14583. });
  14584. svr.Get("/dir/next", [](const Request &req, Response &res) {
  14585. res.set_content(req.target, "text/plain");
  14586. });
  14587. svr.Get("/other", [](const Request &req, Response &res) {
  14588. res.set_content(req.target, "text/plain");
  14589. });
  14590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14591. auto se = detail::scope_exit([&] {
  14592. svr.stop();
  14593. thread.join();
  14594. ASSERT_FALSE(svr.is_running());
  14595. });
  14596. svr.wait_until_ready();
  14597. const std::vector<std::pair<std::string, std::string>> cases = {
  14598. {"next", "/dir/next"},
  14599. {"./next?x=1", "/dir/next?x=1"},
  14600. {"../other", "/other"},
  14601. };
  14602. for (const auto &c : cases) {
  14603. Client cli(HOST, PORT);
  14604. cli.set_follow_location(true);
  14605. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  14606. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  14607. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  14608. EXPECT_EQ(c.second, res->body) << c.first;
  14609. }
  14610. }
  14611. #ifdef CPPHTTPLIB_SSL_ENABLED
  14612. TEST(RedirectTest, Issue2185_Online) {
  14613. SSLClient client("github.com");
  14614. client.set_follow_location(true);
  14615. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14616. "Coollab-Windows.zip");
  14617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14618. EXPECT_EQ(StatusCode::OK_200, res->status);
  14619. EXPECT_EQ(9920427U, res->body.size());
  14620. }
  14621. #endif
  14622. TEST(VulnerabilityTest, CRLFInjection) {
  14623. Server svr;
  14624. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14625. res.set_content("Hello 1", "text/plain");
  14626. });
  14627. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14628. res.set_content("Hello 2", "text/plain");
  14629. });
  14630. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14631. res.set_content("Hello 3", "text/plain");
  14632. });
  14633. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14634. res.set_content("Hello 4", "text/plain");
  14635. });
  14636. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14637. for (const auto &x : req.headers) {
  14638. auto key = x.first;
  14639. EXPECT_STRNE("evil", key.c_str());
  14640. }
  14641. });
  14642. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14643. auto se = detail::scope_exit([&] {
  14644. svr.stop();
  14645. thread.join();
  14646. ASSERT_FALSE(svr.is_running());
  14647. });
  14648. svr.wait_until_ready();
  14649. {
  14650. Client cli(HOST, PORT);
  14651. cli.Post("/test1", "A=B",
  14652. "application/x-www-form-urlencoded\r\nevil: hello1");
  14653. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14654. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14655. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14656. }
  14657. }
  14658. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14659. auto server_thread = std::thread([] {
  14660. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14661. default_socket_options(srv);
  14662. sockaddr_in addr{};
  14663. addr.sin_family = AF_INET;
  14664. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14665. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14666. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14667. ::listen(srv, 1);
  14668. sockaddr_in cli_addr{};
  14669. socklen_t cli_len = sizeof(cli_addr);
  14670. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14671. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14672. std::string buf_all;
  14673. char buf[2048];
  14674. ssize_t n;
  14675. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14676. buf_all.append(buf, static_cast<size_t>(n));
  14677. size_t pos;
  14678. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14679. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14680. auto e = request_block.find("\r\n");
  14681. if (e != std::string::npos) {
  14682. auto request_line = request_block.substr(0, e);
  14683. std::string msg =
  14684. "CRLF injection detected in request line: '" + request_line + "'";
  14685. EXPECT_FALSE(true) << msg;
  14686. }
  14687. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14688. ::send(cli,
  14689. #ifdef _WIN32
  14690. static_cast<const char *>(resp.c_str()),
  14691. static_cast<int>(resp.size()),
  14692. #else
  14693. resp.c_str(), resp.size(),
  14694. #endif
  14695. 0);
  14696. buf_all.erase(0, pos + 4);
  14697. }
  14698. }
  14699. detail::close_socket(cli);
  14700. detail::close_socket(srv);
  14701. });
  14702. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14703. auto cli = Client("127.0.0.1", PORT + 1);
  14704. auto headers = Headers{
  14705. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14706. {"Connection", "keep-alive"}};
  14707. auto res = cli.Get("/hi", headers);
  14708. EXPECT_FALSE(res);
  14709. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14710. server_thread.join();
  14711. }
  14712. // A request rejected before any byte reaches the socket must fail right away
  14713. // instead of waiting for a response the server will never send.
  14714. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  14715. // The kernel completes the TCP handshake from the listen backlog, so the
  14716. // client connects, but nothing ever reads, responds or closes.
  14717. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14718. default_socket_options(srv);
  14719. sockaddr_in addr{};
  14720. addr.sin_family = AF_INET;
  14721. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14722. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14723. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14724. ASSERT_EQ(0, ::listen(srv, 8));
  14725. auto cli = Client("127.0.0.1", PORT + 1);
  14726. cli.set_read_timeout(10, 0);
  14727. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  14728. return std::chrono::duration_cast<std::chrono::milliseconds>(
  14729. std::chrono::steady_clock::now() - start)
  14730. .count();
  14731. };
  14732. {
  14733. Request req;
  14734. req.method = "GE T";
  14735. req.path = "/";
  14736. auto start = std::chrono::steady_clock::now();
  14737. auto res = cli.send(req);
  14738. EXPECT_FALSE(res);
  14739. EXPECT_EQ(Error::Write, res.error());
  14740. EXPECT_LT(elapsed_ms(start), 1000);
  14741. }
  14742. {
  14743. auto start = std::chrono::steady_clock::now();
  14744. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  14745. EXPECT_FALSE(res);
  14746. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14747. EXPECT_LT(elapsed_ms(start), 1000);
  14748. }
  14749. EXPECT_FALSE(cli.is_socket_open());
  14750. detail::close_socket(srv);
  14751. }
  14752. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  14753. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14754. default_socket_options(srv);
  14755. sockaddr_in addr{};
  14756. addr.sin_family = AF_INET;
  14757. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14758. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14759. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14760. ASSERT_EQ(0, ::listen(srv, 1));
  14761. std::string received;
  14762. auto server_thread = std::thread([&] {
  14763. auto sock = ::accept(srv, nullptr, nullptr);
  14764. if (sock == INVALID_SOCKET) { return; }
  14765. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  14766. char buf[2048];
  14767. ssize_t n;
  14768. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  14769. received.append(buf, static_cast<size_t>(n));
  14770. }
  14771. detail::close_socket(sock);
  14772. });
  14773. {
  14774. auto cli = Client("127.0.0.1", PORT + 1);
  14775. // "Z" sorts after the default headers, so writing straight to the socket
  14776. // would have sent the request line and those headers before the rejection.
  14777. auto handle =
  14778. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  14779. EXPECT_FALSE(handle.is_valid());
  14780. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  14781. }
  14782. server_thread.join();
  14783. detail::close_socket(srv);
  14784. EXPECT_TRUE(received.empty()) << received;
  14785. }
  14786. TEST(PathParamsTest, StaticMatch) {
  14787. const auto pattern = "/users/all";
  14788. detail::PathParamsMatcher matcher(pattern);
  14789. Request request;
  14790. request.path = "/users/all";
  14791. ASSERT_TRUE(matcher.match(request));
  14792. std::unordered_map<std::string, std::string> expected_params = {};
  14793. EXPECT_EQ(request.path_params, expected_params);
  14794. }
  14795. TEST(PathParamsTest, StaticMismatch) {
  14796. const auto pattern = "/users/all";
  14797. detail::PathParamsMatcher matcher(pattern);
  14798. Request request;
  14799. request.path = "/users/1";
  14800. ASSERT_FALSE(matcher.match(request));
  14801. }
  14802. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14803. const auto pattern = "/users/:id/subscriptions";
  14804. detail::PathParamsMatcher matcher(pattern);
  14805. Request request;
  14806. request.path = "/users/42/subscriptions";
  14807. ASSERT_TRUE(matcher.match(request));
  14808. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14809. EXPECT_EQ(request.path_params, expected_params);
  14810. }
  14811. TEST(PathParamsTest, SingleParamInTheEnd) {
  14812. const auto pattern = "/users/:id";
  14813. detail::PathParamsMatcher matcher(pattern);
  14814. Request request;
  14815. request.path = "/users/24";
  14816. ASSERT_TRUE(matcher.match(request));
  14817. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14818. EXPECT_EQ(request.path_params, expected_params);
  14819. }
  14820. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14821. const auto pattern = "/users/:id/";
  14822. detail::PathParamsMatcher matcher(pattern);
  14823. Request request;
  14824. request.path = "/users/42/";
  14825. ASSERT_TRUE(matcher.match(request));
  14826. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14827. EXPECT_EQ(request.path_params, expected_params);
  14828. }
  14829. TEST(PathParamsTest, EmptyParam) {
  14830. const auto pattern = "/users/:id/";
  14831. detail::PathParamsMatcher matcher(pattern);
  14832. Request request;
  14833. request.path = "/users//";
  14834. ASSERT_TRUE(matcher.match(request));
  14835. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14836. EXPECT_EQ(request.path_params, expected_params);
  14837. }
  14838. TEST(PathParamsTest, FragmentMismatch) {
  14839. const auto pattern = "/users/:id/";
  14840. detail::PathParamsMatcher matcher(pattern);
  14841. Request request;
  14842. request.path = "/admins/24/";
  14843. ASSERT_FALSE(matcher.match(request));
  14844. }
  14845. TEST(PathParamsTest, ExtraFragments) {
  14846. const auto pattern = "/users/:id";
  14847. detail::PathParamsMatcher matcher(pattern);
  14848. Request request;
  14849. request.path = "/users/42/subscriptions";
  14850. ASSERT_FALSE(matcher.match(request));
  14851. }
  14852. TEST(PathParamsTest, MissingTrailingParam) {
  14853. const auto pattern = "/users/:id";
  14854. detail::PathParamsMatcher matcher(pattern);
  14855. Request request;
  14856. request.path = "/users";
  14857. ASSERT_FALSE(matcher.match(request));
  14858. }
  14859. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14860. const auto pattern = "/users/:id/subscriptions";
  14861. detail::PathParamsMatcher matcher(pattern);
  14862. Request request;
  14863. request.path = "/users/subscriptions";
  14864. ASSERT_FALSE(matcher.match(request));
  14865. }
  14866. TEST(PathParamsTest, MultipleParams) {
  14867. const auto pattern = "/users/:userid/subscriptions/:subid";
  14868. detail::PathParamsMatcher matcher(pattern);
  14869. Request request;
  14870. request.path = "/users/42/subscriptions/2";
  14871. ASSERT_TRUE(matcher.match(request));
  14872. std::unordered_map<std::string, std::string> expected_params = {
  14873. {"userid", "42"}, {"subid", "2"}};
  14874. EXPECT_EQ(request.path_params, expected_params);
  14875. }
  14876. TEST(PathParamsTest, SequenceOfParams) {
  14877. const auto pattern = "/values/:x/:y/:z";
  14878. detail::PathParamsMatcher matcher(pattern);
  14879. Request request;
  14880. request.path = "/values/1/2/3";
  14881. ASSERT_TRUE(matcher.match(request));
  14882. std::unordered_map<std::string, std::string> expected_params = {
  14883. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14884. EXPECT_EQ(request.path_params, expected_params);
  14885. }
  14886. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14887. const auto pattern = "/prefix:suffix";
  14888. detail::PathParamsMatcher matcher(pattern);
  14889. Request request;
  14890. request.path = "/prefix:suffix";
  14891. ASSERT_TRUE(matcher.match(request));
  14892. const std::unordered_map<std::string, std::string> expected_params = {};
  14893. EXPECT_EQ(request.path_params, expected_params);
  14894. }
  14895. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14896. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14897. // calling thread's stack on a long enough path for a quantified pattern;
  14898. // RegexMatcher must refuse to run regex matching on paths beyond
  14899. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14900. detail::RegexMatcher matcher("/files/(.*)");
  14901. Request within_limit;
  14902. within_limit.path = "/files/" + std::string(10, 'A');
  14903. EXPECT_TRUE(matcher.match(within_limit));
  14904. Request over_limit;
  14905. over_limit.path =
  14906. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14907. EXPECT_FALSE(matcher.match(over_limit));
  14908. }
  14909. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14910. Server svr;
  14911. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14912. res.set_content("ok", "text/plain");
  14913. });
  14914. auto port = svr.bind_to_any_port(HOST);
  14915. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14916. auto se = detail::scope_exit([&] {
  14917. svr.stop();
  14918. thread.join();
  14919. ASSERT_FALSE(svr.is_running());
  14920. });
  14921. svr.wait_until_ready();
  14922. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14923. // request URI limit; this used to be able to crash the process.
  14924. std::string path =
  14925. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14926. std::string req = "GET " + path +
  14927. " HTTP/1.1\r\n"
  14928. "Host: " +
  14929. std::string(HOST) + ":" + std::to_string(port) +
  14930. "\r\n"
  14931. "Connection: close\r\n"
  14932. "\r\n";
  14933. std::string response;
  14934. ASSERT_TRUE(send_request(5, req, &response, port));
  14935. EXPECT_NE(std::string::npos, response.find("404"));
  14936. }
  14937. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14938. Server svr;
  14939. auto handler = [](const Request & /*req*/, Response &res) {
  14940. res.set_content("hit", "text/plain");
  14941. };
  14942. // No regex metacharacter, so this one is compared literally
  14943. svr.Get("/literal/route", handler);
  14944. // '.' is a regex metacharacter, so this one must keep regex semantics
  14945. svr.Get("/a.c", handler);
  14946. auto port = svr.bind_to_any_port(HOST);
  14947. std::thread t([&]() { svr.listen_after_bind(); });
  14948. auto se = detail::scope_exit([&] {
  14949. svr.stop();
  14950. t.join();
  14951. ASSERT_FALSE(svr.is_running());
  14952. });
  14953. svr.wait_until_ready();
  14954. Client cli(HOST, port);
  14955. struct {
  14956. const char *path;
  14957. int status;
  14958. } cases[] = {
  14959. {"/literal/route", StatusCode::OK_200},
  14960. {"/literal/routes", StatusCode::NotFound_404},
  14961. {"/literal/rout", StatusCode::NotFound_404},
  14962. {"/abc", StatusCode::OK_200},
  14963. {"/a.c", StatusCode::OK_200},
  14964. };
  14965. for (const auto &x : cases) {
  14966. auto res = cli.Get(x.path);
  14967. ASSERT_TRUE(res) << x.path;
  14968. EXPECT_EQ(x.status, res->status) << x.path;
  14969. }
  14970. }
  14971. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14972. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14973. // from exhausting the stack, so it must only constrain routes that actually
  14974. // run a regular expression. A literal route is matched by comparison and
  14975. // stays usable at any length.
  14976. Server svr;
  14977. const std::string pattern =
  14978. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14979. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14980. res.set_content("hit", "text/plain");
  14981. });
  14982. auto port = svr.bind_to_any_port(HOST);
  14983. std::thread t([&]() { svr.listen_after_bind(); });
  14984. auto se = detail::scope_exit([&] {
  14985. svr.stop();
  14986. t.join();
  14987. ASSERT_FALSE(svr.is_running());
  14988. });
  14989. svr.wait_until_ready();
  14990. Client cli(HOST, port);
  14991. auto res = cli.Get(pattern);
  14992. ASSERT_TRUE(res);
  14993. EXPECT_EQ(StatusCode::OK_200, res->status);
  14994. }
  14995. TEST(ParseUrlTest, VariousPatterns) {
  14996. {
  14997. detail::UrlComponents uc;
  14998. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14999. EXPECT_EQ("http", uc.scheme);
  15000. EXPECT_EQ("example.com", uc.host);
  15001. EXPECT_EQ("8080", uc.port);
  15002. EXPECT_EQ("/path", uc.path);
  15003. EXPECT_EQ("?q=1", uc.query);
  15004. }
  15005. {
  15006. detail::UrlComponents uc;
  15007. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15008. EXPECT_EQ("https", uc.scheme);
  15009. EXPECT_EQ("example.com", uc.host);
  15010. EXPECT_TRUE(uc.port.empty());
  15011. EXPECT_EQ("/path", uc.path);
  15012. }
  15013. {
  15014. detail::UrlComponents uc;
  15015. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15016. EXPECT_EQ("::1", uc.host);
  15017. EXPECT_EQ("8080", uc.port);
  15018. EXPECT_EQ("/path", uc.path);
  15019. }
  15020. {
  15021. detail::UrlComponents uc;
  15022. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15023. }
  15024. {
  15025. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15026. // the path while the connection still targets the bracketed host.
  15027. detail::UrlComponents uc;
  15028. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15029. }
  15030. {
  15031. detail::UrlComponents uc;
  15032. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15033. }
  15034. {
  15035. detail::UrlComponents uc;
  15036. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15037. EXPECT_EQ("::1", uc.host);
  15038. EXPECT_TRUE(uc.port.empty());
  15039. EXPECT_EQ("/path", uc.path);
  15040. }
  15041. {
  15042. detail::UrlComponents uc;
  15043. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15044. EXPECT_TRUE(uc.scheme.empty());
  15045. EXPECT_EQ("example.com", uc.host);
  15046. EXPECT_EQ("/path", uc.path);
  15047. EXPECT_EQ("?q=1", uc.query);
  15048. }
  15049. {
  15050. detail::UrlComponents uc;
  15051. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15052. EXPECT_TRUE(uc.host.empty());
  15053. EXPECT_EQ("/path", uc.path);
  15054. EXPECT_EQ("?q=1", uc.query);
  15055. }
  15056. {
  15057. detail::UrlComponents uc;
  15058. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15059. EXPECT_EQ("example.com", uc.host);
  15060. EXPECT_EQ("8080", uc.port);
  15061. }
  15062. {
  15063. // Unix socket path — must not be parsed as host
  15064. detail::UrlComponents uc;
  15065. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15066. EXPECT_TRUE(uc.host.empty());
  15067. }
  15068. {
  15069. detail::UrlComponents uc;
  15070. ASSERT_TRUE(detail::parse_url("", uc));
  15071. EXPECT_TRUE(uc.host.empty());
  15072. EXPECT_TRUE(uc.path.empty());
  15073. }
  15074. {
  15075. detail::UrlComponents uc;
  15076. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15077. }
  15078. {
  15079. detail::UrlComponents uc;
  15080. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15081. }
  15082. {
  15083. // Accepted by parse_url; callers restrict to http/https
  15084. detail::UrlComponents uc;
  15085. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15086. EXPECT_EQ("ftp", uc.scheme);
  15087. }
  15088. {
  15089. detail::UrlComponents uc;
  15090. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15091. }
  15092. {
  15093. detail::UrlComponents uc;
  15094. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15095. }
  15096. }
  15097. TEST(ParseUrlTest, FragmentHandling) {
  15098. {
  15099. detail::UrlComponents uc;
  15100. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15101. EXPECT_EQ("/path", uc.path);
  15102. EXPECT_TRUE(uc.query.empty());
  15103. }
  15104. {
  15105. detail::UrlComponents uc;
  15106. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15107. EXPECT_TRUE(uc.path.empty());
  15108. EXPECT_TRUE(uc.query.empty());
  15109. }
  15110. }
  15111. TEST(ParseUrlTest, UserinfoHandling) {
  15112. // Userinfo with @ but no colon — host includes @
  15113. detail::UrlComponents uc;
  15114. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15115. EXPECT_EQ("user@host.com", uc.host);
  15116. EXPECT_EQ("/path", uc.path);
  15117. }
  15118. TEST(ParseUrlTest, IPv6EdgeCases) {
  15119. {
  15120. detail::UrlComponents uc;
  15121. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15122. EXPECT_TRUE(uc.scheme.empty());
  15123. EXPECT_EQ("::1", uc.host);
  15124. EXPECT_EQ("8080", uc.port);
  15125. }
  15126. {
  15127. // Zone ID '%25' is not in [a-fA-F0-9:]
  15128. detail::UrlComponents uc;
  15129. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15130. }
  15131. }
  15132. TEST(ParseUrlTest, SchemeEdgeCases) {
  15133. {
  15134. detail::UrlComponents uc;
  15135. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15136. }
  15137. {
  15138. detail::UrlComponents uc;
  15139. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15140. }
  15141. {
  15142. detail::UrlComponents uc;
  15143. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15144. }
  15145. }
  15146. TEST(ParseUrlTest, PortEdgeCases) {
  15147. {
  15148. detail::UrlComponents uc;
  15149. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15150. EXPECT_TRUE(uc.port.empty());
  15151. EXPECT_EQ("/path", uc.path);
  15152. }
  15153. {
  15154. // parse_url accepts any port string; validation is done by parse_port
  15155. detail::UrlComponents uc;
  15156. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15157. EXPECT_EQ("abc", uc.port);
  15158. }
  15159. }
  15160. TEST(ParseUrlTest, WebSocketPatterns) {
  15161. {
  15162. detail::UrlComponents uc;
  15163. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15164. EXPECT_EQ("ws", uc.scheme);
  15165. EXPECT_EQ("echo.example.com", uc.host);
  15166. EXPECT_EQ("8080", uc.port);
  15167. EXPECT_EQ("/ws", uc.path);
  15168. }
  15169. {
  15170. detail::UrlComponents uc;
  15171. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15172. EXPECT_EQ("wss", uc.scheme);
  15173. EXPECT_EQ("echo.example.com", uc.host);
  15174. EXPECT_TRUE(uc.port.empty());
  15175. EXPECT_EQ("/ws", uc.path);
  15176. }
  15177. }
  15178. TEST(ParseUrlTest, QueryOnly) {
  15179. detail::UrlComponents uc;
  15180. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15181. EXPECT_TRUE(uc.host.empty());
  15182. EXPECT_TRUE(uc.path.empty());
  15183. EXPECT_EQ("?q=1&r=2", uc.query);
  15184. }
  15185. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15186. detail::UrlComponents uc;
  15187. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15188. EXPECT_TRUE(uc.scheme.empty());
  15189. EXPECT_EQ("example.com", uc.host);
  15190. EXPECT_EQ("443", uc.port);
  15191. EXPECT_EQ("/path", uc.path);
  15192. }
  15193. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15194. // If ipv6 regex working, regex match codepath is taken.
  15195. // else port will default to 80 in Client impl
  15196. int clientImplMagicPort = 80;
  15197. int port = 4321;
  15198. // above ports must be different to avoid false negative
  15199. EXPECT_NE(clientImplMagicPort, port);
  15200. std::string ipV6TestURL = "http://[ff06::c3]";
  15201. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15202. CLIENT_PRIVATE_KEY_FILE);
  15203. EXPECT_EQ(cli.port(), port);
  15204. }
  15205. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15206. auto file_path = "./www/dir/index.html";
  15207. auto dir_path = "./www/dir";
  15208. detail::FileStat stat_file(file_path);
  15209. EXPECT_TRUE(stat_file.is_file());
  15210. EXPECT_FALSE(stat_file.is_dir());
  15211. detail::FileStat stat_dir(dir_path);
  15212. EXPECT_FALSE(stat_dir.is_file());
  15213. EXPECT_TRUE(stat_dir.is_dir());
  15214. }
  15215. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15216. // IPv4 with default HTTP port (80)
  15217. EXPECT_EQ("example.com",
  15218. detail::make_host_and_port_string("example.com", 80, false));
  15219. // IPv4 with default HTTPS port (443)
  15220. EXPECT_EQ("example.com",
  15221. detail::make_host_and_port_string("example.com", 443, true));
  15222. // IPv4 with non-default HTTP port
  15223. EXPECT_EQ("example.com:8080",
  15224. detail::make_host_and_port_string("example.com", 8080, false));
  15225. // IPv4 with non-default HTTPS port
  15226. EXPECT_EQ("example.com:8443",
  15227. detail::make_host_and_port_string("example.com", 8443, true));
  15228. // IPv6 with default HTTP port (80)
  15229. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15230. // IPv6 with default HTTPS port (443)
  15231. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15232. // IPv6 with non-default HTTP port
  15233. EXPECT_EQ("[::1]:8080",
  15234. detail::make_host_and_port_string("::1", 8080, false));
  15235. // IPv6 with non-default HTTPS port
  15236. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15237. // IPv6 full address with default port
  15238. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15239. detail::make_host_and_port_string(
  15240. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15241. // IPv6 full address with non-default port
  15242. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15243. detail::make_host_and_port_string(
  15244. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15245. // IPv6 localhost with non-default port
  15246. EXPECT_EQ("[::1]:3000",
  15247. detail::make_host_and_port_string("::1", 3000, false));
  15248. // IPv6 with zone ID (link-local address) with default port
  15249. EXPECT_EQ("[fe80::1%eth0]",
  15250. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15251. // IPv6 with zone ID (link-local address) with non-default port
  15252. EXPECT_EQ("[fe80::1%eth0]:8080",
  15253. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15254. // Edge case: Port 443 with is_ssl=false (should add port)
  15255. EXPECT_EQ("example.com:443",
  15256. detail::make_host_and_port_string("example.com", 443, false));
  15257. // Edge case: Port 80 with is_ssl=true (should add port)
  15258. EXPECT_EQ("example.com:80",
  15259. detail::make_host_and_port_string("example.com", 80, true));
  15260. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15261. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15262. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15263. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15264. // Security fix: Already bracketed IPv6 should not get double brackets
  15265. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15266. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15267. EXPECT_EQ("[::1]:8080",
  15268. detail::make_host_and_port_string("[::1]", 8080, false));
  15269. EXPECT_EQ("[2001:db8::1]:8080",
  15270. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15271. EXPECT_EQ("[fe80::1%eth0]",
  15272. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15273. EXPECT_EQ("[fe80::1%eth0]:8080",
  15274. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15275. // Edge case: Empty host (should return as-is)
  15276. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15277. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15278. // This is a known limitation but shouldn't crash
  15279. EXPECT_EQ("[host:name]",
  15280. detail::make_host_and_port_string("host:name", 80, false));
  15281. // Port number edge cases (no validation, but should not crash)
  15282. EXPECT_EQ("example.com:0",
  15283. detail::make_host_and_port_string("example.com", 0, false));
  15284. EXPECT_EQ("example.com:-1",
  15285. detail::make_host_and_port_string("example.com", -1, false));
  15286. EXPECT_EQ("example.com:65535",
  15287. detail::make_host_and_port_string("example.com", 65535, false));
  15288. EXPECT_EQ("example.com:65536",
  15289. detail::make_host_and_port_string("example.com", 65536, false));
  15290. }
  15291. #ifdef CPPHTTPLIB_SSL_ENABLED
  15292. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15293. httplib::SSLClient cli("roblox.com", 443);
  15294. cli.set_follow_location(true);
  15295. auto res = cli.Get("/");
  15296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15297. EXPECT_EQ(StatusCode::OK_200, res->status);
  15298. }
  15299. #endif
  15300. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15301. Server svr;
  15302. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15303. EXPECT_EQ(res.status, 400);
  15304. });
  15305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15306. auto se = detail::scope_exit([&] {
  15307. svr.stop();
  15308. thread.join();
  15309. ASSERT_FALSE(svr.is_running());
  15310. });
  15311. svr.wait_until_ready();
  15312. Client cli(HOST, PORT);
  15313. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15314. }
  15315. TEST(InvalidHeaderCharsTest, is_field_name) {
  15316. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15317. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15318. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15319. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15320. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15321. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15322. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15323. EXPECT_FALSE(detail::fields::is_field_name(""));
  15324. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15325. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15326. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15327. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15328. }
  15329. TEST(InvalidHeaderCharsTest, is_field_value) {
  15330. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15331. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15332. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15333. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15334. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15335. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15336. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15337. EXPECT_TRUE(detail::fields::is_field_value(""));
  15338. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15339. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15340. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15341. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15342. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15343. }
  15344. TEST(InvalidHeaderCharsTest, OnServer) {
  15345. Server svr;
  15346. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15347. std::string header = "Not Set";
  15348. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15349. res.set_header(header, "value");
  15350. res.set_content("Page Content Page Content", "text/plain");
  15351. });
  15352. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15353. std::string header = "Not Set";
  15354. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15355. res.set_header("X-Test", header);
  15356. res.set_content("Page Content Page Content", "text/plain");
  15357. });
  15358. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15359. auto se = detail::scope_exit([&] {
  15360. svr.stop();
  15361. thread.join();
  15362. ASSERT_FALSE(svr.is_running());
  15363. });
  15364. svr.wait_until_ready();
  15365. Client cli(HOST, PORT);
  15366. {
  15367. auto res = cli.Get(
  15368. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15370. EXPECT_EQ("Page Content Page Content", res->body);
  15371. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15372. }
  15373. {
  15374. auto res = cli.Get(
  15375. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15377. EXPECT_EQ("Page Content Page Content", res->body);
  15378. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15379. }
  15380. }
  15381. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15382. auto handled = false;
  15383. Server svr;
  15384. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15385. thread t = thread([&] { svr.listen(HOST, PORT); });
  15386. auto se = detail::scope_exit([&] {
  15387. svr.stop();
  15388. t.join();
  15389. ASSERT_FALSE(svr.is_running());
  15390. ASSERT_FALSE(handled);
  15391. });
  15392. svr.wait_until_ready();
  15393. auto req = "POST /test HTTP/1.1\r\n"
  15394. "Content-Length: x\r\n"
  15395. "\r\n";
  15396. std::string response;
  15397. ASSERT_TRUE(send_request(1, req, &response));
  15398. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15399. response.substr(0, response.find("\r\n")));
  15400. }
  15401. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15402. // case-insensitive, and a server that receives a 100-continue expectation in
  15403. // an HTTP/1.0 request MUST ignore it.
  15404. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15405. std::string response;
  15406. ASSERT_TRUE(send_request(1, req, &response, port));
  15407. *got_100 = response.find("100 Continue") != std::string::npos;
  15408. }
  15409. class ExpectTokenTest : public ::testing::Test {
  15410. protected:
  15411. void SetUp() override {
  15412. svr_.Post("/p", [](const Request &, Response &res) {
  15413. res.set_content("ok", "text/plain");
  15414. });
  15415. port_ = svr_.bind_to_any_port(HOST);
  15416. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15417. svr_.wait_until_ready();
  15418. }
  15419. void TearDown() override {
  15420. svr_.stop();
  15421. if (thread_.joinable()) { thread_.join(); }
  15422. }
  15423. std::string request(const char *version, const char *expect_value) const {
  15424. return std::string("POST /p ") + version +
  15425. "\r\n"
  15426. "Host: localhost\r\n"
  15427. "Content-Length: 2\r\n"
  15428. "Connection: close\r\n"
  15429. "Expect: " +
  15430. expect_value +
  15431. "\r\n"
  15432. "\r\n"
  15433. "hi";
  15434. }
  15435. Server svr_;
  15436. int port_ = 0;
  15437. thread thread_;
  15438. };
  15439. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15440. bool got_100 = false;
  15441. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15442. EXPECT_TRUE(got_100);
  15443. }
  15444. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15445. bool got_100 = true;
  15446. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15447. EXPECT_FALSE(got_100);
  15448. }
  15449. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15450. bool got_100 = false;
  15451. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15452. EXPECT_TRUE(got_100);
  15453. }
  15454. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15455. bool got_100 = false;
  15456. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15457. EXPECT_TRUE(got_100);
  15458. }
  15459. // `100 Continue` is sent only when the server starts reading the body, so a
  15460. // request rejected before that never invites the client to send it. The
  15461. // requests below carry the expectation but withhold the body, as a client
  15462. // waiting for `100 Continue` would.
  15463. // A POST that expects `100 Continue` and withholds its two-byte body.
  15464. static std::string expect_headers_only(const std::string &path) {
  15465. return "POST " + path +
  15466. " HTTP/1.1\r\n"
  15467. "Host: localhost\r\n"
  15468. "Content-Length: 2\r\n"
  15469. "Expect: 100-continue\r\n"
  15470. "\r\n";
  15471. }
  15472. class ExpectLazyContinueTest : public ::testing::Test {
  15473. protected:
  15474. void SetUp() override {
  15475. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15476. if (req.path == "/pre-routing") {
  15477. res.status = StatusCode::Unauthorized_401;
  15478. return Server::HandlerResponse::Handled;
  15479. }
  15480. return Server::HandlerResponse::Unhandled;
  15481. });
  15482. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15483. if (req.matched_route == "/pre-request") {
  15484. res.status = StatusCode::Forbidden_403;
  15485. return Server::HandlerResponse::Handled;
  15486. }
  15487. return Server::HandlerResponse::Unhandled;
  15488. });
  15489. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15490. res.set_content("ok", "text/plain");
  15491. });
  15492. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15493. res.set_content("ok", "text/plain");
  15494. });
  15495. svr_.Post("/reader-used", [](const Request &, Response &res,
  15496. const ContentReader &content_reader) {
  15497. std::string body;
  15498. content_reader([&](const char *data, size_t len) {
  15499. body.append(data, len);
  15500. return true;
  15501. });
  15502. res.set_content(body, "text/plain");
  15503. });
  15504. svr_.Post("/reader-unused",
  15505. [](const Request &, Response &res, const ContentReader &) {
  15506. res.set_content("ignored", "text/plain");
  15507. });
  15508. port_ = svr_.bind_to_any_port(HOST);
  15509. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15510. svr_.wait_until_ready();
  15511. }
  15512. void TearDown() override {
  15513. svr_.stop();
  15514. if (thread_.joinable()) { thread_.join(); }
  15515. }
  15516. // Sends `req` and reads until the server closes the connection. Returns
  15517. // false if the read had to wait for the client-side timeout instead.
  15518. bool send_until_closed(const std::string &req, std::string *resp) const {
  15519. auto start = std::chrono::steady_clock::now();
  15520. if (!send_request(3, req, resp, port_)) { return false; }
  15521. auto elapsed = std::chrono::steady_clock::now() - start;
  15522. return elapsed < std::chrono::seconds(2);
  15523. }
  15524. // The final response comes without `100 Continue`, and the server closes
  15525. // the connection since the body may or may not follow.
  15526. void expect_final_without_interim(const std::string &path,
  15527. const char *status_line) const {
  15528. std::string resp;
  15529. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15530. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15531. EXPECT_EQ(0u, resp.find(status_line));
  15532. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15533. }
  15534. Server svr_;
  15535. int port_ = 0;
  15536. thread thread_;
  15537. };
  15538. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15539. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15540. }
  15541. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15542. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15543. }
  15544. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15545. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15546. }
  15547. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15548. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15549. }
  15550. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15551. // The body follows once `100 Continue` has had time to arrive.
  15552. auto req = expect_headers_only("/reader-used");
  15553. req.insert(req.size() - 2, "Connection: close\r\n");
  15554. std::string resp;
  15555. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15556. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15557. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15558. EXPECT_NE(std::string::npos, resp.find("hi"));
  15559. }
  15560. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15561. // Large enough for the client to add `Expect: 100-continue` itself.
  15562. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15563. std::atomic<bool> body_sent{false};
  15564. Client cli(HOST, port_);
  15565. auto res = cli.Post(
  15566. "/pre-request", length,
  15567. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15568. body_sent = true;
  15569. std::string chunk(len, 'x');
  15570. sink.write(chunk.data(), chunk.size());
  15571. return true;
  15572. },
  15573. "application/octet-stream");
  15574. ASSERT_TRUE(res);
  15575. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15576. EXPECT_FALSE(body_sent);
  15577. }
  15578. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15579. Server svr;
  15580. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15581. return StatusCode::ExpectationFailed_417;
  15582. });
  15583. svr.Post("/p", [](const Request &, Response &res) {
  15584. res.set_content("ok", "text/plain");
  15585. });
  15586. auto port = svr.bind_to_any_port(HOST);
  15587. thread t = thread([&] { svr.listen_after_bind(); });
  15588. auto se = detail::scope_exit([&] {
  15589. svr.stop();
  15590. t.join();
  15591. });
  15592. svr.wait_until_ready();
  15593. std::string resp;
  15594. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15595. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15596. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15597. // Exactly one response: the route handler must not run after the 417.
  15598. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15599. }
  15600. #ifndef _WIN32
  15601. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15602. static constexpr char reject[] = "Unauthorized";
  15603. static constexpr char accept[] = "Upload accepted";
  15604. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15605. Server svr;
  15606. svr.set_expect_100_continue_handler(
  15607. [](const Request & /*req*/, Response &res) {
  15608. res.status = StatusCode::Unauthorized_401;
  15609. res.set_content(reject, "text/plain");
  15610. return res.status;
  15611. });
  15612. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15613. res.set_content(accept, "text/plain");
  15614. });
  15615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15616. auto se = detail::scope_exit([&] {
  15617. svr.stop();
  15618. thread.join();
  15619. ASSERT_FALSE(svr.is_running());
  15620. });
  15621. svr.wait_until_ready();
  15622. {
  15623. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15624. curl_easy_init(), &curl_easy_cleanup};
  15625. ASSERT_NE(curl, nullptr);
  15626. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15627. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15628. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15629. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15630. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15631. &curl_slist_free_all};
  15632. ASSERT_NE(list, nullptr);
  15633. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15634. struct read_data {
  15635. size_t read_size;
  15636. size_t total_size;
  15637. } data = {0, total_size};
  15638. using read_callback_t =
  15639. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15640. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15641. void *userdata) -> size_t {
  15642. read_data *d = (read_data *)userdata;
  15643. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15644. std::fill_n(ptr, size * nmemb, 'A');
  15645. d->read_size += size * nmemb;
  15646. return size * nmemb;
  15647. };
  15648. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15649. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15650. std::vector<char> buffer;
  15651. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15652. using write_callback_t =
  15653. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15654. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15655. void *userdata) -> size_t {
  15656. std::vector<char> *buf = (std::vector<char> *)userdata;
  15657. buf->reserve(buf->size() + size * nmemb + 1);
  15658. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15659. return size * nmemb;
  15660. };
  15661. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15662. {
  15663. const auto res = curl_easy_perform(curl.get());
  15664. ASSERT_EQ(res, CURLE_OK);
  15665. }
  15666. {
  15667. auto response_code = long{};
  15668. const auto res =
  15669. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15670. ASSERT_EQ(res, CURLE_OK);
  15671. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15672. }
  15673. {
  15674. auto dl = curl_off_t{};
  15675. const auto res =
  15676. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15677. ASSERT_EQ(res, CURLE_OK);
  15678. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15679. }
  15680. {
  15681. buffer.push_back('\0');
  15682. ASSERT_STRCASEEQ(buffer.data(), reject);
  15683. }
  15684. }
  15685. }
  15686. #endif
  15687. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15688. // Regression test for #2458.
  15689. //
  15690. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15691. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15692. // ticket can make the client socket spuriously readable during the
  15693. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15694. // the client withholds the body and then blocks reading a response that never
  15695. // comes, failing with `Failed to read connection`.
  15696. //
  15697. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15698. // within the timeout. This raw OpenSSL server deliberately never sends
  15699. // `100 Continue`; the client must still deliver the body and receive 200.
  15700. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15701. signal(SIGPIPE, SIG_IGN);
  15702. const auto port = PORT + 4;
  15703. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15704. ASSERT_NE(srv, INVALID_SOCKET);
  15705. int opt = 1;
  15706. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15707. sockaddr_in addr{};
  15708. addr.sin_family = AF_INET;
  15709. addr.sin_port = htons(static_cast<uint16_t>(port));
  15710. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15711. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15712. ASSERT_EQ(0, ::listen(srv, 1));
  15713. std::atomic<size_t> server_body_bytes{0};
  15714. auto server_thread = std::thread([&] {
  15715. sockaddr_in cli_addr{};
  15716. socklen_t cli_len = sizeof(cli_addr);
  15717. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15718. if (cli == INVALID_SOCKET) { return; }
  15719. // Bound the lifetime of the server side so a buggy client (which never
  15720. // sends the body) cannot make this thread block forever on join.
  15721. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15722. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15723. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15724. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15725. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15726. SSL *ssl = SSL_new(ctx);
  15727. SSL_set_fd(ssl, static_cast<int>(cli));
  15728. if (SSL_accept(ssl) > 0) {
  15729. // Read the request headers. Reading here also flushes the TLS 1.3
  15730. // session tickets to the client. Deliberately do NOT send
  15731. // `100 Continue`.
  15732. std::string buf;
  15733. char tmp[1024];
  15734. while (buf.find("\r\n\r\n") == std::string::npos) {
  15735. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15736. if (n <= 0) { break; }
  15737. buf.append(tmp, static_cast<size_t>(n));
  15738. }
  15739. // A correct client sends the body now; count what arrives.
  15740. auto pos = buf.find("\r\n\r\n");
  15741. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15742. while (body < 4096) {
  15743. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15744. if (n <= 0) { break; }
  15745. body += static_cast<size_t>(n);
  15746. }
  15747. server_body_bytes = body;
  15748. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15749. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15750. SSL_shutdown(ssl);
  15751. }
  15752. SSL_free(ssl);
  15753. detail::close_socket(cli);
  15754. SSL_CTX_free(ctx);
  15755. });
  15756. auto se = detail::scope_exit([&] {
  15757. server_thread.join();
  15758. detail::close_socket(srv);
  15759. });
  15760. SSLClient cli("127.0.0.1", port);
  15761. cli.enable_server_certificate_verification(false);
  15762. cli.set_connection_timeout(5, 0);
  15763. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15764. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15765. std::string body(4096, 'A');
  15766. auto res = cli.Put("/api/test", body, "application/json");
  15767. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15768. EXPECT_EQ(StatusCode::OK_200, res->status);
  15769. EXPECT_EQ(body.size(), server_body_bytes.load());
  15770. }
  15771. #endif
  15772. template <typename S, typename C>
  15773. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15774. svr.Get("/stream", [&](const Request &, Response &res) {
  15775. auto data = new std::string("01234567890123456789");
  15776. res.set_content_provider(
  15777. data->size(), "text/plain",
  15778. [&, data](size_t offset, size_t length, DataSink &sink) {
  15779. const size_t DATA_CHUNK_SIZE = 4;
  15780. const auto &d = *data;
  15781. std::this_thread::sleep_for(std::chrono::seconds(1));
  15782. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15783. return true;
  15784. },
  15785. [data](bool success) {
  15786. EXPECT_FALSE(success);
  15787. delete data;
  15788. });
  15789. });
  15790. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15791. auto i = new size_t(0);
  15792. res.set_content_provider(
  15793. "text/plain",
  15794. [i](size_t, DataSink &sink) {
  15795. if (*i < 5) {
  15796. std::this_thread::sleep_for(std::chrono::seconds(1));
  15797. sink.write("abcd", 4);
  15798. (*i)++;
  15799. } else {
  15800. sink.done();
  15801. }
  15802. return true;
  15803. },
  15804. [i](bool success) {
  15805. EXPECT_FALSE(success);
  15806. delete i;
  15807. });
  15808. });
  15809. svr.Get("/chunked", [&](const Request &, Response &res) {
  15810. auto i = new size_t(0);
  15811. res.set_chunked_content_provider(
  15812. "text/plain",
  15813. [i](size_t, DataSink &sink) {
  15814. if (*i < 5) {
  15815. std::this_thread::sleep_for(std::chrono::seconds(1));
  15816. sink.os << "abcd";
  15817. (*i)++;
  15818. } else {
  15819. sink.done();
  15820. }
  15821. return true;
  15822. },
  15823. [i](bool success) {
  15824. EXPECT_FALSE(success);
  15825. delete i;
  15826. });
  15827. });
  15828. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15829. auto se = detail::scope_exit([&] {
  15830. svr.stop();
  15831. listen_thread.join();
  15832. ASSERT_FALSE(svr.is_running());
  15833. });
  15834. svr.wait_until_ready();
  15835. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15836. {
  15837. auto start = std::chrono::steady_clock::now();
  15838. auto res = cli.Get("/stream");
  15839. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15840. std::chrono::steady_clock::now() - start)
  15841. .count();
  15842. ASSERT_FALSE(res);
  15843. EXPECT_EQ(Error::Read, res.error());
  15844. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15845. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15846. }
  15847. {
  15848. auto start = std::chrono::steady_clock::now();
  15849. auto res = cli.Get("/stream_without_length");
  15850. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15851. std::chrono::steady_clock::now() - start)
  15852. .count();
  15853. ASSERT_FALSE(res);
  15854. EXPECT_EQ(Error::Read, res.error());
  15855. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15856. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15857. }
  15858. {
  15859. auto start = std::chrono::steady_clock::now();
  15860. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15861. EXPECT_EQ("abcd", string(data, data_length));
  15862. return true;
  15863. });
  15864. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15865. std::chrono::steady_clock::now() - start)
  15866. .count();
  15867. ASSERT_FALSE(res);
  15868. EXPECT_EQ(Error::Read, res.error());
  15869. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15870. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15871. }
  15872. }
  15873. TEST(MaxTimeoutTest, ContentStream) {
  15874. time_t timeout = 2000;
  15875. time_t threshold = 200;
  15876. Server svr;
  15877. Client cli("localhost", PORT);
  15878. max_timeout_test(svr, cli, timeout, threshold);
  15879. }
  15880. #ifdef CPPHTTPLIB_SSL_ENABLED
  15881. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15882. time_t timeout = 2000;
  15883. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15884. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15885. SSLClient cli("localhost", PORT);
  15886. cli.enable_server_certificate_verification(false);
  15887. max_timeout_test(svr, cli, timeout, threshold);
  15888. }
  15889. #endif
  15890. class EventDispatcher {
  15891. public:
  15892. EventDispatcher() {}
  15893. bool wait_event(DataSink *sink) {
  15894. unique_lock<mutex> lk(m_);
  15895. int id = id_;
  15896. // Wait with timeout to prevent hanging if client disconnects
  15897. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15898. [&] { return cid_ == id; })) {
  15899. return false; // Timeout occurred
  15900. }
  15901. sink->write(message_.data(), message_.size());
  15902. return true;
  15903. }
  15904. void send_event(const string &message) {
  15905. lock_guard<mutex> lk(m_);
  15906. cid_ = id_++;
  15907. message_ = message;
  15908. cv_.notify_all();
  15909. }
  15910. private:
  15911. mutex m_;
  15912. condition_variable cv_;
  15913. atomic_int id_{0};
  15914. atomic_int cid_{-1};
  15915. string message_;
  15916. };
  15917. TEST(ClientInThreadTest, Issue2068) {
  15918. EventDispatcher ed;
  15919. Server svr;
  15920. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15921. res.set_chunked_content_provider("text/event-stream",
  15922. [&](size_t /*offset*/, DataSink &sink) {
  15923. return ed.wait_event(&sink);
  15924. });
  15925. });
  15926. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15927. svr.wait_until_ready();
  15928. thread event_thread([&] {
  15929. int id = 0;
  15930. while (svr.is_running()) {
  15931. this_thread::sleep_for(chrono::milliseconds(500));
  15932. std::stringstream ss;
  15933. ss << "data: " << id << "\n\n";
  15934. ed.send_event(ss.str());
  15935. id++;
  15936. }
  15937. });
  15938. auto se = detail::scope_exit([&] {
  15939. svr.stop();
  15940. listen_thread.join();
  15941. event_thread.join();
  15942. ASSERT_FALSE(svr.is_running());
  15943. });
  15944. {
  15945. auto client = detail::make_unique<Client>(HOST, PORT);
  15946. client->set_read_timeout(std::chrono::minutes(10));
  15947. std::atomic<bool> stop{false};
  15948. std::thread t([&] {
  15949. client->Get("/event1",
  15950. [&](const char *, size_t) -> bool { return !stop; });
  15951. });
  15952. std::this_thread::sleep_for(std::chrono::seconds(2));
  15953. stop = true;
  15954. client->stop();
  15955. t.join();
  15956. // Reset client after thread has finished
  15957. client.reset();
  15958. }
  15959. }
  15960. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  15961. auto handled = false;
  15962. Server svr;
  15963. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15964. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15965. auto se = detail::scope_exit([&] {
  15966. svr.stop();
  15967. t.join();
  15968. ASSERT_FALSE(svr.is_running());
  15969. ASSERT_FALSE(handled);
  15970. });
  15971. svr.wait_until_ready();
  15972. // Two Content-Length headers with different values — must be rejected
  15973. auto req = "POST /test HTTP/1.1\r\n"
  15974. "Content-Length: 5\r\n"
  15975. "Content-Length: 10\r\n"
  15976. "\r\n"
  15977. "hello";
  15978. std::string response;
  15979. ASSERT_TRUE(send_request(1, req, &response));
  15980. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15981. response.substr(0, response.find("\r\n")));
  15982. }
  15983. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  15984. auto handled = false;
  15985. Server svr;
  15986. svr.Post("/test", [&](const Request &, Response &res) {
  15987. handled = true;
  15988. res.set_content("ok", "text/plain");
  15989. });
  15990. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15991. auto se = detail::scope_exit([&] {
  15992. svr.stop();
  15993. t.join();
  15994. ASSERT_FALSE(svr.is_running());
  15995. ASSERT_TRUE(handled);
  15996. });
  15997. svr.wait_until_ready();
  15998. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  15999. auto req = "POST /test HTTP/1.1\r\n"
  16000. "Content-Length: 5\r\n"
  16001. "Content-Length: 5\r\n"
  16002. "\r\n"
  16003. "hello";
  16004. std::string response;
  16005. ASSERT_TRUE(send_request(1, req, &response));
  16006. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16007. }
  16008. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16009. Server svr;
  16010. svr.Get("/", [](const Request &req, Response &res) {
  16011. EXPECT_EQ(2U, req.trailers.size());
  16012. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16013. // Denied
  16014. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16015. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16016. // Accepted
  16017. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16018. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16019. EXPECT_TRUE(req.has_trailer("X-World"));
  16020. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16021. res.set_content("ok", "text/plain");
  16022. });
  16023. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16024. auto se = detail::scope_exit([&] {
  16025. svr.stop();
  16026. t.join();
  16027. ASSERT_FALSE(svr.is_running());
  16028. });
  16029. svr.wait_until_ready();
  16030. const std::string req = "GET / HTTP/1.1\r\n"
  16031. "Transfer-Encoding: chunked\r\n"
  16032. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16033. "\r\n"
  16034. "0\r\n"
  16035. "Content-Length: 10\r\n"
  16036. "Host: internal.local\r\n"
  16037. "Content-Type: malicious/content\r\n"
  16038. "Cookie: any\r\n"
  16039. "Set-Cookie: any\r\n"
  16040. "X-Forwarded-For: attacker.com\r\n"
  16041. "X-Real-Ip: 1.1.1.1\r\n"
  16042. "X-Hello: hello\r\n"
  16043. "X-World: world\r\n"
  16044. "\r\n";
  16045. std::string res;
  16046. ASSERT_TRUE(send_request(1, req, &res));
  16047. }
  16048. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16049. // several field lines, and the combined value is what has to be parsed. A
  16050. // Trailer field split across lines therefore declares every name it lists;
  16051. // reading only the first line silently drops the trailers the later lines
  16052. // declare. The prohibited-trailer filter still applies to every line.
  16053. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16054. Server svr;
  16055. size_t observed_trailer_count = 0;
  16056. std::string observed_hello;
  16057. std::string observed_world;
  16058. bool observed_content_length = true;
  16059. svr.Get("/", [&](const Request &req, Response &res) {
  16060. observed_trailer_count = req.trailers.size();
  16061. observed_hello = req.get_trailer_value("X-Hello");
  16062. observed_world = req.get_trailer_value("X-World");
  16063. observed_content_length = req.has_trailer("Content-Length");
  16064. res.set_content("ok", "text/plain");
  16065. });
  16066. auto port = svr.bind_to_any_port(HOST);
  16067. thread t = thread([&]() { svr.listen_after_bind(); });
  16068. auto se = detail::scope_exit([&] {
  16069. svr.stop();
  16070. t.join();
  16071. ASSERT_FALSE(svr.is_running());
  16072. });
  16073. svr.wait_until_ready();
  16074. const std::string req = "GET / HTTP/1.1\r\n"
  16075. "Transfer-Encoding: chunked\r\n"
  16076. "Trailer: X-Hello\r\n"
  16077. "Trailer: X-World, Content-Length\r\n"
  16078. "\r\n"
  16079. "0\r\n"
  16080. "X-Hello: hello\r\n"
  16081. "X-World: world\r\n"
  16082. "Content-Length: 10\r\n"
  16083. "\r\n";
  16084. std::string res;
  16085. ASSERT_TRUE(send_request(1, req, &res, port));
  16086. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16087. // Accepted: both field lines contribute to the declared set
  16088. EXPECT_EQ(2U, observed_trailer_count);
  16089. EXPECT_EQ(observed_hello, "hello");
  16090. EXPECT_EQ(observed_world, "world");
  16091. // Denied: a prohibited name stays prohibited on a later field line
  16092. EXPECT_FALSE(observed_content_length);
  16093. }
  16094. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16095. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16096. // unbounded run of fields that are never declared, because the counter would
  16097. // only advance for declared fields.
  16098. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16099. Server svr;
  16100. bool handler_called = false;
  16101. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16102. handler_called = true;
  16103. res.set_content("ok", "text/plain");
  16104. });
  16105. auto port = svr.bind_to_any_port(HOST);
  16106. thread t = thread([&]() { svr.listen_after_bind(); });
  16107. auto se = detail::scope_exit([&] {
  16108. svr.stop();
  16109. t.join();
  16110. ASSERT_FALSE(svr.is_running());
  16111. });
  16112. svr.wait_until_ready();
  16113. // Declare nothing, then send far more undeclared trailer fields than the
  16114. // header-count limit. Parsing must stop and reject the request rather than
  16115. // read every line.
  16116. std::string req = "GET / HTTP/1.1\r\n"
  16117. "Transfer-Encoding: chunked\r\n"
  16118. "\r\n"
  16119. "0\r\n";
  16120. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16121. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16122. }
  16123. req += "\r\n";
  16124. std::string res;
  16125. ASSERT_TRUE(send_request(1, req, &res, port));
  16126. // The request is rejected before the handler runs.
  16127. EXPECT_FALSE(handler_called);
  16128. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16129. }
  16130. // The set of declared trailer names is capped so a peer cannot grow it without
  16131. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16132. // declared past the cap is not honored, even if the field is actually sent.
  16133. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16134. Server svr;
  16135. // One name inside the cap and one past it, so the test tracks the cap rather
  16136. // than a fixed count.
  16137. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16138. const std::string within_cap_name = "X-T-0";
  16139. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16140. bool observed_within_cap = false;
  16141. bool observed_past_cap = false;
  16142. svr.Get("/", [&](const Request &req, Response &res) {
  16143. observed_within_cap = req.has_trailer(within_cap_name);
  16144. observed_past_cap = req.has_trailer(past_cap_name);
  16145. res.set_content("ok", "text/plain");
  16146. });
  16147. auto port = svr.bind_to_any_port(HOST);
  16148. thread t = thread([&]() { svr.listen_after_bind(); });
  16149. auto se = detail::scope_exit([&] {
  16150. svr.stop();
  16151. t.join();
  16152. ASSERT_FALSE(svr.is_running());
  16153. });
  16154. svr.wait_until_ready();
  16155. // Declare more trailer names than the cap in a single Trailer field, then
  16156. // actually send the first (within the cap) and the last (past it).
  16157. std::string trailer_decl = "Trailer: ";
  16158. for (int i = 0; i < declared_count; i++) {
  16159. if (i != 0) { trailer_decl += ", "; }
  16160. trailer_decl += "X-T-" + std::to_string(i);
  16161. }
  16162. trailer_decl += "\r\n";
  16163. const std::string req = "GET / HTTP/1.1\r\n"
  16164. "Transfer-Encoding: chunked\r\n" +
  16165. trailer_decl +
  16166. "\r\n"
  16167. "0\r\n" +
  16168. within_cap_name + ": a\r\n" + past_cap_name +
  16169. ": b\r\n"
  16170. "\r\n";
  16171. std::string res;
  16172. ASSERT_TRUE(send_request(1, req, &res, port));
  16173. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16174. // A name within the cap is honored; one declared past the cap is dropped.
  16175. EXPECT_TRUE(observed_within_cap);
  16176. EXPECT_FALSE(observed_past_cap);
  16177. }
  16178. // A direct client that is not listed in trusted_proxies must not be able to
  16179. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16180. // the peer address on the actual TCP connection determines whether the
  16181. // header is honored.
  16182. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16183. Server svr;
  16184. // Deliberately does NOT include the loopback address the test client
  16185. // actually connects from, so the direct connection is not a trusted proxy.
  16186. svr.set_trusted_proxies({"203.0.113.66"});
  16187. std::string observed_remote_addr;
  16188. svr.Get("/ip", [&](const Request &req, Response &res) {
  16189. observed_remote_addr = req.remote_addr;
  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", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16202. EXPECT_EQ(StatusCode::OK_200, res->status);
  16203. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16204. // ignored entirely and the real connection-level address retained.
  16205. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16206. observed_remote_addr == "127.0.0.1");
  16207. }
  16208. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16209. Server svr;
  16210. std::string observed_remote_addr;
  16211. std::string observed_xff;
  16212. svr.Get("/ip", [&](const Request &req, Response &res) {
  16213. observed_remote_addr = req.remote_addr;
  16214. observed_xff = req.get_header_value("X-Forwarded-For");
  16215. res.set_content("ok", "text/plain");
  16216. });
  16217. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16218. auto se = detail::scope_exit([&] {
  16219. svr.stop();
  16220. t.join();
  16221. ASSERT_FALSE(svr.is_running());
  16222. });
  16223. svr.wait_until_ready();
  16224. Client cli(HOST, PORT);
  16225. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16227. EXPECT_EQ(StatusCode::OK_200, res->status);
  16228. EXPECT_EQ(observed_xff, "203.0.113.66");
  16229. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16230. observed_remote_addr == "127.0.0.1");
  16231. }
  16232. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16233. Server svr;
  16234. svr.set_trusted_proxies({"203.0.113.66"});
  16235. std::string observed_remote_addr;
  16236. std::string observed_xff;
  16237. svr.Get("/ip", [&](const Request &req, Response &res) {
  16238. observed_remote_addr = req.remote_addr;
  16239. observed_xff = req.get_header_value("X-Forwarded-For");
  16240. res.set_content("ok", "text/plain");
  16241. });
  16242. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16243. auto se = detail::scope_exit([&] {
  16244. svr.stop();
  16245. t.join();
  16246. ASSERT_FALSE(svr.is_running());
  16247. });
  16248. svr.wait_until_ready();
  16249. Client cli(HOST, PORT);
  16250. auto res = cli.Get("/ip");
  16251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16252. EXPECT_EQ(StatusCode::OK_200, res->status);
  16253. EXPECT_EQ(observed_xff, "");
  16254. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16255. observed_remote_addr == "127.0.0.1");
  16256. }
  16257. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16258. Server svr;
  16259. // Include the loopback address the test client actually connects from, so
  16260. // the direct connection itself is recognized as the trusted proxy hop.
  16261. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16262. std::string observed_remote_addr;
  16263. std::string observed_xff;
  16264. svr.Get("/ip", [&](const Request &req, Response &res) {
  16265. observed_remote_addr = req.remote_addr;
  16266. observed_xff = req.get_header_value("X-Forwarded-For");
  16267. res.set_content("ok", "text/plain");
  16268. });
  16269. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16270. auto se = detail::scope_exit([&] {
  16271. svr.stop();
  16272. t.join();
  16273. ASSERT_FALSE(svr.is_running());
  16274. });
  16275. svr.wait_until_ready();
  16276. Client cli(HOST, PORT);
  16277. auto res = cli.Get(
  16278. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16280. EXPECT_EQ(StatusCode::OK_200, res->status);
  16281. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16282. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16283. }
  16284. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16285. Server svr;
  16286. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16287. std::string observed_remote_addr;
  16288. std::string observed_xff;
  16289. svr.Get("/ip", [&](const Request &req, Response &res) {
  16290. observed_remote_addr = req.remote_addr;
  16291. observed_xff = req.get_header_value("X-Forwarded-For");
  16292. res.set_content("ok", "text/plain");
  16293. });
  16294. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16295. auto se = detail::scope_exit([&] {
  16296. svr.stop();
  16297. t.join();
  16298. ASSERT_FALSE(svr.is_running());
  16299. });
  16300. svr.wait_until_ready();
  16301. Client cli(HOST, PORT);
  16302. auto res = cli.Get(
  16303. "/ip",
  16304. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16306. EXPECT_EQ(StatusCode::OK_200, res->status);
  16307. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16308. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16309. }
  16310. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16311. Server svr;
  16312. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16313. std::string observed_remote_addr;
  16314. std::string observed_xff;
  16315. svr.Get("/ip", [&](const Request &req, Response &res) {
  16316. observed_remote_addr = req.remote_addr;
  16317. observed_xff = req.get_header_value("X-Forwarded-For");
  16318. res.set_content("ok", "text/plain");
  16319. });
  16320. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16321. auto se = detail::scope_exit([&] {
  16322. svr.stop();
  16323. t.join();
  16324. ASSERT_FALSE(svr.is_running());
  16325. });
  16326. svr.wait_until_ready();
  16327. Client cli(HOST, PORT);
  16328. auto res = cli.Get(
  16329. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16331. EXPECT_EQ(StatusCode::OK_200, res->status);
  16332. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16333. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16334. // and must not be selected.
  16335. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16336. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16337. }
  16338. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16339. Server svr;
  16340. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16341. std::string observed_remote_addr;
  16342. svr.Get("/ip", [&](const Request &req, Response &res) {
  16343. observed_remote_addr = req.remote_addr;
  16344. res.set_content("ok", "text/plain");
  16345. });
  16346. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16347. auto se = detail::scope_exit([&] {
  16348. svr.stop();
  16349. t.join();
  16350. ASSERT_FALSE(svr.is_running());
  16351. });
  16352. svr.wait_until_ready();
  16353. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16354. // a forged address and the trusted proxy's own address; the forged value must
  16355. // not win over the address the trusted proxy actually recorded.
  16356. Client cli(HOST, PORT);
  16357. auto res = cli.Get(
  16358. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16360. EXPECT_EQ(StatusCode::OK_200, res->status);
  16361. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16362. }
  16363. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16364. Server svr;
  16365. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16366. std::string observed_remote_addr;
  16367. std::string observed_xff;
  16368. svr.Get("/ip", [&](const Request &req, Response &res) {
  16369. observed_remote_addr = req.remote_addr;
  16370. observed_xff = req.get_header_value("X-Forwarded-For");
  16371. res.set_content("ok", "text/plain");
  16372. });
  16373. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16374. auto se = detail::scope_exit([&] {
  16375. svr.stop();
  16376. t.join();
  16377. ASSERT_FALSE(svr.is_running());
  16378. });
  16379. svr.wait_until_ready();
  16380. Client cli(HOST, PORT);
  16381. auto res = cli.Get(
  16382. "/ip",
  16383. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16385. EXPECT_EQ(StatusCode::OK_200, res->status);
  16386. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16387. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16388. }
  16389. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16390. Server svr;
  16391. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16392. std::string observed_remote_addr;
  16393. std::string observed_xff;
  16394. svr.Get("/ip", [&](const Request &req, Response &res) {
  16395. observed_remote_addr = req.remote_addr;
  16396. observed_xff = req.get_header_value("X-Forwarded-For");
  16397. res.set_content("ok", "text/plain");
  16398. });
  16399. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16400. auto se = detail::scope_exit([&] {
  16401. svr.stop();
  16402. t.join();
  16403. ASSERT_FALSE(svr.is_running());
  16404. });
  16405. svr.wait_until_ready();
  16406. std::string raw_req =
  16407. "GET /ip HTTP/1.1\r\n"
  16408. "Host: localhost\r\n"
  16409. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16410. "Connection: close\r\n"
  16411. "\r\n";
  16412. std::string out;
  16413. ASSERT_TRUE(send_request(5, raw_req, &out));
  16414. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16415. // Header parser trims surrounding whitespace of the header value
  16416. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16417. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16418. }
  16419. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16420. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16421. // their own X-Forwarded-For as a separate field line rather than extending the
  16422. // one the client sent, so every occurrence has to be taken into account.
  16423. // Reading only the first one hands back the address the client chose.
  16424. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16425. Server svr;
  16426. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16427. std::string observed_remote_addr;
  16428. size_t observed_xff_count = 0;
  16429. svr.Get("/ip", [&](const Request &req, Response &res) {
  16430. observed_remote_addr = req.remote_addr;
  16431. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16432. res.set_content("ok", "text/plain");
  16433. });
  16434. auto port = svr.bind_to_any_port(HOST);
  16435. thread t = thread([&]() { svr.listen_after_bind(); });
  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. // The client supplies the first field line; the trusted proxy appends the
  16443. // address it observed as a second one.
  16444. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16445. "Host: localhost\r\n"
  16446. "X-Forwarded-For: 1.2.3.4\r\n"
  16447. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16448. "Connection: close\r\n"
  16449. "\r\n";
  16450. std::string out;
  16451. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16452. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16453. EXPECT_EQ(observed_xff_count, 2U);
  16454. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16455. // The same chain spread over one field line per hop derives the same client
  16456. // address, i.e. the split and the comma-joined representations agree.
  16457. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16458. "Host: localhost\r\n"
  16459. "X-Forwarded-For: 1.2.3.4\r\n"
  16460. "X-Forwarded-For: 198.51.100.23\r\n"
  16461. "X-Forwarded-For: 192.0.2.45\r\n"
  16462. "Connection: close\r\n"
  16463. "\r\n";
  16464. out.clear();
  16465. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16466. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16467. EXPECT_EQ(observed_xff_count, 3U);
  16468. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16469. }
  16470. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16471. // crash the server (it used to call front() on an empty vector inside
  16472. // get_client_ip). The connection-level remote address must be retained instead.
  16473. static void run_malformed_xff_test(const std::string &xff_value) {
  16474. Server svr;
  16475. svr.set_trusted_proxies({"192.0.2.45"});
  16476. std::string observed_remote_addr;
  16477. svr.Get("/ip", [&](const Request &req, Response &res) {
  16478. observed_remote_addr = req.remote_addr;
  16479. res.set_content("ok", "text/plain");
  16480. });
  16481. int port = 0;
  16482. thread t = thread([&]() {
  16483. port = svr.bind_to_any_port(HOST);
  16484. svr.listen_after_bind();
  16485. });
  16486. auto se = detail::scope_exit([&] {
  16487. svr.stop();
  16488. t.join();
  16489. ASSERT_FALSE(svr.is_running());
  16490. });
  16491. svr.wait_until_ready();
  16492. Client cli(HOST, port);
  16493. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16495. EXPECT_EQ(StatusCode::OK_200, res->status);
  16496. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16497. observed_remote_addr == "127.0.0.1");
  16498. }
  16499. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16500. run_malformed_xff_test("");
  16501. }
  16502. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16503. run_malformed_xff_test(",");
  16504. }
  16505. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16506. run_malformed_xff_test(", , ,");
  16507. }
  16508. // The same rule applies to Accept: a request whose acceptable types are spread
  16509. // over several field lines must be negotiated against all of them.
  16510. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16511. // case-insensitive connection options. Comparing the whole field value against
  16512. // one option misses a client that sends several of them, and misses every
  16513. // casing but the one written in the comparison.
  16514. //
  16515. // Sends req, reads the response, then reuses the same socket for a second
  16516. // request to find out whether the server kept the connection.
  16517. static void probe_connection_reuse(int port, const std::string &req,
  16518. bool *announced_close, bool *reusable) {
  16519. auto error = Error::Success;
  16520. auto sock = detail::create_client_socket(
  16521. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16522. /*connection_timeout_sec=*/5, 0,
  16523. /*read_timeout_sec=*/1, 0,
  16524. /*write_timeout_sec=*/5, 0, std::string(), error);
  16525. ASSERT_NE(sock, INVALID_SOCKET);
  16526. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16527. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16528. "Host: localhost\r\n"
  16529. "Connection: close\r\n"
  16530. "\r\n";
  16531. std::string first_response;
  16532. std::string second_response;
  16533. detail::process_client_socket(
  16534. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16535. [&](Stream &strm) {
  16536. if (strm.write(req.data(), req.size()) !=
  16537. static_cast<ssize_t>(req.size())) {
  16538. return false;
  16539. }
  16540. char buf[512];
  16541. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16542. // Headers plus the two-byte body of the handler below
  16543. while (reader.getline()) {
  16544. first_response += reader.ptr();
  16545. if (first_response.find("ok") != std::string::npos) { break; }
  16546. }
  16547. if (strm.write(second.data(), second.size()) !=
  16548. static_cast<ssize_t>(second.size())) {
  16549. return true;
  16550. }
  16551. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16552. while (reader2.getline()) {
  16553. second_response += reader2.ptr();
  16554. if (second_response.find("ok") != std::string::npos) { break; }
  16555. }
  16556. return true;
  16557. });
  16558. *announced_close =
  16559. first_response.find("Connection: close") != std::string::npos;
  16560. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16561. }
  16562. class ConnectionTokenTest : public ::testing::Test {
  16563. protected:
  16564. void SetUp() override {
  16565. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16566. res.set_content("ok", "text/plain");
  16567. });
  16568. port_ = svr_.bind_to_any_port(HOST);
  16569. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16570. svr_.wait_until_ready();
  16571. }
  16572. void TearDown() override {
  16573. svr_.stop();
  16574. if (thread_.joinable()) { thread_.join(); }
  16575. }
  16576. Server svr_;
  16577. int port_ = 0;
  16578. thread thread_;
  16579. };
  16580. // "close" alongside another option still closes the connection, and the
  16581. // response says so rather than leaving the peer to discover it.
  16582. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16583. bool announced_close = false;
  16584. bool reusable = true;
  16585. probe_connection_reuse(port_,
  16586. "GET /keepalive HTTP/1.1\r\n"
  16587. "Host: localhost\r\n"
  16588. "Connection: keep-alive, close\r\n"
  16589. "\r\n",
  16590. &announced_close, &reusable);
  16591. EXPECT_TRUE(announced_close);
  16592. EXPECT_FALSE(reusable);
  16593. }
  16594. // "close" split over two field lines is the same list, so it is honored too.
  16595. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16596. bool announced_close = false;
  16597. bool reusable = true;
  16598. probe_connection_reuse(port_,
  16599. "GET /keepalive HTTP/1.1\r\n"
  16600. "Host: localhost\r\n"
  16601. "Connection: keep-alive\r\n"
  16602. "Connection: close\r\n"
  16603. "\r\n",
  16604. &announced_close, &reusable);
  16605. EXPECT_TRUE(announced_close);
  16606. EXPECT_FALSE(reusable);
  16607. }
  16608. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16609. // keep-alive in the spelling everyone actually sends keeps its connection.
  16610. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16611. bool announced_close = false;
  16612. bool reusable = false;
  16613. probe_connection_reuse(port_,
  16614. "GET /keepalive HTTP/1.0\r\n"
  16615. "Host: localhost\r\n"
  16616. "Connection: keep-alive\r\n"
  16617. "\r\n",
  16618. &announced_close, &reusable);
  16619. EXPECT_FALSE(announced_close);
  16620. EXPECT_TRUE(reusable);
  16621. }
  16622. // A token the value merely contains is not the token itself.
  16623. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16624. bool announced_close = false;
  16625. bool reusable = false;
  16626. probe_connection_reuse(port_,
  16627. "GET /keepalive HTTP/1.1\r\n"
  16628. "Host: localhost\r\n"
  16629. "Connection: notclose\r\n"
  16630. "\r\n",
  16631. &announced_close, &reusable);
  16632. EXPECT_FALSE(announced_close);
  16633. EXPECT_TRUE(reusable);
  16634. }
  16635. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16636. Server svr;
  16637. std::vector<std::string> observed_types;
  16638. svr.Get("/", [&](const Request &req, Response &res) {
  16639. observed_types = req.accept_content_types;
  16640. res.set_content("ok", "text/plain");
  16641. });
  16642. auto port = svr.bind_to_any_port(HOST);
  16643. thread t = thread([&]() { svr.listen_after_bind(); });
  16644. auto se = detail::scope_exit([&] {
  16645. svr.stop();
  16646. t.join();
  16647. ASSERT_FALSE(svr.is_running());
  16648. });
  16649. svr.wait_until_ready();
  16650. Client cli(HOST, port);
  16651. Headers headers;
  16652. headers.emplace("Accept", "text/plain;q=0.5");
  16653. headers.emplace("Accept", "application/json");
  16654. auto res = cli.Get("/", headers);
  16655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16656. EXPECT_EQ(StatusCode::OK_200, res->status);
  16657. // Sorted by q-value, so the second field line's type comes first
  16658. ASSERT_EQ(2U, observed_types.size());
  16659. EXPECT_EQ("application/json", observed_types[0]);
  16660. EXPECT_EQ("text/plain", observed_types[1]);
  16661. }
  16662. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16663. // empty field line must not contribute a bare comma to the combined value.
  16664. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16665. Server svr;
  16666. std::vector<std::string> observed_types;
  16667. svr.Get("/", [&](const Request &req, Response &res) {
  16668. observed_types = req.accept_content_types;
  16669. res.set_content("ok", "text/plain");
  16670. });
  16671. auto port = svr.bind_to_any_port(HOST);
  16672. thread t = thread([&]() { svr.listen_after_bind(); });
  16673. auto se = detail::scope_exit([&] {
  16674. svr.stop();
  16675. t.join();
  16676. ASSERT_FALSE(svr.is_running());
  16677. });
  16678. svr.wait_until_ready();
  16679. // Empty first field line, then a real one
  16680. std::string raw_req = "GET / HTTP/1.1\r\n"
  16681. "Host: localhost\r\n"
  16682. "Accept:\r\n"
  16683. "Accept: application/json\r\n"
  16684. "Connection: close\r\n"
  16685. "\r\n";
  16686. std::string out;
  16687. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16688. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16689. ASSERT_EQ(1U, observed_types.size());
  16690. EXPECT_EQ("application/json", observed_types[0]);
  16691. }
  16692. // The skip in get_combined_header_value() is what keeps an empty field line
  16693. // from contributing a bare comma. Only a trailing empty field line exercises
  16694. // it: a leading one is already covered by the "combined is still empty" check,
  16695. // and parse_accept_header() now ignores the empty element either way, so the
  16696. // request-level test above can no longer tell the two apart.
  16697. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16698. Headers headers;
  16699. headers.emplace("Accept", "text/html");
  16700. headers.emplace("Accept", "");
  16701. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16702. headers.clear();
  16703. headers.emplace("Accept", "");
  16704. headers.emplace("Accept", "application/json");
  16705. EXPECT_EQ("application/json",
  16706. detail::get_combined_header_value(headers, "Accept"));
  16707. }
  16708. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16709. // An encoding offered on a later Accept-Encoding field line is still offered.
  16710. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16711. Server svr;
  16712. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16713. res.set_content(std::string(1024, 'x'), "text/plain");
  16714. });
  16715. auto port = svr.bind_to_any_port(HOST);
  16716. thread t = thread([&]() { svr.listen_after_bind(); });
  16717. auto se = detail::scope_exit([&] {
  16718. svr.stop();
  16719. t.join();
  16720. ASSERT_FALSE(svr.is_running());
  16721. });
  16722. svr.wait_until_ready();
  16723. Client cli(HOST, port);
  16724. cli.set_decompress(false);
  16725. Headers headers;
  16726. headers.emplace("Accept-Encoding", "identity");
  16727. headers.emplace("Accept-Encoding", "gzip");
  16728. auto res = cli.Get("/", headers);
  16729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16730. EXPECT_EQ(StatusCode::OK_200, res->status);
  16731. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16732. }
  16733. #endif
  16734. #ifndef _WIN32
  16735. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16736. Server svr;
  16737. svr.Post("/post", [&](const Request &req, Response &res) {
  16738. res.set_content(req.body, "text/plain");
  16739. });
  16740. svr.Put("/put", [&](const Request &req, Response &res) {
  16741. res.set_content(req.body, "text/plain");
  16742. });
  16743. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16744. res.set_content(req.body, "text/plain");
  16745. });
  16746. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16747. res.set_content(req.body, "text/plain");
  16748. });
  16749. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16750. auto se = detail::scope_exit([&] {
  16751. svr.stop();
  16752. t.join();
  16753. ASSERT_FALSE(svr.is_running());
  16754. });
  16755. svr.wait_until_ready();
  16756. std::string resp;
  16757. // POST without Content-Length
  16758. ASSERT_TRUE(send_request(5,
  16759. "POST /post HTTP/1.1\r\n"
  16760. "Host: localhost\r\n"
  16761. "Connection: close\r\n"
  16762. "\r\n",
  16763. &resp));
  16764. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16765. // PUT without Content-Length
  16766. resp.clear();
  16767. ASSERT_TRUE(send_request(5,
  16768. "PUT /put HTTP/1.1\r\n"
  16769. "Host: localhost\r\n"
  16770. "Connection: close\r\n"
  16771. "\r\n",
  16772. &resp));
  16773. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16774. // PATCH without Content-Length
  16775. resp.clear();
  16776. ASSERT_TRUE(send_request(5,
  16777. "PATCH /patch HTTP/1.1\r\n"
  16778. "Host: localhost\r\n"
  16779. "Connection: close\r\n"
  16780. "\r\n",
  16781. &resp));
  16782. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16783. // DELETE without Content-Length
  16784. resp.clear();
  16785. ASSERT_TRUE(send_request(5,
  16786. "DELETE /delete HTTP/1.1\r\n"
  16787. "Host: localhost\r\n"
  16788. "Connection: close\r\n"
  16789. "\r\n",
  16790. &resp));
  16791. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16792. }
  16793. #endif
  16794. //==============================================================================
  16795. // open_stream() Tests
  16796. //==============================================================================
  16797. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16798. std::string result;
  16799. char buf[8192];
  16800. ssize_t n;
  16801. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16802. result.append(buf, static_cast<size_t>(n));
  16803. }
  16804. return result;
  16805. }
  16806. // Mock stream for unit tests
  16807. class MockStream : public Stream {
  16808. public:
  16809. std::string data;
  16810. size_t pos = 0;
  16811. ssize_t error_after = -1; // -1 = no error
  16812. explicit MockStream(const std::string &d, ssize_t err = -1)
  16813. : data(d), error_after(err) {}
  16814. bool is_readable() const override { return true; }
  16815. bool wait_readable() const override { return true; }
  16816. bool wait_writable() const override { return true; }
  16817. ssize_t read(char *ptr, size_t size) override {
  16818. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16819. if (pos >= data.size()) return 0;
  16820. size_t limit =
  16821. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16822. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16823. std::memcpy(ptr, data.data() + pos, to_read);
  16824. pos += to_read;
  16825. return static_cast<ssize_t>(to_read);
  16826. }
  16827. ssize_t write(const char *, size_t) override { return -1; }
  16828. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16829. ip = "127.0.0.1";
  16830. port = 0;
  16831. }
  16832. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16833. ip = "127.0.0.1";
  16834. port = 0;
  16835. }
  16836. socket_t socket() const override { return INVALID_SOCKET; }
  16837. time_t duration() const override { return 0; }
  16838. };
  16839. TEST(StreamHandleTest, Basic) {
  16840. ClientImpl::StreamHandle handle;
  16841. EXPECT_FALSE(handle.is_valid());
  16842. handle.response = detail::make_unique<Response>();
  16843. handle.error = Error::Connection;
  16844. EXPECT_FALSE(handle.is_valid());
  16845. handle.error = Error::Success;
  16846. EXPECT_TRUE(handle.is_valid());
  16847. }
  16848. TEST(BodyReaderTest, Basic) {
  16849. MockStream stream("Hello, World!");
  16850. detail::BodyReader reader;
  16851. reader.stream = &stream;
  16852. reader.content_length = 13;
  16853. char buf[32];
  16854. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16855. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16856. EXPECT_TRUE(reader.eof);
  16857. }
  16858. TEST(BodyReaderTest, NoStream) {
  16859. detail::BodyReader reader;
  16860. char buf[32];
  16861. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16862. EXPECT_EQ(Error::Connection, reader.last_error);
  16863. }
  16864. TEST(BodyReaderTest, Error) {
  16865. MockStream stream("Hello, World!", 5);
  16866. detail::BodyReader reader;
  16867. reader.stream = &stream;
  16868. reader.content_length = 13;
  16869. char buf[32];
  16870. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16871. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16872. EXPECT_EQ(Error::Read, reader.last_error);
  16873. }
  16874. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16875. // Mock-based StreamHandle tests relying on private internals are removed.
  16876. class OpenStreamTest : public ::testing::Test {
  16877. protected:
  16878. void SetUp() override {
  16879. svr_.Get("/hello", [](const Request &, Response &res) {
  16880. res.set_content("Hello World!", "text/plain");
  16881. });
  16882. svr_.Get("/large", [](const Request &, Response &res) {
  16883. res.set_content(std::string(10000, 'X'), "text/plain");
  16884. });
  16885. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16886. res.set_content("Hello World!", "image/jpeg");
  16887. res.set_header("Content-Encoding", "UTF-8");
  16888. });
  16889. svr_.Get("/chunked", [](const Request &, Response &res) {
  16890. res.set_chunked_content_provider("text/plain",
  16891. [](size_t offset, DataSink &sink) {
  16892. if (offset < 15) {
  16893. sink.write("chunk", 5);
  16894. return true;
  16895. }
  16896. sink.done();
  16897. return true;
  16898. });
  16899. });
  16900. svr_.Get("/compressible", [](const Request &, Response &res) {
  16901. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16902. DataSink &sink) {
  16903. if (offset < 100 * 1024) {
  16904. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16905. sink.write(chunk.data(), chunk.size());
  16906. return true;
  16907. }
  16908. sink.done();
  16909. return true;
  16910. });
  16911. });
  16912. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16913. [](const Request & /*req*/, Response &res) {
  16914. auto i = new int(0);
  16915. res.set_header("Trailer", "Content-Length, X-Allowed");
  16916. res.set_chunked_content_provider(
  16917. "text/plain",
  16918. [i](size_t /*offset*/, DataSink &sink) {
  16919. switch (*i) {
  16920. case 0: sink.os << "123"; break;
  16921. case 1: sink.os << "456"; break;
  16922. case 2: sink.os << "789"; break;
  16923. case 3: {
  16924. sink.done_with_trailer(
  16925. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16926. } break;
  16927. }
  16928. (*i)++;
  16929. return true;
  16930. },
  16931. [i](bool success) {
  16932. EXPECT_TRUE(success);
  16933. delete i;
  16934. });
  16935. });
  16936. // Echo headers endpoint for header-related tests
  16937. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16938. std::string body;
  16939. for (const auto &h : req.headers) {
  16940. body.append(h.first);
  16941. body.push_back(':');
  16942. body.append(h.second);
  16943. body.push_back('\n');
  16944. }
  16945. res.set_content(body, "text/plain");
  16946. });
  16947. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16948. std::string body;
  16949. for (const auto &h : req.headers) {
  16950. body.append(h.first);
  16951. body.push_back(':');
  16952. body.append(h.second);
  16953. body.push_back('\n');
  16954. }
  16955. res.set_content(body, "text/plain");
  16956. });
  16957. port_ = svr_.bind_to_any_port("127.0.0.1");
  16958. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16959. svr_.wait_until_ready();
  16960. }
  16961. void TearDown() override {
  16962. svr_.stop();
  16963. if (thread_.joinable()) thread_.join();
  16964. }
  16965. Server svr_;
  16966. std::thread thread_;
  16967. int port_ = 0;
  16968. };
  16969. TEST_F(OpenStreamTest, Basic) {
  16970. Client cli("127.0.0.1", port_);
  16971. auto handle = cli.open_stream("GET", "/hello");
  16972. EXPECT_TRUE(handle.is_valid());
  16973. EXPECT_EQ("Hello World!", read_all(handle));
  16974. }
  16975. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  16976. Client cli("127.0.0.1", port_);
  16977. auto handle = cli.open_stream("GET", "/unknown-encoding");
  16978. ASSERT_TRUE(handle.is_valid());
  16979. EXPECT_EQ("Hello World!", read_all(handle));
  16980. }
  16981. TEST_F(OpenStreamTest, SmallBuffer) {
  16982. Client cli("127.0.0.1", port_);
  16983. auto handle = cli.open_stream("GET", "/hello");
  16984. std::string result;
  16985. char buf[4];
  16986. ssize_t n;
  16987. while ((n = handle.read(buf, sizeof(buf))) > 0)
  16988. result.append(buf, static_cast<size_t>(n));
  16989. EXPECT_EQ("Hello World!", result);
  16990. }
  16991. TEST_F(OpenStreamTest, DefaultHeaders) {
  16992. Client cli("127.0.0.1", port_);
  16993. // open_stream GET should include Host, User-Agent and Accept-Encoding
  16994. {
  16995. auto handle = cli.open_stream("GET", "/echo-headers");
  16996. ASSERT_TRUE(handle.is_valid());
  16997. auto body = read_all(handle);
  16998. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  16999. std::string::npos);
  17000. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17001. std::string::npos);
  17002. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17003. }
  17004. // open_stream POST with body and no explicit content_type should NOT add
  17005. // text/plain Content-Type (behavior differs from non-streaming path), but
  17006. // should include Content-Length
  17007. {
  17008. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17009. ASSERT_TRUE(handle.is_valid());
  17010. auto body = read_all(handle);
  17011. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17012. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17013. }
  17014. // open_stream POST with explicit Content-Type should preserve it
  17015. {
  17016. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17017. {{"Content-Type", "application/custom"}},
  17018. "{}", "application/custom");
  17019. ASSERT_TRUE(handle.is_valid());
  17020. auto body = read_all(handle);
  17021. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17022. }
  17023. // User-specified User-Agent must not be overwritten for stream API
  17024. {
  17025. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17026. {{"User-Agent", "MyAgent/1.2"}});
  17027. ASSERT_TRUE(handle.is_valid());
  17028. auto body = read_all(handle);
  17029. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17030. }
  17031. }
  17032. TEST_F(OpenStreamTest, Large) {
  17033. Client cli("127.0.0.1", port_);
  17034. auto handle = cli.open_stream("GET", "/large");
  17035. EXPECT_EQ(10000u, read_all(handle).size());
  17036. }
  17037. TEST_F(OpenStreamTest, ConnectionError) {
  17038. Client cli("127.0.0.1", 9999);
  17039. auto handle = cli.open_stream("GET", "/hello");
  17040. EXPECT_FALSE(handle.is_valid());
  17041. }
  17042. TEST_F(OpenStreamTest, Chunked) {
  17043. Client cli("127.0.0.1", port_);
  17044. auto handle = cli.open_stream("GET", "/chunked");
  17045. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17046. "Transfer-Encoding") == "chunked");
  17047. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17048. }
  17049. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17050. Client cli("127.0.0.1", port_);
  17051. auto handle =
  17052. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17053. ASSERT_TRUE(handle.is_valid());
  17054. // Consume body to allow trailers to be received/parsed
  17055. auto body = read_all(handle);
  17056. // Explicitly parse trailers (ensure trailers are available for assertion)
  17057. handle.parse_trailers_if_needed();
  17058. EXPECT_EQ(std::string("123456789"), body);
  17059. // The response should include a Trailer header declaring both names
  17060. ASSERT_TRUE(handle.response);
  17061. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17062. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17063. handle.response->get_header_value("Trailer"));
  17064. // Prohibited trailer must not be present
  17065. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17066. // Allowed trailer should be present
  17067. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17068. EXPECT_EQ(std::string("yes"),
  17069. handle.response->get_trailer_value("X-Allowed"));
  17070. // Verify trailers are NOT present as regular headers
  17071. EXPECT_EQ(std::string(""),
  17072. handle.response->get_header_value("Content-Length"));
  17073. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17074. }
  17075. static std::thread serve_single_response(std::promise<int> &port_promise,
  17076. const std::string &response) {
  17077. return std::thread([&port_promise, response] {
  17078. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17079. default_socket_options(srv);
  17080. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17081. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17082. sockaddr_in addr{};
  17083. addr.sin_family = AF_INET;
  17084. addr.sin_port = htons(0); // Let OS assign a free port
  17085. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17086. int opt = 1;
  17087. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17088. #ifdef _WIN32
  17089. reinterpret_cast<const char *>(&opt),
  17090. #else
  17091. &opt,
  17092. #endif
  17093. sizeof(opt));
  17094. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17095. ::listen(srv, 1) != 0) {
  17096. port_promise.set_value(-1);
  17097. detail::close_socket(srv);
  17098. return;
  17099. }
  17100. socklen_t addr_len = sizeof(addr);
  17101. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17102. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17103. sockaddr_in cli_addr{};
  17104. socklen_t cli_len = sizeof(cli_addr);
  17105. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17106. if (cli != INVALID_SOCKET) {
  17107. // Read the complete HTTP request (until the blank line that terminates
  17108. // headers) before sending the response. If the server closes the socket
  17109. // while the client's request data is still unread in the kernel receive
  17110. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17111. // connection on both sides: it discards the client's receive buffer
  17112. // (which already holds our response) and causes any in-progress write on
  17113. // the client to fail with ECONNRESET. Reading all request data first
  17114. // ensures close() emits a graceful FIN.
  17115. {
  17116. char rbuf[256];
  17117. std::string req;
  17118. while (req.find("\r\n\r\n") == std::string::npos) {
  17119. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17120. if (n <= 0) { break; }
  17121. req.append(rbuf, static_cast<size_t>(n));
  17122. }
  17123. }
  17124. ::send(cli,
  17125. #ifdef _WIN32
  17126. static_cast<const char *>(response.c_str()),
  17127. static_cast<int>(response.size()),
  17128. #else
  17129. response.c_str(), response.size(),
  17130. #endif
  17131. 0);
  17132. detail::close_socket(cli);
  17133. }
  17134. detail::close_socket(srv);
  17135. });
  17136. }
  17137. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17138. #ifndef _WIN32
  17139. signal(SIGPIPE, SIG_IGN);
  17140. #endif
  17141. std::promise<int> port_promise;
  17142. auto port_future = port_promise.get_future();
  17143. auto server_thread =
  17144. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17145. "Content-Type: text/plain\r\n"
  17146. "Content-Length: not-a-number\r\n"
  17147. "Connection: close\r\n"
  17148. "\r\n"
  17149. "hello");
  17150. auto port = port_future.get();
  17151. ASSERT_GT(port, 0);
  17152. Client cli("127.0.0.1", port);
  17153. auto handle = cli.open_stream("GET", "/");
  17154. EXPECT_FALSE(handle.is_valid());
  17155. server_thread.join();
  17156. }
  17157. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17158. #ifndef _WIN32
  17159. signal(SIGPIPE, SIG_IGN);
  17160. #endif
  17161. std::promise<int> port_promise;
  17162. auto port_future = port_promise.get_future();
  17163. auto server_thread = serve_single_response(
  17164. port_promise, "HTTP/1.1 200 OK\r\n"
  17165. "Content-Type: text/plain\r\n"
  17166. "Content-Length: 99999999999999999999999999\r\n"
  17167. "Connection: close\r\n"
  17168. "\r\n"
  17169. "hello");
  17170. auto port = port_future.get();
  17171. ASSERT_GT(port, 0);
  17172. // Historically std::stoull would throw std::out_of_range here and crash
  17173. // the process, then parsing silently clamped to a bogus framing length and
  17174. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17175. // so the stream fails to open, matching the not-a-number case above. The
  17176. // process still must NOT terminate.
  17177. Client cli("127.0.0.1", port);
  17178. auto handle = cli.open_stream("GET", "/");
  17179. EXPECT_FALSE(handle.is_valid());
  17180. server_thread.join();
  17181. }
  17182. // Serves `response` to the single request `fn` makes with a fresh client.
  17183. template <typename Fn>
  17184. static void with_single_response(const std::string &response, Fn fn) {
  17185. #ifndef _WIN32
  17186. signal(SIGPIPE, SIG_IGN);
  17187. #endif
  17188. std::promise<int> port_promise;
  17189. auto port_future = port_promise.get_future();
  17190. auto server_thread = serve_single_response(port_promise, response);
  17191. auto se = detail::scope_exit([&] { server_thread.join(); });
  17192. auto port = port_future.get();
  17193. ASSERT_GT(port, 0);
  17194. Client cli("127.0.0.1", port);
  17195. fn(cli);
  17196. }
  17197. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17198. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17199. // the chunked coding and drop Content-Length, so a front-end that trusts
  17200. // Content-Length would disagree about where the body ends (response
  17201. // smuggling). The client must reject such a response.
  17202. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17203. for (const char *te : {"chunked", "gzip, chunked"}) {
  17204. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17205. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17206. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17207. "5\r\nhello\r\n0\r\n\r\n";
  17208. with_single_response(response, [&](Client &cli) {
  17209. auto res = cli.Get("/");
  17210. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17211. EXPECT_EQ(Error::Read, res.error()) << te;
  17212. });
  17213. with_single_response(response, [&](Client &cli) {
  17214. auto handle = cli.open_stream("GET", "/");
  17215. EXPECT_FALSE(handle.is_valid()) << te;
  17216. EXPECT_EQ(Error::Read, handle.error) << te;
  17217. });
  17218. }
  17219. }
  17220. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17221. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17222. // closing the connection (unlike a request, which must be rejected).
  17223. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17224. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17225. "Transfer-Encoding: chunked\r\n"
  17226. "Connection: close\r\n"
  17227. "\r\n"
  17228. "5\r\nhello\r\n0\r\n\r\n",
  17229. "HTTP/1.1 200 OK\r\n"
  17230. "Transfer-Encoding: gzip\r\n"
  17231. "Connection: close\r\n"
  17232. "\r\n"
  17233. "hello"}) {
  17234. with_single_response(response, [&](Client &cli) {
  17235. auto res = cli.Get("/");
  17236. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17237. EXPECT_EQ("hello", res->body);
  17238. });
  17239. with_single_response(response, [&](Client &cli) {
  17240. auto handle = cli.open_stream("GET", "/");
  17241. ASSERT_TRUE(handle.is_valid()) << response;
  17242. EXPECT_EQ("hello", read_all(handle));
  17243. });
  17244. }
  17245. }
  17246. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17247. // framing headers describe nothing to read and must not be rejected.
  17248. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17249. const std::string framing = "Content-Length: 5\r\n"
  17250. "Transfer-Encoding: chunked\r\n"
  17251. "Connection: close\r\n"
  17252. "\r\n";
  17253. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17254. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17255. });
  17256. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17257. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17258. });
  17259. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17260. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17261. with_single_response(response, [&](Client &cli) {
  17262. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17263. });
  17264. with_single_response(response, [&](Client &cli) {
  17265. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17266. });
  17267. }
  17268. }
  17269. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17270. TEST_F(OpenStreamTest, Gzip) {
  17271. Client cli("127.0.0.1", port_);
  17272. auto handle = cli.open_stream("GET", "/compressible", {},
  17273. {{"Accept-Encoding", "gzip"}});
  17274. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17275. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17276. }
  17277. #endif
  17278. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17279. TEST_F(OpenStreamTest, Brotli) {
  17280. Client cli("127.0.0.1", port_);
  17281. auto handle =
  17282. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17283. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17284. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17285. }
  17286. #endif
  17287. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17288. TEST_F(OpenStreamTest, Zstd) {
  17289. Client cli("127.0.0.1", port_);
  17290. auto handle = cli.open_stream("GET", "/compressible", {},
  17291. {{"Accept-Encoding", "zstd"}});
  17292. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17293. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17294. }
  17295. #endif
  17296. #ifdef CPPHTTPLIB_SSL_ENABLED
  17297. class SSLOpenStreamTest : public ::testing::Test {
  17298. protected:
  17299. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17300. void SetUp() override {
  17301. svr_.Get("/hello", [](const Request &, Response &res) {
  17302. res.set_content("Hello SSL World!", "text/plain");
  17303. });
  17304. svr_.Get("/chunked", [](const Request &, Response &res) {
  17305. res.set_chunked_content_provider("text/plain",
  17306. [](size_t offset, DataSink &sink) {
  17307. if (offset < 15) {
  17308. sink.write("chunk", 5);
  17309. return true;
  17310. }
  17311. sink.done();
  17312. return true;
  17313. });
  17314. });
  17315. svr_.Post("/echo", [](const Request &req, Response &res) {
  17316. res.set_content(req.body, req.get_header_value("Content-Type"));
  17317. });
  17318. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17319. std::string body = req.body;
  17320. res.set_chunked_content_provider(
  17321. "text/plain", [body](size_t offset, DataSink &sink) {
  17322. if (offset < body.size()) {
  17323. sink.write(body.data() + offset, body.size() - offset);
  17324. }
  17325. sink.done();
  17326. return true;
  17327. });
  17328. });
  17329. port_ = svr_.bind_to_any_port("127.0.0.1");
  17330. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17331. svr_.wait_until_ready();
  17332. }
  17333. void TearDown() override {
  17334. svr_.stop();
  17335. if (thread_.joinable()) thread_.join();
  17336. }
  17337. SSLServer svr_;
  17338. std::thread thread_;
  17339. int port_ = 0;
  17340. };
  17341. TEST_F(SSLOpenStreamTest, Basic) {
  17342. SSLClient cli("127.0.0.1", port_);
  17343. cli.enable_server_certificate_verification(false);
  17344. auto handle = cli.open_stream("GET", "/hello");
  17345. ASSERT_TRUE(handle.is_valid());
  17346. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17347. }
  17348. TEST_F(SSLOpenStreamTest, Chunked) {
  17349. SSLClient cli("127.0.0.1", port_);
  17350. cli.enable_server_certificate_verification(false);
  17351. auto handle = cli.open_stream("GET", "/chunked");
  17352. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17353. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17354. "Transfer-Encoding") == "chunked");
  17355. auto body = read_all(handle);
  17356. EXPECT_EQ("chunkchunkchunk", body);
  17357. }
  17358. TEST_F(SSLOpenStreamTest, Post) {
  17359. SSLClient cli("127.0.0.1", port_);
  17360. cli.enable_server_certificate_verification(false);
  17361. auto handle =
  17362. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17363. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17364. EXPECT_EQ(200, handle.response->status);
  17365. auto body = read_all(handle);
  17366. EXPECT_EQ("Hello SSL POST", body);
  17367. }
  17368. TEST_F(SSLOpenStreamTest, PostChunked) {
  17369. SSLClient cli("127.0.0.1", port_);
  17370. cli.enable_server_certificate_verification(false);
  17371. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17372. "Chunked SSL Data", "text/plain");
  17373. ASSERT_TRUE(handle.is_valid());
  17374. EXPECT_EQ(200, handle.response->status);
  17375. auto body = read_all(handle);
  17376. EXPECT_EQ("Chunked SSL Data", body);
  17377. }
  17378. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17379. // Content-Length is terminated by the server closing the connection. When the
  17380. // SSL peer sends a close_notify after the body, the client must treat it as a
  17381. // clean EOF and return a successful response rather than an error.
  17382. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17384. ASSERT_TRUE(svr.is_valid());
  17385. svr.set_keep_alive_max_count(1);
  17386. const std::string expected_body = "Hello from connection-close response!";
  17387. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17388. res.set_content_provider("text/plain",
  17389. [&](size_t offset, DataSink &sink) -> bool {
  17390. if (offset < expected_body.size()) {
  17391. sink.write(expected_body.data() + offset,
  17392. expected_body.size() - offset);
  17393. }
  17394. sink.done();
  17395. return true;
  17396. });
  17397. });
  17398. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17399. auto se = detail::scope_exit([&] {
  17400. svr.stop();
  17401. listen_thread.join();
  17402. ASSERT_FALSE(svr.is_running());
  17403. });
  17404. svr.wait_until_ready();
  17405. SSLClient cli(HOST, PORT);
  17406. cli.enable_server_certificate_verification(false);
  17407. auto res = cli.Get("/no-content-length");
  17408. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17409. EXPECT_EQ(StatusCode::OK_200, res->status);
  17410. EXPECT_EQ(expected_body, res->body);
  17411. }
  17412. #endif // CPPHTTPLIB_SSL_ENABLED
  17413. //==============================================================================
  17414. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17415. // results for various scenarios.
  17416. //==============================================================================
  17417. TEST(ParityTest, GetVsOpenStream) {
  17418. Server svr;
  17419. const std::string path = "/parity";
  17420. const std::string content = "Parity test content: hello world";
  17421. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17422. res.set_content(content, "text/plain");
  17423. });
  17424. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17425. auto se = detail::scope_exit([&] {
  17426. svr.stop();
  17427. t.join();
  17428. ASSERT_FALSE(svr.is_running());
  17429. });
  17430. svr.wait_until_ready();
  17431. Client cli(HOST, PORT);
  17432. // Non-stream path
  17433. auto r1 = cli.Get(path);
  17434. ASSERT_TRUE(r1);
  17435. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17436. // Stream path
  17437. auto h = cli.open_stream("GET", path);
  17438. ASSERT_TRUE(h.is_valid());
  17439. EXPECT_EQ(r1->body, read_all(h));
  17440. }
  17441. // Helper to compress data with provided compressor type T
  17442. template <typename Compressor>
  17443. static std::string compress_payload_for_parity(const std::string &in) {
  17444. std::string out;
  17445. Compressor compressor;
  17446. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17447. [&](const char *data, size_t n) {
  17448. out.append(data, n);
  17449. return true;
  17450. });
  17451. EXPECT_TRUE(ok);
  17452. return out;
  17453. }
  17454. // Helper function for compression parity tests
  17455. template <typename Compressor>
  17456. static void test_compression_parity(const std::string &original,
  17457. const std::string &path,
  17458. const std::string &encoding) {
  17459. const std::string compressed =
  17460. compress_payload_for_parity<Compressor>(original);
  17461. Server svr;
  17462. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17463. res.set_content(compressed, "application/octet-stream");
  17464. res.set_header("Content-Encoding", encoding);
  17465. });
  17466. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17467. auto se = detail::scope_exit([&] {
  17468. svr.stop();
  17469. t.join();
  17470. ASSERT_FALSE(svr.is_running());
  17471. });
  17472. svr.wait_until_ready();
  17473. Client cli(HOST, PORT);
  17474. // Non-streaming
  17475. {
  17476. auto res = cli.Get(path);
  17477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17478. EXPECT_EQ(StatusCode::OK_200, res->status);
  17479. EXPECT_EQ(original, res->body);
  17480. }
  17481. // Streaming
  17482. {
  17483. auto h = cli.open_stream("GET", path);
  17484. ASSERT_TRUE(h.is_valid());
  17485. EXPECT_EQ(original, read_all(h));
  17486. }
  17487. }
  17488. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17489. TEST(ParityTest, Gzip) {
  17490. test_compression_parity<detail::gzip_compressor>(
  17491. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17492. }
  17493. #endif
  17494. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17495. TEST(ParityTest, Brotli) {
  17496. test_compression_parity<detail::brotli_compressor>(
  17497. "Hello, brotli parity test payload", "/parity-br", "br");
  17498. }
  17499. #endif
  17500. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17501. TEST(ParityTest, Zstd) {
  17502. test_compression_parity<detail::zstd_compressor>(
  17503. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17504. }
  17505. #endif
  17506. //==============================================================================
  17507. // New Stream API Tests
  17508. //==============================================================================
  17509. inline std::string read_body(httplib::stream::Result &result) {
  17510. std::string body;
  17511. while (result.next()) {
  17512. body.append(result.data(), result.size());
  17513. }
  17514. return body;
  17515. }
  17516. TEST(ClientConnectionTest, Basic) {
  17517. httplib::ClientConnection conn;
  17518. EXPECT_FALSE(conn.is_open());
  17519. conn.sock = 1;
  17520. EXPECT_TRUE(conn.is_open());
  17521. httplib::ClientConnection conn2(std::move(conn));
  17522. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17523. conn2.sock = INVALID_SOCKET;
  17524. }
  17525. // Unified test server for all stream::* tests
  17526. class StreamApiTest : public ::testing::Test {
  17527. protected:
  17528. void SetUp() override {
  17529. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17530. res.set_content("Hello World!", "text/plain");
  17531. });
  17532. svr_.Get("/echo-params",
  17533. [](const httplib::Request &req, httplib::Response &res) {
  17534. std::string r;
  17535. for (const auto &p : req.params) {
  17536. if (!r.empty()) r += "&";
  17537. r += p.first + "=" + p.second;
  17538. }
  17539. res.set_content(r, "text/plain");
  17540. });
  17541. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17542. res.set_content(req.body, req.get_header_value("Content-Type"));
  17543. });
  17544. svr_.Post("/echo-headers",
  17545. [](const httplib::Request &req, httplib::Response &res) {
  17546. std::string r;
  17547. for (const auto &h : req.headers)
  17548. r += h.first + ": " + h.second + "\n";
  17549. res.set_content(r, "text/plain");
  17550. });
  17551. svr_.Post("/echo-params",
  17552. [](const httplib::Request &req, httplib::Response &res) {
  17553. std::string r = "params:";
  17554. for (const auto &p : req.params)
  17555. r += p.first + "=" + p.second + ";";
  17556. res.set_content(r + " body:" + req.body, "text/plain");
  17557. });
  17558. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17559. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17560. });
  17561. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17562. res.set_content("PUT:" + req.body, "text/plain");
  17563. });
  17564. svr_.Patch("/echo",
  17565. [](const httplib::Request &req, httplib::Response &res) {
  17566. res.set_content("PATCH:" + req.body, "text/plain");
  17567. });
  17568. svr_.Delete(
  17569. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17570. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17571. "text/plain");
  17572. });
  17573. svr_.Get("/head-test",
  17574. [](const httplib::Request &, httplib::Response &res) {
  17575. res.set_content("body for HEAD", "text/plain");
  17576. });
  17577. svr_.Options("/options",
  17578. [](const httplib::Request &, httplib::Response &res) {
  17579. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17580. });
  17581. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17582. svr_.wait_until_ready();
  17583. }
  17584. void TearDown() override {
  17585. svr_.stop();
  17586. if (thread_.joinable()) thread_.join();
  17587. }
  17588. httplib::Server svr_;
  17589. std::thread thread_;
  17590. };
  17591. // stream::Get tests
  17592. TEST_F(StreamApiTest, GetBasic) {
  17593. httplib::Client cli(HOST, PORT);
  17594. auto result = httplib::stream::Get(cli, "/hello");
  17595. ASSERT_TRUE(result.is_valid());
  17596. EXPECT_EQ(200, result.status());
  17597. EXPECT_EQ("Hello World!", read_body(result));
  17598. }
  17599. TEST_F(StreamApiTest, GetWithParams) {
  17600. httplib::Client cli(HOST, PORT);
  17601. httplib::Params params{{"foo", "bar"}};
  17602. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17603. ASSERT_TRUE(result.is_valid());
  17604. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17605. }
  17606. TEST_F(StreamApiTest, GetConnectionError) {
  17607. httplib::Client cli(HOST, 9999);
  17608. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17609. }
  17610. TEST_F(StreamApiTest, Get404) {
  17611. httplib::Client cli(HOST, PORT);
  17612. auto result = httplib::stream::Get(cli, "/nonexistent");
  17613. EXPECT_TRUE(result.is_valid());
  17614. EXPECT_EQ(404, result.status());
  17615. }
  17616. // stream::Post tests
  17617. TEST_F(StreamApiTest, PostBasic) {
  17618. httplib::Client cli(HOST, PORT);
  17619. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17620. "application/json");
  17621. ASSERT_TRUE(result.is_valid());
  17622. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17623. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17624. }
  17625. TEST_F(StreamApiTest, PostWithHeaders) {
  17626. httplib::Client cli(HOST, PORT);
  17627. httplib::Headers headers{{"X-Custom", "value"}};
  17628. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17629. "text/plain");
  17630. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17631. }
  17632. TEST_F(StreamApiTest, PostWithParams) {
  17633. httplib::Client cli(HOST, PORT);
  17634. httplib::Params params{{"k", "v"}};
  17635. auto result =
  17636. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17637. auto body = read_body(result);
  17638. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17639. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17640. }
  17641. TEST_F(StreamApiTest, PostLarge) {
  17642. httplib::Client cli(HOST, PORT);
  17643. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17644. size_t total = 0;
  17645. while (result.next()) {
  17646. total += result.size();
  17647. }
  17648. EXPECT_EQ(100u * 1024u, total);
  17649. }
  17650. // stream::Put/Patch tests
  17651. TEST_F(StreamApiTest, PutAndPatch) {
  17652. httplib::Client cli(HOST, PORT);
  17653. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17654. EXPECT_EQ("PUT:test", read_body(put));
  17655. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17656. EXPECT_EQ("PATCH:test", read_body(patch));
  17657. }
  17658. // stream::Delete tests
  17659. TEST_F(StreamApiTest, Delete) {
  17660. httplib::Client cli(HOST, PORT);
  17661. auto del1 = httplib::stream::Delete(cli, "/resource");
  17662. EXPECT_EQ("Deleted", read_body(del1));
  17663. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17664. EXPECT_EQ("Deleted:data", read_body(del2));
  17665. }
  17666. // stream::Head/Options tests
  17667. TEST_F(StreamApiTest, HeadAndOptions) {
  17668. httplib::Client cli(HOST, PORT);
  17669. auto head = httplib::stream::Head(cli, "/head-test");
  17670. EXPECT_TRUE(head.is_valid());
  17671. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17672. auto opts = httplib::stream::Options(cli, "/options");
  17673. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17674. }
  17675. // SSL stream::* tests
  17676. #ifdef CPPHTTPLIB_SSL_ENABLED
  17677. class SSLStreamApiTest : public ::testing::Test {
  17678. protected:
  17679. void SetUp() override {
  17680. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17681. res.set_content("Hello SSL!", "text/plain");
  17682. });
  17683. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17684. res.set_content(req.body, "text/plain");
  17685. });
  17686. port_ = svr_.bind_to_any_port("127.0.0.1");
  17687. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17688. svr_.wait_until_ready();
  17689. }
  17690. void TearDown() override {
  17691. svr_.stop();
  17692. if (thread_.joinable()) thread_.join();
  17693. }
  17694. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17695. std::thread thread_;
  17696. int port_ = 0;
  17697. };
  17698. TEST_F(SSLStreamApiTest, GetAndPost) {
  17699. httplib::SSLClient cli("127.0.0.1", port_);
  17700. cli.enable_server_certificate_verification(false);
  17701. auto get = httplib::stream::Get(cli, "/hello");
  17702. EXPECT_EQ("Hello SSL!", read_body(get));
  17703. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17704. EXPECT_EQ("test", read_body(post));
  17705. }
  17706. #endif
  17707. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17708. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17709. // BodyReader
  17710. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17711. // Test that read timeout during streaming is detected
  17712. // Use a large content-length response where server delays mid-stream
  17713. Server svr;
  17714. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17715. // Send a large response with delay in the middle
  17716. res.set_content_provider(
  17717. 1000, // content_length
  17718. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17719. if (offset < 100) {
  17720. // Send first 100 bytes immediately
  17721. std::string data(100, 'A');
  17722. sink.write(data.c_str(), data.size());
  17723. return true;
  17724. }
  17725. // Then delay longer than client timeout
  17726. std::this_thread::sleep_for(std::chrono::seconds(3));
  17727. std::string data(900, 'B');
  17728. sink.write(data.c_str(), data.size());
  17729. return true;
  17730. });
  17731. });
  17732. auto port = 8091;
  17733. std::thread t([&]() { svr.listen("localhost", port); });
  17734. svr.wait_until_ready();
  17735. Client cli("localhost", port);
  17736. cli.set_read_timeout(1, 0); // 1 second timeout
  17737. auto handle = cli.open_stream("GET", "/slow-stream");
  17738. ASSERT_TRUE(handle.is_valid());
  17739. char buf[256];
  17740. ssize_t total = 0;
  17741. ssize_t n;
  17742. bool got_error = false;
  17743. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17744. total += n;
  17745. }
  17746. if (n < 0) {
  17747. got_error = true;
  17748. // Should be timeout or read error
  17749. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17750. handle.get_read_error() == Error::Read)
  17751. << "Actual error: " << to_string(handle.get_read_error());
  17752. }
  17753. // Either we got an error, or we got less data than expected
  17754. EXPECT_TRUE(got_error || total < 1000)
  17755. << "Expected timeout but got all " << total << " bytes";
  17756. svr.stop();
  17757. t.join();
  17758. }
  17759. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17760. // Test connection closed detection via BodyReader
  17761. Server svr;
  17762. std::atomic<bool> close_now{false};
  17763. svr.Get("/will-close", [&](const Request &, Response &res) {
  17764. res.set_content_provider(
  17765. 10000, // Large content_length that we won't fully send
  17766. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17767. if (offset < 100) {
  17768. std::string data(100, 'X');
  17769. sink.write(data.c_str(), data.size());
  17770. return true;
  17771. }
  17772. // Wait for signal then abort
  17773. while (!close_now) {
  17774. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17775. }
  17776. return false; // Abort - server will close connection
  17777. });
  17778. });
  17779. auto port = 8092;
  17780. std::thread t([&]() { svr.listen("localhost", port); });
  17781. svr.wait_until_ready();
  17782. Client cli("localhost", port);
  17783. auto handle = cli.open_stream("GET", "/will-close");
  17784. ASSERT_TRUE(handle.is_valid());
  17785. char buf[256];
  17786. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17787. EXPECT_GT(n, 0) << "First read should succeed";
  17788. // Signal server to close
  17789. close_now = true;
  17790. // Keep reading until error or EOF
  17791. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17792. // Keep reading
  17793. }
  17794. // Should get an error since content_length wasn't satisfied
  17795. if (n < 0) {
  17796. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17797. handle.get_read_error() == Error::Read)
  17798. << "Actual error: " << to_string(handle.get_read_error());
  17799. }
  17800. svr.stop();
  17801. t.join();
  17802. }
  17803. #ifdef CPPHTTPLIB_SSL_ENABLED
  17804. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  17805. // Test that read timeout during SSL streaming is detected
  17806. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17807. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17808. res.set_content_provider(
  17809. 1000, "text/plain",
  17810. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17811. if (offset < 100) {
  17812. std::string data(100, 'A');
  17813. sink.write(data.c_str(), data.size());
  17814. return true;
  17815. }
  17816. std::this_thread::sleep_for(std::chrono::seconds(3));
  17817. std::string data(900, 'B');
  17818. sink.write(data.c_str(), data.size());
  17819. return true;
  17820. });
  17821. });
  17822. auto port = 8093;
  17823. std::thread t([&]() { svr.listen("localhost", port); });
  17824. svr.wait_until_ready();
  17825. SSLClient cli("localhost", port);
  17826. cli.enable_server_certificate_verification(false);
  17827. cli.set_read_timeout(1, 0); // 1 second timeout
  17828. auto handle = cli.open_stream("GET", "/slow-stream");
  17829. ASSERT_TRUE(handle.is_valid());
  17830. char buf[256];
  17831. ssize_t total = 0;
  17832. ssize_t n;
  17833. bool got_error = false;
  17834. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17835. total += n;
  17836. }
  17837. if (n < 0) {
  17838. got_error = true;
  17839. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17840. handle.get_read_error() == Error::Read)
  17841. << "Actual error: " << to_string(handle.get_read_error());
  17842. }
  17843. EXPECT_TRUE(got_error || total < 1000)
  17844. << "Expected timeout but got all " << total << " bytes";
  17845. svr.stop();
  17846. t.join();
  17847. }
  17848. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17849. // Test SSL connection closed detection
  17850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17851. std::atomic<bool> close_now{false};
  17852. svr.Get("/will-close", [&](const Request &, Response &res) {
  17853. res.set_content_provider(
  17854. 10000, "text/plain",
  17855. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17856. if (offset < 100) {
  17857. std::string data(100, 'X');
  17858. sink.write(data.c_str(), data.size());
  17859. return true;
  17860. }
  17861. while (!close_now) {
  17862. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17863. }
  17864. return false;
  17865. });
  17866. });
  17867. auto port = 8094;
  17868. std::thread t([&]() { svr.listen("localhost", port); });
  17869. svr.wait_until_ready();
  17870. SSLClient cli("localhost", port);
  17871. cli.enable_server_certificate_verification(false);
  17872. auto handle = cli.open_stream("GET", "/will-close");
  17873. ASSERT_TRUE(handle.is_valid());
  17874. char buf[256];
  17875. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17876. EXPECT_GT(n, 0);
  17877. // Signal server to close
  17878. close_now = true;
  17879. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17880. // Keep reading
  17881. }
  17882. if (n < 0) {
  17883. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17884. handle.get_read_error() == Error::Read)
  17885. << "Actual error: " << to_string(handle.get_read_error());
  17886. }
  17887. svr.stop();
  17888. t.join();
  17889. }
  17890. #endif
  17891. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17892. using namespace httplib;
  17893. // Create a test file
  17894. const char *fname = "etag_testfile.txt";
  17895. const char *content = "etag-content";
  17896. {
  17897. std::ofstream ofs(fname);
  17898. ofs << content;
  17899. ASSERT_TRUE(ofs.good());
  17900. }
  17901. Server svr;
  17902. svr.set_mount_point("/static", ".");
  17903. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17904. svr.wait_until_ready();
  17905. Client cli(HOST, PORT);
  17906. // First request: should get 200 with ETag header
  17907. auto res1 = cli.Get("/static/etag_testfile.txt");
  17908. ASSERT_TRUE(res1);
  17909. ASSERT_EQ(200, res1->status);
  17910. ASSERT_TRUE(res1->has_header("ETag"));
  17911. std::string etag = res1->get_header_value("ETag");
  17912. EXPECT_FALSE(etag.empty());
  17913. // Verify ETag format: W/"hex-hex"
  17914. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17915. EXPECT_EQ('W', etag[0]);
  17916. EXPECT_EQ('/', etag[1]);
  17917. EXPECT_EQ('"', etag[2]);
  17918. EXPECT_EQ('"', etag.back());
  17919. // Exact match: expect 304 Not Modified
  17920. Headers h2 = {{"If-None-Match", etag}};
  17921. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17922. ASSERT_TRUE(res2);
  17923. EXPECT_EQ(304, res2->status);
  17924. // Wildcard match: expect 304 Not Modified
  17925. Headers h3 = {{"If-None-Match", "*"}};
  17926. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17927. ASSERT_TRUE(res3);
  17928. EXPECT_EQ(304, res3->status);
  17929. // Non-matching ETag: expect 200
  17930. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17931. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17932. ASSERT_TRUE(res4);
  17933. EXPECT_EQ(200, res4->status);
  17934. // Multiple ETags with one matching: expect 304
  17935. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17936. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17937. ASSERT_TRUE(res5);
  17938. EXPECT_EQ(304, res5->status);
  17939. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17940. // that equivalent to the single comma-separated list above, so the match on
  17941. // the second line must still be found.
  17942. Headers h6;
  17943. h6.emplace("If-None-Match", "W/\"other\"");
  17944. h6.emplace("If-None-Match", etag);
  17945. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17946. ASSERT_TRUE(res6);
  17947. EXPECT_EQ(304, res6->status);
  17948. svr.stop();
  17949. t.join();
  17950. std::remove(fname);
  17951. }
  17952. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  17953. using namespace httplib;
  17954. Server svr;
  17955. svr.set_mount_point("/static", ".");
  17956. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17957. svr.wait_until_ready();
  17958. Client cli(HOST, PORT);
  17959. // Send If-None-Match: * to a non-existent file
  17960. Headers h = {{"If-None-Match", "*"}};
  17961. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  17962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17963. EXPECT_EQ(404, res->status);
  17964. svr.stop();
  17965. t.join();
  17966. }
  17967. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  17968. using namespace httplib;
  17969. // Create a test file
  17970. const char *fname = "etag_boundary_testfile.txt";
  17971. const char *content = "boundary-test";
  17972. {
  17973. std::ofstream ofs(fname);
  17974. ofs << content;
  17975. ASSERT_TRUE(ofs.good());
  17976. }
  17977. Server svr;
  17978. svr.set_mount_point("/static", ".");
  17979. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17980. svr.wait_until_ready();
  17981. Client cli(HOST, PORT);
  17982. // Get the actual ETag
  17983. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  17984. ASSERT_TRUE(res1);
  17985. ASSERT_EQ(200, res1->status);
  17986. ASSERT_TRUE(res1->has_header("ETag"));
  17987. std::string etag = res1->get_header_value("ETag");
  17988. // Test 1: Very long ETag value (longer than actual ETag)
  17989. // Should NOT match and return 200 (not trigger out-of-bounds read)
  17990. Headers h1 = {{"If-None-Match", "W/"
  17991. "\"very-long-etag-value-that-is-much-longer-"
  17992. "than-the-actual-etag-value\""}};
  17993. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  17994. ASSERT_TRUE(res2);
  17995. EXPECT_EQ(200, res2->status); // Should not match
  17996. // Test 2: Long string followed by wildcard
  17997. // Should match on "*" and return 304 (without out-of-bounds read on the long
  17998. // string)
  17999. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18000. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18001. ASSERT_TRUE(res3);
  18002. EXPECT_EQ(304, res3->status); // Should match on "*"
  18003. // Test 3: Wildcard followed by long string
  18004. // Should match on "*" immediately and return 304
  18005. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18006. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18007. ASSERT_TRUE(res4);
  18008. EXPECT_EQ(304, res4->status); // Should match on "*"
  18009. // Test 4: Multiple long non-matching values
  18010. // Should NOT match and return 200 (test that all comparisons are safe)
  18011. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18012. "W/\"second-long-non-matching-value\", "
  18013. "W/\"third-long-non-matching-value\""}};
  18014. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18015. ASSERT_TRUE(res5);
  18016. EXPECT_EQ(200, res5->status); // Should not match
  18017. // Test 5: Single character that is not "*" (edge case)
  18018. Headers h5 = {{"If-None-Match", "X"}};
  18019. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18020. ASSERT_TRUE(res6);
  18021. EXPECT_EQ(200, res6->status); // Should not match
  18022. svr.stop();
  18023. t.join();
  18024. std::remove(fname);
  18025. }
  18026. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18027. using namespace httplib;
  18028. // Create a test file
  18029. const char *fname = "ims_testfile.txt";
  18030. const char *content = "if-modified-since-test";
  18031. {
  18032. std::ofstream ofs(fname);
  18033. ofs << content;
  18034. ASSERT_TRUE(ofs.good());
  18035. }
  18036. Server svr;
  18037. svr.set_mount_point("/static", ".");
  18038. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18039. svr.wait_until_ready();
  18040. Client cli(HOST, PORT);
  18041. // First request: should get 200 with Last-Modified header
  18042. auto res1 = cli.Get("/static/ims_testfile.txt");
  18043. ASSERT_TRUE(res1);
  18044. ASSERT_EQ(200, res1->status);
  18045. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18046. std::string last_modified = res1->get_header_value("Last-Modified");
  18047. EXPECT_FALSE(last_modified.empty());
  18048. // If-Modified-Since with same time: expect 304
  18049. Headers h2 = {{"If-Modified-Since", last_modified}};
  18050. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18051. ASSERT_TRUE(res2);
  18052. EXPECT_EQ(304, res2->status);
  18053. // If-Modified-Since with future time: expect 304
  18054. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18055. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18056. ASSERT_TRUE(res3);
  18057. EXPECT_EQ(304, res3->status);
  18058. // If-Modified-Since with past time: expect 200
  18059. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18060. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18061. ASSERT_TRUE(res4);
  18062. EXPECT_EQ(200, res4->status);
  18063. // If-None-Match takes precedence over If-Modified-Since
  18064. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18065. ASSERT_TRUE(res1->has_header("ETag"));
  18066. std::string etag = res1->get_header_value("ETag");
  18067. Headers h5 = {{"If-None-Match", etag},
  18068. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18069. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18070. ASSERT_TRUE(res5);
  18071. EXPECT_EQ(304, res5->status);
  18072. svr.stop();
  18073. t.join();
  18074. std::remove(fname);
  18075. }
  18076. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18077. using namespace httplib;
  18078. Server svr;
  18079. // Endpoint that returns compressible content
  18080. svr.Get("/compressible", [](const Request &, Response &res) {
  18081. // Return a large enough body to trigger compression
  18082. std::string body(1000, 'a');
  18083. res.set_content(body, "text/plain");
  18084. });
  18085. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18086. svr.wait_until_ready();
  18087. Client cli(HOST, PORT);
  18088. // Request with gzip support: should get Vary header when compressed
  18089. cli.set_compress(true);
  18090. auto res1 = cli.Get("/compressible");
  18091. ASSERT_TRUE(res1);
  18092. EXPECT_EQ(200, res1->status);
  18093. // If Content-Encoding is set, Vary should also be set
  18094. if (res1->has_header("Content-Encoding")) {
  18095. EXPECT_TRUE(res1->has_header("Vary"));
  18096. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18097. }
  18098. // Request without Accept-Encoding header: should not have compression
  18099. Headers h_no_compress;
  18100. auto res2 = cli.Get("/compressible", h_no_compress);
  18101. ASSERT_TRUE(res2);
  18102. EXPECT_EQ(200, res2->status);
  18103. // Verify Vary header is present when compression is applied
  18104. // (the exact behavior depends on server configuration)
  18105. svr.stop();
  18106. t.join();
  18107. }
  18108. TEST(ETagTest, IfRangeWithETag) {
  18109. using namespace httplib;
  18110. // Create a test file with known content
  18111. const char *fname = "if_range_testfile.txt";
  18112. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18113. {
  18114. std::ofstream ofs(fname);
  18115. ofs << content;
  18116. ASSERT_TRUE(ofs.good());
  18117. }
  18118. Server svr;
  18119. svr.set_mount_point("/static", ".");
  18120. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18121. svr.wait_until_ready();
  18122. Client cli(HOST, PORT);
  18123. // First request: get ETag
  18124. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18125. ASSERT_TRUE(res1);
  18126. ASSERT_EQ(200, res1->status);
  18127. ASSERT_TRUE(res1->has_header("ETag"));
  18128. std::string etag = res1->get_header_value("ETag");
  18129. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18130. // Since our server generates weak ETags (W/"..."), If-Range with our
  18131. // ETag should NOT result in partial content - it should return full content.
  18132. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18133. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18134. ASSERT_TRUE(res2);
  18135. // Weak ETag in If-Range -> full content (200), not partial (206)
  18136. EXPECT_EQ(200, res2->status);
  18137. EXPECT_EQ(content, res2->body);
  18138. EXPECT_FALSE(res2->has_header("Content-Range"));
  18139. // Range request with non-matching If-Range (ETag): should get 200 (full
  18140. // content)
  18141. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18142. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18143. ASSERT_TRUE(res3);
  18144. EXPECT_EQ(200, res3->status);
  18145. EXPECT_EQ(content, res3->body);
  18146. EXPECT_FALSE(res3->has_header("Content-Range"));
  18147. // Range request with strong ETag (hypothetical - our server doesn't generate
  18148. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18149. // should return full content)
  18150. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18151. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18152. ASSERT_TRUE(res4);
  18153. EXPECT_EQ(200, res4->status);
  18154. EXPECT_EQ(content, res4->body);
  18155. EXPECT_FALSE(res4->has_header("Content-Range"));
  18156. svr.stop();
  18157. t.join();
  18158. std::remove(fname);
  18159. }
  18160. TEST(ETagTest, IfRangeWithDate) {
  18161. using namespace httplib;
  18162. // Create a test file
  18163. const char *fname = "if_range_date_testfile.txt";
  18164. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18165. {
  18166. std::ofstream ofs(fname);
  18167. ofs << content;
  18168. ASSERT_TRUE(ofs.good());
  18169. }
  18170. Server svr;
  18171. svr.set_mount_point("/static", ".");
  18172. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18173. svr.wait_until_ready();
  18174. Client cli(HOST, PORT);
  18175. // First request: get Last-Modified
  18176. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18177. ASSERT_TRUE(res1);
  18178. ASSERT_EQ(200, res1->status);
  18179. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18180. std::string last_modified = res1->get_header_value("Last-Modified");
  18181. // Range request with matching If-Range (date): should get 206
  18182. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18183. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18184. ASSERT_TRUE(res2);
  18185. EXPECT_EQ(206, res2->status);
  18186. EXPECT_EQ("FGHIJ", res2->body);
  18187. // Range request with old If-Range date: should get 200 (full content)
  18188. Headers h3 = {{"Range", "bytes=5-9"},
  18189. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18190. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18191. ASSERT_TRUE(res3);
  18192. EXPECT_EQ(200, res3->status);
  18193. EXPECT_EQ(content, res3->body);
  18194. // Range request with future If-Range date: should get 206
  18195. Headers h4 = {{"Range", "bytes=0-4"},
  18196. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18197. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18198. ASSERT_TRUE(res4);
  18199. EXPECT_EQ(206, res4->status);
  18200. EXPECT_EQ("ABCDE", res4->body);
  18201. svr.stop();
  18202. t.join();
  18203. std::remove(fname);
  18204. }
  18205. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18206. using namespace httplib;
  18207. const char *fname = "etag_malformed.txt";
  18208. const char *content = "malformed-etag";
  18209. {
  18210. std::ofstream ofs(fname);
  18211. ofs << content;
  18212. ASSERT_TRUE(ofs.good());
  18213. }
  18214. Server svr;
  18215. svr.set_mount_point("/static", ".");
  18216. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18217. svr.wait_until_ready();
  18218. Client cli(HOST, PORT);
  18219. // baseline: should get 200 and an ETag
  18220. auto res1 = cli.Get("/static/etag_malformed.txt");
  18221. ASSERT_TRUE(res1);
  18222. ASSERT_EQ(200, res1->status);
  18223. ASSERT_TRUE(res1->has_header("ETag"));
  18224. // Malformed ETag value (missing quotes) should be treated as non-matching
  18225. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18226. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18227. ASSERT_TRUE(res_bad);
  18228. EXPECT_EQ(200, res_bad->status);
  18229. // Whitespace-only header value should be considered invalid / non-matching
  18230. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18231. "Host: localhost\r\n"
  18232. "If-None-Match: \r\n"
  18233. "Connection: close\r\n"
  18234. "\r\n";
  18235. std::string out;
  18236. ASSERT_TRUE(send_request(5, raw_req, &out));
  18237. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18238. svr.stop();
  18239. t.join();
  18240. std::remove(fname);
  18241. }
  18242. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18243. using namespace httplib;
  18244. const char *fname = "ims_invalid_format.txt";
  18245. const char *content = "ims-bad-format";
  18246. {
  18247. std::ofstream ofs(fname);
  18248. ofs << content;
  18249. ASSERT_TRUE(ofs.good());
  18250. }
  18251. Server svr;
  18252. svr.set_mount_point("/static", ".");
  18253. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18254. svr.wait_until_ready();
  18255. Client cli(HOST, PORT);
  18256. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18257. ASSERT_TRUE(res1);
  18258. ASSERT_EQ(200, res1->status);
  18259. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18260. // If-Modified-Since with invalid format should not result in 304
  18261. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18262. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18263. ASSERT_TRUE(res_bad);
  18264. EXPECT_EQ(200, res_bad->status);
  18265. // If-Range with invalid date format should be treated as mismatch -> full
  18266. // content (200)
  18267. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18268. {"If-Range", "invalid-date"}};
  18269. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18270. ASSERT_TRUE(res_ifrange);
  18271. EXPECT_EQ(200, res_ifrange->status);
  18272. svr.stop();
  18273. t.join();
  18274. std::remove(fname);
  18275. }
  18276. TEST(ETagTest, IfRangeWithMalformedETag) {
  18277. using namespace httplib;
  18278. const char *fname = "ifrange_malformed.txt";
  18279. const std::string content = "0123456789";
  18280. {
  18281. std::ofstream ofs(fname);
  18282. ofs << content;
  18283. ASSERT_TRUE(ofs.good());
  18284. }
  18285. Server svr;
  18286. svr.set_mount_point("/static", ".");
  18287. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18288. svr.wait_until_ready();
  18289. Client cli(HOST, PORT);
  18290. // First request: get ETag
  18291. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18292. ASSERT_TRUE(res1);
  18293. ASSERT_EQ(200, res1->status);
  18294. ASSERT_TRUE(res1->has_header("ETag"));
  18295. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18296. // full content (200)
  18297. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18298. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18299. ASSERT_TRUE(res2);
  18300. EXPECT_EQ(200, res2->status);
  18301. EXPECT_EQ(content, res2->body);
  18302. svr.stop();
  18303. t.join();
  18304. std::remove(fname);
  18305. }
  18306. TEST(ETagTest, ExtremeLargeDateValues) {
  18307. using namespace httplib;
  18308. const char *fname = "ims_extreme_date.txt";
  18309. const char *content = "ims-extreme-date";
  18310. {
  18311. std::ofstream ofs(fname);
  18312. ofs << content;
  18313. ASSERT_TRUE(ofs.good());
  18314. }
  18315. Server svr;
  18316. svr.set_mount_point("/static", ".");
  18317. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18318. svr.wait_until_ready();
  18319. Client cli(HOST, PORT);
  18320. auto res1 = cli.Get(std::string("/static/") + fname);
  18321. ASSERT_TRUE(res1);
  18322. ASSERT_EQ(200, res1->status);
  18323. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18324. // Extremely large year that may overflow date parsing routines.
  18325. Headers h_large_date = {
  18326. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18327. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18328. ASSERT_TRUE(res_bad);
  18329. // Expect server to treat this as invalid/mismatch and return full content
  18330. EXPECT_EQ(200, res_bad->status);
  18331. // If-Range with extremely large date should be treated as mismatch -> full
  18332. // content (200)
  18333. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18334. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18335. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18336. ASSERT_TRUE(res_ifrange);
  18337. EXPECT_EQ(200, res_ifrange->status);
  18338. svr.stop();
  18339. t.join();
  18340. std::remove(fname);
  18341. }
  18342. TEST(ETagTest, NegativeFileModificationTime) {
  18343. using namespace httplib;
  18344. const char *fname = "ims_negative_mtime.txt";
  18345. const std::string content = "negative-mtime";
  18346. {
  18347. std::ofstream ofs(fname);
  18348. ofs << content;
  18349. ASSERT_TRUE(ofs.good());
  18350. }
  18351. // Try to set file mtime to a negative value. This may fail on some
  18352. // platforms/filesystems; if it fails, the test will still verify server
  18353. // behaves safely by performing a regular conditional request.
  18354. #if defined(__APPLE__) || defined(__linux__)
  18355. bool set_negative = false;
  18356. do {
  18357. struct timeval times[2];
  18358. // access time: now
  18359. times[0].tv_sec = time(nullptr);
  18360. times[0].tv_usec = 0;
  18361. // modification time: negative (e.g., -1)
  18362. times[1].tv_sec = -1;
  18363. times[1].tv_usec = 0;
  18364. if (utimes(fname, times) == 0) { set_negative = true; }
  18365. } while (0);
  18366. #else
  18367. bool set_negative = false;
  18368. #endif
  18369. Server svr;
  18370. svr.set_mount_point("/static", ".");
  18371. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18372. svr.wait_until_ready();
  18373. Client cli(HOST, PORT);
  18374. auto res1 = cli.Get(std::string("/static/") + fname);
  18375. ASSERT_TRUE(res1);
  18376. ASSERT_EQ(200, res1->status);
  18377. bool has_last_modified = res1->has_header("Last-Modified");
  18378. std::string last_modified;
  18379. if (has_last_modified) {
  18380. last_modified = res1->get_header_value("Last-Modified");
  18381. }
  18382. if (set_negative) {
  18383. // If we successfully set a negative mtime, ensure server returns a
  18384. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18385. // with an old date and ensure server handles it without crash.
  18386. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18387. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18388. ASSERT_TRUE(res2);
  18389. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18390. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18391. } else {
  18392. // Could not set negative mtime on this platform; fall back to verifying
  18393. // that normal invalid/malformed dates are treated safely (non-304).
  18394. Headers h_bad_date = {
  18395. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18396. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18397. ASSERT_TRUE(res_bad);
  18398. EXPECT_EQ(200, res_bad->status);
  18399. }
  18400. svr.stop();
  18401. t.join();
  18402. std::remove(fname);
  18403. }
  18404. //==============================================================================
  18405. // SSE Parsing Tests
  18406. //==============================================================================
  18407. class SSEParsingTest : public ::testing::Test {
  18408. protected:
  18409. // Test helper that mimics SSE parsing behavior
  18410. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  18411. int &retry_ms) {
  18412. // Blank line signals end of event
  18413. if (line.empty() || line == "\r") { return true; }
  18414. // Lines starting with ':' are comments (ignored)
  18415. if (!line.empty() && line[0] == ':') { return false; }
  18416. // Find the colon separator
  18417. auto colon_pos = line.find(':');
  18418. if (colon_pos == std::string::npos) {
  18419. // Line with no colon is treated as field name with empty value
  18420. return false;
  18421. }
  18422. std::string field = line.substr(0, colon_pos);
  18423. std::string value;
  18424. // Value starts after colon, skip optional single space
  18425. if (colon_pos + 1 < line.size()) {
  18426. size_t value_start = colon_pos + 1;
  18427. if (line[value_start] == ' ') { value_start++; }
  18428. value = line.substr(value_start);
  18429. // Remove trailing \r if present
  18430. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  18431. }
  18432. // Handle known fields
  18433. if (field == "event") {
  18434. msg.event = value;
  18435. } else if (field == "data") {
  18436. // Multiple data lines are concatenated with newlines
  18437. if (!msg.data.empty()) { msg.data += "\n"; }
  18438. msg.data += value;
  18439. } else if (field == "id") {
  18440. // Empty id is valid (clears the last event ID)
  18441. msg.id = value;
  18442. } else if (field == "retry") {
  18443. // Parse retry interval in milliseconds
  18444. {
  18445. int v = 0;
  18446. auto res =
  18447. detail::from_chars(value.data(), value.data() + value.size(), v);
  18448. if (res.ec == std::errc{}) { retry_ms = v; }
  18449. }
  18450. }
  18451. // Unknown fields are ignored per SSE spec
  18452. return false;
  18453. }
  18454. };
  18455. // Test: Single-line data
  18456. TEST_F(SSEParsingTest, SingleLineData) {
  18457. sse::SSEMessage msg;
  18458. int retry_ms = 3000;
  18459. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  18460. EXPECT_EQ(msg.data, "hello");
  18461. EXPECT_EQ(msg.event, "message");
  18462. // Blank line ends event
  18463. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18464. }
  18465. // Test: Multi-line data
  18466. TEST_F(SSEParsingTest, MultiLineData) {
  18467. sse::SSEMessage msg;
  18468. int retry_ms = 3000;
  18469. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  18470. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  18471. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  18472. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  18473. }
  18474. // Test: Custom event types
  18475. TEST_F(SSEParsingTest, CustomEventType) {
  18476. sse::SSEMessage msg;
  18477. int retry_ms = 3000;
  18478. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  18479. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  18480. EXPECT_EQ(msg.event, "update");
  18481. EXPECT_EQ(msg.data, "payload");
  18482. }
  18483. // Test: Event ID handling
  18484. TEST_F(SSEParsingTest, EventIdHandling) {
  18485. sse::SSEMessage msg;
  18486. int retry_ms = 3000;
  18487. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  18488. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  18489. EXPECT_EQ(msg.id, "12345");
  18490. }
  18491. // Test: Empty event ID (clears last event ID)
  18492. TEST_F(SSEParsingTest, EmptyEventId) {
  18493. sse::SSEMessage msg;
  18494. msg.id = "previous";
  18495. int retry_ms = 3000;
  18496. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  18497. EXPECT_EQ(msg.id, "");
  18498. }
  18499. // Test: Retry field parsing
  18500. TEST_F(SSEParsingTest, RetryFieldParsing) {
  18501. sse::SSEMessage msg;
  18502. int retry_ms = 3000;
  18503. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  18504. EXPECT_EQ(retry_ms, 5000);
  18505. }
  18506. // Test: Invalid retry value
  18507. TEST_F(SSEParsingTest, InvalidRetryValue) {
  18508. sse::SSEMessage msg;
  18509. int retry_ms = 3000;
  18510. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  18511. EXPECT_EQ(retry_ms, 3000); // Unchanged
  18512. }
  18513. // Test: Comments (lines starting with :)
  18514. TEST_F(SSEParsingTest, CommentsIgnored) {
  18515. sse::SSEMessage msg;
  18516. int retry_ms = 3000;
  18517. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  18518. EXPECT_EQ(msg.data, "");
  18519. EXPECT_EQ(msg.event, "message");
  18520. }
  18521. // Test: Colon in value
  18522. TEST_F(SSEParsingTest, ColonInValue) {
  18523. sse::SSEMessage msg;
  18524. int retry_ms = 3000;
  18525. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  18526. EXPECT_EQ(msg.data, "hello:world:test");
  18527. }
  18528. // Test: Line with no colon (field name only)
  18529. TEST_F(SSEParsingTest, FieldNameOnly) {
  18530. sse::SSEMessage msg;
  18531. int retry_ms = 3000;
  18532. // According to SSE spec, this is treated as field name with empty value
  18533. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  18534. // Since we don't recognize "data" without colon, data should be empty
  18535. EXPECT_EQ(msg.data, "");
  18536. }
  18537. // Test: Trailing \r handling
  18538. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18539. sse::SSEMessage msg;
  18540. int retry_ms = 3000;
  18541. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  18542. EXPECT_EQ(msg.data, "hello");
  18543. }
  18544. // Test: Unknown fields ignored
  18545. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18546. sse::SSEMessage msg;
  18547. int retry_ms = 3000;
  18548. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  18549. EXPECT_EQ(msg.data, "");
  18550. EXPECT_EQ(msg.event, "message");
  18551. }
  18552. // Test: Space after colon is optional
  18553. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18554. sse::SSEMessage msg1, msg2;
  18555. int retry_ms = 3000;
  18556. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  18557. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  18558. EXPECT_EQ(msg1.data, "hello");
  18559. EXPECT_EQ(msg2.data, "hello");
  18560. }
  18561. // Test: SSEMessage clear
  18562. TEST_F(SSEParsingTest, MessageClear) {
  18563. sse::SSEMessage msg;
  18564. msg.event = "custom";
  18565. msg.data = "some data";
  18566. msg.id = "123";
  18567. msg.clear();
  18568. EXPECT_EQ(msg.event, "message");
  18569. EXPECT_EQ(msg.data, "");
  18570. EXPECT_EQ(msg.id, "");
  18571. }
  18572. // Test: Complete event parsing
  18573. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18574. sse::SSEMessage msg;
  18575. int retry_ms = 3000;
  18576. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  18577. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  18578. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  18579. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  18580. // Blank line ends event
  18581. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18582. EXPECT_EQ(msg.event, "notification");
  18583. EXPECT_EQ(msg.id, "evt-42");
  18584. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  18585. EXPECT_EQ(retry_ms, 1000);
  18586. }
  18587. //==============================================================================
  18588. // Integration Tests with Server
  18589. //==============================================================================
  18590. class SSEIntegrationTest : public ::testing::Test {
  18591. protected:
  18592. void SetUp() override {
  18593. stop_server_.store(false);
  18594. events_.clear();
  18595. server_ = httplib::detail::make_unique<Server>();
  18596. setup_server();
  18597. start_server();
  18598. }
  18599. void TearDown() override {
  18600. stop_server_.store(true);
  18601. event_cv_.notify_all();
  18602. server_->stop();
  18603. if (server_thread_.joinable()) { server_thread_.join(); }
  18604. }
  18605. void setup_server() {
  18606. // Simple SSE endpoint
  18607. server_->Get("/events", [this](const Request &req, Response &res) {
  18608. auto last_id = req.get_header_value("Last-Event-ID");
  18609. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18610. res.set_chunked_content_provider(
  18611. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18612. std::unique_lock<std::mutex> lock(event_mutex_);
  18613. if (event_cv_.wait_for(
  18614. lock, std::chrono::milliseconds(200), [this] {
  18615. return !events_.empty() || stop_server_.load();
  18616. })) {
  18617. if (stop_server_.load()) { return false; }
  18618. if (!events_.empty()) {
  18619. std::string event = events_.front();
  18620. events_.erase(events_.begin());
  18621. sink.write(event.data(), event.size());
  18622. return true;
  18623. }
  18624. }
  18625. return !stop_server_.load();
  18626. });
  18627. });
  18628. // Endpoint that returns error
  18629. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18630. res.status = 500;
  18631. res.set_content("Internal Server Error", "text/plain");
  18632. });
  18633. // Endpoint for custom event types
  18634. server_->Get("/custom-events", [](const Request &, Response &res) {
  18635. res.set_chunked_content_provider(
  18636. "text/event-stream", [](size_t offset, DataSink &sink) {
  18637. if (offset == 0) {
  18638. std::string event = "event: update\ndata: updated\n\n"
  18639. "event: delete\ndata: deleted\n\n";
  18640. sink.write(event.data(), event.size());
  18641. }
  18642. return false; // End stream after sending
  18643. });
  18644. });
  18645. }
  18646. void start_server() {
  18647. port_ = server_->bind_to_any_port(HOST);
  18648. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18649. // Wait for server to start
  18650. while (!server_->is_running()) {
  18651. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18652. }
  18653. }
  18654. int get_port() const { return port_; }
  18655. void send_event(const std::string &event) {
  18656. std::lock_guard<std::mutex> lock(event_mutex_);
  18657. events_.push_back(event);
  18658. event_cv_.notify_all();
  18659. }
  18660. std::unique_ptr<Server> server_;
  18661. std::thread server_thread_;
  18662. std::mutex event_mutex_;
  18663. std::condition_variable event_cv_;
  18664. std::vector<std::string> events_;
  18665. std::atomic<bool> stop_server_{false};
  18666. std::string last_received_event_id_;
  18667. int port_ = 0;
  18668. };
  18669. // Test: Successful connection and on_open callback
  18670. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18671. // Add a simple endpoint that sends one event and closes
  18672. server_->Get("/simple-event", [](const Request &, Response &res) {
  18673. res.set_chunked_content_provider(
  18674. "text/event-stream", [](size_t offset, DataSink &sink) {
  18675. if (offset == 0) {
  18676. std::string event = "data: hello\n\n";
  18677. sink.write(event.data(), event.size());
  18678. }
  18679. return false; // Close stream after sending
  18680. });
  18681. });
  18682. Client client("localhost", get_port());
  18683. sse::SSEClient sse(client, "/simple-event");
  18684. std::atomic<bool> open_called{false};
  18685. std::atomic<bool> message_received{false};
  18686. sse.on_open([&open_called]() { open_called.store(true); });
  18687. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18688. if (msg.data == "hello") { message_received.store(true); }
  18689. });
  18690. sse.set_reconnect_interval(100);
  18691. sse.set_max_reconnect_attempts(1);
  18692. // Start async
  18693. sse.start_async();
  18694. // Wait for message to be processed
  18695. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18696. sse.stop();
  18697. EXPECT_TRUE(open_called.load());
  18698. EXPECT_TRUE(message_received.load());
  18699. }
  18700. // Test: on_message callback
  18701. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18702. // Endpoint that sends multiple events then closes
  18703. server_->Get("/multi-event", [](const Request &, Response &res) {
  18704. res.set_chunked_content_provider(
  18705. "text/event-stream", [](size_t offset, DataSink &sink) {
  18706. if (offset == 0) {
  18707. std::string events = "data: message1\n\ndata: message2\n\n";
  18708. sink.write(events.data(), events.size());
  18709. }
  18710. return false;
  18711. });
  18712. });
  18713. Client client("localhost", get_port());
  18714. sse::SSEClient sse(client, "/multi-event");
  18715. std::vector<std::string> received_messages;
  18716. std::mutex messages_mutex;
  18717. sse.on_message([&](const sse::SSEMessage &msg) {
  18718. std::lock_guard<std::mutex> lock(messages_mutex);
  18719. received_messages.push_back(msg.data);
  18720. });
  18721. sse.set_reconnect_interval(100);
  18722. sse.set_max_reconnect_attempts(1);
  18723. sse.start_async();
  18724. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18725. sse.stop();
  18726. std::lock_guard<std::mutex> lock(messages_mutex);
  18727. EXPECT_GE(received_messages.size(), 2u);
  18728. if (received_messages.size() >= 2) {
  18729. EXPECT_EQ(received_messages[0], "message1");
  18730. EXPECT_EQ(received_messages[1], "message2");
  18731. }
  18732. }
  18733. // Test: on_event for specific types
  18734. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18735. Client client("localhost", get_port());
  18736. sse::SSEClient sse(client, "/custom-events");
  18737. std::atomic<bool> update_received{false};
  18738. std::atomic<bool> delete_received{false};
  18739. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18740. if (msg.data == "updated") { update_received.store(true); }
  18741. });
  18742. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18743. if (msg.data == "deleted") { delete_received.store(true); }
  18744. });
  18745. sse.set_max_reconnect_attempts(1);
  18746. sse.start_async();
  18747. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18748. sse.stop();
  18749. EXPECT_TRUE(update_received.load());
  18750. EXPECT_TRUE(delete_received.load());
  18751. }
  18752. // Test: on_error callback on connection failure
  18753. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18754. // Connect to a non-existent port
  18755. Client client("localhost", 59999);
  18756. sse::SSEClient sse(client, "/events");
  18757. std::atomic<bool> error_called{false};
  18758. Error received_error = Error::Success;
  18759. sse.on_error([&](Error err) {
  18760. error_called.store(true);
  18761. received_error = err;
  18762. });
  18763. sse.set_reconnect_interval(50);
  18764. sse.set_max_reconnect_attempts(1);
  18765. sse.start_async();
  18766. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18767. sse.stop();
  18768. EXPECT_TRUE(error_called.load());
  18769. EXPECT_NE(received_error, Error::Success);
  18770. }
  18771. // Test: Last-Event-ID header sent on reconnect
  18772. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18773. // Endpoint that sends event with ID
  18774. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18775. res.set_chunked_content_provider(
  18776. "text/event-stream", [](size_t offset, DataSink &sink) {
  18777. if (offset == 0) {
  18778. std::string event = "id: evt-123\ndata: test\n\n";
  18779. sink.write(event.data(), event.size());
  18780. }
  18781. return false;
  18782. });
  18783. });
  18784. Client client("localhost", get_port());
  18785. sse::SSEClient sse(client, "/event-with-id");
  18786. std::atomic<bool> id_received{false};
  18787. sse.on_message([&](const sse::SSEMessage &msg) {
  18788. if (!msg.id.empty()) { id_received.store(true); }
  18789. });
  18790. sse.set_reconnect_interval(100);
  18791. sse.set_max_reconnect_attempts(1);
  18792. sse.start_async();
  18793. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18794. sse.stop();
  18795. EXPECT_TRUE(id_received.load());
  18796. EXPECT_EQ(sse.last_event_id(), "evt-123");
  18797. }
  18798. // Test: Manual stop
  18799. TEST_F(SSEIntegrationTest, ManualStop) {
  18800. // Endpoint that sends one event and stays open briefly
  18801. std::atomic<bool> handler_running{true};
  18802. server_->Get("/stay-open", [&handler_running](const Request &,
  18803. Response &res) {
  18804. res.set_chunked_content_provider(
  18805. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  18806. if (offset == 0) {
  18807. std::string event = "data: connected\n\n";
  18808. sink.write(event.data(), event.size());
  18809. }
  18810. // Keep connection open while handler_running is true
  18811. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18812. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18813. }
  18814. return false;
  18815. });
  18816. });
  18817. Client client("localhost", get_port());
  18818. sse::SSEClient sse(client, "/stay-open");
  18819. std::atomic<bool> connected{false};
  18820. sse.on_open([&connected]() { connected.store(true); });
  18821. sse.set_reconnect_interval(100);
  18822. sse.set_max_reconnect_attempts(1);
  18823. sse.start_async();
  18824. // Wait for connection to establish
  18825. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18826. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18827. }
  18828. EXPECT_TRUE(connected.load());
  18829. EXPECT_TRUE(sse.is_connected());
  18830. // Signal handler to stop
  18831. handler_running.store(false);
  18832. // Stop SSE client
  18833. sse.stop();
  18834. EXPECT_FALSE(sse.is_connected());
  18835. }
  18836. // Test: SSEClient with custom headers
  18837. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18838. // Setup a server endpoint that checks for custom header
  18839. std::atomic<bool> header_received{false};
  18840. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18841. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18842. header_received.store(true);
  18843. }
  18844. res.set_chunked_content_provider("text/event-stream",
  18845. [](size_t, DataSink &) { return false; });
  18846. });
  18847. Client client("localhost", get_port());
  18848. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18849. sse::SSEClient sse(client, "/header-check", headers);
  18850. sse.set_max_reconnect_attempts(1);
  18851. sse.start_async();
  18852. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18853. sse.stop();
  18854. EXPECT_TRUE(header_received.load());
  18855. }
  18856. // Test: Reconnect interval configuration
  18857. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18858. Client client("localhost", get_port());
  18859. sse::SSEClient sse(client, "/events");
  18860. auto &result = sse.set_reconnect_interval(500);
  18861. // Builder pattern should return reference to self
  18862. EXPECT_EQ(&result, &sse);
  18863. }
  18864. // Test: Max reconnect attempts
  18865. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18866. // Connect to non-existent port to force reconnects
  18867. Client client("localhost", 59998);
  18868. sse::SSEClient sse(client, "/events");
  18869. std::atomic<int> error_count{0};
  18870. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18871. sse.set_reconnect_interval(50);
  18872. sse.set_max_reconnect_attempts(2);
  18873. auto start = std::chrono::steady_clock::now();
  18874. sse.start(); // Blocking call
  18875. auto end = std::chrono::steady_clock::now();
  18876. // Should have stopped after 2 failed attempts
  18877. EXPECT_GE(error_count.load(), 2);
  18878. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18879. auto duration =
  18880. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18881. #ifdef _WIN32
  18882. // Windows is much slower for socket connection failures
  18883. EXPECT_LT(duration.count(), 7000);
  18884. #else
  18885. EXPECT_LT(duration.count(), 1000);
  18886. #endif
  18887. }
  18888. // Test: Multi-line data in integration
  18889. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18890. // Endpoint with multi-line data
  18891. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18892. res.set_chunked_content_provider(
  18893. "text/event-stream", [](size_t offset, DataSink &sink) {
  18894. if (offset == 0) {
  18895. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18896. sink.write(event.data(), event.size());
  18897. }
  18898. return false;
  18899. });
  18900. });
  18901. Client client("localhost", get_port());
  18902. sse::SSEClient sse(client, "/multiline-data");
  18903. std::string received_data;
  18904. std::mutex data_mutex;
  18905. sse.on_message([&](const sse::SSEMessage &msg) {
  18906. std::lock_guard<std::mutex> lock(data_mutex);
  18907. received_data = msg.data;
  18908. });
  18909. sse.set_reconnect_interval(100);
  18910. sse.set_max_reconnect_attempts(1);
  18911. sse.start_async();
  18912. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18913. sse.stop();
  18914. std::lock_guard<std::mutex> lock(data_mutex);
  18915. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18916. }
  18917. // Test: Auto-reconnect after server disconnection
  18918. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18919. std::atomic<int> connection_count{0};
  18920. std::atomic<int> message_count{0};
  18921. // Endpoint that sends one event and closes, forcing reconnect
  18922. server_->Get("/reconnect-test",
  18923. [&connection_count](const Request &, Response &res) {
  18924. connection_count.fetch_add(1);
  18925. res.set_chunked_content_provider(
  18926. "text/event-stream", [](size_t offset, DataSink &sink) {
  18927. if (offset == 0) {
  18928. std::string event = "data: hello\n\n";
  18929. sink.write(event.data(), event.size());
  18930. }
  18931. return false; // Close connection after sending
  18932. });
  18933. });
  18934. Client client("localhost", get_port());
  18935. sse::SSEClient sse(client, "/reconnect-test");
  18936. sse.on_message([&message_count](const sse::SSEMessage &) {
  18937. message_count.fetch_add(1);
  18938. });
  18939. sse.set_reconnect_interval(100);
  18940. sse.set_max_reconnect_attempts(3);
  18941. sse.start_async();
  18942. // Wait long enough for multiple reconnects
  18943. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18944. sse.stop();
  18945. // Should have connected multiple times (initial + reconnects)
  18946. EXPECT_GE(connection_count.load(), 2);
  18947. // Should have received messages from multiple connections
  18948. EXPECT_GE(message_count.load(), 2);
  18949. }
  18950. // Test: A retry field that is not all ASCII digits is ignored
  18951. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  18952. std::atomic<int> connection_count{0};
  18953. server_->Get("/bad-retry",
  18954. [&connection_count](const Request &, Response &res) {
  18955. connection_count.fetch_add(1);
  18956. res.set_chunked_content_provider(
  18957. "text/event-stream", [](size_t offset, DataSink &sink) {
  18958. if (offset == 0) {
  18959. std::string event = "retry: -1\ndata: hello\n\n";
  18960. sink.write(event.data(), event.size());
  18961. }
  18962. return false;
  18963. });
  18964. });
  18965. Client client("localhost", get_port());
  18966. sse::SSEClient sse(client, "/bad-retry");
  18967. sse.set_reconnect_interval(10000);
  18968. sse.start_async();
  18969. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18970. sse.stop();
  18971. EXPECT_EQ(connection_count.load(), 1);
  18972. }
  18973. // Test: A retry field of all ASCII digits sets the reconnection time
  18974. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  18975. std::atomic<int> connection_count{0};
  18976. server_->Get("/zero-retry",
  18977. [&connection_count](const Request &, Response &res) {
  18978. connection_count.fetch_add(1);
  18979. res.set_chunked_content_provider(
  18980. "text/event-stream", [](size_t offset, DataSink &sink) {
  18981. if (offset == 0) {
  18982. std::string event = "retry: 0\ndata: hello\n\n";
  18983. sink.write(event.data(), event.size());
  18984. }
  18985. return false;
  18986. });
  18987. });
  18988. Client client("localhost", get_port());
  18989. sse::SSEClient sse(client, "/zero-retry");
  18990. sse.set_reconnect_interval(10000);
  18991. sse.start_async();
  18992. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18993. sse.stop();
  18994. // The server-supplied interval is applied, but never below 100ms, so
  18995. // "retry: 0" does not cause a busy reconnect loop
  18996. EXPECT_GE(connection_count.load(), 2);
  18997. EXPECT_LE(connection_count.load(), 10);
  18998. }
  18999. // Test: Last-Event-ID sent on reconnect
  19000. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19001. std::atomic<int> connection_count{0};
  19002. std::vector<std::string> received_last_event_ids;
  19003. std::mutex id_mutex;
  19004. // Endpoint that checks Last-Event-ID header and sends event with ID
  19005. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19006. int conn = connection_count.fetch_add(1);
  19007. // Capture the Last-Event-ID header from each connection
  19008. {
  19009. std::lock_guard<std::mutex> lock(id_mutex);
  19010. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19011. }
  19012. res.set_chunked_content_provider(
  19013. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19014. if (offset == 0) {
  19015. std::string event =
  19016. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19017. sink.write(event.data(), event.size());
  19018. }
  19019. return false;
  19020. });
  19021. });
  19022. Client client("localhost", get_port());
  19023. sse::SSEClient sse(client, "/reconnect-with-id");
  19024. sse.set_reconnect_interval(100);
  19025. sse.set_max_reconnect_attempts(3);
  19026. sse.start_async();
  19027. // Wait for at least 2 connections
  19028. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19029. sse.stop();
  19030. // Verify behavior
  19031. std::lock_guard<std::mutex> lock(id_mutex);
  19032. EXPECT_GE(received_last_event_ids.size(), 2u);
  19033. // First connection should have no Last-Event-ID
  19034. if (!received_last_event_ids.empty()) {
  19035. EXPECT_EQ(received_last_event_ids[0], "");
  19036. }
  19037. // Second connection should have Last-Event-ID from first connection
  19038. if (received_last_event_ids.size() >= 2) {
  19039. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19040. }
  19041. }
  19042. // Test: set_headers updates headers used on reconnect
  19043. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19044. std::vector<std::string> received_tokens;
  19045. std::mutex token_mutex;
  19046. // Endpoint that captures Authorization header
  19047. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19048. {
  19049. std::lock_guard<std::mutex> lock(token_mutex);
  19050. received_tokens.push_back(req.get_header_value("Authorization"));
  19051. }
  19052. res.set_chunked_content_provider(
  19053. "text/event-stream", [](size_t offset, DataSink &sink) {
  19054. if (offset == 0) {
  19055. std::string event = "data: hello\n\n";
  19056. sink.write(event.data(), event.size());
  19057. }
  19058. return false; // Close connection to trigger reconnect
  19059. });
  19060. });
  19061. Client client("localhost", get_port());
  19062. Headers headers = {{"Authorization", "Bearer old-token"}};
  19063. sse::SSEClient sse(client, "/auth-check", headers);
  19064. // Update headers on each successful connection
  19065. sse.on_open(
  19066. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19067. sse.set_reconnect_interval(100);
  19068. sse.set_max_reconnect_attempts(3);
  19069. sse.start_async();
  19070. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19071. sse.stop();
  19072. std::lock_guard<std::mutex> lock(token_mutex);
  19073. ASSERT_GE(received_tokens.size(), 2u);
  19074. // First connection uses original header
  19075. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19076. // Second connection uses updated header from set_headers
  19077. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19078. }
  19079. // Test: 401 allows reconnection (so on_error can refresh headers)
  19080. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19081. std::atomic<int> connection_count{0};
  19082. // Endpoint: returns 401 on first attempt, 200 on second
  19083. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19084. int conn = connection_count.fetch_add(1);
  19085. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19086. res.status = StatusCode::Unauthorized_401;
  19087. res.set_content("Unauthorized", "text/plain");
  19088. return;
  19089. }
  19090. res.set_chunked_content_provider(
  19091. "text/event-stream", [](size_t offset, DataSink &sink) {
  19092. if (offset == 0) {
  19093. std::string event = "data: authenticated\n\n";
  19094. sink.write(event.data(), event.size());
  19095. }
  19096. return false;
  19097. });
  19098. });
  19099. Client client("localhost", get_port());
  19100. Headers headers = {{"Authorization", "Bearer expired"}};
  19101. sse::SSEClient sse(client, "/auth-retry", headers);
  19102. std::atomic<bool> message_received{false};
  19103. // Refresh token on error
  19104. sse.on_error(
  19105. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19106. sse.on_message([&](const sse::SSEMessage &msg) {
  19107. if (msg.data == "authenticated") { message_received.store(true); }
  19108. });
  19109. sse.set_reconnect_interval(100);
  19110. sse.set_max_reconnect_attempts(3);
  19111. sse.start_async();
  19112. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19113. sse.stop();
  19114. // Should have reconnected after 401 and succeeded with new token
  19115. EXPECT_GE(connection_count.load(), 2);
  19116. EXPECT_TRUE(message_received.load());
  19117. }
  19118. TEST(Issue2318Test, EmptyHostString) {
  19119. {
  19120. httplib::Client cli_empty("", PORT);
  19121. auto res = cli_empty.Get("/");
  19122. ASSERT_FALSE(res);
  19123. EXPECT_EQ(httplib::Error::Connection, res.error());
  19124. }
  19125. {
  19126. httplib::Client cli(" ", PORT);
  19127. auto res = cli.Get("/");
  19128. ASSERT_FALSE(res);
  19129. EXPECT_EQ(httplib::Error::Connection, res.error());
  19130. }
  19131. }
  19132. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19133. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19134. Server svr;
  19135. // Set a small payload limit (1KB)
  19136. svr.set_payload_max_length(1024);
  19137. svr.Post("/test", [&](const Request &req, Response &res) {
  19138. res.set_content("Body size: " + std::to_string(req.body.size()),
  19139. "text/plain");
  19140. });
  19141. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19142. auto se = detail::scope_exit([&] {
  19143. svr.stop();
  19144. listen_thread.join();
  19145. });
  19146. svr.wait_until_ready();
  19147. // Create data that compresses well but exceeds limit when decompressed
  19148. // 8KB of repeated null bytes compresses to a very small size
  19149. std::string original_data(8 * 1024, '\0');
  19150. // Compress the data using gzip
  19151. std::string compressed_data;
  19152. detail::gzip_compressor compressor;
  19153. compressor.compress(original_data.data(), original_data.size(), true,
  19154. [&](const char *data, size_t size) {
  19155. compressed_data.append(data, size);
  19156. return true;
  19157. });
  19158. // Verify compression worked (compressed should be much smaller)
  19159. ASSERT_LT(compressed_data.size(), original_data.size());
  19160. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19161. // Send compressed data with Content-Encoding: gzip
  19162. Client cli(HOST, PORT);
  19163. Headers headers = {{"Content-Encoding", "gzip"}};
  19164. auto res =
  19165. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19166. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19168. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19169. }
  19170. #endif
  19171. // ============================================================================
  19172. // OpenSSL-Specific Tests
  19173. // ============================================================================
  19174. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19175. X509 *readCertificate(const std::string &strFileName) {
  19176. std::ifstream inStream(strFileName);
  19177. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19178. std::istreambuf_iterator<char>());
  19179. if (strCertPEM.empty()) return (nullptr);
  19180. BIO *pbCert = BIO_new(BIO_s_mem());
  19181. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19182. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19183. BIO_free(pbCert);
  19184. return (pCert);
  19185. }
  19186. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19187. std::ifstream inStream(strFileName);
  19188. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19189. std::istreambuf_iterator<char>());
  19190. if (strPrivateKeyPEM.empty()) return (nullptr);
  19191. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19192. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19193. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19194. BIO_free(pbPrivKey);
  19195. return (pPrivateKey);
  19196. }
  19197. TEST(BindServerTest, UpdateCerts) {
  19198. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19199. int port = svr.bind_to_any_port("0.0.0.0");
  19200. ASSERT_TRUE(svr.is_valid());
  19201. ASSERT_TRUE(port > 0);
  19202. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19203. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19204. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19205. ASSERT_TRUE(cert != nullptr);
  19206. ASSERT_TRUE(ca_cert != nullptr);
  19207. ASSERT_TRUE(key != nullptr);
  19208. X509_STORE *cert_store = X509_STORE_new();
  19209. X509_STORE_add_cert(cert_store, ca_cert);
  19210. // svr.update_certs(cert, key, cert_store); // deprecated
  19211. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19212. CLIENT_CA_CERT_FILE);
  19213. ASSERT_TRUE(svr.is_valid());
  19214. svr.stop();
  19215. X509_STORE_free(cert_store);
  19216. X509_free(cert);
  19217. X509_free(ca_cert);
  19218. EVP_PKEY_free(key);
  19219. }
  19220. // Test that update_certs() updates client CA list correctly
  19221. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19222. // Start with file-based constructor
  19223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19224. ASSERT_TRUE(svr.is_valid());
  19225. // Initially no client CA list should be set
  19226. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19227. ASSERT_TRUE(ssl_ctx != nullptr);
  19228. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19229. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19230. EXPECT_EQ(0, count_before);
  19231. // Now update with client CA (PEM string)
  19232. std::string cert_pem, key_pem, ca_pem;
  19233. read_file(SERVER_CERT_FILE, cert_pem);
  19234. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19235. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19236. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19237. ASSERT_TRUE(svr.is_valid());
  19238. // Now client CA list should be set
  19239. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19240. ASSERT_TRUE(ca_list_after != nullptr);
  19241. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19242. }
  19243. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19244. // Test that the file-path SSLServer constructor properly sets the client CA
  19245. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19247. ASSERT_TRUE(svr.is_valid());
  19248. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19249. ASSERT_TRUE(ssl_ctx != nullptr);
  19250. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19251. ASSERT_TRUE(ca_list != nullptr);
  19252. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19253. }
  19254. #endif
  19255. // ============================================================================
  19256. // MbedTLS-Specific Tests
  19257. // ============================================================================
  19258. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19259. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19260. using namespace httplib::tls;
  19261. // Track if callback was invoked
  19262. bool callback_invoked = false;
  19263. // The callback receives void* ctx which is actually MbedTlsContext*
  19264. // We can access the mbedtls_ssl_config via the context
  19265. auto setup_callback = [&callback_invoked](void *ctx) {
  19266. callback_invoked = true;
  19267. // Cast to MbedTlsContext* to access the ssl config
  19268. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19269. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19270. // Use static variables to hold certificate data (simplified for test)
  19271. static mbedtls_x509_crt own_cert;
  19272. static mbedtls_pk_context own_key;
  19273. static mbedtls_x509_crt ca_chain;
  19274. static bool initialized = false;
  19275. if (!initialized) {
  19276. mbedtls_x509_crt_init(&own_cert);
  19277. mbedtls_pk_init(&own_key);
  19278. mbedtls_x509_crt_init(&ca_chain);
  19279. // Load server certificate
  19280. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19281. return false;
  19282. }
  19283. // Load server private key.
  19284. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19285. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19286. #if MBEDTLS_VERSION_MAJOR == 3
  19287. ,
  19288. mbedtls_ctr_drbg_random, nullptr
  19289. #endif
  19290. ) != 0) {
  19291. return false;
  19292. }
  19293. // Load CA chain for client verification
  19294. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19295. return false;
  19296. }
  19297. initialized = true;
  19298. }
  19299. // Configure the SSL config
  19300. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19301. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19302. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19303. // Set minimum TLS version using mbedTLS native API
  19304. #if MBEDTLS_VERSION_MAJOR >= 3
  19305. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19306. #else
  19307. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19308. MBEDTLS_SSL_MINOR_VERSION_3);
  19309. #endif
  19310. return true;
  19311. };
  19312. SSLServer svr(setup_callback);
  19313. ASSERT_TRUE(svr.is_valid());
  19314. ASSERT_TRUE(callback_invoked);
  19315. svr.Get("/test", [&](const Request &req, Response &res) {
  19316. res.set_content("test", "text/plain");
  19317. auto cert = req.peer_cert();
  19318. ASSERT_TRUE(static_cast<bool>(cert));
  19319. auto common_name = cert.subject_cn();
  19320. EXPECT_EQ("Common Name", common_name);
  19321. });
  19322. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19323. auto se = detail::scope_exit([&] {
  19324. svr.stop();
  19325. t.join();
  19326. ASSERT_FALSE(svr.is_running());
  19327. });
  19328. svr.wait_until_ready();
  19329. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19330. cli.enable_server_certificate_verification(false);
  19331. cli.set_connection_timeout(30);
  19332. auto res = cli.Get("/test");
  19333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19334. ASSERT_EQ(StatusCode::OK_200, res->status);
  19335. }
  19336. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19337. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19338. // keep-alive SSL session, which reads through that config in
  19339. // mbedtls_ssl_close_notify.
  19340. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19342. ASSERT_TRUE(svr.is_valid());
  19343. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19344. res.set_content("test", "text/plain");
  19345. });
  19346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19347. auto se = detail::scope_exit([&] {
  19348. svr.stop();
  19349. t.join();
  19350. ASSERT_FALSE(svr.is_running());
  19351. });
  19352. svr.wait_until_ready();
  19353. {
  19354. SSLClient cli(HOST, PORT);
  19355. cli.enable_server_certificate_verification(false);
  19356. cli.set_keep_alive(true);
  19357. auto res = cli.Get("/test");
  19358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19359. ASSERT_EQ(StatusCode::OK_200, res->status);
  19360. // cli is destructed here with the keep-alive SSL session still open.
  19361. }
  19362. }
  19363. #endif
  19364. // WebSocket Tests
  19365. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19366. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19367. // defining the meaning of these bits has been negotiated.
  19368. auto make_frame = [](uint8_t first_byte) {
  19369. std::string frame;
  19370. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19371. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19372. frame += "Hello";
  19373. return frame;
  19374. };
  19375. // RSV1 set (0x40)
  19376. {
  19377. detail::BufferStream strm;
  19378. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19379. ws::Opcode opcode;
  19380. std::string payload;
  19381. bool fin;
  19382. EXPECT_EQ(
  19383. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19384. ws::impl::FrameRead::Fail);
  19385. }
  19386. // RSV2 set (0x20)
  19387. {
  19388. detail::BufferStream strm;
  19389. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19390. ws::Opcode opcode;
  19391. std::string payload;
  19392. bool fin;
  19393. EXPECT_EQ(
  19394. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19395. ws::impl::FrameRead::Fail);
  19396. }
  19397. // RSV3 set (0x10)
  19398. {
  19399. detail::BufferStream strm;
  19400. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19401. ws::Opcode opcode;
  19402. std::string payload;
  19403. bool fin;
  19404. EXPECT_EQ(
  19405. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19406. ws::impl::FrameRead::Fail);
  19407. }
  19408. // No RSV bits set - should succeed
  19409. {
  19410. detail::BufferStream strm;
  19411. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19412. ws::Opcode opcode;
  19413. std::string payload;
  19414. bool fin;
  19415. EXPECT_EQ(
  19416. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19417. ws::impl::FrameRead::Ok);
  19418. EXPECT_EQ(ws::Opcode::Text, opcode);
  19419. EXPECT_EQ("Hello", payload);
  19420. EXPECT_TRUE(fin);
  19421. }
  19422. }
  19423. TEST(WebSocketTest, ControlFrameValidation) {
  19424. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19425. // payload length <= 125.
  19426. // Ping with FIN=0 - must be rejected
  19427. {
  19428. detail::BufferStream strm;
  19429. std::string frame;
  19430. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19431. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19432. strm.write(frame.data(), frame.size());
  19433. ws::Opcode opcode;
  19434. std::string payload;
  19435. bool fin;
  19436. EXPECT_EQ(
  19437. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19438. ws::impl::FrameRead::Fail);
  19439. }
  19440. // Close with FIN=0 - must be rejected
  19441. {
  19442. detail::BufferStream strm;
  19443. std::string frame;
  19444. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19445. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19446. strm.write(frame.data(), frame.size());
  19447. ws::Opcode opcode;
  19448. std::string payload;
  19449. bool fin;
  19450. EXPECT_EQ(
  19451. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19452. ws::impl::FrameRead::Fail);
  19453. }
  19454. // Ping with payload_len=126 (extended length) - must be rejected
  19455. {
  19456. detail::BufferStream strm;
  19457. std::string frame;
  19458. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19459. frame += static_cast<char>(126); // payload_len=126 (>125)
  19460. frame += static_cast<char>(0x00); // extended length high byte
  19461. frame += static_cast<char>(126); // extended length low byte
  19462. frame += std::string(126, 'x');
  19463. strm.write(frame.data(), frame.size());
  19464. ws::Opcode opcode;
  19465. std::string payload;
  19466. bool fin;
  19467. EXPECT_EQ(
  19468. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19469. ws::impl::FrameRead::Fail);
  19470. }
  19471. // Ping with FIN=1 and payload_len=125 - should succeed
  19472. {
  19473. detail::BufferStream strm;
  19474. std::string frame;
  19475. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19476. frame += static_cast<char>(125); // payload_len=125
  19477. frame += std::string(125, 'x');
  19478. strm.write(frame.data(), frame.size());
  19479. ws::Opcode opcode;
  19480. std::string payload;
  19481. bool fin;
  19482. EXPECT_EQ(
  19483. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19484. ws::impl::FrameRead::Ok);
  19485. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19486. EXPECT_EQ(125u, payload.size());
  19487. EXPECT_TRUE(fin);
  19488. }
  19489. }
  19490. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19491. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19492. // length MUST be 0.
  19493. // MSB set - must be rejected
  19494. {
  19495. detail::BufferStream strm;
  19496. std::string frame;
  19497. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19498. frame += static_cast<char>(127); // 64-bit extended length
  19499. frame += static_cast<char>(0x80); // MSB set (invalid)
  19500. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19501. strm.write(frame.data(), frame.size());
  19502. ws::Opcode opcode;
  19503. std::string payload;
  19504. bool fin;
  19505. EXPECT_EQ(
  19506. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19507. ws::impl::FrameRead::Fail);
  19508. }
  19509. // MSB clear - should pass length parsing (will be rejected by max_len,
  19510. // but that's a different check; use a small length to verify)
  19511. {
  19512. detail::BufferStream strm;
  19513. std::string frame;
  19514. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19515. frame += static_cast<char>(127); // 64-bit extended length
  19516. frame += std::string(7, '\0'); // high bytes = 0
  19517. frame += static_cast<char>(0x03); // length = 3
  19518. frame += "abc";
  19519. strm.write(frame.data(), frame.size());
  19520. ws::Opcode opcode;
  19521. std::string payload;
  19522. bool fin;
  19523. EXPECT_EQ(
  19524. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19525. ws::impl::FrameRead::Ok);
  19526. EXPECT_EQ(ws::Opcode::Text, opcode);
  19527. EXPECT_EQ("abc", payload);
  19528. }
  19529. }
  19530. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19531. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19532. // Valid UTF-8
  19533. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19534. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19535. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19536. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19537. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19538. // Invalid UTF-8
  19539. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19540. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19541. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19542. EXPECT_FALSE(
  19543. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19544. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19545. }
  19546. TEST(WebSocketTest, ConnectAndDisconnect) {
  19547. Server svr;
  19548. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19549. std::string msg;
  19550. while (ws.read(msg)) {}
  19551. });
  19552. auto port = svr.bind_to_any_port(HOST);
  19553. std::thread t([&]() { svr.listen_after_bind(); });
  19554. svr.wait_until_ready();
  19555. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19556. auto res = client.connect();
  19557. ASSERT_TRUE(res);
  19558. EXPECT_EQ(Error::Success, res.error());
  19559. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19560. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19561. EXPECT_TRUE(client.is_open());
  19562. client.close();
  19563. EXPECT_FALSE(client.is_open());
  19564. svr.stop();
  19565. t.join();
  19566. }
  19567. TEST(WebSocketTest, ValidURL) {
  19568. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19569. EXPECT_TRUE(ws1.is_valid());
  19570. ws::WebSocketClient ws2("ws://example.com/path");
  19571. EXPECT_TRUE(ws2.is_valid());
  19572. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19573. EXPECT_TRUE(ws3.is_valid());
  19574. #ifdef CPPHTTPLIB_SSL_ENABLED
  19575. ws::WebSocketClient wss1("wss://example.com/path");
  19576. EXPECT_TRUE(wss1.is_valid());
  19577. ws::WebSocketClient wss2("wss://example.com:443/path");
  19578. EXPECT_TRUE(wss2.is_valid());
  19579. #endif
  19580. }
  19581. TEST(WebSocketTest, InvalidURL) {
  19582. // No scheme
  19583. ws::WebSocketClient ws1("localhost:8080/path");
  19584. EXPECT_FALSE(ws1.is_valid());
  19585. // No path
  19586. ws::WebSocketClient ws2("ws://localhost:8080");
  19587. EXPECT_FALSE(ws2.is_valid());
  19588. // Empty string
  19589. ws::WebSocketClient ws3("");
  19590. EXPECT_FALSE(ws3.is_valid());
  19591. // Missing host
  19592. ws::WebSocketClient ws4("ws://:8080/path");
  19593. EXPECT_FALSE(ws4.is_valid());
  19594. // Port number overflow — should not crash
  19595. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19596. EXPECT_FALSE(ws5.is_valid());
  19597. // Port out of range
  19598. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19599. EXPECT_FALSE(ws6.is_valid());
  19600. }
  19601. TEST(WebSocketTest, UnsupportedScheme) {
  19602. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19603. ws::WebSocketClient ws1("http://localhost:8080/path");
  19604. EXPECT_FALSE(ws1.is_valid());
  19605. ws::WebSocketClient ws2("https://localhost:8080/path");
  19606. EXPECT_FALSE(ws2.is_valid());
  19607. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19608. EXPECT_FALSE(ws3.is_valid());
  19609. #else
  19610. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19611. std::invalid_argument);
  19612. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19613. std::invalid_argument);
  19614. #endif
  19615. }
  19616. TEST(WebSocketTest, ConnectWhenInvalid) {
  19617. ws::WebSocketClient ws("not a valid url");
  19618. EXPECT_FALSE(ws.is_valid());
  19619. auto res = ws.connect();
  19620. EXPECT_FALSE(res);
  19621. EXPECT_EQ(Error::Connection, res.error());
  19622. EXPECT_EQ(-1, res.status());
  19623. }
  19624. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19625. // Grab a port that is free, then close it again so nothing listens there
  19626. Server svr;
  19627. auto port = svr.bind_to_any_port(HOST);
  19628. svr.stop();
  19629. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19630. auto res = client.connect();
  19631. ASSERT_FALSE(res);
  19632. EXPECT_EQ(Error::Connection, res.error());
  19633. EXPECT_EQ(-1, res.status());
  19634. }
  19635. TEST(WebSocketTest, DefaultPort) {
  19636. ws::WebSocketClient ws1("ws://example.com/path");
  19637. EXPECT_TRUE(ws1.is_valid());
  19638. // ws:// defaults to port 80 (verified by successful parse)
  19639. #ifdef CPPHTTPLIB_SSL_ENABLED
  19640. ws::WebSocketClient ws2("wss://example.com/path");
  19641. EXPECT_TRUE(ws2.is_valid());
  19642. // wss:// defaults to port 443 (verified by successful parse)
  19643. #endif
  19644. }
  19645. TEST(WebSocketTest, IPv6LiteralAddress) {
  19646. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19647. EXPECT_TRUE(ws1.is_valid());
  19648. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  19649. EXPECT_TRUE(ws2.is_valid());
  19650. }
  19651. TEST(WebSocketTest, ComplexPath) {
  19652. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  19653. EXPECT_TRUE(ws1.is_valid());
  19654. ws::WebSocketClient ws2("ws://localhost:8080/");
  19655. EXPECT_TRUE(ws2.is_valid());
  19656. }
  19657. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  19658. Server svr;
  19659. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19660. std::string msg;
  19661. while (ws.read(msg)) {}
  19662. });
  19663. auto port = svr.bind_to_any_port(HOST);
  19664. std::thread t([&]() { svr.listen_after_bind(); });
  19665. svr.wait_until_ready();
  19666. auto another_host = "example.com";
  19667. auto wrong_ip = "192.0.2.1";
  19668. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19669. client.set_hostname_addr_map({{another_host, wrong_ip}});
  19670. ASSERT_TRUE(client.connect());
  19671. EXPECT_TRUE(client.is_open());
  19672. client.close();
  19673. svr.stop();
  19674. t.join();
  19675. }
  19676. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  19677. Server svr;
  19678. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19679. std::string msg;
  19680. while (ws.read(msg)) {}
  19681. });
  19682. auto port = svr.bind_to_any_port(HOST);
  19683. std::thread t([&]() { svr.listen_after_bind(); });
  19684. svr.wait_until_ready();
  19685. auto wrong_ip = "192.0.2.1";
  19686. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19687. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  19688. client.set_connection_timeout(1);
  19689. client.set_read_timeout(1);
  19690. client.set_write_timeout(1);
  19691. EXPECT_FALSE(client.connect());
  19692. EXPECT_FALSE(client.is_open());
  19693. svr.stop();
  19694. t.join();
  19695. }
  19696. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  19697. // A mapped value that is not an IP literal must be resolved. HOST resolves
  19698. // from the hosts file, so this test needs no external DNS. "target.invalid"
  19699. // (RFC 6761) is only a map key and the Host header value.
  19700. auto host = "target.invalid";
  19701. Server svr;
  19702. std::string received_host;
  19703. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19704. received_host = req.get_header_value("Host");
  19705. std::string msg;
  19706. while (ws.read(msg)) {}
  19707. });
  19708. auto port = svr.bind_to_any_port(HOST);
  19709. std::thread t([&]() { svr.listen_after_bind(); });
  19710. // ASSERT_* below returns from the test body, which would leave t joinable
  19711. // and make ~thread call std::terminate.
  19712. auto se = detail::scope_exit([&] {
  19713. svr.stop();
  19714. if (t.joinable()) { t.join(); }
  19715. });
  19716. svr.wait_until_ready();
  19717. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  19718. std::to_string(port) + "/ws");
  19719. client.set_hostname_addr_map({{host, HOST}});
  19720. ASSERT_TRUE(client.connect());
  19721. EXPECT_TRUE(client.is_open());
  19722. client.close();
  19723. svr.stop();
  19724. t.join();
  19725. // The mapping only redirects the connection; the identity stays host_.
  19726. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  19727. }
  19728. class WebSocketIntegrationTest : public ::testing::Test {
  19729. protected:
  19730. void SetUp() override {
  19731. server_ = httplib::detail::make_unique<Server>();
  19732. setup_server();
  19733. start_server();
  19734. }
  19735. void TearDown() override {
  19736. server_->stop();
  19737. if (server_thread_.joinable()) { server_thread_.join(); }
  19738. }
  19739. void setup_server() {
  19740. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19741. std::string msg;
  19742. ws::ReadResult ret;
  19743. while ((ret = ws.read(msg))) {
  19744. if (ret == ws::Binary) {
  19745. ws.send(msg.data(), msg.size());
  19746. } else {
  19747. ws.send(msg);
  19748. }
  19749. }
  19750. });
  19751. server_->WebSocket("/ws-echo-string",
  19752. [](const Request &, ws::WebSocket &ws) {
  19753. std::string msg;
  19754. while (ws.read(msg)) {
  19755. ws.send("echo: " + msg);
  19756. }
  19757. });
  19758. server_->WebSocket(
  19759. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19760. // Echo back request metadata
  19761. ws.send("path:" + req.path);
  19762. ws.send("header:" + req.get_header_value("X-Test-Header"));
  19763. std::string msg;
  19764. while (ws.read(msg)) {}
  19765. });
  19766. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  19767. std::string msg;
  19768. ws.read(msg); // wait for a message
  19769. ws.close();
  19770. });
  19771. server_->WebSocket("/ws-close-status",
  19772. [](const Request &, ws::WebSocket &ws) {
  19773. std::string msg;
  19774. ws.read(msg); // wait for a message
  19775. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  19776. });
  19777. server_->WebSocket(
  19778. "/ws-subprotocol",
  19779. [](const Request &, ws::WebSocket &ws) {
  19780. std::string msg;
  19781. while (ws.read(msg)) {
  19782. ws.send(msg);
  19783. }
  19784. },
  19785. [](const std::vector<std::string> &protocols) -> std::string {
  19786. for (const auto &p : protocols) {
  19787. if (p == "graphql-ws") { return p; }
  19788. }
  19789. return "";
  19790. });
  19791. }
  19792. void start_server() {
  19793. port_ = server_->bind_to_any_port(HOST);
  19794. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19795. server_->wait_until_ready();
  19796. }
  19797. std::unique_ptr<Server> server_;
  19798. std::thread server_thread_;
  19799. int port_ = 0;
  19800. };
  19801. TEST_F(WebSocketIntegrationTest, TextEcho) {
  19802. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19803. "/ws-echo");
  19804. ASSERT_TRUE(client.connect());
  19805. ASSERT_TRUE(client.is_open());
  19806. ASSERT_TRUE(client.send("Hello WebSocket"));
  19807. std::string msg;
  19808. EXPECT_EQ(ws::Text, client.read(msg));
  19809. EXPECT_EQ("Hello WebSocket", msg);
  19810. client.close();
  19811. }
  19812. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  19813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19814. "/ws-echo");
  19815. ASSERT_TRUE(client.connect());
  19816. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  19817. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  19818. std::string msg;
  19819. EXPECT_EQ(ws::Binary, client.read(msg));
  19820. EXPECT_EQ(binary_data, msg);
  19821. client.close();
  19822. }
  19823. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  19824. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19825. "/ws-echo");
  19826. ASSERT_TRUE(client.connect());
  19827. for (int i = 0; i < 10; i++) {
  19828. auto text = "message " + std::to_string(i);
  19829. ASSERT_TRUE(client.send(text));
  19830. std::string msg;
  19831. ASSERT_TRUE(client.read(msg));
  19832. EXPECT_EQ(text, msg);
  19833. }
  19834. client.close();
  19835. }
  19836. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  19837. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19838. "/ws-close");
  19839. ASSERT_TRUE(client.connect());
  19840. // Send a message to trigger the server to close
  19841. ASSERT_TRUE(client.send("trigger close"));
  19842. // The server will close, so read should return false
  19843. std::string msg;
  19844. EXPECT_FALSE(client.read(msg));
  19845. EXPECT_FALSE(client.is_open());
  19846. }
  19847. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  19848. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19849. "/ws-echo");
  19850. ASSERT_TRUE(client.connect());
  19851. // 128KB message
  19852. std::string large_data(128 * 1024, 'X');
  19853. ASSERT_TRUE(client.send(large_data));
  19854. std::string msg;
  19855. ASSERT_TRUE(client.read(msg));
  19856. EXPECT_EQ(large_data, msg);
  19857. client.close();
  19858. }
  19859. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  19860. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19861. "/ws-echo");
  19862. ASSERT_TRUE(client.connect());
  19863. const int num_threads = 4;
  19864. std::vector<std::thread> threads;
  19865. std::atomic<int> send_count{0};
  19866. for (int t = 0; t < num_threads; t++) {
  19867. threads.emplace_back([&client, &send_count, t]() {
  19868. for (int i = 0; i < 5; i++) {
  19869. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19870. if (client.send(text)) { send_count++; }
  19871. }
  19872. });
  19873. }
  19874. for (auto &th : threads) {
  19875. th.join();
  19876. }
  19877. int received = 0;
  19878. std::string msg;
  19879. while (received < send_count.load()) {
  19880. if (!client.read(msg)) { break; }
  19881. received++;
  19882. }
  19883. EXPECT_EQ(send_count.load(), received);
  19884. client.close();
  19885. }
  19886. TEST_F(WebSocketIntegrationTest, ReadString) {
  19887. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19888. "/ws-echo-string");
  19889. ASSERT_TRUE(client.connect());
  19890. ASSERT_TRUE(client.send("hello"));
  19891. std::string msg;
  19892. ASSERT_TRUE(client.read(msg));
  19893. EXPECT_EQ("echo: hello", msg);
  19894. ASSERT_TRUE(client.send("world"));
  19895. ASSERT_TRUE(client.read(msg));
  19896. EXPECT_EQ("echo: world", msg);
  19897. client.close();
  19898. }
  19899. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19900. Headers headers = {{"X-Test-Header", "test-value"}};
  19901. ws::WebSocketClient client(
  19902. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19903. ASSERT_TRUE(client.connect());
  19904. std::string msg;
  19905. ASSERT_TRUE(client.read(msg));
  19906. EXPECT_EQ("path:/ws-request-info", msg);
  19907. ASSERT_TRUE(client.read(msg));
  19908. EXPECT_EQ("header:test-value", msg);
  19909. client.close();
  19910. }
  19911. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19912. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19913. "/ws-echo");
  19914. client.set_read_timeout(1, 0); // 1 second
  19915. ASSERT_TRUE(client.connect());
  19916. // Don't send anything — server echo handler waits for a message, so read()
  19917. // should time out. The connection survives it: nothing was consumed.
  19918. std::string msg;
  19919. EXPECT_EQ(client.read(msg), ws::Timeout);
  19920. EXPECT_TRUE(client.is_open());
  19921. // And it is still usable afterwards.
  19922. EXPECT_TRUE(client.send("after timeout"));
  19923. EXPECT_EQ(client.read(msg), ws::Text);
  19924. EXPECT_EQ(msg, "after timeout");
  19925. }
  19926. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  19927. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19928. "/ws-echo");
  19929. client.set_read_timeout(1, 0);
  19930. ASSERT_TRUE(client.connect());
  19931. ASSERT_TRUE(client.send("first"));
  19932. std::string msg;
  19933. ASSERT_EQ(client.read(msg), ws::Text);
  19934. ASSERT_EQ(msg, "first");
  19935. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  19936. // not be used with a read timeout: it would reprocess the previous message.
  19937. EXPECT_EQ(client.read(msg), ws::Timeout);
  19938. EXPECT_EQ(msg, "first");
  19939. }
  19940. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  19941. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19942. "/ws-echo");
  19943. ASSERT_TRUE(client.connect());
  19944. // Setting it once the connection is open reaches the live stream, not just
  19945. // the seed for the next connect().
  19946. client.set_read_timeout(1, 0);
  19947. std::string msg;
  19948. EXPECT_EQ(client.read(msg), ws::Timeout);
  19949. EXPECT_TRUE(client.is_open());
  19950. }
  19951. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  19952. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19953. "/ws-echo");
  19954. client.set_read_timeout(5, 0);
  19955. ASSERT_TRUE(client.connect());
  19956. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19957. // The server should reject it and close the connection.
  19958. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  19959. client.send(oversized);
  19960. // The server's read() should have failed due to payload limit,
  19961. // so our read() should return false (connection closed).
  19962. std::string msg;
  19963. EXPECT_FALSE(client.read(msg));
  19964. }
  19965. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  19966. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19967. "/ws-echo");
  19968. client.set_read_timeout(10, 0);
  19969. ASSERT_TRUE(client.connect());
  19970. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19971. // This should succeed.
  19972. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  19973. ASSERT_TRUE(client.send(at_limit));
  19974. std::string msg;
  19975. ASSERT_TRUE(client.read(msg));
  19976. EXPECT_EQ(at_limit.size(), msg.size());
  19977. client.close();
  19978. }
  19979. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  19980. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19981. "/nonexistent");
  19982. auto res = client.connect();
  19983. EXPECT_FALSE(res);
  19984. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19985. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  19986. EXPECT_FALSE(client.is_open());
  19987. }
  19988. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  19989. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19990. "/ws-echo");
  19991. ASSERT_TRUE(client.connect());
  19992. ASSERT_TRUE(client.send(""));
  19993. std::string msg;
  19994. EXPECT_EQ(ws::Text, client.read(msg));
  19995. EXPECT_EQ("", msg);
  19996. client.close();
  19997. }
  19998. TEST_F(WebSocketIntegrationTest, Reconnect) {
  19999. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20000. "/ws-echo");
  20001. // First connection
  20002. ASSERT_TRUE(client.connect());
  20003. ASSERT_TRUE(client.send("first"));
  20004. std::string msg;
  20005. ASSERT_TRUE(client.read(msg));
  20006. EXPECT_EQ("first", msg);
  20007. client.close();
  20008. EXPECT_FALSE(client.is_open());
  20009. // Reconnect using the same client object
  20010. ASSERT_TRUE(client.connect());
  20011. ASSERT_TRUE(client.is_open());
  20012. ASSERT_TRUE(client.send("second"));
  20013. ASSERT_TRUE(client.read(msg));
  20014. EXPECT_EQ("second", msg);
  20015. client.close();
  20016. }
  20017. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20018. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20019. "/ws-close-status");
  20020. ASSERT_TRUE(client.connect());
  20021. // Trigger the server to close with GoingAway status
  20022. ASSERT_TRUE(client.send("trigger"));
  20023. // read() should return false after receiving the close frame
  20024. std::string msg;
  20025. EXPECT_FALSE(client.read(msg));
  20026. EXPECT_FALSE(client.is_open());
  20027. }
  20028. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20029. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20030. "/ws-echo");
  20031. ASSERT_TRUE(client.connect());
  20032. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20033. EXPECT_FALSE(client.is_open());
  20034. }
  20035. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20036. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20037. ws::WebSocketClient client(
  20038. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20039. ASSERT_TRUE(client.connect());
  20040. // Server should have selected graphql-ws
  20041. EXPECT_EQ("graphql-ws", client.subprotocol());
  20042. client.close();
  20043. }
  20044. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20045. Headers headers;
  20046. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20047. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20048. ws::WebSocketClient client(
  20049. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20050. ASSERT_TRUE(client.connect());
  20051. // The offer on the second field line counts too, so graphql-ws is selected
  20052. EXPECT_EQ("graphql-ws", client.subprotocol());
  20053. client.close();
  20054. }
  20055. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20056. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20057. ws::WebSocketClient client(
  20058. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20059. ASSERT_TRUE(client.connect());
  20060. // Server should not have selected any subprotocol
  20061. EXPECT_TRUE(client.subprotocol().empty());
  20062. client.close();
  20063. }
  20064. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20065. // Connect without requesting any subprotocol
  20066. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20067. "/ws-subprotocol");
  20068. ASSERT_TRUE(client.connect());
  20069. EXPECT_TRUE(client.subprotocol().empty());
  20070. client.close();
  20071. }
  20072. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20073. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20074. "/ws-echo");
  20075. client.set_tcp_nodelay(true);
  20076. client.set_connection_timeout(3, 0);
  20077. bool socket_options_called = false;
  20078. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20079. ASSERT_TRUE(client.connect());
  20080. ASSERT_TRUE(client.is_open());
  20081. EXPECT_TRUE(socket_options_called);
  20082. ASSERT_TRUE(client.send("hello"));
  20083. std::string msg;
  20084. auto result = client.read(msg);
  20085. EXPECT_EQ(result, ws::ReadResult::Text);
  20086. EXPECT_EQ(msg, "hello");
  20087. client.close();
  20088. }
  20089. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20090. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20091. "/ws-echo");
  20092. client.set_connection_timeout(std::chrono::seconds(3));
  20093. client.set_write_timeout(std::chrono::seconds(3));
  20094. // A sub-second remainder exercises the seconds/microseconds split.
  20095. client.set_read_timeout(std::chrono::milliseconds(1500));
  20096. ASSERT_TRUE(client.connect());
  20097. auto start = std::chrono::steady_clock::now();
  20098. std::string msg;
  20099. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20100. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20101. std::chrono::steady_clock::now() - start)
  20102. .count();
  20103. // Above 1s so that dropping the microseconds half of the split fails here.
  20104. // Ignoring the setter altogether would not reach this line at all: a client
  20105. // waits forever by default.
  20106. EXPECT_GE(elapsed, 1400);
  20107. EXPECT_LT(elapsed, 30000);
  20108. }
  20109. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20110. Server svr;
  20111. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20112. if (!req.has_header("Authorization")) {
  20113. res.status = StatusCode::Unauthorized_401;
  20114. res.set_content("Unauthorized", "text/plain");
  20115. return Server::HandlerResponse::Handled;
  20116. }
  20117. return Server::HandlerResponse::Unhandled;
  20118. });
  20119. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20120. std::string msg;
  20121. while (ws.read(msg)) {
  20122. ws.send(msg);
  20123. }
  20124. });
  20125. auto port = svr.bind_to_any_port("localhost");
  20126. std::thread t([&]() { svr.listen_after_bind(); });
  20127. svr.wait_until_ready();
  20128. // Without Authorization header - should be rejected before upgrade
  20129. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20130. EXPECT_FALSE(client1.connect());
  20131. // The rejection is framed like any other HTTP response
  20132. {
  20133. Client cli("localhost", port);
  20134. Headers headers = {{"Upgrade", "websocket"},
  20135. {"Connection", "Upgrade"},
  20136. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20137. {"Sec-WebSocket-Version", "13"}};
  20138. auto res = cli.Get("/ws", headers);
  20139. ASSERT_TRUE(res);
  20140. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20141. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20142. EXPECT_EQ("Unauthorized", res->body);
  20143. }
  20144. // With Authorization header - should succeed
  20145. Headers headers = {{"Authorization", "Bearer token123"}};
  20146. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20147. headers);
  20148. ASSERT_TRUE(client2.connect());
  20149. ASSERT_TRUE(client2.send("hello"));
  20150. std::string msg;
  20151. ASSERT_TRUE(client2.read(msg));
  20152. EXPECT_EQ("hello", msg);
  20153. client2.close();
  20154. svr.stop();
  20155. t.join();
  20156. }
  20157. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20158. Server svr;
  20159. std::atomic<int> pre_request_calls{0};
  20160. std::atomic<bool> route_matched{false};
  20161. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20162. pre_request_calls++;
  20163. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20164. if (req.get_header_value("Authorization") != "Bearer token123") {
  20165. res.status = StatusCode::Unauthorized_401;
  20166. res.set_content("Unauthorized", "text/plain");
  20167. return Server::HandlerResponse::Handled;
  20168. }
  20169. return Server::HandlerResponse::Unhandled;
  20170. });
  20171. std::atomic<bool> handler_called{false};
  20172. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20173. handler_called = true;
  20174. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20175. });
  20176. auto port = svr.bind_to_any_port("localhost");
  20177. std::thread t([&]() { svr.listen_after_bind(); });
  20178. svr.wait_until_ready();
  20179. // Without Authorization header - should be rejected before upgrade
  20180. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20181. "/ws/1");
  20182. EXPECT_FALSE(client1.connect());
  20183. EXPECT_FALSE(handler_called);
  20184. EXPECT_EQ(1, pre_request_calls);
  20185. EXPECT_TRUE(route_matched);
  20186. // The rejection is an ordinary HTTP response, not a protocol switch
  20187. {
  20188. Client cli("localhost", port);
  20189. Headers headers = {{"Upgrade", "websocket"},
  20190. {"Connection", "Upgrade"},
  20191. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20192. {"Sec-WebSocket-Version", "13"}};
  20193. auto res = cli.Get("/ws/1", headers);
  20194. ASSERT_TRUE(res);
  20195. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20196. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20197. EXPECT_EQ("Unauthorized", res->body);
  20198. }
  20199. EXPECT_FALSE(handler_called);
  20200. // With Authorization header - should succeed
  20201. Headers headers = {{"Authorization", "Bearer token123"}};
  20202. ws::WebSocketClient client2(
  20203. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20204. ASSERT_TRUE(client2.connect());
  20205. std::string msg;
  20206. ASSERT_TRUE(client2.read(msg));
  20207. EXPECT_EQ("/ws/:id 2", msg);
  20208. EXPECT_TRUE(handler_called);
  20209. client2.close();
  20210. svr.stop();
  20211. t.join();
  20212. }
  20213. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20214. Server svr;
  20215. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20216. // A read timeout is how a handler gets control back. Without it, a handler
  20217. // parked in read() can never write on the connection it is reading.
  20218. ws.set_read_timeout(std::chrono::milliseconds(100));
  20219. std::string msg;
  20220. while (ws.is_open()) {
  20221. auto r = ws.read(msg);
  20222. if (r == httplib::ws::Timeout) {
  20223. ws.send("tick");
  20224. continue;
  20225. }
  20226. if (r == httplib::ws::Fail) { break; }
  20227. ws.send(msg);
  20228. }
  20229. });
  20230. auto port = svr.bind_to_any_port("localhost");
  20231. std::thread t([&]() { svr.listen_after_bind(); });
  20232. svr.wait_until_ready();
  20233. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20234. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20235. ASSERT_TRUE(client.connect());
  20236. // The client sends nothing, so anything it receives came out of the
  20237. // handler's timeout path.
  20238. std::string msg;
  20239. ASSERT_EQ(client.read(msg), ws::Text);
  20240. EXPECT_EQ("tick", msg);
  20241. client.close();
  20242. svr.stop();
  20243. t.join();
  20244. }
  20245. // Stream::read may return fewer bytes than asked for. This is that contract at
  20246. // its worst -- one byte per call -- which is what a frame header straddling a
  20247. // read buffer's boundary looks like to the frame parser.
  20248. class WsByteAtATimeStream : public Stream {
  20249. public:
  20250. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20251. bool is_readable() const override { return true; }
  20252. bool wait_readable() const override { return true; }
  20253. bool wait_writable() const override { return true; }
  20254. ssize_t read(char *ptr, size_t size) override {
  20255. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20256. *ptr = data_[pos_++];
  20257. return 1;
  20258. }
  20259. ssize_t write(const char *, size_t size) override {
  20260. return static_cast<ssize_t>(size);
  20261. }
  20262. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20263. ip = "127.0.0.1";
  20264. port = 0;
  20265. }
  20266. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20267. ip = "127.0.0.1";
  20268. port = 0;
  20269. }
  20270. socket_t socket() const override { return INVALID_SOCKET; }
  20271. time_t duration() const override { return 0; }
  20272. private:
  20273. std::string data_;
  20274. size_t pos_ = 0;
  20275. };
  20276. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20277. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20278. // length and the mask key are all multi-byte fields here. Each used to be
  20279. // read with a single read() call, which fails as soon as one is split.
  20280. std::string body(200, 'x');
  20281. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20282. std::string frame;
  20283. frame += static_cast<char>(0x81); // FIN + Text
  20284. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20285. frame += static_cast<char>(body.size() >> 8);
  20286. frame += static_cast<char>(body.size() & 0xff);
  20287. for (size_t i = 0; i < 4; i++) {
  20288. frame += static_cast<char>(mask[i]);
  20289. }
  20290. for (size_t i = 0; i < body.size(); i++) {
  20291. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20292. }
  20293. WsByteAtATimeStream strm(frame);
  20294. ws::Opcode opcode;
  20295. std::string payload;
  20296. bool fin = false;
  20297. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20298. /*expect_masked=*/true, 1024),
  20299. ws::impl::FrameRead::Ok);
  20300. EXPECT_TRUE(fin);
  20301. EXPECT_EQ(opcode, ws::Opcode::Text);
  20302. EXPECT_EQ(payload, body);
  20303. }
  20304. TEST(WebSocketTest, QueryStringInHandshake) {
  20305. Server svr;
  20306. std::mutex mtx;
  20307. std::string received_target;
  20308. std::string received_token;
  20309. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20310. {
  20311. std::lock_guard<std::mutex> lock(mtx);
  20312. received_target = req.target;
  20313. if (req.has_param("token")) {
  20314. received_token = req.get_param_value("token");
  20315. }
  20316. }
  20317. std::string msg;
  20318. while (ws.read(msg)) {
  20319. ws.send(msg);
  20320. }
  20321. });
  20322. auto port = svr.bind_to_any_port("localhost");
  20323. std::thread t([&]() { svr.listen_after_bind(); });
  20324. svr.wait_until_ready();
  20325. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20326. "/ws?token=ABC&session=123");
  20327. ASSERT_TRUE(client.connect());
  20328. // Round-trip ensures the handler has run and captured the request.
  20329. ASSERT_TRUE(client.send("hello"));
  20330. std::string msg;
  20331. ASSERT_TRUE(client.read(msg));
  20332. EXPECT_EQ("hello", msg);
  20333. client.close();
  20334. {
  20335. std::lock_guard<std::mutex> lock(mtx);
  20336. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20337. EXPECT_EQ("ABC", received_token);
  20338. }
  20339. svr.stop();
  20340. t.join();
  20341. }
  20342. // Run a handshake against a throwaway server and hand the request the server
  20343. // received back to the caller, so tests can assert on the headers the client
  20344. // actually put on the wire.
  20345. static void capture_websocket_handshake_request(
  20346. const Headers &client_headers,
  20347. std::function<void(const Request &, int port)> verify) {
  20348. Server svr;
  20349. std::mutex mtx;
  20350. Request received;
  20351. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20352. {
  20353. std::lock_guard<std::mutex> lock(mtx);
  20354. received = req;
  20355. }
  20356. std::string msg;
  20357. while (ws.read(msg)) {
  20358. ws.send(msg);
  20359. }
  20360. });
  20361. auto port = svr.bind_to_any_port("localhost");
  20362. std::thread t([&]() { svr.listen_after_bind(); });
  20363. auto se = detail::scope_exit([&] {
  20364. svr.stop();
  20365. t.join();
  20366. });
  20367. svr.wait_until_ready();
  20368. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20369. client_headers);
  20370. ASSERT_TRUE(client.connect());
  20371. ASSERT_TRUE(client.send("hello"));
  20372. std::string msg;
  20373. ASSERT_TRUE(client.read(msg));
  20374. client.close();
  20375. {
  20376. std::lock_guard<std::mutex> lock(mtx);
  20377. verify(received, port);
  20378. }
  20379. }
  20380. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20381. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20382. // Non-default port must be present in the Host header. Default ports
  20383. // (80/443) are omitted; that logic is covered by
  20384. // MakeHostAndPortStringTest.
  20385. EXPECT_EQ("localhost:" + std::to_string(port),
  20386. req.get_header_value("Host"));
  20387. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20388. req.get_header_value("User-Agent"));
  20389. EXPECT_FALSE(req.has_header("Accept"));
  20390. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20391. EXPECT_FALSE(req.has_header("Content-Length"));
  20392. });
  20393. }
  20394. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20395. capture_websocket_handshake_request(
  20396. {{"Host", "example.com"},
  20397. {"User-Agent", "custom-agent"},
  20398. {"X-Custom", "value"}},
  20399. [](const Request &req, int) {
  20400. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20401. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20402. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20403. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20404. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20405. });
  20406. }
  20407. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20408. capture_websocket_handshake_request(
  20409. {{"Upgrade", "bogus"},
  20410. {"Connection", "close"},
  20411. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20412. {"Sec-WebSocket-Version", "8"}},
  20413. [](const Request &req, int) {
  20414. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20415. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20416. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20417. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20418. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20419. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20420. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20421. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20422. req.get_header_value("Sec-WebSocket-Key"));
  20423. });
  20424. }
  20425. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20426. // A header the client refuses to send must abort the handshake before any
  20427. // part of it reaches the wire; a lone request line would otherwise sit in
  20428. // the peer's buffer as a truncated request.
  20429. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20430. ASSERT_NE(INVALID_SOCKET, srv);
  20431. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20432. sockaddr_in addr{};
  20433. addr.sin_family = AF_INET;
  20434. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20435. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20436. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20437. ASSERT_EQ(0, ::listen(srv, 1));
  20438. sockaddr_in bound{};
  20439. socklen_t bound_len = sizeof(bound);
  20440. ASSERT_EQ(
  20441. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20442. auto port = ntohs(bound.sin_port);
  20443. ssize_t received = -1;
  20444. std::thread t([&] {
  20445. // Bound every blocking call so a regression fails the test with a bad
  20446. // value instead of hanging the suite.
  20447. fd_set rfds;
  20448. FD_ZERO(&rfds);
  20449. FD_SET(srv, &rfds);
  20450. timeval tv{5, 0};
  20451. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20452. 0) {
  20453. return;
  20454. }
  20455. sockaddr_in cli_addr{};
  20456. socklen_t cli_len = sizeof(cli_addr);
  20457. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20458. if (cli == INVALID_SOCKET) { return; }
  20459. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20460. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20461. char buf[4096];
  20462. received = ::recv(cli, buf, sizeof(buf), 0);
  20463. });
  20464. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20465. // connect() has already shut the socket down by the time it returns false,
  20466. // so the peer sees EOF without waiting for the client to be destroyed.
  20467. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20468. {{"X-Bad", "a\r\nInjected: 1"}});
  20469. EXPECT_FALSE(client.connect());
  20470. t.join();
  20471. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20472. EXPECT_EQ(0, received);
  20473. }
  20474. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20475. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20476. // contains "upgrade" as a substring is a different token and must not
  20477. // start a WebSocket handshake.
  20478. auto make_request = [](const std::vector<std::string> &connection_values) {
  20479. Request req;
  20480. req.method = "GET";
  20481. req.headers.emplace("Upgrade", "websocket");
  20482. for (const auto &value : connection_values) {
  20483. req.headers.emplace("Connection", value);
  20484. }
  20485. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20486. req.headers.emplace("Sec-WebSocket-Version", "13");
  20487. return req;
  20488. };
  20489. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20490. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20491. EXPECT_TRUE(
  20492. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20493. EXPECT_TRUE(
  20494. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20495. EXPECT_TRUE(
  20496. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20497. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20498. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20499. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20500. EXPECT_FALSE(
  20501. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20502. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20503. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20504. }
  20505. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20506. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20507. // asks recipients to match each protocol-name case-insensitively, and RFC
  20508. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20509. // client naming websocket alongside another protocol, or on a second field
  20510. // line, is offering websocket; a value that merely contains "websocket" as a
  20511. // substring is a different protocol name and is not.
  20512. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20513. Request req;
  20514. req.method = "GET";
  20515. for (const auto &value : upgrade_values) {
  20516. req.headers.emplace("Upgrade", value);
  20517. }
  20518. req.headers.emplace("Connection", "Upgrade");
  20519. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20520. req.headers.emplace("Sec-WebSocket-Version", "13");
  20521. return req;
  20522. };
  20523. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20524. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20525. EXPECT_TRUE(
  20526. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20527. EXPECT_TRUE(
  20528. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20529. EXPECT_TRUE(
  20530. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20531. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20532. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20533. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20534. EXPECT_FALSE(
  20535. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20536. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20537. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20538. }
  20539. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20540. Server svr;
  20541. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20542. auto port = svr.bind_to_any_port("localhost");
  20543. std::thread t([&]() { svr.listen_after_bind(); });
  20544. auto se = detail::scope_exit([&] {
  20545. svr.stop();
  20546. t.join();
  20547. });
  20548. svr.wait_until_ready();
  20549. Headers headers = {{"Upgrade", "websocket"},
  20550. {"Connection", "notupgrade"},
  20551. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20552. {"Sec-WebSocket-Version", "13"}};
  20553. Client cli("localhost", port);
  20554. auto res = cli.Get("/ws", headers);
  20555. // The route exists only as a WebSocket route, so a request that fails the
  20556. // handshake check falls through to ordinary routing.
  20557. ASSERT_TRUE(res);
  20558. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20559. }
  20560. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20561. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20562. // Connection value is the only thing left for the client to reject.
  20563. Server svr;
  20564. svr.Get("/ws", [](const Request &req, Response &res) {
  20565. res.status = StatusCode::SwitchingProtocol_101;
  20566. res.set_header("Upgrade", "websocket");
  20567. res.set_header("Connection", "notupgrade");
  20568. res.set_header("Sec-WebSocket-Accept",
  20569. detail::websocket_accept_key(
  20570. req.get_header_value("Sec-WebSocket-Key")));
  20571. });
  20572. auto port = svr.bind_to_any_port("localhost");
  20573. std::thread t([&]() { svr.listen_after_bind(); });
  20574. auto se = detail::scope_exit([&] {
  20575. svr.stop();
  20576. t.join();
  20577. });
  20578. svr.wait_until_ready();
  20579. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20580. auto res = client.connect();
  20581. EXPECT_FALSE(res);
  20582. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20583. EXPECT_FALSE(client.is_open());
  20584. }
  20585. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20586. // The socket path doubles as the URL host, so it must not contain '/'.
  20587. const char *shard = getenv("GTEST_SHARD_INDEX");
  20588. const std::string sock_path =
  20589. shard ? std::string("httplib-ws-") + shard + ".sock"
  20590. : std::string("httplib-ws.sock");
  20591. std::remove(sock_path.c_str());
  20592. Server svr;
  20593. std::mutex mtx;
  20594. std::string received_host;
  20595. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20596. {
  20597. std::lock_guard<std::mutex> lock(mtx);
  20598. received_host = req.get_header_value("Host");
  20599. }
  20600. std::string msg;
  20601. while (ws.read(msg)) {
  20602. ws.send(msg);
  20603. }
  20604. });
  20605. svr.set_address_family(AF_UNIX);
  20606. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20607. auto se = detail::scope_exit([&] {
  20608. svr.stop();
  20609. t.join();
  20610. std::remove(sock_path.c_str());
  20611. });
  20612. svr.wait_until_ready();
  20613. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  20614. client.set_address_family(AF_UNIX);
  20615. ASSERT_TRUE(client.connect());
  20616. ASSERT_TRUE(client.send("hello"));
  20617. std::string msg;
  20618. ASSERT_TRUE(client.read(msg));
  20619. client.close();
  20620. {
  20621. std::lock_guard<std::mutex> lock(mtx);
  20622. // There is no host:port for a Unix socket, so the same "localhost"
  20623. // placeholder the HTTP client uses is expected.
  20624. EXPECT_EQ("localhost", received_host);
  20625. }
  20626. }
  20627. // Two threads must never parse WebSocket frames from the same stream.
  20628. // close() used to read the peer's Close reply with its own frame read, so it
  20629. // raced a reader thread that was in the middle of a payload: the payload loop
  20630. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  20631. // so bytes taken by close() were replaced with bytes from further along the
  20632. // stream. The message kept its length and silently changed content.
  20633. //
  20634. // The raw peer below sends a frame header plus part of the payload, waits for
  20635. // the handler to call close(), and only then sends the rest. Whichever thread
  20636. // would win the race for those bytes, the message must arrive intact, because
  20637. // close() must not touch the stream while read() owns it.
  20638. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  20639. #ifndef _WIN32
  20640. signal(SIGPIPE, SIG_IGN);
  20641. #endif
  20642. const size_t payload_len = 120; // fits the 7-bit length field
  20643. const size_t prefix_len = 8;
  20644. const int attempts = 8;
  20645. std::string expected(payload_len, '\0');
  20646. for (size_t i = 0; i < payload_len; i++) {
  20647. expected[i] = static_cast<char>('a' + i % 26);
  20648. }
  20649. std::atomic<bool> peer_stalled{false};
  20650. std::atomic<bool> handler_done{false};
  20651. std::mutex received_mutex;
  20652. std::vector<std::string> received;
  20653. // Bound every wait, so a regression fails the test instead of hanging the
  20654. // suite.
  20655. auto wait_for = [](const std::atomic<bool> &flag) {
  20656. for (int i = 0; i < 500 && !flag; i++) {
  20657. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20658. }
  20659. };
  20660. Server svr;
  20661. svr.set_websocket_ping_interval(0);
  20662. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  20663. std::thread reader([&]() {
  20664. std::string msg;
  20665. while (ws.read(msg)) {
  20666. std::lock_guard<std::mutex> guard(received_mutex);
  20667. received.push_back(msg);
  20668. }
  20669. });
  20670. // Wait until the peer stalls mid-payload, so the reader thread is parked
  20671. // inside read_websocket_frame() when close() runs.
  20672. wait_for(peer_stalled);
  20673. ws.close();
  20674. reader.join();
  20675. handler_done = true;
  20676. });
  20677. auto port = svr.bind_to_any_port("127.0.0.1");
  20678. std::thread t([&]() { svr.listen_after_bind(); });
  20679. auto se = detail::scope_exit([&] {
  20680. svr.stop();
  20681. t.join();
  20682. });
  20683. svr.wait_until_ready();
  20684. auto send_bytes = [](socket_t s, const std::string &data) {
  20685. #ifdef _WIN32
  20686. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  20687. #else
  20688. auto n = ::send(s, data.data(), data.size(), 0);
  20689. #endif
  20690. return n == static_cast<decltype(n)>(data.size());
  20691. };
  20692. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  20693. // Every length used here fits the 7-bit length field.
  20694. auto masked_header = [](uint8_t first_byte, size_t len) {
  20695. std::string h;
  20696. h += static_cast<char>(first_byte);
  20697. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  20698. h.append(4, '\0'); // mask key
  20699. return h;
  20700. };
  20701. for (int attempt = 0; attempt < attempts; attempt++) {
  20702. peer_stalled = false;
  20703. handler_done = false;
  20704. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  20705. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  20706. auto se_sock = detail::scope_exit([&] {
  20707. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  20708. });
  20709. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20710. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20711. sockaddr_in addr{};
  20712. addr.sin_family = AF_INET;
  20713. addr.sin_port = htons(static_cast<uint16_t>(port));
  20714. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20715. ASSERT_EQ(
  20716. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  20717. << "attempt " << attempt;
  20718. ASSERT_TRUE(send_bytes(sock,
  20719. "GET /ws HTTP/1.1\r\n"
  20720. "Host: 127.0.0.1\r\n"
  20721. "Upgrade: websocket\r\n"
  20722. "Connection: Upgrade\r\n"
  20723. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  20724. "Sec-WebSocket-Version: 13\r\n"
  20725. "\r\n"))
  20726. << "attempt " << attempt;
  20727. std::string response;
  20728. while (response.find("\r\n\r\n") == std::string::npos) {
  20729. char buf[512];
  20730. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  20731. if (n <= 0) { break; }
  20732. response.append(buf, static_cast<size_t>(n));
  20733. }
  20734. ASSERT_NE(std::string::npos, response.find(" 101 "))
  20735. << "attempt " << attempt;
  20736. // Send the header of a Binary message but only the first prefix_len bytes
  20737. // of its payload, leaving the reader thread stalled inside the payload.
  20738. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  20739. expected.substr(0, prefix_len)))
  20740. << "attempt " << attempt;
  20741. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20742. peer_stalled = true;
  20743. // Let close() send its Close frame and park in its own read before the
  20744. // rest of the payload arrives, so both threads are waiting for it.
  20745. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20746. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  20747. close_frame += static_cast<char>(0x03); // status 1000
  20748. close_frame += static_cast<char>(0xE8);
  20749. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  20750. << "attempt " << attempt;
  20751. // Closing the peer releases the reader thread even on the buggy path,
  20752. // where it waits for bytes another thread already consumed.
  20753. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20754. detail::close_socket(sock);
  20755. sock = INVALID_SOCKET;
  20756. wait_for(handler_done);
  20757. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  20758. }
  20759. std::lock_guard<std::mutex> guard(received_mutex);
  20760. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  20761. << "a message in flight when close() ran was dropped";
  20762. for (size_t i = 0; i < received.size(); i++) {
  20763. EXPECT_EQ(expected, received[i]) << "message " << i;
  20764. }
  20765. }
  20766. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20767. class WebSocketSSLIntegrationTest : public ::testing::Test {
  20768. protected:
  20769. void SetUp() override {
  20770. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  20771. SERVER_PRIVATE_KEY_FILE);
  20772. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20773. std::string msg;
  20774. ws::ReadResult ret;
  20775. while ((ret = ws.read(msg))) {
  20776. if (ret == ws::Binary) {
  20777. ws.send(msg.data(), msg.size());
  20778. } else {
  20779. ws.send(msg);
  20780. }
  20781. }
  20782. });
  20783. port_ = server_->bind_to_any_port(HOST);
  20784. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20785. server_->wait_until_ready();
  20786. }
  20787. void TearDown() override {
  20788. server_->stop();
  20789. if (server_thread_.joinable()) { server_thread_.join(); }
  20790. }
  20791. std::unique_ptr<SSLServer> server_;
  20792. std::thread server_thread_;
  20793. int port_ = 0;
  20794. };
  20795. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  20796. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20797. "/ws-echo");
  20798. client.enable_server_certificate_verification(false);
  20799. ASSERT_TRUE(client.connect());
  20800. ASSERT_TRUE(client.is_open());
  20801. ASSERT_TRUE(client.send("Hello WSS"));
  20802. std::string msg;
  20803. EXPECT_EQ(ws::Text, client.read(msg));
  20804. EXPECT_EQ("Hello WSS", msg);
  20805. client.close();
  20806. }
  20807. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  20808. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  20809. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  20810. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  20811. // client (without calling close() first) is the only path that runs
  20812. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  20813. // bug exactly.
  20814. //
  20815. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  20816. // when linked against an instrumented libssl; run under Valgrind to catch it
  20817. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  20818. // suite (the freed session otherwise stalls on the close handshake) — this test
  20819. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  20820. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  20821. {
  20822. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20823. "/ws-echo");
  20824. client.enable_server_certificate_verification(false);
  20825. client.set_read_timeout(2, 0);
  20826. client.set_write_timeout(2, 0);
  20827. ASSERT_TRUE(client.connect());
  20828. ASSERT_TRUE(client.is_open());
  20829. ASSERT_TRUE(client.send("still open"));
  20830. // Intentionally do NOT call client.close(): leaving scope runs
  20831. // shutdown_and_close() with the WebSocket still open, which must send the
  20832. // close frame while the TLS session is still alive.
  20833. }
  20834. }
  20835. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  20836. // shutdown_and_close() at the start of connect(), reproducing the same
  20837. // use-after-free within the test body rather than at scope exit. The second
  20838. // connect must succeed and echo, proving the close handshake ran over a live
  20839. // session. See the note above about memory-tool requirements.
  20840. TEST_F(WebSocketSSLIntegrationTest,
  20841. ReconnectWhileOpenSendsCloseOverLiveSession) {
  20842. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20843. "/ws-echo");
  20844. client.enable_server_certificate_verification(false);
  20845. client.set_read_timeout(2, 0);
  20846. client.set_write_timeout(2, 0);
  20847. ASSERT_TRUE(client.connect());
  20848. ASSERT_TRUE(client.is_open());
  20849. ASSERT_TRUE(client.send("still open"));
  20850. // Reconnect without closing first: connect() calls shutdown_and_close() on
  20851. // the still-open connection, which must not touch a freed TLS session.
  20852. ASSERT_TRUE(client.connect());
  20853. ASSERT_TRUE(client.is_open());
  20854. ASSERT_TRUE(client.send("after reconnect"));
  20855. std::string msg;
  20856. EXPECT_EQ(ws::Text, client.read(msg));
  20857. EXPECT_EQ("after reconnect", msg);
  20858. client.close();
  20859. }
  20860. #endif
  20861. #ifdef CPPHTTPLIB_SSL_ENABLED
  20862. class WebSocketSSLCATest : public ::testing::Test {
  20863. protected:
  20864. void SetUp() override {
  20865. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  20866. SERVER_PRIVATE_KEY_FILE);
  20867. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20868. std::string msg;
  20869. while (ws.read(msg)) {
  20870. ws.send(msg);
  20871. }
  20872. });
  20873. port_ = server_->bind_to_any_port("127.0.0.1");
  20874. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20875. server_->wait_until_ready();
  20876. }
  20877. void TearDown() override {
  20878. server_->stop();
  20879. if (server_thread_.joinable()) { server_thread_.join(); }
  20880. }
  20881. std::string url() const {
  20882. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  20883. }
  20884. std::unique_ptr<SSLServer> server_;
  20885. std::thread server_thread_;
  20886. int port_ = 0;
  20887. };
  20888. // A custom CA loaded as PEM verifies the server with full certificate
  20889. // verification enabled
  20890. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  20891. ws::WebSocketClient client(url());
  20892. std::string cert;
  20893. read_file(SERVER_CERT2_FILE, cert);
  20894. client.load_ca_cert_store(cert.c_str(), cert.size());
  20895. ASSERT_TRUE(client.connect());
  20896. ASSERT_TRUE(client.send("hello"));
  20897. std::string msg;
  20898. EXPECT_EQ(ws::Text, client.read(msg));
  20899. EXPECT_EQ("hello", msg);
  20900. client.close();
  20901. }
  20902. // A custom CA that does not cover the server must fail verification (the
  20903. // custom CA is exclusive; system certs are not loaded alongside it)
  20904. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  20905. ws::WebSocketClient client(url());
  20906. std::string cert;
  20907. read_file(CLIENT_CA_CERT_FILE, cert);
  20908. client.load_ca_cert_store(cert.c_str(), cert.size());
  20909. auto res = client.connect();
  20910. ASSERT_FALSE(res);
  20911. EXPECT_EQ(Error::SSLServerVerification, res.error());
  20912. EXPECT_EQ(-1, res.status());
  20913. EXPECT_NE(0u, res.ssl_backend_error());
  20914. }
  20915. // The same CA as a file path rather than PEM in memory
  20916. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  20917. ws::WebSocketClient client(url());
  20918. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20919. ASSERT_TRUE(client.connect());
  20920. ASSERT_TRUE(client.send("hello"));
  20921. std::string msg;
  20922. EXPECT_EQ(ws::Text, client.read(msg));
  20923. EXPECT_EQ("hello", msg);
  20924. client.close();
  20925. }
  20926. // ...and a CA file that does not cover the server still fails, so it is the
  20927. // path above that decides the outcome
  20928. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  20929. ws::WebSocketClient client(url());
  20930. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20931. ASSERT_FALSE(client.connect());
  20932. }
  20933. // Regression test: reconnecting with a native custom CA store used to reuse
  20934. // a store handle the previous TLS context had already freed (use-after-free
  20935. // under the OpenSSL backend). The context now lives as long as the client.
  20936. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  20937. ws::WebSocketClient client(url());
  20938. std::string cert;
  20939. read_file(SERVER_CERT2_FILE, cert);
  20940. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  20941. ASSERT_TRUE(client.connect());
  20942. client.close();
  20943. ASSERT_TRUE(client.connect());
  20944. ASSERT_TRUE(client.send("again"));
  20945. std::string msg;
  20946. EXPECT_EQ(ws::Text, client.read(msg));
  20947. EXPECT_EQ("again", msg);
  20948. client.close();
  20949. }
  20950. // Regression test: a certificate with a trusted chain but no identity match
  20951. // for the server IP must be rejected. The Mbed TLS backend used to skip
  20952. // verification entirely for IP hosts, so this connection succeeded there.
  20953. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  20954. // chain verification while the identity check must still fail.
  20955. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  20956. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20957. ASSERT_TRUE(svr.is_valid());
  20958. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20959. std::string msg;
  20960. while (ws.read(msg)) {
  20961. ws.send(msg);
  20962. }
  20963. });
  20964. auto port = svr.bind_to_any_port("127.0.0.1");
  20965. auto t = std::thread([&]() { svr.listen_after_bind(); });
  20966. auto se = detail::scope_exit([&] {
  20967. svr.stop();
  20968. t.join();
  20969. });
  20970. svr.wait_until_ready();
  20971. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  20972. "/echo");
  20973. std::string cert;
  20974. read_file(SERVER_CERT_FILE, cert);
  20975. client.load_ca_cert_store(cert.c_str(), cert.size());
  20976. ASSERT_FALSE(client.connect());
  20977. }
  20978. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  20979. // SNI, so nothing binds the host name to the TLS session. These bind the
  20980. // server to "localhost" instead, the only shape that exercises the SNI and
  20981. // hostname-verification path with certificate verification left enabled.
  20982. class WebSocketSSLDnsHostTest : public ::testing::Test {
  20983. protected:
  20984. void Start(const char *cert_file) {
  20985. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  20986. SERVER_PRIVATE_KEY_FILE);
  20987. ASSERT_TRUE(server_->is_valid());
  20988. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20989. std::string msg;
  20990. while (ws.read(msg)) {
  20991. ws.send(msg);
  20992. }
  20993. });
  20994. port_ = server_->bind_to_any_port("localhost");
  20995. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20996. server_->wait_until_ready();
  20997. }
  20998. void TearDown() override {
  20999. if (server_) { server_->stop(); }
  21000. if (server_thread_.joinable()) { server_thread_.join(); }
  21001. }
  21002. std::string url() const {
  21003. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21004. }
  21005. std::unique_ptr<SSLServer> server_;
  21006. std::thread server_thread_;
  21007. int port_ = 0;
  21008. };
  21009. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21010. // out and the connection is usable
  21011. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21012. Start(SERVER_CERT2_FILE);
  21013. ws::WebSocketClient client(url());
  21014. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21015. ASSERT_TRUE(client.connect());
  21016. ASSERT_TRUE(client.send("hello"));
  21017. std::string msg;
  21018. EXPECT_EQ(ws::Text, client.read(msg));
  21019. EXPECT_EQ("hello", msg);
  21020. client.close();
  21021. }
  21022. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21023. // while the identity check must still reject "localhost"
  21024. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21025. Start(SERVER_CERT_FILE);
  21026. ws::WebSocketClient client(url());
  21027. client.set_ca_cert_path(SERVER_CERT_FILE);
  21028. auto res = client.connect();
  21029. ASSERT_FALSE(res);
  21030. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21031. EXPECT_EQ(-1, res.status());
  21032. }
  21033. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21034. // disabled: the chain is still checked, only the identity check is skipped
  21035. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21036. Start(SERVER_CERT_FILE);
  21037. ws::WebSocketClient client(url());
  21038. client.set_ca_cert_path(SERVER_CERT_FILE);
  21039. client.enable_server_hostname_verification(false);
  21040. ASSERT_TRUE(client.connect());
  21041. ASSERT_TRUE(client.send("hello"));
  21042. std::string msg;
  21043. EXPECT_EQ(ws::Text, client.read(msg));
  21044. EXPECT_EQ("hello", msg);
  21045. client.close();
  21046. }
  21047. // A CA that did not sign the server certificate fails the chain, even though
  21048. // the name would match
  21049. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21050. Start(SERVER_CERT2_FILE);
  21051. ws::WebSocketClient client(url());
  21052. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21053. ASSERT_FALSE(client.connect());
  21054. }
  21055. // With verification disabled, neither the chain nor the name is checked
  21056. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21057. Start(SERVER_CERT_FILE);
  21058. ws::WebSocketClient client(url());
  21059. client.enable_server_certificate_verification(false);
  21060. ASSERT_TRUE(client.connect());
  21061. ASSERT_TRUE(client.send("hello"));
  21062. std::string msg;
  21063. EXPECT_EQ(ws::Text, client.read(msg));
  21064. EXPECT_EQ("hello", msg);
  21065. client.close();
  21066. }
  21067. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21068. protected:
  21069. void SetUp() override {
  21070. server_ = httplib::detail::make_unique<SSLServer>(
  21071. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21072. ASSERT_TRUE(server_->is_valid());
  21073. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21074. std::string msg;
  21075. while (ws.read(msg)) {
  21076. ws.send(msg);
  21077. }
  21078. });
  21079. port_ = server_->bind_to_any_port("localhost");
  21080. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21081. server_->wait_until_ready();
  21082. }
  21083. void TearDown() override {
  21084. server_->stop();
  21085. if (server_thread_.joinable()) { server_thread_.join(); }
  21086. }
  21087. std::string url() const {
  21088. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21089. }
  21090. void ConnectWithClientCert(const std::string &client_cert_file,
  21091. const std::string &client_private_key_file,
  21092. const char *private_key_password) {
  21093. std::string cert_pem, key_pem;
  21094. read_file(client_cert_file, cert_pem);
  21095. read_file(client_private_key_file, key_pem);
  21096. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21097. key_pem.c_str(), key_pem.size(),
  21098. private_key_password};
  21099. ws::WebSocketClient client(url(), pem);
  21100. ASSERT_TRUE(client.is_valid());
  21101. client.enable_server_certificate_verification(false);
  21102. ASSERT_TRUE(client.connect());
  21103. ASSERT_TRUE(client.send("hello"));
  21104. std::string msg;
  21105. EXPECT_EQ(ws::Text, client.read(msg));
  21106. EXPECT_EQ("hello", msg);
  21107. client.close();
  21108. }
  21109. std::unique_ptr<SSLServer> server_;
  21110. std::thread server_thread_;
  21111. int port_ = 0;
  21112. };
  21113. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21114. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21115. }
  21116. // Control for the tests above: the fixture's server really does require a
  21117. // client certificate, so it is the PEM the constructor installed that decides
  21118. // the outcome.
  21119. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21120. ws::WebSocketClient client(url());
  21121. ASSERT_TRUE(client.is_valid());
  21122. client.enable_server_certificate_verification(false);
  21123. EXPECT_FALSE(client.connect());
  21124. }
  21125. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21126. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21127. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21128. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21129. }
  21130. #endif
  21131. #if !defined(_WIN32)
  21132. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21133. auto secret_dir = std::string("./symlink_test_secret");
  21134. auto served_dir = std::string("./symlink_test_served");
  21135. auto secret_file = secret_dir + "/secret.txt";
  21136. auto symlink_path = served_dir + "/escape";
  21137. // Setup: create directories and files
  21138. mkdir(secret_dir.c_str(), 0755);
  21139. mkdir(served_dir.c_str(), 0755);
  21140. {
  21141. std::ofstream ofs(secret_file);
  21142. ofs << "SECRET_DATA";
  21143. }
  21144. // Create symlink using absolute path so it resolves correctly
  21145. #ifdef PATH_MAX
  21146. char abs_secret[PATH_MAX];
  21147. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21148. #else
  21149. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21150. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21151. ASSERT_NE(nullptr, abs_secret);
  21152. #endif
  21153. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21154. auto se = detail::scope_exit([&] {
  21155. unlink(symlink_path.c_str());
  21156. unlink(secret_file.c_str());
  21157. rmdir(served_dir.c_str());
  21158. rmdir(secret_dir.c_str());
  21159. });
  21160. Server svr;
  21161. svr.set_mount_point("/", served_dir);
  21162. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21163. auto se2 = detail::scope_exit([&] {
  21164. svr.stop();
  21165. listen_thread.join();
  21166. });
  21167. svr.wait_until_ready();
  21168. Client cli("localhost", PORT);
  21169. // Symlink pointing outside base dir should be blocked
  21170. auto res = cli.Get("/escape/secret.txt");
  21171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21172. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21173. }
  21174. #endif
  21175. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  21176. // "GET /smuggled" request), reads the first response, and only then sends the
  21177. // embedded request as the body. Returns how many times /smuggled ran.
  21178. //
  21179. // The body is sent AFTER receiving the first response (as in the original
  21180. // PoC) so that the stream_line_reader cannot buffer it together with the
  21181. // headers of the first request.
  21182. static int count_smuggled_requests(const std::string &outer_head,
  21183. std::string &first_response) {
  21184. Server svr;
  21185. svr.set_mount_point("/", "./www");
  21186. std::atomic<int> smuggled_count(0);
  21187. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21188. smuggled_count++;
  21189. res.set_content("oops", "text/plain");
  21190. });
  21191. svr.Post("/post", [&](const Request &req, Response &res) {
  21192. res.set_content(req.body, "text/plain");
  21193. });
  21194. auto port = svr.bind_to_any_port("localhost");
  21195. thread t = thread([&] { svr.listen_after_bind(); });
  21196. auto se = detail::scope_exit([&] {
  21197. svr.stop();
  21198. t.join();
  21199. });
  21200. svr.wait_until_ready();
  21201. auto error = Error::Success;
  21202. auto sock = detail::create_client_socket(
  21203. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21204. /*connection_timeout_sec=*/2, 0,
  21205. /*read_timeout_sec=*/2, 0,
  21206. /*write_timeout_sec=*/2, 0, std::string(), error);
  21207. EXPECT_NE(INVALID_SOCKET, sock);
  21208. if (sock == INVALID_SOCKET) { return -1; }
  21209. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21210. // The "smuggled" request will be sent as the body of the outer request
  21211. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21212. "Host: localhost\r\n"
  21213. "Connection: close\r\n"
  21214. "\r\n";
  21215. auto head = outer_head;
  21216. auto len = std::to_string(smuggled.size());
  21217. for (auto pos = head.find("{len}"); pos != std::string::npos;
  21218. pos = head.find("{len}", pos + len.size())) {
  21219. head.replace(pos, 5, len);
  21220. }
  21221. // Step 1: Send only the outer request headers (no body yet)
  21222. auto sent = send(sock, head.data(), head.size(), 0);
  21223. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  21224. // Step 2: Read the first response
  21225. char buf[4096];
  21226. for (;;) {
  21227. auto n = recv(sock, buf, sizeof(buf), 0);
  21228. if (n <= 0) break;
  21229. first_response.append(buf, static_cast<size_t>(n));
  21230. // Stop once we have a complete response (headers + body)
  21231. auto hdr_end = first_response.find("\r\n\r\n");
  21232. if (hdr_end != std::string::npos) {
  21233. // Check for Content-Length to know when the body is complete
  21234. auto cl_pos = first_response.find("Content-Length:");
  21235. if (cl_pos != std::string::npos) {
  21236. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21237. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21238. auto cl = std::stoul(
  21239. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21240. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21241. } else {
  21242. break; // No Content-Length, assume headers-only response
  21243. }
  21244. }
  21245. }
  21246. // Step 3: Now send the body, which looks like a new HTTP request. On a
  21247. // vulnerable server the keep-alive loop reads this as a second request. The
  21248. // server may already have closed the connection, so the result is ignored.
  21249. send(sock, smuggled.data(), smuggled.size(), 0);
  21250. // Half-close so that a server which drained the body sees EOF and closes,
  21251. // instead of the read below waiting for the read timeout.
  21252. #ifdef _WIN32
  21253. ::shutdown(sock, SD_SEND);
  21254. #else
  21255. ::shutdown(sock, SHUT_WR);
  21256. #endif
  21257. // Step 4: Read until the server closes the connection
  21258. for (;;) {
  21259. auto n = recv(sock, buf, sizeof(buf), 0);
  21260. if (n <= 0) break;
  21261. }
  21262. return smuggled_count.load();
  21263. }
  21264. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21265. // A GET request with Content-Length to a static file handler must have its
  21266. // body drained before the keep-alive connection is reused. Otherwise the
  21267. // unread body bytes are interpreted as the next HTTP request.
  21268. std::string first_response;
  21269. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21270. "Host: localhost\r\n"
  21271. "Content-Length: {len}\r\n"
  21272. "\r\n",
  21273. first_response));
  21274. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  21275. }
  21276. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  21277. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  21278. // be answered with 400 and the connection closed. Treating it as "no body"
  21279. // leaves the body to be parsed as the next request.
  21280. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  21281. const char *targets[] = {
  21282. "GET /file", // handler that never reads the body
  21283. "GET /not-found", // no handler matches (404)
  21284. "POST /post", // handler that reads the body
  21285. };
  21286. for (auto target : targets) {
  21287. for (auto value : values) {
  21288. std::string first_response;
  21289. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  21290. " HTTP/1.1\r\n"
  21291. "Host: localhost\r\n"
  21292. "Content-Length: " +
  21293. value + "\r\n\r\n",
  21294. first_response))
  21295. << target << " with Content-Length: " << value;
  21296. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  21297. << target << " with Content-Length: " << value;
  21298. }
  21299. }
  21300. }
  21301. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  21302. // A 400 for an unparseable request line leaves the rest of the message
  21303. // unread, so the connection must be closed rather than reused.
  21304. std::string first_response;
  21305. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  21306. "Host: localhost\r\n"
  21307. "Content-Length: {len}\r\n"
  21308. "\r\n",
  21309. first_response));
  21310. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21311. }
  21312. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  21313. // Same as above for a header block that fails to parse.
  21314. std::string first_response;
  21315. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21316. "Host: localhost\r\n"
  21317. "Bad Header\r\n"
  21318. "Content-Length: {len}\r\n"
  21319. "\r\n",
  21320. first_response));
  21321. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21322. }
  21323. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  21324. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  21325. // server must not read another request on that connection, even when the
  21326. // request had no body to drain.
  21327. std::string first_response;
  21328. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  21329. "Host: localhost\r\n"
  21330. "\r\n",
  21331. first_response));
  21332. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  21333. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  21334. }
  21335. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21336. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21337. // must be rejected with 400 Bad Request.
  21338. Server svr;
  21339. svr.Post("/test", [&](const Request &, Response &res) {
  21340. res.set_content("ok", "text/plain");
  21341. });
  21342. thread t = thread([&] { svr.listen(HOST, PORT); });
  21343. auto se = detail::scope_exit([&] {
  21344. svr.stop();
  21345. t.join();
  21346. ASSERT_FALSE(svr.is_running());
  21347. });
  21348. svr.wait_until_ready();
  21349. // Exact "chunked"
  21350. {
  21351. auto req = "POST /test HTTP/1.1\r\n"
  21352. "Host: localhost\r\n"
  21353. "Content-Length: 5\r\n"
  21354. "Transfer-Encoding: chunked\r\n"
  21355. "Connection: close\r\n"
  21356. "\r\n"
  21357. "hello";
  21358. std::string response;
  21359. ASSERT_TRUE(send_request(1, req, &response));
  21360. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21361. response.substr(0, response.find("\r\n")));
  21362. }
  21363. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21364. {
  21365. auto req = "POST /test HTTP/1.1\r\n"
  21366. "Host: localhost\r\n"
  21367. "Content-Length: 5\r\n"
  21368. "Transfer-Encoding: gzip, chunked\r\n"
  21369. "Connection: close\r\n"
  21370. "\r\n"
  21371. "hello";
  21372. std::string response;
  21373. ASSERT_TRUE(send_request(1, req, &response));
  21374. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21375. response.substr(0, response.find("\r\n")));
  21376. }
  21377. }
  21378. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21379. Server svr;
  21380. svr.Post("/test", [&](const Request &, Response &res) {
  21381. res.set_content("ok", "text/plain");
  21382. });
  21383. thread t = thread([&] { svr.listen(HOST, PORT); });
  21384. auto se = detail::scope_exit([&] {
  21385. svr.stop();
  21386. t.join();
  21387. ASSERT_FALSE(svr.is_running());
  21388. });
  21389. svr.wait_until_ready();
  21390. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21391. // length cannot be determined, so the server must answer 400 and close
  21392. // rather than treat the request as bodyless and leave the body in the
  21393. // socket for the next request to pick up.
  21394. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21395. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21396. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21397. std::string response;
  21398. ASSERT_TRUE(send_request(1, req, &response));
  21399. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21400. response.substr(0, response.find("\r\n")))
  21401. << transfer_encoding;
  21402. }
  21403. // RFC 9110 5.3: the codings may also be split across several
  21404. // Transfer-Encoding lines, which combine in the order they were received.
  21405. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21406. // just like the single-line "chunked, gzip" above.
  21407. {
  21408. auto req = "POST /test HTTP/1.1\r\n"
  21409. "Host: localhost\r\n"
  21410. "Transfer-Encoding: chunked\r\n"
  21411. "Transfer-Encoding: gzip\r\n"
  21412. "\r\n"
  21413. "0\r\n\r\n";
  21414. std::string response;
  21415. ASSERT_TRUE(send_request(1, req, &response));
  21416. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21417. response.substr(0, response.find("\r\n")));
  21418. }
  21419. // A sequence ending in chunked stays valid.
  21420. auto req = "POST /test HTTP/1.1\r\n"
  21421. "Host: localhost\r\n"
  21422. "Transfer-Encoding: gzip, chunked\r\n"
  21423. "Connection: close\r\n"
  21424. "\r\n"
  21425. "0\r\n\r\n";
  21426. std::string response;
  21427. ASSERT_TRUE(send_request(1, req, &response));
  21428. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21429. // ...including when it is spread over several lines.
  21430. auto split_req = "POST /test HTTP/1.1\r\n"
  21431. "Host: localhost\r\n"
  21432. "Transfer-Encoding: gzip\r\n"
  21433. "Transfer-Encoding: chunked\r\n"
  21434. "Connection: close\r\n"
  21435. "\r\n"
  21436. "0\r\n\r\n";
  21437. std::string split_response;
  21438. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21439. EXPECT_EQ("HTTP/1.1 200 OK",
  21440. split_response.substr(0, split_response.find("\r\n")));
  21441. }
  21442. // Regression for issue #2450: a DELETE without Content-Length on a
  21443. // keep-alive connection must not let the post-response drain consume the
  21444. // next request's bytes.
  21445. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21446. Server svr;
  21447. std::atomic<int> delete_count(0);
  21448. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21449. delete_count++;
  21450. res.status = StatusCode::NoContent_204;
  21451. });
  21452. auto port = svr.bind_to_any_port(HOST);
  21453. thread t = thread([&] { svr.listen_after_bind(); });
  21454. auto se = detail::scope_exit([&] {
  21455. svr.stop();
  21456. t.join();
  21457. });
  21458. svr.wait_until_ready();
  21459. auto error = Error::Success;
  21460. auto sock = detail::create_client_socket(
  21461. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21462. /*connection_timeout_sec=*/2, 0,
  21463. /*read_timeout_sec=*/2, 0,
  21464. /*write_timeout_sec=*/2, 0, std::string(), error);
  21465. ASSERT_NE(INVALID_SOCKET, sock);
  21466. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21467. auto send_request_and_read_response = [&](const std::string &req,
  21468. std::string &out) -> bool {
  21469. auto sent = send(sock, req.data(), req.size(), 0);
  21470. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21471. char buf[4096];
  21472. for (;;) {
  21473. auto n = recv(sock, buf, sizeof(buf), 0);
  21474. if (n <= 0) { return !out.empty(); }
  21475. out.append(buf, static_cast<size_t>(n));
  21476. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21477. }
  21478. };
  21479. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21480. "Host: localhost\r\n"
  21481. "\r\n";
  21482. std::string resp1;
  21483. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21484. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21485. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21486. "Host: localhost\r\n"
  21487. "Connection: close\r\n"
  21488. "\r\n";
  21489. std::string resp2;
  21490. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21491. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21492. EXPECT_EQ(2, delete_count.load());
  21493. }
  21494. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21495. Server svr;
  21496. svr.Post("/ingest", [&](const Request &, Response &res,
  21497. const ContentReader &content_reader) {
  21498. auto consumed = content_reader([](const char *, size_t) { return false; });
  21499. EXPECT_FALSE(consumed);
  21500. res.status = StatusCode::Conflict_409;
  21501. res.set_header("Connection", "close");
  21502. });
  21503. auto port = svr.bind_to_any_port(HOST);
  21504. thread t = thread([&] { svr.listen_after_bind(); });
  21505. auto se = detail::scope_exit([&] {
  21506. svr.stop();
  21507. t.join();
  21508. });
  21509. svr.wait_until_ready();
  21510. auto error = Error::Success;
  21511. auto sock = detail::create_client_socket(
  21512. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21513. /*connection_timeout_sec=*/2, 0,
  21514. /*read_timeout_sec=*/1, 0,
  21515. /*write_timeout_sec=*/2, 0, std::string(), error);
  21516. ASSERT_NE(INVALID_SOCKET, sock);
  21517. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21518. std::string request = "POST /ingest HTTP/1.1\r\n"
  21519. "Host: localhost\r\n"
  21520. "Transfer-Encoding: chunked\r\n"
  21521. "\r\n"
  21522. "4\r\n"
  21523. "data\r\n";
  21524. auto sent = send(sock, request.data(), request.size(), 0);
  21525. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21526. std::string response;
  21527. ssize_t received = 0;
  21528. do {
  21529. char buf[4096];
  21530. received = recv(sock, buf, sizeof(buf), 0);
  21531. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21532. } while (received > 0);
  21533. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21534. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21535. EXPECT_EQ(0, received);
  21536. }
  21537. namespace no_proxy_test {
  21538. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21539. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21540. // calling listen().
  21541. class ScopedServer {
  21542. public:
  21543. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21544. ~ScopedServer() {
  21545. svr_.stop();
  21546. if (th_.joinable()) { th_.join(); }
  21547. }
  21548. Server &svr() { return svr_; }
  21549. int port() const { return port_; }
  21550. void listen() {
  21551. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21552. svr_.wait_until_ready();
  21553. }
  21554. private:
  21555. Server svr_;
  21556. std::thread th_;
  21557. int port_ = 0;
  21558. };
  21559. class ProxyAndTargetServers {
  21560. public:
  21561. ProxyAndTargetServers() {
  21562. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21563. proxy_hits_++;
  21564. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21565. res.set_content("via-proxy", "text/plain");
  21566. });
  21567. target_.Get(".*", [this](const Request &req, Response &res) {
  21568. target_hits_++;
  21569. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21570. res.set_content("direct", "text/plain");
  21571. });
  21572. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21573. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21574. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21575. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21576. proxy_mock_.wait_until_ready();
  21577. target_.wait_until_ready();
  21578. }
  21579. ~ProxyAndTargetServers() {
  21580. proxy_mock_.stop();
  21581. target_.stop();
  21582. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21583. if (target_thread_.joinable()) { target_thread_.join(); }
  21584. }
  21585. Server &proxy_mock() { return proxy_mock_; }
  21586. Server &target() { return target_; }
  21587. int proxy_port() const { return proxy_port_; }
  21588. int target_port() const { return target_port_; }
  21589. int proxy_hits() const { return proxy_hits_.load(); }
  21590. int target_hits() const { return target_hits_.load(); }
  21591. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21592. void reset_counters() {
  21593. proxy_hits_ = 0;
  21594. target_hits_ = 0;
  21595. last_had_proxy_authz_ = false;
  21596. }
  21597. private:
  21598. Server proxy_mock_;
  21599. Server target_;
  21600. std::thread proxy_thread_;
  21601. std::thread target_thread_;
  21602. int proxy_port_ = 0;
  21603. int target_port_ = 0;
  21604. std::atomic<int> proxy_hits_{0};
  21605. std::atomic<int> target_hits_{0};
  21606. std::atomic<bool> last_had_proxy_authz_{false};
  21607. };
  21608. inline std::unique_ptr<Client> make_client(const std::string &host,
  21609. ProxyAndTargetServers &s) {
  21610. auto cli = detail::make_unique<Client>(host, s.target_port());
  21611. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  21612. cli->set_proxy("127.0.0.1", s.proxy_port());
  21613. return cli;
  21614. }
  21615. } // namespace no_proxy_test
  21616. using no_proxy_test::make_client;
  21617. using no_proxy_test::ProxyAndTargetServers;
  21618. TEST(NoProxyTest, ExactHostnameBypasses) {
  21619. ProxyAndTargetServers s;
  21620. auto cli = make_client("example.com", s);
  21621. cli->set_no_proxy({"example.com"});
  21622. auto res = cli->Get("/");
  21623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21624. EXPECT_EQ(0, s.proxy_hits());
  21625. EXPECT_EQ(1, s.target_hits());
  21626. }
  21627. TEST(NoProxyTest, SubdomainBypasses) {
  21628. ProxyAndTargetServers s;
  21629. auto cli = make_client("foo.example.com", s);
  21630. cli->set_no_proxy({"example.com"});
  21631. auto res = cli->Get("/");
  21632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21633. EXPECT_EQ(0, s.proxy_hits());
  21634. EXPECT_EQ(1, s.target_hits());
  21635. }
  21636. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  21637. // Regression guard: "evilexample.com" must not be considered a subdomain
  21638. // of "example.com". Without the dot-boundary rule, a naive endsWith
  21639. // check would let traffic bypass the proxy and leak credentials direct
  21640. // to the attacker host.
  21641. ProxyAndTargetServers s;
  21642. auto cli = make_client("evilexample.com", s);
  21643. cli->set_no_proxy({"example.com"});
  21644. auto res = cli->Get("/");
  21645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21646. EXPECT_GE(s.proxy_hits(), 1);
  21647. EXPECT_EQ(0, s.target_hits());
  21648. }
  21649. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  21650. ProxyAndTargetServers s;
  21651. auto cli = make_client("example.com.evil.com", s);
  21652. cli->set_no_proxy({"example.com"});
  21653. auto res = cli->Get("/");
  21654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21655. EXPECT_GE(s.proxy_hits(), 1);
  21656. EXPECT_EQ(0, s.target_hits());
  21657. }
  21658. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  21659. ProxyAndTargetServers s;
  21660. auto cli = make_client("example.com", s);
  21661. cli->set_no_proxy({".example.com"});
  21662. auto res = cli->Get("/");
  21663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21664. EXPECT_EQ(0, s.proxy_hits());
  21665. EXPECT_EQ(1, s.target_hits());
  21666. }
  21667. TEST(NoProxyTest, CaseInsensitiveHostname) {
  21668. ProxyAndTargetServers s;
  21669. auto cli = make_client("Example.COM", s);
  21670. cli->set_no_proxy({"EXAMPLE.com"});
  21671. auto res = cli->Get("/");
  21672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21673. EXPECT_EQ(0, s.proxy_hits());
  21674. EXPECT_EQ(1, s.target_hits());
  21675. }
  21676. TEST(NoProxyTest, TrailingDotIsNormalized) {
  21677. ProxyAndTargetServers s;
  21678. auto cli = make_client("example.com.", s);
  21679. cli->set_no_proxy({"example.com"});
  21680. auto res = cli->Get("/");
  21681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21682. EXPECT_EQ(0, s.proxy_hits());
  21683. EXPECT_EQ(1, s.target_hits());
  21684. }
  21685. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  21686. // Trailing dots must be normalized on BOTH sides — host and entry.
  21687. // An implementation that only strips the host-side trailing dot would
  21688. // fail to match host "example.com" against entry "example.com." because
  21689. // a literal substring search would compare 11 chars against 12.
  21690. ProxyAndTargetServers s;
  21691. auto cli = make_client("example.com", s);
  21692. cli->set_no_proxy({"example.com."});
  21693. auto res = cli->Get("/");
  21694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21695. EXPECT_EQ(0, s.proxy_hits());
  21696. EXPECT_EQ(1, s.target_hits());
  21697. }
  21698. TEST(NoProxyTest, WildcardBypassesEverything) {
  21699. ProxyAndTargetServers s;
  21700. auto cli = make_client("anything.invalid.test", s);
  21701. cli->set_no_proxy({"*"});
  21702. auto res = cli->Get("/");
  21703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21704. EXPECT_EQ(0, s.proxy_hits());
  21705. EXPECT_EQ(1, s.target_hits());
  21706. }
  21707. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  21708. ProxyAndTargetServers s;
  21709. Client cli("127.0.0.1", s.target_port());
  21710. cli.set_proxy("127.0.0.1", s.proxy_port());
  21711. cli.set_no_proxy({"127.0.0.1"});
  21712. auto res = cli.Get("/");
  21713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21714. EXPECT_EQ(0, s.proxy_hits());
  21715. EXPECT_EQ(1, s.target_hits());
  21716. }
  21717. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  21718. ProxyAndTargetServers s;
  21719. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  21720. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  21721. cli.set_proxy("127.0.0.1", s.proxy_port());
  21722. cli.set_no_proxy({"::1"});
  21723. auto res = cli.Get("/");
  21724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21725. EXPECT_EQ(0, s.proxy_hits());
  21726. EXPECT_EQ(1, s.target_hits());
  21727. }
  21728. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  21729. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  21730. // must still be recognized as IPv6 for CIDR matching. Implementations
  21731. // that detect IPv6 only when the host begins with '[' would parse the
  21732. // host as a hostname and miss the match.
  21733. ProxyAndTargetServers s;
  21734. Client cli("fe80::1", s.target_port());
  21735. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21736. cli.set_proxy("127.0.0.1", s.proxy_port());
  21737. cli.set_no_proxy({"fe80::/10"});
  21738. auto res = cli.Get("/");
  21739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21740. EXPECT_EQ(0, s.proxy_hits());
  21741. EXPECT_EQ(1, s.target_hits());
  21742. }
  21743. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  21744. ProxyAndTargetServers s;
  21745. Client cli("::1", s.target_port());
  21746. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  21747. cli.set_proxy("127.0.0.1", s.proxy_port());
  21748. cli.set_no_proxy({"[::1]"});
  21749. auto res = cli.Get("/");
  21750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21751. EXPECT_EQ(0, s.proxy_hits());
  21752. EXPECT_EQ(1, s.target_hits());
  21753. }
  21754. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  21755. ProxyAndTargetServers s;
  21756. Client cli("fe80::1", s.target_port());
  21757. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21758. cli.set_proxy("127.0.0.1", s.proxy_port());
  21759. cli.set_no_proxy({"[fe80::]/10"});
  21760. auto res = cli.Get("/");
  21761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21762. EXPECT_EQ(0, s.proxy_hits());
  21763. EXPECT_EQ(1, s.target_hits());
  21764. }
  21765. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  21766. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  21767. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  21768. // tricks via address-family conversion.
  21769. ProxyAndTargetServers s;
  21770. Client cli("::ffff:127.0.0.1", s.target_port());
  21771. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  21772. cli.set_proxy("127.0.0.1", s.proxy_port());
  21773. cli.set_no_proxy({"127.0.0.1"});
  21774. auto res = cli.Get("/");
  21775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21776. EXPECT_GE(s.proxy_hits(), 1);
  21777. EXPECT_EQ(0, s.target_hits());
  21778. }
  21779. TEST(NoProxyTest, IPv4CidrMatch) {
  21780. ProxyAndTargetServers s;
  21781. Client cli("127.0.0.1", s.target_port());
  21782. cli.set_proxy("127.0.0.1", s.proxy_port());
  21783. cli.set_no_proxy({"127.0.0.0/8"});
  21784. auto res = cli.Get("/");
  21785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21786. EXPECT_EQ(0, s.proxy_hits());
  21787. EXPECT_EQ(1, s.target_hits());
  21788. }
  21789. TEST(NoProxyTest, IPv4CidrNonMatch) {
  21790. ProxyAndTargetServers s;
  21791. Client cli("127.0.0.1", s.target_port());
  21792. cli.set_proxy("127.0.0.1", s.proxy_port());
  21793. cli.set_no_proxy({"10.0.0.0/8"});
  21794. auto res = cli.Get("/");
  21795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21796. EXPECT_GE(s.proxy_hits(), 1);
  21797. EXPECT_EQ(0, s.target_hits());
  21798. }
  21799. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  21800. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  21801. // IPv4 target matches.
  21802. ProxyAndTargetServers s;
  21803. Client cli("127.0.0.1", s.target_port());
  21804. cli.set_proxy("127.0.0.1", s.proxy_port());
  21805. cli.set_no_proxy({"0.0.0.0/0"});
  21806. auto res = cli.Get("/");
  21807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21808. EXPECT_EQ(0, s.proxy_hits());
  21809. EXPECT_EQ(1, s.target_hits());
  21810. }
  21811. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  21812. ProxyAndTargetServers s;
  21813. Client cli("127.0.0.1", s.target_port());
  21814. cli.set_proxy("127.0.0.1", s.proxy_port());
  21815. cli.set_no_proxy({"127.0.0.1"});
  21816. auto res = cli.Get("/");
  21817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21818. EXPECT_EQ(0, s.proxy_hits());
  21819. EXPECT_EQ(1, s.target_hits());
  21820. }
  21821. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  21822. ProxyAndTargetServers s;
  21823. Client cli("127.0.0.1", s.target_port());
  21824. cli.set_proxy("127.0.0.1", s.proxy_port());
  21825. cli.set_no_proxy({"127.0.0.0/33"});
  21826. auto res = cli.Get("/");
  21827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21828. EXPECT_GE(s.proxy_hits(), 1);
  21829. EXPECT_EQ(0, s.target_hits());
  21830. }
  21831. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  21832. // Empty prefix after the slash must be rejected, not silently treated as /32.
  21833. ProxyAndTargetServers s;
  21834. Client cli("127.0.0.1", s.target_port());
  21835. cli.set_proxy("127.0.0.1", s.proxy_port());
  21836. cli.set_no_proxy({"127.0.0.1/"});
  21837. auto res = cli.Get("/");
  21838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21839. EXPECT_GE(s.proxy_hits(), 1);
  21840. EXPECT_EQ(0, s.target_hits());
  21841. }
  21842. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  21843. ProxyAndTargetServers s;
  21844. auto cli = make_client("internal.corp", s);
  21845. cli->set_proxy_basic_auth("u", "p");
  21846. cli->set_no_proxy({"internal.corp"});
  21847. auto res = cli->Get("/");
  21848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21849. EXPECT_EQ(1, s.target_hits());
  21850. EXPECT_EQ(0, s.proxy_hits());
  21851. EXPECT_FALSE(s.last_had_proxy_authz())
  21852. << "Proxy-Authorization must not be sent direct to the target";
  21853. }
  21854. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  21855. ProxyAndTargetServers s;
  21856. auto cli = make_client("public.example", s);
  21857. cli->set_proxy_basic_auth("u", "p");
  21858. cli->set_no_proxy({"internal.corp"}); // does not match
  21859. auto res = cli->Get("/");
  21860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21861. EXPECT_GE(s.proxy_hits(), 1);
  21862. EXPECT_TRUE(s.last_had_proxy_authz());
  21863. }
  21864. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  21865. ProxyAndTargetServers s;
  21866. auto cli = make_client("anything.test", s);
  21867. auto res = cli->Get("/");
  21868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21869. EXPECT_GE(s.proxy_hits(), 1);
  21870. EXPECT_EQ(0, s.target_hits());
  21871. }
  21872. TEST(NoProxyTest, PortSpecificEntryRejected) {
  21873. ProxyAndTargetServers s;
  21874. auto cli = make_client("example.com", s);
  21875. cli->set_no_proxy({"example.com:8080"});
  21876. auto res = cli->Get("/");
  21877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21878. EXPECT_GE(s.proxy_hits(), 1);
  21879. EXPECT_EQ(0, s.target_hits());
  21880. }
  21881. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  21882. ProxyAndTargetServers s;
  21883. auto cli = make_client("anything.test", s);
  21884. cli->set_no_proxy({"", " ", "\t"});
  21885. auto res = cli->Get("/");
  21886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21887. EXPECT_GE(s.proxy_hits(), 1);
  21888. EXPECT_EQ(0, s.target_hits());
  21889. }
  21890. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  21891. // An entry with leading/trailing whitespace must still match — env-style
  21892. // values are commonly pasted with stray spaces and an implementation
  21893. // that feeds the raw token directly to inet_pton would fail to match
  21894. // valid CIDRs because of the spaces.
  21895. ProxyAndTargetServers s;
  21896. Client cli("127.0.0.1", s.target_port());
  21897. cli.set_proxy("127.0.0.1", s.proxy_port());
  21898. cli.set_no_proxy({" 127.0.0.0/8 "});
  21899. auto res = cli.Get("/");
  21900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21901. EXPECT_EQ(0, s.proxy_hits());
  21902. EXPECT_EQ(1, s.target_hits());
  21903. }
  21904. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  21905. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  21906. // go direct and must NOT carry Proxy-Authorization.
  21907. std::atomic<int> proxy_hits{0};
  21908. std::atomic<int> target_hits{0};
  21909. std::atomic<bool> target_saw_authz{false};
  21910. no_proxy_test::ScopedServer proxy_mock, target;
  21911. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21912. proxy_hits++;
  21913. res.status = 302;
  21914. res.set_header("Location", "http://127.0.0.1:" +
  21915. std::to_string(target.port()) + "/landed");
  21916. });
  21917. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21918. target_hits++;
  21919. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  21920. res.set_content("direct", "text/plain");
  21921. });
  21922. proxy_mock.listen();
  21923. target.listen();
  21924. Client cli("public.example", target.port());
  21925. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21926. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21927. cli.set_proxy_basic_auth("u", "p");
  21928. cli.set_no_proxy({"127.0.0.1"});
  21929. cli.set_follow_location(true);
  21930. auto res = cli.Get("/redir");
  21931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21932. EXPECT_GE(proxy_hits.load(), 1);
  21933. EXPECT_GE(target_hits.load(), 1);
  21934. EXPECT_FALSE(target_saw_authz.load());
  21935. }
  21936. #ifdef CPPHTTPLIB_SSL_ENABLED
  21937. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  21938. // Direct origin replying 407 must not trigger the digest retry; otherwise
  21939. // proxy creds would be sent to the (possibly hostile) origin.
  21940. std::atomic<int> target_hits{0};
  21941. std::atomic<bool> target_saw_proxy_authz{false};
  21942. no_proxy_test::ScopedServer target;
  21943. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21944. target_hits++;
  21945. if (req.has_header("Proxy-Authorization")) {
  21946. target_saw_proxy_authz = true;
  21947. }
  21948. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21949. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  21950. "nonce=\"abc\", algorithm=MD5");
  21951. });
  21952. target.listen();
  21953. // The proxy address is set to the target's port: the bypass MUST kick in;
  21954. // if it doesn't, the test still routes "via proxy" to the same server and
  21955. // the Proxy-Authorization assertion below catches the leak.
  21956. Client cli("evil.example", target.port());
  21957. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  21958. cli.set_proxy("127.0.0.1", target.port());
  21959. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21960. cli.set_no_proxy({"evil.example"});
  21961. auto res = cli.Get("/x");
  21962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21963. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21964. EXPECT_EQ(1, target_hits.load());
  21965. EXPECT_FALSE(target_saw_proxy_authz.load());
  21966. }
  21967. #endif
  21968. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  21969. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  21970. std::atomic<int> proxy_hits{0};
  21971. std::atomic<int> bypass_hits{0};
  21972. std::atomic<bool> proxy_saw_c_url{false};
  21973. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  21974. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  21975. proxy_hits++;
  21976. if (req.path.find("/start") != std::string::npos) {
  21977. res.status = 302;
  21978. res.set_header("Location", "http://127.0.0.1:" +
  21979. std::to_string(bypass_server.port()) +
  21980. "/middle");
  21981. return;
  21982. }
  21983. if (req.path.find("/end") != std::string::npos) {
  21984. proxy_saw_c_url = true;
  21985. res.set_content("c-via-proxy", "text/plain");
  21986. return;
  21987. }
  21988. res.set_content("unexpected", "text/plain");
  21989. });
  21990. // public.example's "advertised" port is arbitrary (the request never lands
  21991. // there — it goes through the proxy), but use a dynamic value to stay
  21992. // friendly with sharded parallel runs.
  21993. int public_port = bypass_server.port();
  21994. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  21995. bypass_hits++;
  21996. res.status = 302;
  21997. res.set_header("Location", "http://public.example:" +
  21998. std::to_string(public_port) + "/end");
  21999. });
  22000. proxy_mock.listen();
  22001. bypass_server.listen();
  22002. Client cli("public.example", public_port);
  22003. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22004. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22005. cli.set_no_proxy({"127.0.0.1"});
  22006. cli.set_follow_location(true);
  22007. auto res = cli.Get("/start");
  22008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22009. EXPECT_EQ(StatusCode::OK_200, res->status);
  22010. EXPECT_EQ("c-via-proxy", res->body);
  22011. EXPECT_GE(proxy_hits.load(), 2);
  22012. EXPECT_GE(bypass_hits.load(), 1);
  22013. EXPECT_TRUE(proxy_saw_c_url.load());
  22014. }
  22015. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  22016. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  22017. // request reconnects to the correct endpoint.
  22018. std::atomic<int> proxy_hits{0};
  22019. std::atomic<int> target_hits{0};
  22020. no_proxy_test::ScopedServer proxy_mock, target;
  22021. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22022. proxy_hits++;
  22023. res.set_content("via-proxy", "text/plain");
  22024. });
  22025. target.svr().Get(".*", [&](const Request &, Response &res) {
  22026. target_hits++;
  22027. res.set_content("direct", "text/plain");
  22028. });
  22029. proxy_mock.listen();
  22030. target.listen();
  22031. Client cli("public.example", target.port());
  22032. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22033. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22034. cli.set_keep_alive(true);
  22035. auto res1 = cli.Get("/a");
  22036. ASSERT_TRUE(res1);
  22037. EXPECT_EQ("via-proxy", res1->body);
  22038. EXPECT_EQ(1, proxy_hits.load());
  22039. EXPECT_EQ(0, target_hits.load());
  22040. cli.set_no_proxy({"public.example"});
  22041. auto res2 = cli.Get("/b");
  22042. ASSERT_TRUE(res2);
  22043. EXPECT_EQ("direct", res2->body);
  22044. EXPECT_EQ(1, proxy_hits.load());
  22045. EXPECT_EQ(1, target_hits.load());
  22046. }
  22047. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  22048. namespace proxy_tunnel_test {
  22049. // SSLServer counterpart to no_proxy_test::ScopedServer.
  22050. class ScopedSSLServer {
  22051. public:
  22052. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  22053. port_ = svr_.bind_to_any_port("127.0.0.1");
  22054. }
  22055. ~ScopedSSLServer() {
  22056. svr_.stop();
  22057. if (th_.joinable()) { th_.join(); }
  22058. }
  22059. SSLServer &svr() { return svr_; }
  22060. int port() const { return port_; }
  22061. void listen() {
  22062. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22063. svr_.wait_until_ready();
  22064. }
  22065. private:
  22066. SSLServer svr_;
  22067. std::thread th_;
  22068. int port_ = 0;
  22069. };
  22070. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  22071. class ScopedConnectProxy {
  22072. public:
  22073. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  22074. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  22075. if (listen_fd_ < 0) { return; }
  22076. int yes = 1;
  22077. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  22078. sockaddr_in a{};
  22079. a.sin_family = AF_INET;
  22080. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22081. a.sin_port = 0;
  22082. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  22083. return;
  22084. }
  22085. socklen_t alen = sizeof(a);
  22086. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22087. 0) {
  22088. return;
  22089. }
  22090. port_ = ntohs(a.sin_port);
  22091. if (::listen(listen_fd_, 1) != 0) { return; }
  22092. th_ = std::thread([this] { run(); });
  22093. }
  22094. ~ScopedConnectProxy() {
  22095. stop_ = true;
  22096. if (listen_fd_ >= 0) {
  22097. ::shutdown(listen_fd_, SHUT_RDWR);
  22098. ::close(listen_fd_);
  22099. }
  22100. if (th_.joinable()) { th_.join(); }
  22101. }
  22102. int port() const { return port_; }
  22103. int connect_hits() const { return connect_hits_.load(); }
  22104. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22105. std::string connect_request() const {
  22106. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22107. return connect_request_;
  22108. }
  22109. private:
  22110. void run() {
  22111. while (!stop_.load()) {
  22112. fd_set rfds;
  22113. FD_ZERO(&rfds);
  22114. FD_SET(listen_fd_, &rfds);
  22115. timeval tv{0, 100 * 1000};
  22116. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22117. if (sel <= 0) { continue; }
  22118. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22119. if (client_fd < 0) { continue; }
  22120. std::string req;
  22121. char buf[2048];
  22122. while (req.find("\r\n\r\n") == std::string::npos) {
  22123. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22124. if (n <= 0) { break; }
  22125. req.append(buf, static_cast<size_t>(n));
  22126. }
  22127. if (req.compare(0, 7, "CONNECT") != 0) {
  22128. ::close(client_fd);
  22129. continue;
  22130. }
  22131. connect_hits_++;
  22132. {
  22133. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22134. connect_request_ = req;
  22135. }
  22136. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22137. ::send(client_fd, ok, std::strlen(ok), 0);
  22138. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22139. sockaddr_in o{};
  22140. o.sin_family = AF_INET;
  22141. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22142. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22143. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22144. 0) {
  22145. ::close(client_fd);
  22146. ::close(origin_fd);
  22147. continue;
  22148. }
  22149. auto forward = [](int from, int to) {
  22150. char b[8192];
  22151. for (;;) {
  22152. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22153. if (n <= 0) { break; }
  22154. ssize_t off = 0;
  22155. while (off < n) {
  22156. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22157. if (s <= 0) {
  22158. off = n;
  22159. break;
  22160. }
  22161. off += s;
  22162. }
  22163. }
  22164. ::shutdown(to, SHUT_WR);
  22165. };
  22166. std::thread t1([&] { forward(client_fd, origin_fd); });
  22167. std::thread t2([&] { forward(origin_fd, client_fd); });
  22168. t1.join();
  22169. t2.join();
  22170. ::close(client_fd);
  22171. ::close(origin_fd);
  22172. }
  22173. }
  22174. int forward_port_ = -1;
  22175. int listen_fd_ = -1;
  22176. int port_ = 0;
  22177. std::thread th_;
  22178. std::atomic<bool> stop_{false};
  22179. std::atomic<int> connect_hits_{0};
  22180. mutable std::mutex connect_request_mutex_;
  22181. std::string connect_request_;
  22182. };
  22183. // Sends one request through the CONNECT proxy to the TLS origin with a
  22184. // credential configured for each hop, and checks that each credential reaches
  22185. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22186. // origin's (every header in origin_headers) on the tunnelled request.
  22187. void CredentialsStayWithTheirHop(
  22188. const std::function<void(SSLClient &)> &set_credentials,
  22189. const std::string &scheme,
  22190. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22191. std::atomic<int> origin_hits{0};
  22192. std::atomic<bool> origin_saw_proxy_authz{false};
  22193. std::atomic<bool> origin_saw_headers{false};
  22194. ScopedSSLServer origin;
  22195. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22196. origin_hits++;
  22197. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22198. origin_saw_headers =
  22199. std::all_of(origin_headers.begin(), origin_headers.end(),
  22200. [&](const std::string &h) { return req.has_header(h); });
  22201. res.set_content("ok", "text/plain");
  22202. });
  22203. origin.listen();
  22204. ScopedConnectProxy proxy(origin.port());
  22205. ASSERT_NE(0, proxy.port());
  22206. // Pinned to 127.0.0.1 for the same reason as the test below.
  22207. SSLClient cli("127.0.0.1", origin.port());
  22208. cli.enable_server_certificate_verification(false);
  22209. cli.set_proxy("127.0.0.1", proxy.port());
  22210. set_credentials(cli);
  22211. auto res = cli.Get("/x");
  22212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22213. EXPECT_EQ(StatusCode::OK_200, res->status);
  22214. EXPECT_EQ(1, origin_hits.load());
  22215. EXPECT_EQ(1, proxy.connect_hits());
  22216. EXPECT_TRUE(origin_saw_headers.load());
  22217. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22218. << "Proxy-Authorization must not be sent inside the tunnel";
  22219. auto connect_req = proxy.connect_request();
  22220. EXPECT_NE(std::string::npos,
  22221. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22222. for (const auto &h : origin_headers) {
  22223. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22224. << h << " must not be sent to the proxy on CONNECT";
  22225. }
  22226. }
  22227. } // namespace proxy_tunnel_test
  22228. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22229. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22230. [](SSLClient &cli) {
  22231. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22232. cli.set_basic_auth("origin-user", "origin-pass");
  22233. },
  22234. "Basic");
  22235. }
  22236. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22237. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22238. [](SSLClient &cli) {
  22239. cli.set_proxy_bearer_token_auth("proxy-token");
  22240. cli.set_bearer_token_auth("origin-token");
  22241. },
  22242. "Bearer");
  22243. }
  22244. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22245. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22246. [](SSLClient &cli) {
  22247. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22248. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22249. {"Cookie", "sid=origin-session"},
  22250. {"X-Api-Key", "origin-key"}});
  22251. },
  22252. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22253. }
  22254. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22255. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22256. // retry; otherwise proxy creds would be sent to the origin.
  22257. std::atomic<int> origin_hits{0};
  22258. std::atomic<bool> origin_saw_proxy_authz{false};
  22259. proxy_tunnel_test::ScopedSSLServer origin;
  22260. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22261. origin_hits++;
  22262. if (req.has_header("Proxy-Authorization")) {
  22263. origin_saw_proxy_authz = true;
  22264. }
  22265. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22266. res.set_header("Proxy-Authenticate",
  22267. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22268. "algorithm=MD5");
  22269. });
  22270. origin.listen();
  22271. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22272. ASSERT_NE(0, proxy.port());
  22273. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22274. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22275. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22276. // and answer with its own status, making this test flaky.
  22277. SSLClient cli("127.0.0.1", origin.port());
  22278. cli.enable_server_certificate_verification(false);
  22279. cli.set_proxy("127.0.0.1", proxy.port());
  22280. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22281. auto res = cli.Get("/x");
  22282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22283. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22284. EXPECT_EQ(1, origin_hits.load());
  22285. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22286. EXPECT_EQ(1, proxy.connect_hits());
  22287. }
  22288. #endif