test.cc 860 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605
  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. // A root missing from the trust store is left to CryptoAPI, which must still
  11741. // reject a chain whose root Windows does not trust either.
  11742. TEST(SSLClientTest, WindowsCertificateVerification_UnknownIssuerRejected) {
  11743. // Issued by the test root CA, which is not in the Windows root store
  11744. SSLServer svr(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11745. ASSERT_TRUE(svr.is_valid());
  11746. svr.Get("/", [](const Request &, Response &res) {
  11747. res.set_content("ok", "text/plain");
  11748. });
  11749. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11750. auto se = detail::scope_exit([&] {
  11751. svr.stop();
  11752. t.join();
  11753. ASSERT_FALSE(svr.is_running());
  11754. });
  11755. svr.wait_until_ready();
  11756. SSLClient cli(HOST, PORT);
  11757. // Keep the hostname check from failing first
  11758. cli.enable_server_hostname_verification(false);
  11759. auto res = cli.Get("/");
  11760. ASSERT_FALSE(res);
  11761. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11762. }
  11763. #endif
  11764. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11765. Client cli("https://google.com");
  11766. auto res = cli.Get("/");
  11767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11768. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11769. }
  11770. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11771. SSLClient cli("google.com");
  11772. cli.set_ca_cert_path(CA_CERT_FILE);
  11773. auto res = cli.Get("/");
  11774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11775. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11776. }
  11777. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11778. SSLClient cli("google.com");
  11779. cli.enable_server_certificate_verification(true);
  11780. cli.set_ca_cert_path("hello");
  11781. auto res = cli.Get("/");
  11782. ASSERT_TRUE(!res);
  11783. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11784. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11785. // should be set
  11786. EXPECT_EQ(0, res.ssl_error());
  11787. // Verify backend error is captured for SSLLoadingCerts
  11788. // This error occurs when loading CA certificates fails
  11789. EXPECT_NE(0UL, res.ssl_backend_error());
  11790. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11791. // OpenSSL specific error codes:
  11792. // > openssl errstr 0x80000002
  11793. // error:80000002:system library::No such file or directory
  11794. // > openssl errstr 0xA000126
  11795. // error:0A000126:SSL routines::unexpected eof while reading
  11796. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11797. res.ssl_backend_error() == 0xA000126);
  11798. #endif
  11799. }
  11800. TEST(SSLClientTest, ServerCertificateVerification4) {
  11801. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11802. ASSERT_TRUE(svr.is_valid());
  11803. svr.Get("/test", [&](const Request &, Response &res) {
  11804. res.set_content("test", "text/plain");
  11805. svr.stop();
  11806. ASSERT_TRUE(true);
  11807. });
  11808. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11809. auto se = detail::scope_exit([&] {
  11810. t.join();
  11811. ASSERT_FALSE(svr.is_running());
  11812. });
  11813. svr.wait_until_ready();
  11814. SSLClient cli("127.0.0.1", PORT);
  11815. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11816. cli.enable_server_certificate_verification(true);
  11817. cli.set_connection_timeout(30);
  11818. auto res = cli.Get("/test");
  11819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11820. ASSERT_EQ(StatusCode::OK_200, res->status);
  11821. }
  11822. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11823. std::string cert;
  11824. read_file(CA_CERT_FILE, cert);
  11825. SSLClient cli("google.com");
  11826. cli.load_ca_cert_store(cert.data(), cert.size());
  11827. const auto res = cli.Get("/");
  11828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11829. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11830. }
  11831. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11832. // clang-format off
  11833. static constexpr char cert[] =
  11834. "GlobalSign Root CA\n"
  11835. "==================\n"
  11836. "-----BEGIN CERTIFICATE-----\n"
  11837. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11838. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11839. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11840. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11841. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11842. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11843. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11844. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11845. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11846. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11847. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11848. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11849. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11850. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11851. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11852. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11853. "-----END CERTIFICATE-----\n";
  11854. // clang-format on
  11855. SSLClient cli("google.com");
  11856. cli.load_ca_cert_store(cert, sizeof(cert));
  11857. const auto res = cli.Get("/");
  11858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11859. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11860. }
  11861. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11862. SSLClient cli("www.youtube.com");
  11863. cli.set_ca_cert_path(CA_CERT_FILE);
  11864. cli.enable_server_certificate_verification(true);
  11865. cli.set_follow_location(true);
  11866. auto res = cli.Get("/");
  11867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11868. ASSERT_EQ(StatusCode::OK_200, res->status);
  11869. }
  11870. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11871. SSLClient cli("wWw.YouTube.Com");
  11872. cli.set_ca_cert_path(CA_CERT_FILE);
  11873. cli.enable_server_certificate_verification(true);
  11874. cli.enable_server_hostname_verification(true);
  11875. cli.set_follow_location(true);
  11876. auto res = cli.Get("/");
  11877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11878. ASSERT_EQ(StatusCode::OK_200, res->status);
  11879. }
  11880. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11881. SSLClient cli("gOoGlE.COm");
  11882. cli.enable_server_certificate_verification(true);
  11883. cli.enable_server_hostname_verification(true);
  11884. cli.set_follow_location(true);
  11885. auto res = cli.Get("/");
  11886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11887. ASSERT_EQ(StatusCode::OK_200, res->status);
  11888. }
  11889. TEST(SSLClientTest, Issue2004_Online) {
  11890. Client client("https://google.com");
  11891. client.set_follow_location(true);
  11892. auto res = client.Get("/");
  11893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11894. ASSERT_EQ(StatusCode::OK_200, res->status);
  11895. auto body = res->body;
  11896. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11897. }
  11898. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11899. // Create SSLClient with invalid cert/key to make is_valid() return false
  11900. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11901. "nonexistent_key.pem");
  11902. // is_valid() should be false due to cert loading failure
  11903. ASSERT_FALSE(cli.is_valid());
  11904. auto res = cli.Get("/");
  11905. ASSERT_FALSE(res);
  11906. EXPECT_EQ(Error::SSLConnection, res.error());
  11907. }
  11908. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11909. // Test for Issue #2251: SSL error not properly reported when client cert
  11910. // and key paths are swapped or mismatched
  11911. // This simulates the scenario where user accidentally swaps the cert and key
  11912. // files
  11913. // Using client cert file as private key and vice versa (completely wrong)
  11914. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11915. // Should fail validation due to cert/key mismatch
  11916. ASSERT_FALSE(cli.is_valid());
  11917. // Attempt to make a request should fail with proper error
  11918. auto res = cli.Get("/");
  11919. ASSERT_FALSE(res);
  11920. EXPECT_EQ(Error::SSLConnection, res.error());
  11921. // SSL error should be recorded in the Result object (this is the key fix for
  11922. // Issue #2251)
  11923. auto backend_error = res.ssl_backend_error();
  11924. EXPECT_NE(0u, backend_error);
  11925. }
  11926. // Tests cert/key mismatch detection at the TLS context level
  11927. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11928. // Test that using mismatched cert/key causes connection failure.
  11929. // We verify this at the SSLClient level rather than through internal
  11930. // TLS API functions.
  11931. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11932. cli.enable_server_certificate_verification(false);
  11933. cli.set_connection_timeout(2);
  11934. // The mismatch should cause a connection or handshake error
  11935. auto res = cli.Get("/test");
  11936. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11937. // Either way, the request should fail
  11938. EXPECT_FALSE(res);
  11939. }
  11940. #endif
  11941. #if 0
  11942. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11943. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11944. ASSERT_TRUE(cli != nullptr);
  11945. cli->set_address_family(AF_INET6);
  11946. cli->set_interface("en0");
  11947. auto res = cli->Get("/get");
  11948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11949. ASSERT_EQ(StatusCode::OK_200, res->status);
  11950. }
  11951. #endif
  11952. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11953. #ifdef CPPHTTPLIB_SSL_ENABLED
  11954. void ClientCertPresent(
  11955. const std::string &client_cert_file,
  11956. const std::string &client_private_key_file,
  11957. const std::string &client_encrypted_private_key_pass = std::string()) {
  11958. using namespace httplib::tls;
  11959. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11960. CLIENT_CA_CERT_DIR);
  11961. ASSERT_TRUE(svr.is_valid());
  11962. svr.Get("/test", [&](const Request &req, Response &res) {
  11963. res.set_content("test", "text/plain");
  11964. auto cert = req.peer_cert();
  11965. ASSERT_TRUE(static_cast<bool>(cert));
  11966. std::string common_name = cert.subject_cn();
  11967. EXPECT_EQ("Common Name", common_name);
  11968. });
  11969. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11970. auto se = detail::scope_exit([&] {
  11971. svr.stop();
  11972. t.join();
  11973. ASSERT_FALSE(svr.is_running());
  11974. });
  11975. svr.wait_until_ready();
  11976. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11977. client_encrypted_private_key_pass);
  11978. cli.enable_server_certificate_verification(false);
  11979. cli.set_connection_timeout(30);
  11980. auto res = cli.Get("/test");
  11981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11982. ASSERT_EQ(StatusCode::OK_200, res->status);
  11983. }
  11984. TEST(SSLClientServerTest, ClientCertPresent) {
  11985. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11986. }
  11987. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11988. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11989. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11990. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11991. }
  11992. // PEM memory-based constructor tests (works with all TLS backends)
  11993. void PemMemoryClientCertPresent(
  11994. const std::string &client_cert_file,
  11995. const std::string &client_private_key_file,
  11996. const std::string &client_encrypted_private_key_pass = std::string()) {
  11997. // Read PEM files into memory
  11998. std::string server_cert_pem, server_key_pem;
  11999. std::string client_ca_pem;
  12000. std::string client_cert_pem, client_key_pem;
  12001. read_file(SERVER_CERT_FILE, server_cert_pem);
  12002. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12003. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12004. read_file(client_cert_file, client_cert_pem);
  12005. read_file(client_private_key_file, client_key_pem);
  12006. // Create server with PEM memory
  12007. SSLServer::PemMemory server_pem = {
  12008. server_cert_pem.c_str(),
  12009. server_cert_pem.size(),
  12010. server_key_pem.c_str(),
  12011. server_key_pem.size(),
  12012. client_ca_pem.c_str(),
  12013. client_ca_pem.size(),
  12014. nullptr // no password for server key
  12015. };
  12016. SSLServer svr(server_pem);
  12017. ASSERT_TRUE(svr.is_valid());
  12018. svr.Get("/test", [&](const Request &, Response &res) {
  12019. res.set_content("test", "text/plain");
  12020. });
  12021. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12022. auto se = detail::scope_exit([&] {
  12023. svr.stop();
  12024. t.join();
  12025. ASSERT_FALSE(svr.is_running());
  12026. });
  12027. svr.wait_until_ready();
  12028. // Create client with PEM memory
  12029. const char *password = client_encrypted_private_key_pass.empty()
  12030. ? nullptr
  12031. : client_encrypted_private_key_pass.c_str();
  12032. SSLClient::PemMemory client_pem = {
  12033. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12034. client_key_pem.size(), password};
  12035. SSLClient cli(HOST, PORT, client_pem);
  12036. cli.enable_server_certificate_verification(false);
  12037. cli.set_connection_timeout(30);
  12038. auto res = cli.Get("/test");
  12039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12040. ASSERT_EQ(StatusCode::OK_200, res->status);
  12041. }
  12042. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12043. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12044. }
  12045. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12046. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12047. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12048. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12049. }
  12050. TEST(SSLClientServerTest, ClientCertMissing) {
  12051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12052. CLIENT_CA_CERT_DIR);
  12053. ASSERT_TRUE(svr.is_valid());
  12054. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12055. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12056. auto se = detail::scope_exit([&] {
  12057. svr.stop();
  12058. t.join();
  12059. ASSERT_FALSE(svr.is_running());
  12060. });
  12061. svr.wait_until_ready();
  12062. SSLClient cli(HOST, PORT);
  12063. cli.set_connection_timeout(30);
  12064. auto res = cli.Get("/test");
  12065. ASSERT_TRUE(!res);
  12066. // When client cert is missing and server requires it, connection fails
  12067. // Error type depends on backend implementation
  12068. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12069. res.error() == Error::SSLConnection);
  12070. // Verify backend error is captured
  12071. // Note: This test may have different error codes depending on the exact
  12072. // verification failure
  12073. EXPECT_NE(0UL, res.ssl_backend_error());
  12074. }
  12075. TEST(SSLClientServerTest, TrustDirOptional) {
  12076. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12077. ASSERT_TRUE(svr.is_valid());
  12078. svr.Get("/test", [&](const Request &, Response &res) {
  12079. res.set_content("test", "text/plain");
  12080. });
  12081. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12082. auto se = detail::scope_exit([&] {
  12083. svr.stop();
  12084. t.join();
  12085. ASSERT_FALSE(svr.is_running());
  12086. });
  12087. svr.wait_until_ready();
  12088. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12089. cli.enable_server_certificate_verification(false);
  12090. cli.set_connection_timeout(30);
  12091. auto res = cli.Get("/test");
  12092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12093. ASSERT_EQ(StatusCode::OK_200, res->status);
  12094. }
  12095. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12096. class NoListenSSLServer : public SSLServer {
  12097. public:
  12098. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12099. const char *client_ca_cert_file_path,
  12100. const char *client_ca_cert_dir_path = nullptr)
  12101. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12102. client_ca_cert_dir_path),
  12103. stop_(false) {}
  12104. std::atomic_bool stop_;
  12105. private:
  12106. bool process_and_close_socket(socket_t /*sock*/) override {
  12107. // Don't create SSL context
  12108. while (!stop_.load()) {
  12109. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12110. }
  12111. return true;
  12112. }
  12113. };
  12114. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12115. CLIENT_CA_CERT_FILE);
  12116. ASSERT_TRUE(svr.is_valid());
  12117. svr.Get("/test", [&](const Request &, Response &res) {
  12118. res.set_content("test", "text/plain");
  12119. });
  12120. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12121. auto se = detail::scope_exit([&] {
  12122. svr.stop_ = true;
  12123. svr.stop();
  12124. t.join();
  12125. ASSERT_FALSE(svr.is_running());
  12126. });
  12127. svr.wait_until_ready();
  12128. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12129. cli.enable_server_certificate_verification(false);
  12130. cli.set_connection_timeout(1);
  12131. auto res = cli.Get("/test");
  12132. ASSERT_TRUE(!res);
  12133. EXPECT_EQ(Error::SSLConnection, res.error());
  12134. // Timeout results in WantRead error code (maps to backend-specific value)
  12135. EXPECT_NE(0, res.ssl_error());
  12136. }
  12137. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12138. // Test SSLServer with client certificate verification using the standard
  12139. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12141. CLIENT_CA_CERT_DIR);
  12142. ASSERT_TRUE(svr.is_valid());
  12143. svr.Get("/test", [&](const Request &req, Response &res) {
  12144. res.set_content("test", "text/plain");
  12145. auto cert = req.peer_cert();
  12146. ASSERT_TRUE(static_cast<bool>(cert));
  12147. auto common_name = cert.subject_cn();
  12148. EXPECT_EQ("Common Name", common_name);
  12149. });
  12150. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12151. auto se = detail::scope_exit([&] {
  12152. svr.stop();
  12153. t.join();
  12154. ASSERT_FALSE(svr.is_running());
  12155. });
  12156. svr.wait_until_ready();
  12157. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12158. cli.enable_server_certificate_verification(false);
  12159. cli.set_connection_timeout(30);
  12160. auto res = cli.Get("/test");
  12161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12162. ASSERT_EQ(StatusCode::OK_200, res->status);
  12163. }
  12164. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12165. // Verifies that wildcard matching and exact matching work consistently
  12166. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12167. using namespace httplib::tls;
  12168. // We need a running server to test against
  12169. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12170. ASSERT_TRUE(svr.is_valid());
  12171. svr.Get("/test", [](const Request &, Response &res) {
  12172. res.set_content("ok", "text/plain");
  12173. });
  12174. thread t([&]() { svr.listen(HOST, PORT); });
  12175. auto se = detail::scope_exit([&] {
  12176. svr.stop();
  12177. t.join();
  12178. });
  12179. svr.wait_until_ready();
  12180. bool verify_callback_called = false;
  12181. bool verify_result_wrong = false;
  12182. SSLClient cli(HOST, PORT);
  12183. cli.enable_server_certificate_verification(true);
  12184. cli.set_ca_cert_path(CA_CERT_FILE);
  12185. cli.set_connection_timeout(5);
  12186. // Note: Test certificate has CN="Common Name", not "localhost"
  12187. bool verify_result_cn = false;
  12188. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12189. verify_callback_called = true;
  12190. if (!ctx.cert) return false;
  12191. // Test 1: "Common Name" should match (our test server cert CN)
  12192. verify_result_cn = ctx.check_hostname("Common Name");
  12193. // Test 2: wrong hostname should not match
  12194. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12195. return true; // Accept for the purpose of this test
  12196. });
  12197. auto res = cli.Get("/test");
  12198. // The request may succeed or fail depending on cert configuration
  12199. // but the callback should have been called
  12200. ASSERT_TRUE(verify_callback_called)
  12201. << "Verify callback should have been called";
  12202. // CN="Common Name" should match our test certificate
  12203. //
  12204. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12205. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12206. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12207. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12208. // <openssl/base.h>, which is included transitively when
  12209. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12210. #if defined(OPENSSL_IS_BORINGSSL)
  12211. EXPECT_FALSE(verify_result_cn)
  12212. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12213. #else
  12214. EXPECT_TRUE(verify_result_cn)
  12215. << "verify_hostname should match 'Common Name' (certificate CN)";
  12216. #endif
  12217. // Wrong hostname should not match
  12218. EXPECT_FALSE(verify_result_wrong)
  12219. << "verify_hostname should not match 'wronghost.example.com'";
  12220. }
  12221. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12222. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12223. // X509_check_ip behavior and must hold for every backend.
  12224. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12225. using namespace httplib::tls;
  12226. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12227. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12228. ASSERT_TRUE(svr.is_valid());
  12229. svr.Get("/test", [](const Request &, Response &res) {
  12230. res.set_content("ok", "text/plain");
  12231. });
  12232. thread t([&]() { svr.listen(HOST, PORT); });
  12233. auto se = detail::scope_exit([&] {
  12234. svr.stop();
  12235. t.join();
  12236. });
  12237. svr.wait_until_ready();
  12238. bool verify_callback_called = false;
  12239. bool ip_matched_via_cn = true;
  12240. SSLClient cli(HOST, PORT);
  12241. cli.enable_server_certificate_verification(true);
  12242. cli.set_ca_cert_path(CA_CERT_FILE);
  12243. cli.set_connection_timeout(5);
  12244. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12245. verify_callback_called = true;
  12246. if (!ctx.cert) return false;
  12247. // The IP appears only in the CN, so it must NOT be accepted.
  12248. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12249. return true; // Accept for the purpose of this test
  12250. });
  12251. cli.Get("/test");
  12252. ASSERT_TRUE(verify_callback_called)
  12253. << "Verify callback should have been called";
  12254. EXPECT_FALSE(ip_matched_via_cn)
  12255. << "An IP host must not be authenticated via the certificate CN";
  12256. }
  12257. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12258. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12259. using namespace httplib::tls;
  12260. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12261. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12262. ASSERT_TRUE(svr.is_valid());
  12263. svr.Get("/test", [](const Request &, Response &res) {
  12264. res.set_content("ok", "text/plain");
  12265. });
  12266. thread t([&]() { svr.listen(HOST, PORT); });
  12267. auto se = detail::scope_exit([&] {
  12268. svr.stop();
  12269. t.join();
  12270. });
  12271. svr.wait_until_ready();
  12272. bool verify_callback_called = false;
  12273. bool san_matched = false;
  12274. bool wrong_ipv6_matched = true;
  12275. bool cn_ipv6_matched = true;
  12276. SSLClient cli(HOST, PORT);
  12277. cli.enable_server_certificate_verification(true);
  12278. cli.set_ca_cert_path(CA_CERT_FILE);
  12279. cli.set_connection_timeout(5);
  12280. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12281. verify_callback_called = true;
  12282. if (!ctx.cert) return false;
  12283. // Matches the IPv6 iPAddress SAN.
  12284. san_matched = ctx.check_hostname("2001:db8::1");
  12285. // A different IPv6 address must not match.
  12286. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12287. // "::1" lives only in the CN, so it must not be accepted.
  12288. cn_ipv6_matched = ctx.check_hostname("::1");
  12289. return true; // Accept for the purpose of this test
  12290. });
  12291. cli.Get("/test");
  12292. ASSERT_TRUE(verify_callback_called)
  12293. << "Verify callback should have been called";
  12294. EXPECT_TRUE(san_matched)
  12295. << "verify_hostname should match an IPv6 iPAddress SAN";
  12296. EXPECT_FALSE(wrong_ipv6_matched)
  12297. << "verify_hostname should not match a non-matching IPv6 address";
  12298. EXPECT_FALSE(cn_ipv6_matched)
  12299. << "An IPv6 host must not be authenticated via the certificate CN";
  12300. }
  12301. #endif
  12302. // mbedTLS-specific callback constructor test
  12303. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12304. #ifdef CPPHTTPLIB_SSL_ENABLED
  12305. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12307. ASSERT_TRUE(svr.is_valid());
  12308. // Set up a handler to verify client certificate is present
  12309. bool client_cert_verified = false;
  12310. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12311. // Verify that client certificate was provided
  12312. client_cert_verified = true;
  12313. res.set_content("success", "text/plain");
  12314. });
  12315. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12316. auto se = detail::scope_exit([&] {
  12317. svr.stop();
  12318. t.join();
  12319. ASSERT_FALSE(svr.is_running());
  12320. });
  12321. svr.wait_until_ready();
  12322. // Client with certificate
  12323. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12324. cli.enable_server_certificate_verification(false);
  12325. cli.set_connection_timeout(30);
  12326. auto res = cli.Get("/test");
  12327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12328. ASSERT_EQ(StatusCode::OK_200, res->status);
  12329. ASSERT_TRUE(client_cert_verified);
  12330. EXPECT_EQ("success", res->body);
  12331. }
  12332. #endif
  12333. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12334. // backends
  12335. #ifdef CPPHTTPLIB_SSL_ENABLED
  12336. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12337. using namespace httplib::tls;
  12338. // Test that when client CA cert file is provided,
  12339. // the server properly requests and validates client certificates
  12340. // Create a server with client authentication
  12341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12342. ASSERT_TRUE(svr.is_valid());
  12343. bool handler_called = false;
  12344. svr.Get("/test", [&](const Request &req, Response &res) {
  12345. handler_called = true;
  12346. // Verify that a client certificate was provided
  12347. auto cert = req.peer_cert();
  12348. ASSERT_TRUE(static_cast<bool>(cert));
  12349. // Get the issuer name
  12350. std::string issuer_str = cert.issuer_name();
  12351. ASSERT_FALSE(issuer_str.empty());
  12352. // The client certificate should be issued by our test CA
  12353. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12354. res.set_content("authenticated", "text/plain");
  12355. });
  12356. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12357. auto se = detail::scope_exit([&] {
  12358. svr.stop();
  12359. t.join();
  12360. ASSERT_FALSE(svr.is_running());
  12361. });
  12362. svr.wait_until_ready();
  12363. // Connect with a client certificate issued by the CA
  12364. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12365. cli.enable_server_certificate_verification(false);
  12366. cli.set_connection_timeout(30);
  12367. auto res = cli.Get("/test");
  12368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12369. ASSERT_EQ(StatusCode::OK_200, res->status);
  12370. ASSERT_TRUE(handler_called);
  12371. EXPECT_EQ("authenticated", res->body);
  12372. }
  12373. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12374. using namespace httplib::tls;
  12375. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12376. ASSERT_TRUE(svr.is_valid());
  12377. svr.Get("/test", [](const Request &, Response &res) {
  12378. res.set_content("ok", "text/plain");
  12379. });
  12380. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12381. auto se = detail::scope_exit([&] {
  12382. svr.stop();
  12383. t.join();
  12384. });
  12385. svr.wait_until_ready();
  12386. SSLClient cli(HOST, PORT);
  12387. cli.enable_server_certificate_verification(false);
  12388. cli.set_connection_timeout(30);
  12389. bool cert_checked = false;
  12390. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12391. if (ctx.cert) {
  12392. auto sans = ctx.sans();
  12393. // Test certificate may or may not have SANs - just verify the API
  12394. // works If SANs exist, verify the types are valid
  12395. for (const auto &san : sans) {
  12396. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12397. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12398. san.type == SanType::OTHER);
  12399. EXPECT_FALSE(san.value.empty());
  12400. }
  12401. cert_checked = true;
  12402. }
  12403. return true;
  12404. });
  12405. auto res = cli.Get("/test");
  12406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12407. EXPECT_TRUE(cert_checked);
  12408. }
  12409. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12410. using namespace httplib::tls;
  12411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12412. ASSERT_TRUE(svr.is_valid());
  12413. svr.Get("/test", [](const Request &, Response &res) {
  12414. res.set_content("ok", "text/plain");
  12415. });
  12416. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12417. auto se = detail::scope_exit([&] {
  12418. svr.stop();
  12419. t.join();
  12420. });
  12421. svr.wait_until_ready();
  12422. SSLClient cli(HOST, PORT);
  12423. cli.enable_server_certificate_verification(false);
  12424. cli.set_connection_timeout(30);
  12425. bool validity_checked = false;
  12426. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12427. if (ctx.cert) {
  12428. time_t not_before = 0, not_after = 0;
  12429. bool result = ctx.validity(not_before, not_after);
  12430. EXPECT_TRUE(result);
  12431. // Verify that not_before < now < not_after for a valid cert
  12432. time_t now = time(nullptr);
  12433. EXPECT_LT(not_before, now);
  12434. EXPECT_GT(not_after, now);
  12435. validity_checked = true;
  12436. }
  12437. return true;
  12438. });
  12439. auto res = cli.Get("/test");
  12440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12441. EXPECT_TRUE(validity_checked);
  12442. }
  12443. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12444. using namespace httplib::tls;
  12445. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12446. ASSERT_TRUE(svr.is_valid());
  12447. svr.Get("/test", [](const Request &, Response &res) {
  12448. res.set_content("ok", "text/plain");
  12449. });
  12450. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12451. auto se = detail::scope_exit([&] {
  12452. svr.stop();
  12453. t.join();
  12454. });
  12455. svr.wait_until_ready();
  12456. SSLClient cli(HOST, PORT);
  12457. cli.enable_server_certificate_verification(false);
  12458. cli.set_connection_timeout(30);
  12459. bool serial_checked = false;
  12460. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12461. if (ctx.cert) {
  12462. std::string serial = ctx.serial();
  12463. EXPECT_FALSE(serial.empty());
  12464. // Serial should be a hex string
  12465. for (char c : serial) {
  12466. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12467. (c >= 'a' && c <= 'f'));
  12468. }
  12469. serial_checked = true;
  12470. }
  12471. return true;
  12472. });
  12473. auto res = cli.Get("/test");
  12474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12475. EXPECT_TRUE(serial_checked);
  12476. }
  12477. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12478. // Test 1: Valid CA file - no error should be recorded
  12479. {
  12480. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12481. CLIENT_CA_CERT_FILE);
  12482. ASSERT_TRUE(svr.is_valid());
  12483. // With valid setup, last_ssl_error should be 0
  12484. EXPECT_EQ(0, svr.ssl_last_error());
  12485. }
  12486. // Test 2: Invalid CA file content
  12487. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12488. {
  12489. // Create a temporary file with completely invalid content
  12490. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12491. {
  12492. std::ofstream ofs(temp_invalid_ca);
  12493. ofs << "This is not a certificate file at all\n";
  12494. ofs << "Just plain text content\n";
  12495. }
  12496. // Create server with invalid CA file
  12497. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12498. // Clean up temporary file
  12499. std::remove(temp_invalid_ca);
  12500. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12501. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12502. // Note: SSL_CTX_load_verify_locations typically fails first,
  12503. // but our error handling code path is still exercised
  12504. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12505. }
  12506. }
  12507. TEST(VerifyCallbackTest, VerifyContextFields) {
  12508. using namespace httplib::tls;
  12509. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12510. ASSERT_TRUE(svr.is_valid());
  12511. svr.Get("/test", [](const Request &, Response &res) {
  12512. res.set_content("ok", "text/plain");
  12513. });
  12514. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12515. auto se = detail::scope_exit([&] {
  12516. svr.stop();
  12517. t.join();
  12518. });
  12519. svr.wait_until_ready();
  12520. SSLClient cli(HOST, PORT);
  12521. cli.enable_server_certificate_verification(false);
  12522. cli.set_connection_timeout(30);
  12523. int callback_count = 0;
  12524. bool saw_leaf_cert = false;
  12525. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12526. if (ctx.cert) {
  12527. callback_count++;
  12528. // We should see at least one certificate (the leaf)
  12529. std::string cn = ctx.subject_cn();
  12530. if (!cn.empty()) { saw_leaf_cert = true; }
  12531. // Verify context fields are populated
  12532. EXPECT_NE(ctx.session, nullptr);
  12533. EXPECT_GE(ctx.depth, 0);
  12534. }
  12535. return true;
  12536. });
  12537. auto res = cli.Get("/test");
  12538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12539. EXPECT_GT(callback_count, 0);
  12540. EXPECT_TRUE(saw_leaf_cert);
  12541. }
  12542. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12543. using httplib::tls::TlsError;
  12544. // Test that verify_error_to_string returns empty for success
  12545. std::string success_str = TlsError::verify_error_to_string(0);
  12546. EXPECT_TRUE(success_str.empty());
  12547. // Test that verify_error_to_string returns non-empty for error codes
  12548. // Using a common error code (certificate expired)
  12549. std::string error_str =
  12550. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12551. EXPECT_FALSE(error_str.empty());
  12552. }
  12553. TEST(SessionVerifierTest, CertificateAccepted) {
  12554. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12555. ASSERT_TRUE(svr.is_valid());
  12556. svr.Get("/test", [](const Request &, Response &res) {
  12557. res.set_content("ok", "text/plain");
  12558. });
  12559. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12560. auto se = detail::scope_exit([&] {
  12561. svr.stop();
  12562. t.join();
  12563. });
  12564. svr.wait_until_ready();
  12565. SSLClient cli(HOST, PORT);
  12566. cli.enable_server_certificate_verification(false);
  12567. cli.set_connection_timeout(30);
  12568. bool callback_called = false;
  12569. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12570. EXPECT_NE(session, nullptr);
  12571. callback_called = true;
  12572. return SSLVerifierResponse::CertificateAccepted;
  12573. });
  12574. auto res = cli.Get("/test");
  12575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12576. EXPECT_EQ(200, res->status);
  12577. EXPECT_TRUE(callback_called);
  12578. }
  12579. TEST(SessionVerifierTest, CertificateRejected) {
  12580. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12581. ASSERT_TRUE(svr.is_valid());
  12582. svr.Get("/test", [](const Request &, Response &res) {
  12583. res.set_content("ok", "text/plain");
  12584. });
  12585. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12586. auto se = detail::scope_exit([&] {
  12587. svr.stop();
  12588. t.join();
  12589. });
  12590. svr.wait_until_ready();
  12591. SSLClient cli(HOST, PORT);
  12592. cli.enable_server_certificate_verification(false);
  12593. cli.set_connection_timeout(30);
  12594. bool callback_called = false;
  12595. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12596. EXPECT_NE(session, nullptr);
  12597. callback_called = true;
  12598. return SSLVerifierResponse::CertificateRejected;
  12599. });
  12600. auto res = cli.Get("/test");
  12601. EXPECT_FALSE(res);
  12602. EXPECT_TRUE(callback_called);
  12603. }
  12604. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12605. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12606. ASSERT_TRUE(svr.is_valid());
  12607. svr.Get("/test", [](const Request &, Response &res) {
  12608. res.set_content("ok", "text/plain");
  12609. });
  12610. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12611. auto se = detail::scope_exit([&] {
  12612. svr.stop();
  12613. t.join();
  12614. });
  12615. svr.wait_until_ready();
  12616. // NoDecisionMade with verification disabled should succeed (no default check)
  12617. SSLClient cli(HOST, PORT);
  12618. cli.enable_server_certificate_verification(false);
  12619. cli.set_connection_timeout(30);
  12620. bool callback_called = false;
  12621. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12622. EXPECT_NE(session, nullptr);
  12623. callback_called = true;
  12624. return SSLVerifierResponse::NoDecisionMade;
  12625. });
  12626. auto res = cli.Get("/test");
  12627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12628. EXPECT_EQ(200, res->status);
  12629. EXPECT_TRUE(callback_called);
  12630. }
  12631. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12632. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12633. ASSERT_TRUE(svr.is_valid());
  12634. svr.Get("/test", [](const Request &, Response &res) {
  12635. res.set_content("ok", "text/plain");
  12636. });
  12637. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12638. auto se = detail::scope_exit([&] {
  12639. svr.stop();
  12640. t.join();
  12641. });
  12642. svr.wait_until_ready();
  12643. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12644. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12645. // so we only check that the request fails, not whether the callback was
  12646. // called.
  12647. SSLClient cli(HOST, PORT);
  12648. cli.enable_server_certificate_verification(true);
  12649. cli.set_connection_timeout(30);
  12650. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12651. EXPECT_NE(session, nullptr);
  12652. return SSLVerifierResponse::NoDecisionMade;
  12653. });
  12654. auto res = cli.Get("/test");
  12655. EXPECT_FALSE(res);
  12656. }
  12657. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12658. // Test SSL server using PemMemory constructor with client CA certificates
  12659. // Read PEM files
  12660. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12661. read_file(SERVER_CERT_FILE, server_cert_pem);
  12662. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12663. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12664. // Create SSLServer with PemMemory constructor including client CA
  12665. SSLServer::PemMemory server_pem = {
  12666. server_cert_pem.c_str(),
  12667. server_cert_pem.size(),
  12668. server_key_pem.c_str(),
  12669. server_key_pem.size(),
  12670. client_ca_pem.c_str(),
  12671. client_ca_pem.size(),
  12672. nullptr // no password for server key
  12673. };
  12674. SSLServer svr(server_pem);
  12675. ASSERT_TRUE(svr.is_valid());
  12676. // No SSL error should be recorded for valid setup
  12677. EXPECT_EQ(0, svr.ssl_last_error());
  12678. // Set up server endpoints
  12679. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12680. res.set_content("ok", "text/plain");
  12681. });
  12682. // Start server in a thread
  12683. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12684. svr.wait_until_ready();
  12685. // Connect with client certificate (using constructor with paths)
  12686. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12687. cli.enable_server_certificate_verification(false);
  12688. auto res = cli.Get("/test-pem-ca");
  12689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12690. EXPECT_EQ(200, res->status);
  12691. EXPECT_EQ("ok", res->body);
  12692. svr.stop();
  12693. server_thread.join();
  12694. }
  12695. #endif
  12696. #ifdef _WIN32
  12697. TEST(CleanupTest, WSACleanup) {
  12698. int ret = WSACleanup();
  12699. ASSERT_EQ(0, ret);
  12700. }
  12701. #endif
  12702. #ifndef CPPHTTPLIB_SSL_ENABLED
  12703. TEST(NoSSLSupport, SimpleInterface) {
  12704. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12705. }
  12706. #endif
  12707. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12708. TEST(InvalidScheme, SimpleInterface) {
  12709. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12710. }
  12711. #endif
  12712. TEST(NoScheme, SimpleInterface) {
  12713. Client cli("yahoo.com:80");
  12714. ASSERT_TRUE(cli.is_valid());
  12715. }
  12716. TEST(SendAPI, SimpleInterface_Online) {
  12717. Client cli("http://yahoo.com");
  12718. Request req;
  12719. req.method = "GET";
  12720. req.path = "/";
  12721. auto res = cli.send(req);
  12722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12723. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12724. }
  12725. TEST(SendAPI, WithParamsInRequest) {
  12726. Server svr;
  12727. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12728. EXPECT_TRUE(req.has_param("test"));
  12729. EXPECT_EQ("test_value", req.get_param_value("test"));
  12730. });
  12731. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12732. auto se = detail::scope_exit([&] {
  12733. svr.stop();
  12734. t.join();
  12735. ASSERT_FALSE(svr.is_running());
  12736. });
  12737. svr.wait_until_ready();
  12738. Client cli(HOST, PORT);
  12739. {
  12740. Request req;
  12741. req.method = "GET";
  12742. req.path = "/";
  12743. req.params.emplace("test", "test_value");
  12744. auto res = cli.send(req);
  12745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12746. }
  12747. {
  12748. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12750. }
  12751. }
  12752. TEST(ClientImplMethods, GetSocketTest) {
  12753. httplib::Server svr;
  12754. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12755. res.status = StatusCode::OK_200;
  12756. });
  12757. auto port = svr.bind_to_any_port("127.0.0.1");
  12758. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12759. auto se = detail::scope_exit([&] {
  12760. svr.stop();
  12761. thread.join();
  12762. ASSERT_FALSE(svr.is_running());
  12763. });
  12764. svr.wait_until_ready();
  12765. {
  12766. httplib::Client cli("127.0.0.1", port);
  12767. cli.set_keep_alive(true);
  12768. // Use the behavior of cpp-httplib of opening the connection
  12769. // only when the first request happens. If that changes,
  12770. // this test would be obsolete.
  12771. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12772. // This also implicitly tests the server. But other tests would fail much
  12773. // earlier than this one to be considered.
  12774. auto res = cli.Get("/");
  12775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12776. EXPECT_EQ(StatusCode::OK_200, res->status);
  12777. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12778. }
  12779. }
  12780. #ifdef CPPHTTPLIB_SSL_ENABLED
  12781. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12782. Client cli("http://yahoo.com");
  12783. auto res = cli.Get("/");
  12784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12785. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12786. cli.set_follow_location(true);
  12787. res = cli.Get("/");
  12788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12789. EXPECT_EQ(StatusCode::OK_200, res->status);
  12790. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12791. }
  12792. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12793. Client cli("https://yahoo.com");
  12794. auto res = cli.Get("/");
  12795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12796. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12797. cli.set_follow_location(true);
  12798. res = cli.Get("/");
  12799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12800. EXPECT_EQ(StatusCode::OK_200, res->status);
  12801. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12802. }
  12803. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12804. Client cli("https://yahoo.com");
  12805. auto res = cli.Get("/");
  12806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12807. ASSERT_FALSE(!res);
  12808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12809. ASSERT_FALSE(res == nullptr);
  12810. ASSERT_TRUE(res != nullptr);
  12811. EXPECT_EQ(Error::Success, res.error());
  12812. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12813. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12814. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12815. cli.set_follow_location(true);
  12816. res = cli.Get("/");
  12817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12818. EXPECT_EQ(Error::Success, res.error());
  12819. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12820. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12821. EXPECT_EQ(StatusCode::OK_200, res->status);
  12822. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12823. }
  12824. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12825. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12826. Client cli("https://cdnjs.cloudflare.com");
  12827. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12828. Headers{{"Accept-Encoding", "br"}});
  12829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12830. EXPECT_EQ(StatusCode::OK_200, res->status);
  12831. EXPECT_EQ(287630U, res->body.size());
  12832. EXPECT_EQ("application/javascript; charset=utf-8",
  12833. res->get_header_value("Content-Type"));
  12834. }
  12835. #endif
  12836. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12837. #undef REDIR_HOST // Silence compiler warning
  12838. #define REDIR_HOST "https://httpbingo.org"
  12839. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12840. Client cli(REDIR_HOST);
  12841. cli.set_follow_location(true);
  12842. auto res =
  12843. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12845. EXPECT_EQ(StatusCode::OK_200, res->status);
  12846. }
  12847. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12848. Client cli(REDIR_HOST);
  12849. cli.set_follow_location(true);
  12850. Params params;
  12851. params.emplace("url", "http://example.com");
  12852. params.emplace("status_code", "302");
  12853. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12855. EXPECT_EQ(StatusCode::OK_200, res->status);
  12856. }
  12857. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12858. Client cli(REDIR_HOST);
  12859. cli.set_follow_location(true);
  12860. Params params;
  12861. params.emplace("url", "http://example.com");
  12862. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12864. EXPECT_EQ(StatusCode::OK_200, res->status);
  12865. }
  12866. TEST(HttpToHttpsRedirectTest, CertFile) {
  12867. auto ssl_port = PORT + 1;
  12868. Server svr;
  12869. ASSERT_TRUE(svr.is_valid());
  12870. svr.Get("/index", [&](const Request &, Response &res) {
  12871. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12872. "/index");
  12873. svr.stop();
  12874. });
  12875. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12876. ASSERT_TRUE(ssl_svr.is_valid());
  12877. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12878. res.set_content("test", "text/plain");
  12879. ssl_svr.stop();
  12880. });
  12881. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12882. thread t2 =
  12883. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12884. auto se = detail::scope_exit([&] {
  12885. t2.join();
  12886. t.join();
  12887. ASSERT_FALSE(svr.is_running());
  12888. });
  12889. svr.wait_until_ready();
  12890. ssl_svr.wait_until_ready();
  12891. Client cli("127.0.0.1", PORT);
  12892. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12893. cli.enable_server_certificate_verification(true);
  12894. cli.set_follow_location(true);
  12895. cli.set_connection_timeout(30);
  12896. auto res = cli.Get("/index");
  12897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12898. ASSERT_EQ(StatusCode::OK_200, res->status);
  12899. }
  12900. TEST(SSLClientRedirectTest, CertFile) {
  12901. auto ssl_port = PORT + 1;
  12902. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12903. ASSERT_TRUE(ssl_svr1.is_valid());
  12904. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12905. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12906. "/index");
  12907. ssl_svr1.stop();
  12908. });
  12909. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12910. ASSERT_TRUE(ssl_svr2.is_valid());
  12911. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12912. res.set_content("test", "text/plain");
  12913. ssl_svr2.stop();
  12914. });
  12915. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12916. thread t2 =
  12917. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12918. auto se = detail::scope_exit([&] {
  12919. t2.join();
  12920. t.join();
  12921. ASSERT_FALSE(ssl_svr1.is_running());
  12922. });
  12923. ssl_svr1.wait_until_ready();
  12924. ssl_svr2.wait_until_ready();
  12925. SSLClient cli("127.0.0.1", PORT);
  12926. std::string cert;
  12927. read_file(SERVER_CERT2_FILE, cert);
  12928. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12929. cli.enable_server_certificate_verification(true);
  12930. cli.set_follow_location(true);
  12931. cli.set_connection_timeout(30);
  12932. auto res = cli.Get("/index");
  12933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12934. ASSERT_EQ(StatusCode::OK_200, res->status);
  12935. }
  12936. #endif
  12937. #ifdef CPPHTTPLIB_SSL_ENABLED
  12938. // Test that set_ca_cert_store() skips system certs (consistent with
  12939. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12940. // should be trusted - system certs should NOT be loaded.
  12941. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12942. // Load a specific cert that is NOT a system CA cert
  12943. std::string cert;
  12944. read_file(SERVER_CERT2_FILE, cert);
  12945. SSLClient cli("google.com");
  12946. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12947. cli.enable_server_certificate_verification(true);
  12948. // This should FAIL because:
  12949. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12950. // 2. System certs should NOT be loaded when custom store is set
  12951. // If system certs WERE loaded, this would succeed
  12952. auto res = cli.Get("/");
  12953. ASSERT_FALSE(res);
  12954. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12955. }
  12956. // Same as above, but through the native store handle path. Regression test:
  12957. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12958. // merged system certs into the user-provided store.
  12959. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12960. std::string cert;
  12961. read_file(SERVER_CERT2_FILE, cert);
  12962. SSLClient cli("google.com");
  12963. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12964. cli.enable_server_certificate_verification(true);
  12965. auto res = cli.Get("/");
  12966. ASSERT_FALSE(res);
  12967. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12968. }
  12969. // A custom store set via the native handle must still verify a server whose
  12970. // cert it does contain.
  12971. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12972. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12973. ASSERT_TRUE(svr.is_valid());
  12974. svr.Get("/test", [&](const Request &, Response &res) {
  12975. res.set_content("test", "text/plain");
  12976. });
  12977. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12978. auto se = detail::scope_exit([&] {
  12979. svr.stop();
  12980. t.join();
  12981. ASSERT_FALSE(svr.is_running());
  12982. });
  12983. svr.wait_until_ready();
  12984. SSLClient cli("127.0.0.1", PORT);
  12985. std::string cert;
  12986. read_file(SERVER_CERT2_FILE, cert);
  12987. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12988. cli.enable_server_certificate_verification(true);
  12989. cli.set_connection_timeout(30);
  12990. auto res = cli.Get("/test");
  12991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12992. ASSERT_EQ(StatusCode::OK_200, res->status);
  12993. }
  12994. // CA certs loaded through the universal Client must be transferred to the
  12995. // client created internally for following an HTTPS redirect. Regression test:
  12996. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12997. // the CA data for redirect transfer.
  12998. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12999. auto ssl_port = PORT + 1;
  13000. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13001. ASSERT_TRUE(ssl_svr1.is_valid());
  13002. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13003. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13004. "/index");
  13005. });
  13006. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13007. ASSERT_TRUE(ssl_svr2.is_valid());
  13008. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13009. res.set_content("test", "text/plain");
  13010. });
  13011. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13012. thread t2 =
  13013. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13014. auto se = detail::scope_exit([&] {
  13015. ssl_svr2.stop();
  13016. ssl_svr1.stop();
  13017. t2.join();
  13018. t.join();
  13019. ASSERT_FALSE(ssl_svr1.is_running());
  13020. });
  13021. ssl_svr1.wait_until_ready();
  13022. ssl_svr2.wait_until_ready();
  13023. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13024. std::string cert;
  13025. read_file(SERVER_CERT2_FILE, cert);
  13026. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13027. cli.enable_server_certificate_verification(true);
  13028. cli.set_follow_location(true);
  13029. cli.set_connection_timeout(30);
  13030. auto res = cli.Get("/index");
  13031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13032. ASSERT_EQ(StatusCode::OK_200, res->status);
  13033. }
  13034. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13035. // so a host signed by a system CA verifies even though a custom CA is set
  13036. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13037. std::string cert;
  13038. read_file(SERVER_CERT2_FILE, cert);
  13039. SSLClient cli("google.com");
  13040. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13041. cli.enable_system_ca(true);
  13042. cli.enable_server_certificate_verification(true);
  13043. auto res = cli.Get("/");
  13044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13045. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13046. }
  13047. // The custom CA remains effective when combined with the system CA
  13048. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13049. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13050. ASSERT_TRUE(svr.is_valid());
  13051. svr.Get("/test", [&](const Request &, Response &res) {
  13052. res.set_content("test", "text/plain");
  13053. });
  13054. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13055. auto se = detail::scope_exit([&] {
  13056. svr.stop();
  13057. t.join();
  13058. ASSERT_FALSE(svr.is_running());
  13059. });
  13060. svr.wait_until_ready();
  13061. SSLClient cli("127.0.0.1", PORT);
  13062. std::string cert;
  13063. read_file(SERVER_CERT2_FILE, cert);
  13064. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13065. cli.enable_system_ca(true);
  13066. cli.enable_server_certificate_verification(true);
  13067. cli.set_connection_timeout(30);
  13068. auto res = cli.Get("/test");
  13069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13070. ASSERT_EQ(StatusCode::OK_200, res->status);
  13071. }
  13072. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13073. // skip chain verification entirely (only the certificate identity was
  13074. // checked), so a server presenting an untrusted certificate with a matching
  13075. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13076. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13077. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13078. ASSERT_TRUE(svr.is_valid());
  13079. svr.Get("/test", [&](const Request &, Response &res) {
  13080. res.set_content("test", "text/plain");
  13081. });
  13082. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13083. auto se = detail::scope_exit([&] {
  13084. svr.stop();
  13085. t.join();
  13086. ASSERT_FALSE(svr.is_running());
  13087. });
  13088. svr.wait_until_ready();
  13089. SSLClient cli("127.0.0.1", PORT);
  13090. std::string cert;
  13091. // A trusted CA that did not sign the server certificate. The server cert
  13092. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13093. // this connection.
  13094. read_file(CLIENT_CA_CERT_FILE, cert);
  13095. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13096. cli.enable_server_certificate_verification(true);
  13097. cli.set_connection_timeout(30);
  13098. auto res = cli.Get("/test");
  13099. ASSERT_FALSE(res);
  13100. }
  13101. // enable_system_ca(false) prevents system CA loading entirely
  13102. TEST(SSLClientTest, DisableSystemCa_Online) {
  13103. SSLClient cli("google.com");
  13104. cli.enable_system_ca(false);
  13105. cli.enable_server_certificate_verification(true);
  13106. auto res = cli.Get("/");
  13107. ASSERT_FALSE(res);
  13108. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13109. // itself when the CA chain is empty
  13110. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13111. res.error() == Error::SSLConnection);
  13112. }
  13113. // The universal Client forwards enable_system_ca()
  13114. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13115. std::string cert;
  13116. read_file(SERVER_CERT2_FILE, cert);
  13117. Client cli("https://google.com");
  13118. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13119. cli.enable_system_ca(true);
  13120. cli.enable_server_certificate_verification(true);
  13121. auto res = cli.Get("/");
  13122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13123. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13124. }
  13125. // The system CA policy must carry over to the client created internally for
  13126. // following a cross-host HTTPS redirect
  13127. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13128. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13129. ASSERT_TRUE(svr.is_valid());
  13130. svr.Get("/index", [&](const Request &, Response &res) {
  13131. res.set_redirect("https://www.google.com/");
  13132. });
  13133. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13134. auto se = detail::scope_exit([&] {
  13135. svr.stop();
  13136. t.join();
  13137. ASSERT_FALSE(svr.is_running());
  13138. });
  13139. svr.wait_until_ready();
  13140. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13141. std::string cert;
  13142. read_file(SERVER_CERT2_FILE, cert);
  13143. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13144. cli.enable_system_ca(true);
  13145. cli.enable_server_certificate_verification(true);
  13146. cli.set_follow_location(true);
  13147. cli.set_connection_timeout(30);
  13148. // Receiving any response proves the redirect client completed the TLS
  13149. // handshake with a system-CA-signed host
  13150. auto res = cli.Get("/index");
  13151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13152. }
  13153. TEST(MultipartFormDataTest, LargeData) {
  13154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13155. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13156. const ContentReader &content_reader) {
  13157. if (req.is_multipart_form_data()) {
  13158. std::vector<FormData> items;
  13159. content_reader(
  13160. [&](const FormData &file) {
  13161. items.push_back(file);
  13162. return true;
  13163. },
  13164. [&](const char *data, size_t data_length) {
  13165. items.back().content.append(data, data_length);
  13166. return true;
  13167. });
  13168. EXPECT_TRUE(std::string(items[0].name) == "document");
  13169. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13170. EXPECT_TRUE(items[0].filename == "2MB_data");
  13171. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13172. EXPECT_TRUE(items[1].name == "hello");
  13173. EXPECT_TRUE(items[1].content == "world");
  13174. EXPECT_TRUE(items[1].filename == "");
  13175. EXPECT_TRUE(items[1].content_type == "");
  13176. } else {
  13177. std::string body;
  13178. content_reader([&](const char *data, size_t data_length) {
  13179. body.append(data, data_length);
  13180. return true;
  13181. });
  13182. }
  13183. });
  13184. auto port = svr.bind_to_any_port(HOST);
  13185. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13186. auto se = detail::scope_exit([&] {
  13187. svr.stop();
  13188. t.join();
  13189. ASSERT_FALSE(svr.is_running());
  13190. });
  13191. svr.wait_until_ready();
  13192. {
  13193. std::string data(1024 * 1024 * 2, '.');
  13194. std::stringstream buffer;
  13195. buffer << data;
  13196. SSLClient cli(HOST, port);
  13197. cli.enable_server_certificate_verification(false);
  13198. UploadFormDataItems items{
  13199. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13200. {"hello", "world", "", ""},
  13201. };
  13202. auto res = cli.Post("/post", items);
  13203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13204. ASSERT_EQ(StatusCode::OK_200, res->status);
  13205. }
  13206. }
  13207. TEST(MultipartFormDataTest, DataProviderItems) {
  13208. std::random_device seed_gen;
  13209. std::mt19937 random(seed_gen());
  13210. std::string rand1;
  13211. rand1.resize(1000);
  13212. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13213. std::string rand2;
  13214. rand2.resize(3000);
  13215. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13216. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13217. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13218. const ContentReader &content_reader) {
  13219. ASSERT_FALSE(req.is_multipart_form_data());
  13220. std::string body;
  13221. content_reader([&](const char *data, size_t data_length) {
  13222. body.append(data, data_length);
  13223. return true;
  13224. });
  13225. EXPECT_EQ(body, "");
  13226. });
  13227. svr.Post("/post-items", [&](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(std::string(items[0].name), "name1");
  13242. EXPECT_EQ(items[0].content, "Testing123");
  13243. EXPECT_EQ(items[0].filename, "filename1");
  13244. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13245. EXPECT_EQ(items[1].name, "name2");
  13246. EXPECT_EQ(items[1].content, "Testing456");
  13247. EXPECT_EQ(items[1].filename, "");
  13248. EXPECT_EQ(items[1].content_type, "");
  13249. });
  13250. svr.Post("/post-providers", [&](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() == 2);
  13264. EXPECT_EQ(items[0].name, "name3");
  13265. EXPECT_EQ(items[0].content, rand1);
  13266. EXPECT_EQ(items[0].filename, "filename3");
  13267. EXPECT_EQ(items[0].content_type, "");
  13268. EXPECT_EQ(items[1].name, "name4");
  13269. EXPECT_EQ(items[1].content, rand2);
  13270. EXPECT_EQ(items[1].filename, "filename4");
  13271. EXPECT_EQ(items[1].content_type, "");
  13272. });
  13273. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13274. const ContentReader &content_reader) {
  13275. ASSERT_TRUE(req.is_multipart_form_data());
  13276. std::vector<FormData> items;
  13277. content_reader(
  13278. [&](const FormData &file) {
  13279. items.push_back(file);
  13280. return true;
  13281. },
  13282. [&](const char *data, size_t data_length) {
  13283. items.back().content.append(data, data_length);
  13284. return true;
  13285. });
  13286. ASSERT_TRUE(items.size() == 4);
  13287. EXPECT_EQ(std::string(items[0].name), "name1");
  13288. EXPECT_EQ(items[0].content, "Testing123");
  13289. EXPECT_EQ(items[0].filename, "filename1");
  13290. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13291. EXPECT_EQ(items[1].name, "name2");
  13292. EXPECT_EQ(items[1].content, "Testing456");
  13293. EXPECT_EQ(items[1].filename, "");
  13294. EXPECT_EQ(items[1].content_type, "");
  13295. EXPECT_EQ(items[2].name, "name3");
  13296. EXPECT_EQ(items[2].content, rand1);
  13297. EXPECT_EQ(items[2].filename, "filename3");
  13298. EXPECT_EQ(items[2].content_type, "");
  13299. EXPECT_EQ(items[3].name, "name4");
  13300. EXPECT_EQ(items[3].content, rand2);
  13301. EXPECT_EQ(items[3].filename, "filename4");
  13302. EXPECT_EQ(items[3].content_type, "");
  13303. });
  13304. auto port = svr.bind_to_any_port("localhost");
  13305. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13306. auto se = detail::scope_exit([&] {
  13307. svr.stop();
  13308. t.join();
  13309. ASSERT_FALSE(svr.is_running());
  13310. });
  13311. svr.wait_until_ready();
  13312. {
  13313. SSLClient cli("localhost", port);
  13314. cli.enable_server_certificate_verification(false);
  13315. UploadFormDataItems items{
  13316. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13317. {"name2", "Testing456", "", ""}, // not a file
  13318. };
  13319. {
  13320. auto res = cli.Post("/post-none", {}, {}, {});
  13321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13322. ASSERT_EQ(StatusCode::OK_200, res->status);
  13323. }
  13324. FormDataProviderItems providers;
  13325. {
  13326. auto res =
  13327. cli.Post("/post-items", {}, items, providers); // empty providers
  13328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13329. ASSERT_EQ(StatusCode::OK_200, res->status);
  13330. }
  13331. providers.push_back({"name3",
  13332. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13333. // test the offset is given correctly at each step
  13334. if (!offset)
  13335. sink.os.write(rand1.data(), 30);
  13336. else if (offset == 30)
  13337. sink.os.write(rand1.data() + 30, 300);
  13338. else if (offset == 330)
  13339. sink.os.write(rand1.data() + 330, 670);
  13340. else if (offset == rand1.size())
  13341. sink.done();
  13342. return true;
  13343. },
  13344. "filename3",
  13345. {}});
  13346. providers.push_back({"name4",
  13347. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13348. // test the offset is given correctly at each step
  13349. if (!offset)
  13350. sink.os.write(rand2.data(), 2000);
  13351. else if (offset == 2000)
  13352. sink.os.write(rand2.data() + 2000, 1);
  13353. else if (offset == 2001)
  13354. sink.os.write(rand2.data() + 2001, 999);
  13355. else if (offset == rand2.size())
  13356. sink.done();
  13357. return true;
  13358. },
  13359. "filename4",
  13360. {}});
  13361. {
  13362. auto res = cli.Post("/post-providers", {}, {}, providers);
  13363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13364. ASSERT_EQ(StatusCode::OK_200, res->status);
  13365. }
  13366. {
  13367. auto res = cli.Post("/post-both", {}, items, providers);
  13368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13369. ASSERT_EQ(StatusCode::OK_200, res->status);
  13370. }
  13371. }
  13372. }
  13373. TEST(MultipartFormDataTest, BadHeader) {
  13374. Server svr;
  13375. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13376. res.set_content("ok", "text/plain");
  13377. });
  13378. thread t = thread([&] { svr.listen(HOST, PORT); });
  13379. auto se = detail::scope_exit([&] {
  13380. svr.stop();
  13381. t.join();
  13382. ASSERT_FALSE(svr.is_running());
  13383. });
  13384. svr.wait_until_ready();
  13385. const std::string body =
  13386. "This is the preamble. It is to be ignored, though it\r\n"
  13387. "is a handy place for composition agents to include an\r\n"
  13388. "explanatory note to non-MIME conformant readers.\r\n"
  13389. "\r\n"
  13390. "\r\n"
  13391. "--simple boundary\r\n"
  13392. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13393. ": BAD...\r\n"
  13394. "\r\n"
  13395. "value1\r\n"
  13396. "--simple boundary\r\n"
  13397. "Content-Disposition: form-data; name=\"field2\"; "
  13398. "filename=\"example.txt\"\r\n"
  13399. "\r\n"
  13400. "value2\r\n"
  13401. "--simple boundary--\r\n"
  13402. "This is the epilogue. It is also to be ignored.\r\n";
  13403. std::string content_type =
  13404. R"(multipart/form-data; boundary="simple boundary")";
  13405. Client cli(HOST, PORT);
  13406. auto res = cli.Post("/post", body, content_type.c_str());
  13407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13408. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13409. }
  13410. TEST(MultipartFormDataTest, WithPreamble) {
  13411. Server svr;
  13412. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13413. res.set_content("ok", "text/plain");
  13414. });
  13415. thread t = thread([&] { svr.listen(HOST, PORT); });
  13416. auto se = detail::scope_exit([&] {
  13417. svr.stop();
  13418. t.join();
  13419. ASSERT_FALSE(svr.is_running());
  13420. });
  13421. svr.wait_until_ready();
  13422. const std::string body =
  13423. "This is the preamble. It is to be ignored, though it\r\n"
  13424. "is a handy place for composition agents to include an\r\n"
  13425. "explanatory note to non-MIME conformant readers.\r\n"
  13426. "\r\n"
  13427. "\r\n"
  13428. "--simple boundary\r\n"
  13429. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13430. "\r\n"
  13431. "value1\r\n"
  13432. "--simple boundary\r\n"
  13433. "Content-Disposition: form-data; name=\"field2\"; "
  13434. "filename=\"example.txt\"\r\n"
  13435. "\r\n"
  13436. "value2\r\n"
  13437. "--simple boundary--\r\n"
  13438. "This is the epilogue. It is also to be ignored.\r\n";
  13439. std::string content_type =
  13440. R"(multipart/form-data; boundary="simple boundary")";
  13441. Client cli(HOST, PORT);
  13442. auto res = cli.Post("/post", body, content_type.c_str());
  13443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13444. EXPECT_EQ(StatusCode::OK_200, res->status);
  13445. }
  13446. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13448. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13449. const ContentReader &content_reader) {
  13450. if (req.is_multipart_form_data()) {
  13451. std::vector<FormData> items;
  13452. content_reader(
  13453. [&](const FormData &file) {
  13454. items.push_back(file);
  13455. return true;
  13456. },
  13457. [&](const char *data, size_t data_length) {
  13458. items.back().content.append(data, data_length);
  13459. return true;
  13460. });
  13461. EXPECT_TRUE(std::string(items[0].name) == "document");
  13462. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13463. EXPECT_TRUE(items[0].filename == "2MB_data");
  13464. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13465. EXPECT_TRUE(items[1].name == "hello");
  13466. EXPECT_TRUE(items[1].content == "world");
  13467. EXPECT_TRUE(items[1].filename == "");
  13468. EXPECT_TRUE(items[1].content_type == "");
  13469. } else {
  13470. std::string body;
  13471. content_reader([&](const char *data, size_t data_length) {
  13472. body.append(data, data_length);
  13473. return true;
  13474. });
  13475. }
  13476. });
  13477. auto port = svr.bind_to_any_port("localhost");
  13478. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13479. auto se = detail::scope_exit([&] {
  13480. svr.stop();
  13481. t.join();
  13482. ASSERT_FALSE(svr.is_running());
  13483. });
  13484. svr.wait_until_ready();
  13485. {
  13486. std::string data(1024 * 1024 * 2, '.');
  13487. std::stringstream buffer;
  13488. buffer << data;
  13489. SSLClient cli("localhost", port);
  13490. cli.enable_server_certificate_verification(false);
  13491. UploadFormDataItems items{
  13492. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13493. {"hello", "world", "", ""},
  13494. };
  13495. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13497. ASSERT_EQ(StatusCode::OK_200, res->status);
  13498. }
  13499. }
  13500. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13501. std::string data(1024 * 1024 * 2, '&');
  13502. std::stringstream buffer;
  13503. buffer << data;
  13504. Client cli("https://localhost:8080");
  13505. UploadFormDataItems items{
  13506. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13507. {"hello", "world", "", ""},
  13508. };
  13509. for (const char &c : " \t\r\n") {
  13510. auto res =
  13511. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13512. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13513. ASSERT_FALSE(res);
  13514. }
  13515. }
  13516. TEST(MultipartFormDataTest, PutFormData) {
  13517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13518. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13519. const ContentReader &content_reader) {
  13520. if (req.is_multipart_form_data()) {
  13521. std::vector<FormData> items;
  13522. content_reader(
  13523. [&](const FormData &file) {
  13524. items.push_back(file);
  13525. return true;
  13526. },
  13527. [&](const char *data, size_t data_length) {
  13528. items.back().content.append(data, data_length);
  13529. return true;
  13530. });
  13531. EXPECT_TRUE(std::string(items[0].name) == "document");
  13532. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13533. EXPECT_TRUE(items[0].filename == "2MB_data");
  13534. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13535. EXPECT_TRUE(items[1].name == "hello");
  13536. EXPECT_TRUE(items[1].content == "world");
  13537. EXPECT_TRUE(items[1].filename == "");
  13538. EXPECT_TRUE(items[1].content_type == "");
  13539. } else {
  13540. std::string body;
  13541. content_reader([&](const char *data, size_t data_length) {
  13542. body.append(data, data_length);
  13543. return true;
  13544. });
  13545. }
  13546. });
  13547. auto port = svr.bind_to_any_port("localhost");
  13548. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13549. auto se = detail::scope_exit([&] {
  13550. svr.stop();
  13551. t.join();
  13552. ASSERT_FALSE(svr.is_running());
  13553. });
  13554. svr.wait_until_ready();
  13555. {
  13556. std::string data(1024 * 1024 * 2, '&');
  13557. std::stringstream buffer;
  13558. buffer << data;
  13559. SSLClient cli("localhost", port);
  13560. cli.enable_server_certificate_verification(false);
  13561. UploadFormDataItems items{
  13562. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13563. {"hello", "world", "", ""},
  13564. };
  13565. auto res = cli.Put("/put", items);
  13566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13567. ASSERT_EQ(StatusCode::OK_200, res->status);
  13568. }
  13569. }
  13570. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13571. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13572. svr.Put("/put_customboundary",
  13573. [&](const Request &req, const Response & /*res*/,
  13574. const ContentReader &content_reader) {
  13575. if (req.is_multipart_form_data()) {
  13576. std::vector<FormData> items;
  13577. content_reader(
  13578. [&](const FormData &file) {
  13579. items.push_back(file);
  13580. return true;
  13581. },
  13582. [&](const char *data, size_t data_length) {
  13583. items.back().content.append(data, data_length);
  13584. return true;
  13585. });
  13586. EXPECT_TRUE(std::string(items[0].name) == "document");
  13587. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13588. EXPECT_TRUE(items[0].filename == "2MB_data");
  13589. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13590. EXPECT_TRUE(items[1].name == "hello");
  13591. EXPECT_TRUE(items[1].content == "world");
  13592. EXPECT_TRUE(items[1].filename == "");
  13593. EXPECT_TRUE(items[1].content_type == "");
  13594. } else {
  13595. std::string body;
  13596. content_reader([&](const char *data, size_t data_length) {
  13597. body.append(data, data_length);
  13598. return true;
  13599. });
  13600. }
  13601. });
  13602. auto port = svr.bind_to_any_port("localhost");
  13603. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13604. auto se = detail::scope_exit([&] {
  13605. svr.stop();
  13606. t.join();
  13607. ASSERT_FALSE(svr.is_running());
  13608. });
  13609. svr.wait_until_ready();
  13610. {
  13611. std::string data(1024 * 1024 * 2, '&');
  13612. std::stringstream buffer;
  13613. buffer << data;
  13614. SSLClient cli("localhost", port);
  13615. cli.enable_server_certificate_verification(false);
  13616. UploadFormDataItems items{
  13617. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13618. {"hello", "world", "", ""},
  13619. };
  13620. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13622. ASSERT_EQ(StatusCode::OK_200, res->status);
  13623. }
  13624. }
  13625. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13626. std::string data(1024 * 1024 * 2, '&');
  13627. std::stringstream buffer;
  13628. buffer << data;
  13629. Client cli("https://localhost:8080");
  13630. cli.enable_server_certificate_verification(false);
  13631. UploadFormDataItems items{
  13632. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13633. {"hello", "world", "", ""},
  13634. };
  13635. for (const char &c : " \t\r\n") {
  13636. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13637. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13638. ASSERT_FALSE(res);
  13639. }
  13640. }
  13641. TEST(MultipartFormDataTest, AlternateFilename) {
  13642. auto handled = false;
  13643. Server svr;
  13644. svr.Post("/test", [&](const Request &req, Response &res) {
  13645. ASSERT_EQ(2u, req.form.files.size());
  13646. ASSERT_EQ(1u, req.form.fields.size());
  13647. // Test files
  13648. const auto &file1 = req.form.get_file("file1");
  13649. ASSERT_EQ("file1", file1.name);
  13650. ASSERT_EQ("A.txt", file1.filename);
  13651. ASSERT_EQ("text/plain", file1.content_type);
  13652. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13653. const auto &file2 = req.form.get_file("file2");
  13654. ASSERT_EQ("file2", file2.name);
  13655. ASSERT_EQ("a.html", file2.filename);
  13656. ASSERT_EQ("text/html", file2.content_type);
  13657. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13658. file2.content);
  13659. // Test text field
  13660. const auto &text = req.form.get_field("text");
  13661. ASSERT_EQ("text default", text);
  13662. res.set_content("ok", "text/plain");
  13663. handled = true;
  13664. });
  13665. thread t = thread([&] { svr.listen(HOST, PORT); });
  13666. auto se = detail::scope_exit([&] {
  13667. svr.stop();
  13668. t.join();
  13669. ASSERT_FALSE(svr.is_running());
  13670. ASSERT_TRUE(handled);
  13671. });
  13672. svr.wait_until_ready();
  13673. auto req = "POST /test HTTP/1.1\r\n"
  13674. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13675. "Content-Length: 399\r\n"
  13676. "\r\n"
  13677. "----------\r\n"
  13678. "Content-Disposition: form-data; name=\"text\"\r\n"
  13679. "\r\n"
  13680. "text default\r\n"
  13681. "----------\r\n"
  13682. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13683. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13684. "Content-Type: text/plain\r\n"
  13685. "\r\n"
  13686. "Content of a.txt.\r\n"
  13687. "\r\n"
  13688. "----------\r\n"
  13689. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13690. "\"a.html\"\r\n"
  13691. "Content-Type: text/html\r\n"
  13692. "\r\n"
  13693. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13694. "\r\n"
  13695. "------------\r\n";
  13696. ASSERT_TRUE(send_request(1, req));
  13697. }
  13698. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13699. auto handled = false;
  13700. Server svr;
  13701. svr.Post("/test", [&](const Request &req, Response &res) {
  13702. // Case-insensitive "utf-8''" prefix with a long value
  13703. const auto &file = req.form.get_file("file1");
  13704. ASSERT_EQ("file1", file.name);
  13705. // 8000 chars exercises both the Content-Disposition parser and the
  13706. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13707. // Prior to the fix, std::regex_match on this header would cause O(N)
  13708. // stack recursion in libstdc++, leading to SIGSEGV.
  13709. std::string expected_filename(8000, 'A');
  13710. ASSERT_EQ(expected_filename, file.filename);
  13711. res.set_content("ok", "text/plain");
  13712. handled = true;
  13713. });
  13714. thread t = thread([&] { svr.listen(HOST, PORT); });
  13715. auto se = detail::scope_exit([&] {
  13716. svr.stop();
  13717. t.join();
  13718. ASSERT_FALSE(svr.is_running());
  13719. ASSERT_TRUE(handled);
  13720. });
  13721. svr.wait_until_ready();
  13722. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13723. // Regression test for GHSA-qq6v-r583-3h69
  13724. std::string long_filename(8000, 'A');
  13725. std::string body = "----------\r\n"
  13726. "Content-Disposition: form-data; name=\"file1\"; "
  13727. "filename*=\"Utf-8''" +
  13728. long_filename +
  13729. "\"\r\n"
  13730. "\r\n"
  13731. "hello\r\n"
  13732. "------------\r\n";
  13733. auto req = "POST /test HTTP/1.1\r\n"
  13734. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13735. "Content-Length: " +
  13736. std::to_string(body.size()) + "\r\n\r\n" + body;
  13737. ASSERT_TRUE(send_request(1, req));
  13738. }
  13739. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13740. auto handled = false;
  13741. Server svr;
  13742. svr.Post("/test", [&](const Request &req, Response &) {
  13743. ASSERT_EQ(2u, req.form.fields.size());
  13744. const auto &text1 = req.form.get_field("text1");
  13745. ASSERT_EQ("text1", text1);
  13746. const auto &text2 = req.form.get_field("text2");
  13747. ASSERT_EQ("text2", text2);
  13748. handled = true;
  13749. });
  13750. thread t = thread([&] { svr.listen(HOST, PORT); });
  13751. auto se = detail::scope_exit([&] {
  13752. svr.stop();
  13753. t.join();
  13754. ASSERT_FALSE(svr.is_running());
  13755. ASSERT_TRUE(handled);
  13756. });
  13757. svr.wait_until_ready();
  13758. auto req = "POST /test HTTP/1.1\r\n"
  13759. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13760. "Content-Length: 146\r\n"
  13761. "\r\n----------\r\n"
  13762. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13763. "\r\n"
  13764. "text1"
  13765. "\r\n----------\r\n"
  13766. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13767. "\r\n"
  13768. "text2"
  13769. "\r\n------------";
  13770. std::string response;
  13771. ASSERT_TRUE(send_request(1, req, &response));
  13772. ASSERT_EQ("200", response.substr(9, 3));
  13773. }
  13774. TEST(MultipartFormDataTest, ContentLength) {
  13775. auto handled = false;
  13776. Server svr;
  13777. svr.Post("/test", [&](const Request &req, Response &) {
  13778. ASSERT_EQ(2u, req.form.fields.size());
  13779. const auto &text1 = req.form.get_field("text1");
  13780. ASSERT_EQ("text1", text1);
  13781. const auto &text2 = req.form.get_field("text2");
  13782. ASSERT_EQ("text2", text2);
  13783. handled = true;
  13784. });
  13785. thread t = thread([&] { svr.listen(HOST, PORT); });
  13786. auto se = detail::scope_exit([&] {
  13787. svr.stop();
  13788. t.join();
  13789. ASSERT_FALSE(svr.is_running());
  13790. ASSERT_TRUE(handled);
  13791. });
  13792. svr.wait_until_ready();
  13793. auto req = "POST /test HTTP/1.1\r\n"
  13794. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13795. "Content-Length: 167\r\n"
  13796. "\r\n----------\r\n"
  13797. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13798. "Content-Length: 5\r\n"
  13799. "\r\n"
  13800. "text1"
  13801. "\r\n----------\r\n"
  13802. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13803. "\r\n"
  13804. "text2"
  13805. "\r\n------------\r\n";
  13806. std::string response;
  13807. ASSERT_TRUE(send_request(1, req, &response));
  13808. ASSERT_EQ("200", response.substr(9, 3));
  13809. }
  13810. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13811. auto handled = false;
  13812. Server svr;
  13813. svr.Post("/test", [&](const Request &req, Response &) {
  13814. ASSERT_EQ(2u, req.form.fields.size());
  13815. const auto &text1 = req.form.get_field("text1");
  13816. ASSERT_EQ("text1", text1);
  13817. // TODO: Add header access for text fields if needed
  13818. const auto &text2 = req.form.get_field("text2");
  13819. ASSERT_EQ("text2", text2);
  13820. // TODO: Header access for text fields needs to be implemented
  13821. // auto &headers = it->second.headers;
  13822. // ASSERT_EQ(3U, headers.size());
  13823. // auto custom_header = headers.find("x-whatever");
  13824. // ASSERT_TRUE(custom_header != headers.end());
  13825. // ASSERT_NE("customvalue", custom_header->second);
  13826. // ASSERT_EQ("CustomValue", custom_header->second);
  13827. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13828. handled = true;
  13829. });
  13830. thread t = thread([&] { svr.listen(HOST, PORT); });
  13831. auto se = detail::scope_exit([&] {
  13832. svr.stop();
  13833. t.join();
  13834. ASSERT_FALSE(svr.is_running());
  13835. ASSERT_TRUE(handled);
  13836. });
  13837. svr.wait_until_ready();
  13838. auto req = "POST /test HTTP/1.1\r\n"
  13839. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13840. "Content-Length: 232\r\n"
  13841. "\r\n----------\r\n"
  13842. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13843. "Content-Length: 5\r\n"
  13844. "X-Test: 1\r\n"
  13845. "\r\n"
  13846. "text1"
  13847. "\r\n----------\r\n"
  13848. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13849. "Content-Type: text/plain\r\n"
  13850. "X-Whatever: CustomValue\r\n"
  13851. "\r\n"
  13852. "text2"
  13853. "\r\n------------\r\n"
  13854. "That should be disregarded. Not even read";
  13855. std::string response;
  13856. ASSERT_TRUE(send_request(1, req, &response));
  13857. ASSERT_EQ("200", response.substr(9, 3));
  13858. }
  13859. TEST(MultipartFormDataTest, LargeHeader) {
  13860. auto handled = false;
  13861. Server svr;
  13862. svr.Post("/test", [&](const Request &req, Response &) {
  13863. ASSERT_EQ(1u, req.form.fields.size());
  13864. const auto &text = req.form.get_field("name1");
  13865. ASSERT_EQ("text1", text);
  13866. handled = true;
  13867. });
  13868. thread t = thread([&] { svr.listen(HOST, PORT); });
  13869. auto se = detail::scope_exit([&] {
  13870. svr.stop();
  13871. t.join();
  13872. ASSERT_FALSE(svr.is_running());
  13873. ASSERT_TRUE(handled);
  13874. });
  13875. svr.wait_until_ready();
  13876. auto boundary = std::string("cpp-httplib-multipart-data");
  13877. std::string content = "--" + boundary +
  13878. "\r\n"
  13879. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13880. "\r\n"
  13881. "text1\r\n"
  13882. "--" +
  13883. boundary + "--\r\n";
  13884. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13885. "Content-Type: multipart/form-data;boundary=" +
  13886. boundary +
  13887. "\r\n"
  13888. "Content-Length: " +
  13889. std::to_string(content.size()) +
  13890. "\r\n"
  13891. "Dummy-Header: ";
  13892. std::string header_suffix = "\r\n"
  13893. "\r\n";
  13894. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13895. size_t header_dummy_size =
  13896. read_buff_size -
  13897. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13898. auto header_dummy = std::string(header_dummy_size, '@');
  13899. auto req = header_prefix + header_dummy + header_suffix + content;
  13900. std::string response;
  13901. ASSERT_TRUE(send_request(1, req, &response));
  13902. ASSERT_EQ("200", response.substr(9, 3));
  13903. }
  13904. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13905. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13906. // (not chunked Transfer-Encoding) after the streaming refactor.
  13907. auto handled = false;
  13908. Server svr;
  13909. svr.Post("/upload", [&](const Request &req, Response &res) {
  13910. auto cl_it = req.headers.find("Content-Length");
  13911. EXPECT_TRUE(cl_it != req.headers.end());
  13912. auto te_it = req.headers.find("Transfer-Encoding");
  13913. EXPECT_TRUE(te_it == req.headers.end());
  13914. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13915. res.set_content("ok", "text/plain");
  13916. handled = true;
  13917. });
  13918. auto port = svr.bind_to_any_port(HOST);
  13919. auto t = thread([&] { svr.listen_after_bind(); });
  13920. auto se = detail::scope_exit([&] {
  13921. svr.stop();
  13922. t.join();
  13923. ASSERT_FALSE(svr.is_running());
  13924. ASSERT_TRUE(handled);
  13925. });
  13926. svr.wait_until_ready();
  13927. UploadFormDataItems items = {
  13928. {"field1", "hello", "", "text/plain"},
  13929. {"file1", "world", "test.txt", "application/octet-stream"},
  13930. };
  13931. Client cli(HOST, port);
  13932. auto res = cli.Post("/upload", {}, items);
  13933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13934. EXPECT_EQ(StatusCode::OK_200, res->status);
  13935. }
  13936. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13937. // Verify that make_multipart_content_provider coalesces many small segments
  13938. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13939. constexpr size_t kItemCount = 1000;
  13940. UploadFormDataItems items;
  13941. items.reserve(kItemCount);
  13942. for (size_t i = 0; i < kItemCount; i++) {
  13943. items.push_back(
  13944. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13945. }
  13946. const std::string boundary = "----test-boundary";
  13947. auto content_length = detail::get_multipart_content_length(items, boundary);
  13948. auto provider = detail::make_multipart_content_provider(items, boundary);
  13949. // Drive the provider the same way write_content_with_progress does
  13950. size_t write_count = 0;
  13951. size_t total_bytes = 0;
  13952. DataSink sink;
  13953. size_t offset = 0;
  13954. sink.write = [&](const char *d, size_t l) -> bool {
  13955. (void)d;
  13956. write_count++;
  13957. total_bytes += l;
  13958. offset += l;
  13959. return true;
  13960. };
  13961. sink.is_writable = []() -> bool { return true; };
  13962. while (offset < content_length) {
  13963. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13964. }
  13965. EXPECT_EQ(content_length, total_bytes);
  13966. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13967. // With buffering into 64KB blocks, write_count should be much smaller.
  13968. auto segment_count = 3 * kItemCount + 1;
  13969. EXPECT_LT(write_count, segment_count / 10);
  13970. }
  13971. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13972. // Integration test: send many UploadFormDataItems and verify the server
  13973. // receives all of them correctly (#2410).
  13974. constexpr size_t kItemCount = 500;
  13975. auto handled = false;
  13976. Server svr;
  13977. svr.Post("/upload", [&](const Request &req, Response &res) {
  13978. EXPECT_EQ(kItemCount, req.form.fields.size());
  13979. for (size_t i = 0; i < kItemCount; i++) {
  13980. auto key = "field" + std::to_string(i);
  13981. auto val = "value" + std::to_string(i);
  13982. auto it = req.form.fields.find(key);
  13983. if (it != req.form.fields.end()) {
  13984. EXPECT_EQ(val, it->second.content);
  13985. } else {
  13986. ADD_FAILURE() << "Missing field: " << key;
  13987. }
  13988. }
  13989. res.set_content("ok", "text/plain");
  13990. handled = true;
  13991. });
  13992. auto port = svr.bind_to_any_port(HOST);
  13993. auto t = thread([&] { svr.listen_after_bind(); });
  13994. auto se = detail::scope_exit([&] {
  13995. svr.stop();
  13996. t.join();
  13997. ASSERT_FALSE(svr.is_running());
  13998. ASSERT_TRUE(handled);
  13999. });
  14000. svr.wait_until_ready();
  14001. UploadFormDataItems items;
  14002. items.reserve(kItemCount);
  14003. for (size_t i = 0; i < kItemCount; i++) {
  14004. items.push_back(
  14005. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14006. }
  14007. Client cli(HOST, port);
  14008. auto res = cli.Post("/upload", items);
  14009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14010. EXPECT_EQ(StatusCode::OK_200, res->status);
  14011. }
  14012. TEST(MultipartFormDataTest, MakeFileProvider) {
  14013. // Verify make_file_provider sends a file's contents correctly.
  14014. const std::string file_content(4096, 'Z');
  14015. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14016. {
  14017. std::ofstream ofs(tmp_path, std::ios::binary);
  14018. ofs.write(file_content.data(),
  14019. static_cast<std::streamsize>(file_content.size()));
  14020. }
  14021. auto handled = false;
  14022. Server svr;
  14023. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14024. const ContentReader &content_reader) {
  14025. ASSERT_TRUE(req.is_multipart_form_data());
  14026. std::vector<FormData> items;
  14027. content_reader(
  14028. [&](const FormData &file) {
  14029. items.push_back(file);
  14030. return true;
  14031. },
  14032. [&](const char *data, size_t data_length) {
  14033. items.back().content.append(data, data_length);
  14034. return true;
  14035. });
  14036. ASSERT_EQ(1u, items.size());
  14037. EXPECT_EQ("myfile", items[0].name);
  14038. EXPECT_EQ("data.bin", items[0].filename);
  14039. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14040. EXPECT_EQ(file_content, items[0].content);
  14041. handled = true;
  14042. });
  14043. auto port = svr.bind_to_any_port(HOST);
  14044. auto t = thread([&] { svr.listen_after_bind(); });
  14045. auto se = detail::scope_exit([&] {
  14046. svr.stop();
  14047. t.join();
  14048. ASSERT_FALSE(svr.is_running());
  14049. ASSERT_TRUE(handled);
  14050. std::remove(tmp_path.c_str());
  14051. });
  14052. svr.wait_until_ready();
  14053. FormDataProviderItems providers;
  14054. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14055. "application/octet-stream"));
  14056. Client cli(HOST, port);
  14057. auto res = cli.Post("/upload", {}, {}, providers);
  14058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14059. EXPECT_EQ(StatusCode::OK_200, res->status);
  14060. }
  14061. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14062. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14063. // (100) headers is rejected with a 400 Bad Request response.
  14064. Server svr;
  14065. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14066. res.set_content("ok", "text/plain");
  14067. });
  14068. thread t = thread([&] { svr.listen(HOST, PORT); });
  14069. auto se = detail::scope_exit([&] {
  14070. svr.stop();
  14071. t.join();
  14072. ASSERT_FALSE(svr.is_running());
  14073. });
  14074. svr.wait_until_ready();
  14075. // Build a multipart part with 101 custom headers (exceeding
  14076. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14077. std::stringstream body;
  14078. body << "--simpleboundary\r\n"
  14079. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14080. for (int i = 0; i < 101; i++) {
  14081. body << "X-Custom-Header-" << i << ": value\r\n";
  14082. }
  14083. body << "\r\n"
  14084. << "value1\r\n"
  14085. << "--simpleboundary--\r\n";
  14086. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14087. Client cli(HOST, PORT);
  14088. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14090. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14091. }
  14092. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14093. // A body that never contains the declared boundary must not be accumulated
  14094. // while the parser waits for it. Buffering it would also make every read
  14095. // rescan everything seen so far, which is quadratic in the body size.
  14096. Server svr;
  14097. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14098. res.set_content("ok", "text/plain");
  14099. });
  14100. auto port = svr.bind_to_any_port(HOST);
  14101. thread t = thread([&] { svr.listen_after_bind(); });
  14102. auto se = detail::scope_exit([&] {
  14103. svr.stop();
  14104. t.join();
  14105. ASSERT_FALSE(svr.is_running());
  14106. });
  14107. svr.wait_until_ready();
  14108. Client cli(HOST, port);
  14109. cli.set_read_timeout(60, 0);
  14110. cli.set_write_timeout(60, 0);
  14111. // '-' is the worst case: it matches the first character of the boundary, so
  14112. // every position has to be checked against it.
  14113. auto post_dashes = [&](size_t size) {
  14114. const std::string body(size, '-');
  14115. auto start = std::chrono::steady_clock::now();
  14116. auto res =
  14117. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14118. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14119. std::chrono::steady_clock::now() - start)
  14120. .count();
  14121. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14122. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14123. return ms;
  14124. };
  14125. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14126. // Windows.
  14127. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14128. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14129. // Comparing the two sizes rather than checking an absolute duration keeps
  14130. // this meaningful across build types and CI load, both of which move the
  14131. // absolute numbers by more than an order of magnitude. Four times the bytes
  14132. // costs about four times the time when parsing is linear, and about sixteen
  14133. // times when the body is buffered and rescanned.
  14134. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14135. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14136. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14137. << "ms, which suggests the body is being buffered and rescanned";
  14138. }
  14139. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14140. // A boundary can only be followed by CRLF or by "--", so anything else is
  14141. // malformed no matter what comes next. The parser must say so right away
  14142. // instead of buffering the rest of the declared body.
  14143. Server svr;
  14144. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14145. res.set_content("ok", "text/plain");
  14146. });
  14147. auto port = svr.bind_to_any_port(HOST);
  14148. thread t = thread([&] { svr.listen_after_bind(); });
  14149. auto se = detail::scope_exit([&] {
  14150. svr.stop();
  14151. t.join();
  14152. ASSERT_FALSE(svr.is_running());
  14153. });
  14154. svr.wait_until_ready();
  14155. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14156. // buffers instead of failing would still be waiting for the remaining bytes.
  14157. const std::string body = "--zzzz\r\n"
  14158. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14159. "\r\n"
  14160. "text1"
  14161. "\r\n--zzzzXX";
  14162. const std::string req = "POST /post HTTP/1.1\r\n"
  14163. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14164. "Content-Length: 1048576\r\n"
  14165. "\r\n" +
  14166. body;
  14167. std::string response;
  14168. ASSERT_TRUE(send_request(3, req, &response, port));
  14169. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14170. EXPECT_EQ("400", response.substr(9, 3));
  14171. }
  14172. // Posts a multipart body split into two writes, so that the server sees the
  14173. // split at whatever offset the caller chose, and expects the single "text1"
  14174. // field to come through.
  14175. static void expect_split_multipart_ok(const std::string &body1,
  14176. const std::string &body2) {
  14177. auto handled = false;
  14178. Server svr;
  14179. svr.Post("/post", [&](const Request &req, Response &) {
  14180. EXPECT_EQ(1u, req.form.fields.size());
  14181. EXPECT_EQ("text1", req.form.get_field("text1"));
  14182. handled = true;
  14183. });
  14184. auto port = svr.bind_to_any_port(HOST);
  14185. thread t = thread([&] { svr.listen_after_bind(); });
  14186. auto se = detail::scope_exit([&] {
  14187. svr.stop();
  14188. t.join();
  14189. ASSERT_FALSE(svr.is_running());
  14190. ASSERT_TRUE(handled);
  14191. });
  14192. svr.wait_until_ready();
  14193. // "Connection: close" makes the server close once it has answered, so the
  14194. // response drain ends immediately instead of idling until the read timeout.
  14195. const std::string head =
  14196. "POST /post HTTP/1.1\r\n"
  14197. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14198. "Connection: close\r\n"
  14199. "Content-Length: " +
  14200. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14201. std::string response;
  14202. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14203. ASSERT_GE(response.size(), 12u) << "no response";
  14204. EXPECT_EQ("200", response.substr(9, 3));
  14205. }
  14206. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14207. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14208. // ignored, including when it does not arrive in the same read as the
  14209. // close-delimiter itself.
  14210. expect_split_multipart_ok("--zzzz\r\n"
  14211. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14212. "\r\n"
  14213. "text1"
  14214. "\r\n--zzzz--",
  14215. "\r\nthis epilogue must be ignored\r\n");
  14216. }
  14217. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14218. // The initial boundary may be preceded by a preamble of any length and may
  14219. // straddle a read boundary. Discarding data while waiting for it must not
  14220. // throw away a partial boundary sitting at the end of the buffer.
  14221. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14222. "zz\r\n"
  14223. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14224. "\r\n"
  14225. "text1"
  14226. "\r\n--zzzz--\r\n");
  14227. }
  14228. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14229. // The received boundary was only checked for being non-empty, so it could be
  14230. // as long as a header is allowed to be. The parser scans the body for
  14231. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14232. // costs a nearly full comparison at nearly every position, making the
  14233. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14234. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14235. Server svr;
  14236. svr.Post("/post", [](const Request &req, Response &res) {
  14237. EXPECT_EQ(1u, req.form.fields.size());
  14238. EXPECT_EQ("text1", req.form.get_field("text1"));
  14239. res.set_content("ok", "text/plain");
  14240. });
  14241. auto port = svr.bind_to_any_port(HOST);
  14242. thread t = thread([&] { svr.listen_after_bind(); });
  14243. auto se = detail::scope_exit([&] {
  14244. svr.stop();
  14245. t.join();
  14246. ASSERT_FALSE(svr.is_running());
  14247. });
  14248. svr.wait_until_ready();
  14249. Client cli(HOST, port);
  14250. auto post_with_boundary_of_length = [&](size_t len) {
  14251. const std::string boundary(len, 'a');
  14252. const std::string body =
  14253. "--" + boundary +
  14254. "\r\n"
  14255. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14256. "\r\n"
  14257. "text1"
  14258. "\r\n--" +
  14259. boundary + "--\r\n";
  14260. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14261. };
  14262. auto res = post_with_boundary_of_length(70);
  14263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14264. EXPECT_EQ(StatusCode::OK_200, res->status);
  14265. res = post_with_boundary_of_length(71);
  14266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14267. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14268. }
  14269. TEST(MakeFileBodyTest, Basic) {
  14270. const std::string file_content(4096, 'Z');
  14271. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14272. {
  14273. std::ofstream ofs(tmp_path, std::ios::binary);
  14274. ofs.write(file_content.data(),
  14275. static_cast<std::streamsize>(file_content.size()));
  14276. }
  14277. auto handled = false;
  14278. Server svr;
  14279. svr.Post("/upload", [&](const Request &req, Response &res) {
  14280. EXPECT_EQ(file_content, req.body);
  14281. handled = true;
  14282. res.status = StatusCode::OK_200;
  14283. });
  14284. auto port = svr.bind_to_any_port(HOST);
  14285. auto t = thread([&] { svr.listen_after_bind(); });
  14286. auto se = detail::scope_exit([&] {
  14287. svr.stop();
  14288. t.join();
  14289. ASSERT_FALSE(svr.is_running());
  14290. ASSERT_TRUE(handled);
  14291. std::remove(tmp_path.c_str());
  14292. });
  14293. svr.wait_until_ready();
  14294. auto fb = make_file_body(tmp_path);
  14295. ASSERT_GT(fb.first, 0u);
  14296. Client cli(HOST, port);
  14297. auto res =
  14298. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14300. EXPECT_EQ(StatusCode::OK_200, res->status);
  14301. }
  14302. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14303. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14304. {
  14305. std::ofstream ofs(path, std::ios::binary);
  14306. const std::string content(100, 'A');
  14307. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14308. }
  14309. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14310. auto body = make_file_body(path);
  14311. ASSERT_EQ(100u, body.first);
  14312. ASSERT_TRUE(static_cast<bool>(body.second));
  14313. // Rewritten shorter after its length was measured - and, on a server, after
  14314. // that length has already gone out as Content-Length.
  14315. {
  14316. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14317. const std::string content(10, 'A');
  14318. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14319. }
  14320. std::string written;
  14321. DataSink sink;
  14322. sink.write = [&](const char *d, size_t l) {
  14323. written.append(d, l);
  14324. return true;
  14325. };
  14326. // The provider has to report failure. write_content_with_progress() advances
  14327. // its offset only by what was written, so a provider that returns true
  14328. // without completing the length it promised is called again straight away,
  14329. // and again.
  14330. EXPECT_FALSE(body.second(0, body.first, sink));
  14331. EXPECT_EQ(std::string(10, 'A'), written);
  14332. }
  14333. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14334. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14335. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14336. {
  14337. std::ofstream ofs(path, std::ios::binary);
  14338. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14339. }
  14340. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14341. auto body = make_file_body(path);
  14342. ASSERT_EQ(content.size(), body.first);
  14343. ASSERT_TRUE(static_cast<bool>(body.second));
  14344. std::string written;
  14345. DataSink sink;
  14346. sink.write = [&](const char *d, size_t l) {
  14347. written.append(d, l);
  14348. return true;
  14349. };
  14350. EXPECT_TRUE(body.second(0, body.first, sink));
  14351. EXPECT_EQ(content, written);
  14352. }
  14353. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14354. static constexpr unsigned int number_of_tasks{1000000};
  14355. std::atomic_uint count{0};
  14356. std::unique_ptr<TaskQueue> task_queue{
  14357. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14358. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14359. auto queued = task_queue->enqueue(
  14360. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14361. EXPECT_TRUE(queued);
  14362. }
  14363. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14364. task_queue->shutdown();
  14365. #else
  14366. EXPECT_NO_THROW(task_queue->shutdown());
  14367. #endif
  14368. EXPECT_EQ(number_of_tasks, count.load());
  14369. }
  14370. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14371. static constexpr unsigned int number_of_tasks{1000000};
  14372. static constexpr unsigned int qlimit{2};
  14373. unsigned int queued_count{0};
  14374. std::atomic_uint count{0};
  14375. std::unique_ptr<TaskQueue> task_queue{
  14376. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14377. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14378. if (task_queue->enqueue(
  14379. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14380. queued_count++;
  14381. }
  14382. }
  14383. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14384. task_queue->shutdown();
  14385. #else
  14386. EXPECT_NO_THROW(task_queue->shutdown());
  14387. #endif
  14388. EXPECT_EQ(queued_count, count.load());
  14389. EXPECT_TRUE(queued_count <= number_of_tasks);
  14390. EXPECT_TRUE(queued_count >= qlimit);
  14391. }
  14392. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14393. // Use a short idle timeout so a dynamic thread spawns, times out and
  14394. // exits during the test, and the pool keeps working afterwards.
  14395. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14396. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14397. /*idle_timeout_sec=*/1}};
  14398. std::atomic_uint count{0};
  14399. std::condition_variable cv;
  14400. std::mutex mtx;
  14401. bool release = false;
  14402. // Block the base thread so the second task spawns a dynamic thread.
  14403. EXPECT_TRUE(task_queue->enqueue([&] {
  14404. std::unique_lock<std::mutex> lock(mtx);
  14405. while (!release) {
  14406. cv.wait(lock);
  14407. }
  14408. count++;
  14409. }));
  14410. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14411. // Let the dynamic thread finish its task and exceed the idle timeout.
  14412. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14413. {
  14414. std::unique_lock<std::mutex> lock(mtx);
  14415. release = true;
  14416. }
  14417. cv.notify_all();
  14418. // The pool must still accept and run tasks after the dynamic thread exited.
  14419. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14420. task_queue->shutdown();
  14421. EXPECT_EQ(3u, count.load());
  14422. }
  14423. TEST(TaskQueueTest, MaxQueuedRequests) {
  14424. static constexpr unsigned int qlimit{3};
  14425. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14426. std::condition_variable sem_cv;
  14427. std::mutex sem_mtx;
  14428. int credits = 0;
  14429. bool queued;
  14430. /* Fill up the queue with tasks that will block until we give them credits to
  14431. * complete. */
  14432. for (unsigned int n = 0; n <= qlimit;) {
  14433. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14434. std::unique_lock<std::mutex> lock(sem_mtx);
  14435. while (credits <= 0) {
  14436. sem_cv.wait(lock);
  14437. }
  14438. /* Consume the credit and signal the test code if they are all gone. */
  14439. if (--credits == 0) { sem_cv.notify_one(); }
  14440. });
  14441. if (n < qlimit) {
  14442. /* The first qlimit enqueues must succeed. */
  14443. EXPECT_TRUE(queued);
  14444. } else {
  14445. /* The last one will succeed only when the worker thread
  14446. * starts and dequeues the first blocking task. Although
  14447. * not necessary for the correctness of this test, we sleep for
  14448. * a short while to avoid busy waiting. */
  14449. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14450. }
  14451. if (queued) { n++; }
  14452. }
  14453. /* Further enqueues must fail since the queue is full. */
  14454. for (auto i = 0; i < 4; i++) {
  14455. queued = task_queue->enqueue([] {});
  14456. EXPECT_FALSE(queued);
  14457. }
  14458. /* Give the credits to allow the previous tasks to complete. */
  14459. {
  14460. std::unique_lock<std::mutex> lock(sem_mtx);
  14461. credits += qlimit + 1;
  14462. }
  14463. sem_cv.notify_all();
  14464. /* Wait for all the credits to be consumed. */
  14465. {
  14466. std::unique_lock<std::mutex> lock(sem_mtx);
  14467. while (credits > 0) {
  14468. sem_cv.wait(lock);
  14469. }
  14470. }
  14471. /* Check that we are able again to enqueue at least qlimit tasks. */
  14472. for (unsigned int i = 0; i < qlimit; i++) {
  14473. queued = task_queue->enqueue([] {});
  14474. EXPECT_TRUE(queued);
  14475. }
  14476. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14477. task_queue->shutdown();
  14478. #else
  14479. EXPECT_NO_THROW(task_queue->shutdown());
  14480. #endif
  14481. }
  14482. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14483. Server svr;
  14484. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14485. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14486. });
  14487. svr.Get("/hello", [](const Request &req, Response &res) {
  14488. res.set_content(req.get_param_value("key"), "text/plain");
  14489. });
  14490. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14491. auto se = detail::scope_exit([&] {
  14492. svr.stop();
  14493. thread.join();
  14494. ASSERT_FALSE(svr.is_running());
  14495. });
  14496. svr.wait_until_ready();
  14497. {
  14498. Client cli(HOST, PORT);
  14499. cli.set_follow_location(true);
  14500. auto res = cli.Get("/");
  14501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14502. EXPECT_EQ(StatusCode::OK_200, res->status);
  14503. EXPECT_EQ("val&key2=val2", res->body);
  14504. }
  14505. }
  14506. #endif
  14507. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14508. Server svr;
  14509. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14510. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14511. });
  14512. svr.Get("/hello", [](const Request &req, Response &res) {
  14513. res.set_content(req.get_param_value("key"), "text/plain");
  14514. });
  14515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14516. auto se = detail::scope_exit([&] {
  14517. svr.stop();
  14518. thread.join();
  14519. ASSERT_FALSE(svr.is_running());
  14520. });
  14521. svr.wait_until_ready();
  14522. {
  14523. Client cli(HOST, PORT);
  14524. cli.set_follow_location(true);
  14525. auto res = cli.Get("/");
  14526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14527. EXPECT_EQ(StatusCode::OK_200, res->status);
  14528. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14529. }
  14530. }
  14531. TEST(RedirectTest, RedirectWithPlusInPath) {
  14532. Server svr;
  14533. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14534. res.set_redirect("/a+b");
  14535. });
  14536. // Route pattern uses regex; escape + as \\+
  14537. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14538. res.set_content(req.path, "text/plain");
  14539. });
  14540. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14541. auto se = detail::scope_exit([&] {
  14542. svr.stop();
  14543. thread.join();
  14544. ASSERT_FALSE(svr.is_running());
  14545. });
  14546. svr.wait_until_ready();
  14547. {
  14548. Client cli(HOST, PORT);
  14549. cli.set_follow_location(true);
  14550. auto res = cli.Get("/");
  14551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14552. EXPECT_EQ(StatusCode::OK_200, res->status);
  14553. EXPECT_EQ("/a+b", res->body);
  14554. }
  14555. }
  14556. TEST(RedirectTest, ResolveRelativeLocation) {
  14557. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14558. const std::vector<std::pair<std::string, std::string>> cases = {
  14559. {"g", "/b/c/g"},
  14560. {"./g", "/b/c/g"},
  14561. {"g/", "/b/c/g/"},
  14562. {"?y", "/b/c/d;p?y"},
  14563. {"g?y", "/b/c/g?y"},
  14564. {"#s", "/b/c/d;p?q#s"},
  14565. {"g#s", "/b/c/g#s"},
  14566. {"g?y#s", "/b/c/g?y#s"},
  14567. {";x", "/b/c/;x"},
  14568. {"g;x", "/b/c/g;x"},
  14569. {".", "/b/c/"},
  14570. {"./", "/b/c/"},
  14571. {"..", "/b/"},
  14572. {"../", "/b/"},
  14573. {"../g", "/b/g"},
  14574. {"../..", "/"},
  14575. {"../../", "/"},
  14576. {"../../g", "/g"},
  14577. {"../../../g", "/g"},
  14578. {"g.", "/b/c/g."},
  14579. {".g", "/b/c/.g"},
  14580. {"g..", "/b/c/g.."},
  14581. {"..g", "/b/c/..g"},
  14582. {"./../g", "/b/g"},
  14583. {"./g/.", "/b/c/g/"},
  14584. {"g/./h", "/b/c/g/h"},
  14585. {"g/../h", "/b/c/h"},
  14586. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14587. {"g;x=1/../y", "/b/c/y"},
  14588. {"g?y/./x", "/b/c/g?y/./x"},
  14589. {"g#s/../x", "/b/c/g#s/../x"},
  14590. // Not relative-path references, so left for parse_url.
  14591. {"/g", "/g"},
  14592. {"//g", "//g"},
  14593. {"http://g/x", "http://g/x"},
  14594. {"g:h", "g:h"},
  14595. };
  14596. for (const auto &c : cases) {
  14597. EXPECT_EQ(c.second,
  14598. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  14599. << c.first;
  14600. }
  14601. }
  14602. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  14603. Server svr;
  14604. svr.Get("/dir/page", [](const Request &req, Response &res) {
  14605. res.set_redirect(req.get_param_value("to"));
  14606. });
  14607. svr.Get("/dir/next", [](const Request &req, Response &res) {
  14608. res.set_content(req.target, "text/plain");
  14609. });
  14610. svr.Get("/other", [](const Request &req, Response &res) {
  14611. res.set_content(req.target, "text/plain");
  14612. });
  14613. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14614. auto se = detail::scope_exit([&] {
  14615. svr.stop();
  14616. thread.join();
  14617. ASSERT_FALSE(svr.is_running());
  14618. });
  14619. svr.wait_until_ready();
  14620. const std::vector<std::pair<std::string, std::string>> cases = {
  14621. {"next", "/dir/next"},
  14622. {"./next?x=1", "/dir/next?x=1"},
  14623. {"../other", "/other"},
  14624. };
  14625. for (const auto &c : cases) {
  14626. Client cli(HOST, PORT);
  14627. cli.set_follow_location(true);
  14628. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  14629. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  14630. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  14631. EXPECT_EQ(c.second, res->body) << c.first;
  14632. }
  14633. }
  14634. #ifdef CPPHTTPLIB_SSL_ENABLED
  14635. TEST(RedirectTest, Issue2185_Online) {
  14636. SSLClient client("github.com");
  14637. client.set_follow_location(true);
  14638. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14639. "Coollab-Windows.zip");
  14640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14641. EXPECT_EQ(StatusCode::OK_200, res->status);
  14642. EXPECT_EQ(9920427U, res->body.size());
  14643. }
  14644. #endif
  14645. TEST(VulnerabilityTest, CRLFInjection) {
  14646. Server svr;
  14647. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14648. res.set_content("Hello 1", "text/plain");
  14649. });
  14650. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14651. res.set_content("Hello 2", "text/plain");
  14652. });
  14653. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14654. res.set_content("Hello 3", "text/plain");
  14655. });
  14656. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14657. res.set_content("Hello 4", "text/plain");
  14658. });
  14659. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14660. for (const auto &x : req.headers) {
  14661. auto key = x.first;
  14662. EXPECT_STRNE("evil", key.c_str());
  14663. }
  14664. });
  14665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14666. auto se = detail::scope_exit([&] {
  14667. svr.stop();
  14668. thread.join();
  14669. ASSERT_FALSE(svr.is_running());
  14670. });
  14671. svr.wait_until_ready();
  14672. {
  14673. Client cli(HOST, PORT);
  14674. cli.Post("/test1", "A=B",
  14675. "application/x-www-form-urlencoded\r\nevil: hello1");
  14676. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14677. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14678. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14679. }
  14680. }
  14681. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14682. auto server_thread = std::thread([] {
  14683. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14684. default_socket_options(srv);
  14685. sockaddr_in addr{};
  14686. addr.sin_family = AF_INET;
  14687. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14688. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14689. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14690. ::listen(srv, 1);
  14691. sockaddr_in cli_addr{};
  14692. socklen_t cli_len = sizeof(cli_addr);
  14693. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14694. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14695. std::string buf_all;
  14696. char buf[2048];
  14697. ssize_t n;
  14698. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14699. buf_all.append(buf, static_cast<size_t>(n));
  14700. size_t pos;
  14701. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14702. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14703. auto e = request_block.find("\r\n");
  14704. if (e != std::string::npos) {
  14705. auto request_line = request_block.substr(0, e);
  14706. std::string msg =
  14707. "CRLF injection detected in request line: '" + request_line + "'";
  14708. EXPECT_FALSE(true) << msg;
  14709. }
  14710. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14711. ::send(cli,
  14712. #ifdef _WIN32
  14713. static_cast<const char *>(resp.c_str()),
  14714. static_cast<int>(resp.size()),
  14715. #else
  14716. resp.c_str(), resp.size(),
  14717. #endif
  14718. 0);
  14719. buf_all.erase(0, pos + 4);
  14720. }
  14721. }
  14722. detail::close_socket(cli);
  14723. detail::close_socket(srv);
  14724. });
  14725. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14726. auto cli = Client("127.0.0.1", PORT + 1);
  14727. auto headers = Headers{
  14728. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14729. {"Connection", "keep-alive"}};
  14730. auto res = cli.Get("/hi", headers);
  14731. EXPECT_FALSE(res);
  14732. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14733. server_thread.join();
  14734. }
  14735. // A request rejected before any byte reaches the socket must fail right away
  14736. // instead of waiting for a response the server will never send.
  14737. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  14738. // The kernel completes the TCP handshake from the listen backlog, so the
  14739. // client connects, but nothing ever reads, responds or closes.
  14740. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14741. default_socket_options(srv);
  14742. sockaddr_in addr{};
  14743. addr.sin_family = AF_INET;
  14744. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14745. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14746. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14747. ASSERT_EQ(0, ::listen(srv, 8));
  14748. auto cli = Client("127.0.0.1", PORT + 1);
  14749. cli.set_read_timeout(10, 0);
  14750. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  14751. return std::chrono::duration_cast<std::chrono::milliseconds>(
  14752. std::chrono::steady_clock::now() - start)
  14753. .count();
  14754. };
  14755. {
  14756. Request req;
  14757. req.method = "GE T";
  14758. req.path = "/";
  14759. auto start = std::chrono::steady_clock::now();
  14760. auto res = cli.send(req);
  14761. EXPECT_FALSE(res);
  14762. EXPECT_EQ(Error::Write, res.error());
  14763. EXPECT_LT(elapsed_ms(start), 1000);
  14764. }
  14765. {
  14766. auto start = std::chrono::steady_clock::now();
  14767. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  14768. EXPECT_FALSE(res);
  14769. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14770. EXPECT_LT(elapsed_ms(start), 1000);
  14771. }
  14772. EXPECT_FALSE(cli.is_socket_open());
  14773. detail::close_socket(srv);
  14774. }
  14775. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  14776. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14777. default_socket_options(srv);
  14778. sockaddr_in addr{};
  14779. addr.sin_family = AF_INET;
  14780. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14781. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14782. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14783. ASSERT_EQ(0, ::listen(srv, 1));
  14784. std::string received;
  14785. auto server_thread = std::thread([&] {
  14786. auto sock = ::accept(srv, nullptr, nullptr);
  14787. if (sock == INVALID_SOCKET) { return; }
  14788. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  14789. char buf[2048];
  14790. ssize_t n;
  14791. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  14792. received.append(buf, static_cast<size_t>(n));
  14793. }
  14794. detail::close_socket(sock);
  14795. });
  14796. {
  14797. auto cli = Client("127.0.0.1", PORT + 1);
  14798. // "Z" sorts after the default headers, so writing straight to the socket
  14799. // would have sent the request line and those headers before the rejection.
  14800. auto handle =
  14801. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  14802. EXPECT_FALSE(handle.is_valid());
  14803. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  14804. }
  14805. server_thread.join();
  14806. detail::close_socket(srv);
  14807. EXPECT_TRUE(received.empty()) << received;
  14808. }
  14809. TEST(PathParamsTest, StaticMatch) {
  14810. const auto pattern = "/users/all";
  14811. detail::PathParamsMatcher matcher(pattern);
  14812. Request request;
  14813. request.path = "/users/all";
  14814. ASSERT_TRUE(matcher.match(request));
  14815. std::unordered_map<std::string, std::string> expected_params = {};
  14816. EXPECT_EQ(request.path_params, expected_params);
  14817. }
  14818. TEST(PathParamsTest, StaticMismatch) {
  14819. const auto pattern = "/users/all";
  14820. detail::PathParamsMatcher matcher(pattern);
  14821. Request request;
  14822. request.path = "/users/1";
  14823. ASSERT_FALSE(matcher.match(request));
  14824. }
  14825. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14826. const auto pattern = "/users/:id/subscriptions";
  14827. detail::PathParamsMatcher matcher(pattern);
  14828. Request request;
  14829. request.path = "/users/42/subscriptions";
  14830. ASSERT_TRUE(matcher.match(request));
  14831. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14832. EXPECT_EQ(request.path_params, expected_params);
  14833. }
  14834. TEST(PathParamsTest, SingleParamInTheEnd) {
  14835. const auto pattern = "/users/:id";
  14836. detail::PathParamsMatcher matcher(pattern);
  14837. Request request;
  14838. request.path = "/users/24";
  14839. ASSERT_TRUE(matcher.match(request));
  14840. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14841. EXPECT_EQ(request.path_params, expected_params);
  14842. }
  14843. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14844. const auto pattern = "/users/:id/";
  14845. detail::PathParamsMatcher matcher(pattern);
  14846. Request request;
  14847. request.path = "/users/42/";
  14848. ASSERT_TRUE(matcher.match(request));
  14849. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14850. EXPECT_EQ(request.path_params, expected_params);
  14851. }
  14852. TEST(PathParamsTest, EmptyParam) {
  14853. const auto pattern = "/users/:id/";
  14854. detail::PathParamsMatcher matcher(pattern);
  14855. Request request;
  14856. request.path = "/users//";
  14857. ASSERT_TRUE(matcher.match(request));
  14858. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14859. EXPECT_EQ(request.path_params, expected_params);
  14860. }
  14861. TEST(PathParamsTest, FragmentMismatch) {
  14862. const auto pattern = "/users/:id/";
  14863. detail::PathParamsMatcher matcher(pattern);
  14864. Request request;
  14865. request.path = "/admins/24/";
  14866. ASSERT_FALSE(matcher.match(request));
  14867. }
  14868. TEST(PathParamsTest, ExtraFragments) {
  14869. const auto pattern = "/users/:id";
  14870. detail::PathParamsMatcher matcher(pattern);
  14871. Request request;
  14872. request.path = "/users/42/subscriptions";
  14873. ASSERT_FALSE(matcher.match(request));
  14874. }
  14875. TEST(PathParamsTest, MissingTrailingParam) {
  14876. const auto pattern = "/users/:id";
  14877. detail::PathParamsMatcher matcher(pattern);
  14878. Request request;
  14879. request.path = "/users";
  14880. ASSERT_FALSE(matcher.match(request));
  14881. }
  14882. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14883. const auto pattern = "/users/:id/subscriptions";
  14884. detail::PathParamsMatcher matcher(pattern);
  14885. Request request;
  14886. request.path = "/users/subscriptions";
  14887. ASSERT_FALSE(matcher.match(request));
  14888. }
  14889. TEST(PathParamsTest, MultipleParams) {
  14890. const auto pattern = "/users/:userid/subscriptions/:subid";
  14891. detail::PathParamsMatcher matcher(pattern);
  14892. Request request;
  14893. request.path = "/users/42/subscriptions/2";
  14894. ASSERT_TRUE(matcher.match(request));
  14895. std::unordered_map<std::string, std::string> expected_params = {
  14896. {"userid", "42"}, {"subid", "2"}};
  14897. EXPECT_EQ(request.path_params, expected_params);
  14898. }
  14899. TEST(PathParamsTest, SequenceOfParams) {
  14900. const auto pattern = "/values/:x/:y/:z";
  14901. detail::PathParamsMatcher matcher(pattern);
  14902. Request request;
  14903. request.path = "/values/1/2/3";
  14904. ASSERT_TRUE(matcher.match(request));
  14905. std::unordered_map<std::string, std::string> expected_params = {
  14906. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14907. EXPECT_EQ(request.path_params, expected_params);
  14908. }
  14909. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14910. const auto pattern = "/prefix:suffix";
  14911. detail::PathParamsMatcher matcher(pattern);
  14912. Request request;
  14913. request.path = "/prefix:suffix";
  14914. ASSERT_TRUE(matcher.match(request));
  14915. const std::unordered_map<std::string, std::string> expected_params = {};
  14916. EXPECT_EQ(request.path_params, expected_params);
  14917. }
  14918. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14919. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14920. // calling thread's stack on a long enough path for a quantified pattern;
  14921. // RegexMatcher must refuse to run regex matching on paths beyond
  14922. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14923. detail::RegexMatcher matcher("/files/(.*)");
  14924. Request within_limit;
  14925. within_limit.path = "/files/" + std::string(10, 'A');
  14926. EXPECT_TRUE(matcher.match(within_limit));
  14927. Request over_limit;
  14928. over_limit.path =
  14929. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14930. EXPECT_FALSE(matcher.match(over_limit));
  14931. }
  14932. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14933. Server svr;
  14934. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14935. res.set_content("ok", "text/plain");
  14936. });
  14937. auto port = svr.bind_to_any_port(HOST);
  14938. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14939. auto se = detail::scope_exit([&] {
  14940. svr.stop();
  14941. thread.join();
  14942. ASSERT_FALSE(svr.is_running());
  14943. });
  14944. svr.wait_until_ready();
  14945. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14946. // request URI limit; this used to be able to crash the process.
  14947. std::string path =
  14948. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14949. std::string req = "GET " + path +
  14950. " HTTP/1.1\r\n"
  14951. "Host: " +
  14952. std::string(HOST) + ":" + std::to_string(port) +
  14953. "\r\n"
  14954. "Connection: close\r\n"
  14955. "\r\n";
  14956. std::string response;
  14957. ASSERT_TRUE(send_request(5, req, &response, port));
  14958. EXPECT_NE(std::string::npos, response.find("404"));
  14959. }
  14960. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14961. Server svr;
  14962. auto handler = [](const Request & /*req*/, Response &res) {
  14963. res.set_content("hit", "text/plain");
  14964. };
  14965. // No regex metacharacter, so this one is compared literally
  14966. svr.Get("/literal/route", handler);
  14967. // '.' is a regex metacharacter, so this one must keep regex semantics
  14968. svr.Get("/a.c", handler);
  14969. auto port = svr.bind_to_any_port(HOST);
  14970. std::thread t([&]() { svr.listen_after_bind(); });
  14971. auto se = detail::scope_exit([&] {
  14972. svr.stop();
  14973. t.join();
  14974. ASSERT_FALSE(svr.is_running());
  14975. });
  14976. svr.wait_until_ready();
  14977. Client cli(HOST, port);
  14978. struct {
  14979. const char *path;
  14980. int status;
  14981. } cases[] = {
  14982. {"/literal/route", StatusCode::OK_200},
  14983. {"/literal/routes", StatusCode::NotFound_404},
  14984. {"/literal/rout", StatusCode::NotFound_404},
  14985. {"/abc", StatusCode::OK_200},
  14986. {"/a.c", StatusCode::OK_200},
  14987. };
  14988. for (const auto &x : cases) {
  14989. auto res = cli.Get(x.path);
  14990. ASSERT_TRUE(res) << x.path;
  14991. EXPECT_EQ(x.status, res->status) << x.path;
  14992. }
  14993. }
  14994. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14995. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14996. // from exhausting the stack, so it must only constrain routes that actually
  14997. // run a regular expression. A literal route is matched by comparison and
  14998. // stays usable at any length.
  14999. Server svr;
  15000. const std::string pattern =
  15001. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15002. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15003. res.set_content("hit", "text/plain");
  15004. });
  15005. auto port = svr.bind_to_any_port(HOST);
  15006. std::thread t([&]() { svr.listen_after_bind(); });
  15007. auto se = detail::scope_exit([&] {
  15008. svr.stop();
  15009. t.join();
  15010. ASSERT_FALSE(svr.is_running());
  15011. });
  15012. svr.wait_until_ready();
  15013. Client cli(HOST, port);
  15014. auto res = cli.Get(pattern);
  15015. ASSERT_TRUE(res);
  15016. EXPECT_EQ(StatusCode::OK_200, res->status);
  15017. }
  15018. TEST(ParseUrlTest, VariousPatterns) {
  15019. {
  15020. detail::UrlComponents uc;
  15021. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15022. EXPECT_EQ("http", uc.scheme);
  15023. EXPECT_EQ("example.com", uc.host);
  15024. EXPECT_EQ("8080", uc.port);
  15025. EXPECT_EQ("/path", uc.path);
  15026. EXPECT_EQ("?q=1", uc.query);
  15027. }
  15028. {
  15029. detail::UrlComponents uc;
  15030. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15031. EXPECT_EQ("https", uc.scheme);
  15032. EXPECT_EQ("example.com", uc.host);
  15033. EXPECT_TRUE(uc.port.empty());
  15034. EXPECT_EQ("/path", uc.path);
  15035. }
  15036. {
  15037. detail::UrlComponents uc;
  15038. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15039. EXPECT_EQ("::1", uc.host);
  15040. EXPECT_EQ("8080", uc.port);
  15041. EXPECT_EQ("/path", uc.path);
  15042. }
  15043. {
  15044. detail::UrlComponents uc;
  15045. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15046. }
  15047. {
  15048. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15049. // the path while the connection still targets the bracketed host.
  15050. detail::UrlComponents uc;
  15051. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15052. }
  15053. {
  15054. detail::UrlComponents uc;
  15055. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15056. }
  15057. {
  15058. detail::UrlComponents uc;
  15059. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15060. EXPECT_EQ("::1", uc.host);
  15061. EXPECT_TRUE(uc.port.empty());
  15062. EXPECT_EQ("/path", uc.path);
  15063. }
  15064. {
  15065. detail::UrlComponents uc;
  15066. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15067. EXPECT_TRUE(uc.scheme.empty());
  15068. EXPECT_EQ("example.com", uc.host);
  15069. EXPECT_EQ("/path", uc.path);
  15070. EXPECT_EQ("?q=1", uc.query);
  15071. }
  15072. {
  15073. detail::UrlComponents uc;
  15074. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15075. EXPECT_TRUE(uc.host.empty());
  15076. EXPECT_EQ("/path", uc.path);
  15077. EXPECT_EQ("?q=1", uc.query);
  15078. }
  15079. {
  15080. detail::UrlComponents uc;
  15081. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15082. EXPECT_EQ("example.com", uc.host);
  15083. EXPECT_EQ("8080", uc.port);
  15084. }
  15085. {
  15086. // Unix socket path — must not be parsed as host
  15087. detail::UrlComponents uc;
  15088. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15089. EXPECT_TRUE(uc.host.empty());
  15090. }
  15091. {
  15092. detail::UrlComponents uc;
  15093. ASSERT_TRUE(detail::parse_url("", uc));
  15094. EXPECT_TRUE(uc.host.empty());
  15095. EXPECT_TRUE(uc.path.empty());
  15096. }
  15097. {
  15098. detail::UrlComponents uc;
  15099. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15100. }
  15101. {
  15102. detail::UrlComponents uc;
  15103. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15104. }
  15105. {
  15106. // Accepted by parse_url; callers restrict to http/https
  15107. detail::UrlComponents uc;
  15108. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15109. EXPECT_EQ("ftp", uc.scheme);
  15110. }
  15111. {
  15112. detail::UrlComponents uc;
  15113. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15114. }
  15115. {
  15116. detail::UrlComponents uc;
  15117. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15118. }
  15119. }
  15120. TEST(ParseUrlTest, FragmentHandling) {
  15121. {
  15122. detail::UrlComponents uc;
  15123. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15124. EXPECT_EQ("/path", uc.path);
  15125. EXPECT_TRUE(uc.query.empty());
  15126. }
  15127. {
  15128. detail::UrlComponents uc;
  15129. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15130. EXPECT_TRUE(uc.path.empty());
  15131. EXPECT_TRUE(uc.query.empty());
  15132. }
  15133. }
  15134. TEST(ParseUrlTest, UserinfoHandling) {
  15135. // Userinfo with @ but no colon — host includes @
  15136. detail::UrlComponents uc;
  15137. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15138. EXPECT_EQ("user@host.com", uc.host);
  15139. EXPECT_EQ("/path", uc.path);
  15140. }
  15141. TEST(ParseUrlTest, IPv6EdgeCases) {
  15142. {
  15143. detail::UrlComponents uc;
  15144. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15145. EXPECT_TRUE(uc.scheme.empty());
  15146. EXPECT_EQ("::1", uc.host);
  15147. EXPECT_EQ("8080", uc.port);
  15148. }
  15149. {
  15150. // Zone ID '%25' is not in [a-fA-F0-9:]
  15151. detail::UrlComponents uc;
  15152. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15153. }
  15154. }
  15155. TEST(ParseUrlTest, SchemeEdgeCases) {
  15156. {
  15157. detail::UrlComponents uc;
  15158. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15159. }
  15160. {
  15161. detail::UrlComponents uc;
  15162. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15163. }
  15164. {
  15165. detail::UrlComponents uc;
  15166. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15167. }
  15168. }
  15169. TEST(ParseUrlTest, PortEdgeCases) {
  15170. {
  15171. detail::UrlComponents uc;
  15172. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15173. EXPECT_TRUE(uc.port.empty());
  15174. EXPECT_EQ("/path", uc.path);
  15175. }
  15176. {
  15177. // parse_url accepts any port string; validation is done by parse_port
  15178. detail::UrlComponents uc;
  15179. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15180. EXPECT_EQ("abc", uc.port);
  15181. }
  15182. }
  15183. TEST(ParseUrlTest, WebSocketPatterns) {
  15184. {
  15185. detail::UrlComponents uc;
  15186. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15187. EXPECT_EQ("ws", uc.scheme);
  15188. EXPECT_EQ("echo.example.com", uc.host);
  15189. EXPECT_EQ("8080", uc.port);
  15190. EXPECT_EQ("/ws", uc.path);
  15191. }
  15192. {
  15193. detail::UrlComponents uc;
  15194. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15195. EXPECT_EQ("wss", uc.scheme);
  15196. EXPECT_EQ("echo.example.com", uc.host);
  15197. EXPECT_TRUE(uc.port.empty());
  15198. EXPECT_EQ("/ws", uc.path);
  15199. }
  15200. }
  15201. TEST(ParseUrlTest, QueryOnly) {
  15202. detail::UrlComponents uc;
  15203. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15204. EXPECT_TRUE(uc.host.empty());
  15205. EXPECT_TRUE(uc.path.empty());
  15206. EXPECT_EQ("?q=1&r=2", uc.query);
  15207. }
  15208. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15209. detail::UrlComponents uc;
  15210. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15211. EXPECT_TRUE(uc.scheme.empty());
  15212. EXPECT_EQ("example.com", uc.host);
  15213. EXPECT_EQ("443", uc.port);
  15214. EXPECT_EQ("/path", uc.path);
  15215. }
  15216. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15217. // If ipv6 regex working, regex match codepath is taken.
  15218. // else port will default to 80 in Client impl
  15219. int clientImplMagicPort = 80;
  15220. int port = 4321;
  15221. // above ports must be different to avoid false negative
  15222. EXPECT_NE(clientImplMagicPort, port);
  15223. std::string ipV6TestURL = "http://[ff06::c3]";
  15224. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15225. CLIENT_PRIVATE_KEY_FILE);
  15226. EXPECT_EQ(cli.port(), port);
  15227. }
  15228. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15229. auto file_path = "./www/dir/index.html";
  15230. auto dir_path = "./www/dir";
  15231. detail::FileStat stat_file(file_path);
  15232. EXPECT_TRUE(stat_file.is_file());
  15233. EXPECT_FALSE(stat_file.is_dir());
  15234. detail::FileStat stat_dir(dir_path);
  15235. EXPECT_FALSE(stat_dir.is_file());
  15236. EXPECT_TRUE(stat_dir.is_dir());
  15237. }
  15238. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15239. // IPv4 with default HTTP port (80)
  15240. EXPECT_EQ("example.com",
  15241. detail::make_host_and_port_string("example.com", 80, false));
  15242. // IPv4 with default HTTPS port (443)
  15243. EXPECT_EQ("example.com",
  15244. detail::make_host_and_port_string("example.com", 443, true));
  15245. // IPv4 with non-default HTTP port
  15246. EXPECT_EQ("example.com:8080",
  15247. detail::make_host_and_port_string("example.com", 8080, false));
  15248. // IPv4 with non-default HTTPS port
  15249. EXPECT_EQ("example.com:8443",
  15250. detail::make_host_and_port_string("example.com", 8443, true));
  15251. // IPv6 with default HTTP port (80)
  15252. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15253. // IPv6 with default HTTPS port (443)
  15254. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15255. // IPv6 with non-default HTTP port
  15256. EXPECT_EQ("[::1]:8080",
  15257. detail::make_host_and_port_string("::1", 8080, false));
  15258. // IPv6 with non-default HTTPS port
  15259. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15260. // IPv6 full address with default port
  15261. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15262. detail::make_host_and_port_string(
  15263. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15264. // IPv6 full address with non-default port
  15265. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15266. detail::make_host_and_port_string(
  15267. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15268. // IPv6 localhost with non-default port
  15269. EXPECT_EQ("[::1]:3000",
  15270. detail::make_host_and_port_string("::1", 3000, false));
  15271. // IPv6 with zone ID (link-local address) with default port
  15272. EXPECT_EQ("[fe80::1%eth0]",
  15273. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15274. // IPv6 with zone ID (link-local address) with non-default port
  15275. EXPECT_EQ("[fe80::1%eth0]:8080",
  15276. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15277. // Edge case: Port 443 with is_ssl=false (should add port)
  15278. EXPECT_EQ("example.com:443",
  15279. detail::make_host_and_port_string("example.com", 443, false));
  15280. // Edge case: Port 80 with is_ssl=true (should add port)
  15281. EXPECT_EQ("example.com:80",
  15282. detail::make_host_and_port_string("example.com", 80, true));
  15283. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15284. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15285. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15286. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15287. // Security fix: Already bracketed IPv6 should not get double brackets
  15288. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15289. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15290. EXPECT_EQ("[::1]:8080",
  15291. detail::make_host_and_port_string("[::1]", 8080, false));
  15292. EXPECT_EQ("[2001:db8::1]:8080",
  15293. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15294. EXPECT_EQ("[fe80::1%eth0]",
  15295. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15296. EXPECT_EQ("[fe80::1%eth0]:8080",
  15297. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15298. // Edge case: Empty host (should return as-is)
  15299. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15300. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15301. // This is a known limitation but shouldn't crash
  15302. EXPECT_EQ("[host:name]",
  15303. detail::make_host_and_port_string("host:name", 80, false));
  15304. // Port number edge cases (no validation, but should not crash)
  15305. EXPECT_EQ("example.com:0",
  15306. detail::make_host_and_port_string("example.com", 0, false));
  15307. EXPECT_EQ("example.com:-1",
  15308. detail::make_host_and_port_string("example.com", -1, false));
  15309. EXPECT_EQ("example.com:65535",
  15310. detail::make_host_and_port_string("example.com", 65535, false));
  15311. EXPECT_EQ("example.com:65536",
  15312. detail::make_host_and_port_string("example.com", 65536, false));
  15313. }
  15314. #ifdef CPPHTTPLIB_SSL_ENABLED
  15315. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15316. httplib::SSLClient cli("roblox.com", 443);
  15317. cli.set_follow_location(true);
  15318. auto res = cli.Get("/");
  15319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15320. EXPECT_EQ(StatusCode::OK_200, res->status);
  15321. }
  15322. #endif
  15323. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15324. Server svr;
  15325. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15326. EXPECT_EQ(res.status, 400);
  15327. });
  15328. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15329. auto se = detail::scope_exit([&] {
  15330. svr.stop();
  15331. thread.join();
  15332. ASSERT_FALSE(svr.is_running());
  15333. });
  15334. svr.wait_until_ready();
  15335. Client cli(HOST, PORT);
  15336. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15337. }
  15338. TEST(InvalidHeaderCharsTest, is_field_name) {
  15339. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15340. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15341. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15342. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15343. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15344. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15345. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15346. EXPECT_FALSE(detail::fields::is_field_name(""));
  15347. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15348. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15349. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15350. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15351. }
  15352. TEST(InvalidHeaderCharsTest, is_field_value) {
  15353. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15354. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15355. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15356. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15357. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15358. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15359. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15360. EXPECT_TRUE(detail::fields::is_field_value(""));
  15361. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15362. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15363. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15364. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15365. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15366. }
  15367. TEST(InvalidHeaderCharsTest, OnServer) {
  15368. Server svr;
  15369. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15370. std::string header = "Not Set";
  15371. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15372. res.set_header(header, "value");
  15373. res.set_content("Page Content Page Content", "text/plain");
  15374. });
  15375. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15376. std::string header = "Not Set";
  15377. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15378. res.set_header("X-Test", header);
  15379. res.set_content("Page Content Page Content", "text/plain");
  15380. });
  15381. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15382. auto se = detail::scope_exit([&] {
  15383. svr.stop();
  15384. thread.join();
  15385. ASSERT_FALSE(svr.is_running());
  15386. });
  15387. svr.wait_until_ready();
  15388. Client cli(HOST, PORT);
  15389. {
  15390. auto res = cli.Get(
  15391. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15393. EXPECT_EQ("Page Content Page Content", res->body);
  15394. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15395. }
  15396. {
  15397. auto res = cli.Get(
  15398. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15400. EXPECT_EQ("Page Content Page Content", res->body);
  15401. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15402. }
  15403. }
  15404. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15405. auto handled = false;
  15406. Server svr;
  15407. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15408. thread t = thread([&] { svr.listen(HOST, PORT); });
  15409. auto se = detail::scope_exit([&] {
  15410. svr.stop();
  15411. t.join();
  15412. ASSERT_FALSE(svr.is_running());
  15413. ASSERT_FALSE(handled);
  15414. });
  15415. svr.wait_until_ready();
  15416. auto req = "POST /test HTTP/1.1\r\n"
  15417. "Content-Length: x\r\n"
  15418. "\r\n";
  15419. std::string response;
  15420. ASSERT_TRUE(send_request(1, req, &response));
  15421. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15422. response.substr(0, response.find("\r\n")));
  15423. }
  15424. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15425. // case-insensitive, and a server that receives a 100-continue expectation in
  15426. // an HTTP/1.0 request MUST ignore it.
  15427. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15428. std::string response;
  15429. ASSERT_TRUE(send_request(1, req, &response, port));
  15430. *got_100 = response.find("100 Continue") != std::string::npos;
  15431. }
  15432. class ExpectTokenTest : public ::testing::Test {
  15433. protected:
  15434. void SetUp() override {
  15435. svr_.Post("/p", [](const Request &, Response &res) {
  15436. res.set_content("ok", "text/plain");
  15437. });
  15438. port_ = svr_.bind_to_any_port(HOST);
  15439. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15440. svr_.wait_until_ready();
  15441. }
  15442. void TearDown() override {
  15443. svr_.stop();
  15444. if (thread_.joinable()) { thread_.join(); }
  15445. }
  15446. std::string request(const char *version, const char *expect_value) const {
  15447. return std::string("POST /p ") + version +
  15448. "\r\n"
  15449. "Host: localhost\r\n"
  15450. "Content-Length: 2\r\n"
  15451. "Connection: close\r\n"
  15452. "Expect: " +
  15453. expect_value +
  15454. "\r\n"
  15455. "\r\n"
  15456. "hi";
  15457. }
  15458. Server svr_;
  15459. int port_ = 0;
  15460. thread thread_;
  15461. };
  15462. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15463. bool got_100 = false;
  15464. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15465. EXPECT_TRUE(got_100);
  15466. }
  15467. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15468. bool got_100 = true;
  15469. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15470. EXPECT_FALSE(got_100);
  15471. }
  15472. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15473. bool got_100 = false;
  15474. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15475. EXPECT_TRUE(got_100);
  15476. }
  15477. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15478. bool got_100 = false;
  15479. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15480. EXPECT_TRUE(got_100);
  15481. }
  15482. // `100 Continue` is sent only when the server starts reading the body, so a
  15483. // request rejected before that never invites the client to send it. The
  15484. // requests below carry the expectation but withhold the body, as a client
  15485. // waiting for `100 Continue` would.
  15486. // A POST that expects `100 Continue` and withholds its two-byte body.
  15487. static std::string expect_headers_only(const std::string &path) {
  15488. return "POST " + path +
  15489. " HTTP/1.1\r\n"
  15490. "Host: localhost\r\n"
  15491. "Content-Length: 2\r\n"
  15492. "Expect: 100-continue\r\n"
  15493. "\r\n";
  15494. }
  15495. class ExpectLazyContinueTest : public ::testing::Test {
  15496. protected:
  15497. void SetUp() override {
  15498. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15499. if (req.path == "/pre-routing") {
  15500. res.status = StatusCode::Unauthorized_401;
  15501. return Server::HandlerResponse::Handled;
  15502. }
  15503. return Server::HandlerResponse::Unhandled;
  15504. });
  15505. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15506. if (req.matched_route == "/pre-request") {
  15507. res.status = StatusCode::Forbidden_403;
  15508. return Server::HandlerResponse::Handled;
  15509. }
  15510. return Server::HandlerResponse::Unhandled;
  15511. });
  15512. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15513. res.set_content("ok", "text/plain");
  15514. });
  15515. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15516. res.set_content("ok", "text/plain");
  15517. });
  15518. svr_.Post("/reader-used", [](const Request &, Response &res,
  15519. const ContentReader &content_reader) {
  15520. std::string body;
  15521. content_reader([&](const char *data, size_t len) {
  15522. body.append(data, len);
  15523. return true;
  15524. });
  15525. res.set_content(body, "text/plain");
  15526. });
  15527. svr_.Post("/reader-unused",
  15528. [](const Request &, Response &res, const ContentReader &) {
  15529. res.set_content("ignored", "text/plain");
  15530. });
  15531. port_ = svr_.bind_to_any_port(HOST);
  15532. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15533. svr_.wait_until_ready();
  15534. }
  15535. void TearDown() override {
  15536. svr_.stop();
  15537. if (thread_.joinable()) { thread_.join(); }
  15538. }
  15539. // Sends `req` and reads until the server closes the connection. Returns
  15540. // false if the read had to wait for the client-side timeout instead.
  15541. bool send_until_closed(const std::string &req, std::string *resp) const {
  15542. auto start = std::chrono::steady_clock::now();
  15543. if (!send_request(3, req, resp, port_)) { return false; }
  15544. auto elapsed = std::chrono::steady_clock::now() - start;
  15545. return elapsed < std::chrono::seconds(2);
  15546. }
  15547. // The final response comes without `100 Continue`, and the server closes
  15548. // the connection since the body may or may not follow.
  15549. void expect_final_without_interim(const std::string &path,
  15550. const char *status_line) const {
  15551. std::string resp;
  15552. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15553. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15554. EXPECT_EQ(0u, resp.find(status_line));
  15555. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15556. }
  15557. Server svr_;
  15558. int port_ = 0;
  15559. thread thread_;
  15560. };
  15561. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15562. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15563. }
  15564. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15565. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15566. }
  15567. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15568. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15569. }
  15570. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15571. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15572. }
  15573. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15574. // The body follows once `100 Continue` has had time to arrive.
  15575. auto req = expect_headers_only("/reader-used");
  15576. req.insert(req.size() - 2, "Connection: close\r\n");
  15577. std::string resp;
  15578. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15579. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15580. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15581. EXPECT_NE(std::string::npos, resp.find("hi"));
  15582. }
  15583. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15584. // Large enough for the client to add `Expect: 100-continue` itself.
  15585. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15586. std::atomic<bool> body_sent{false};
  15587. Client cli(HOST, port_);
  15588. auto res = cli.Post(
  15589. "/pre-request", length,
  15590. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15591. body_sent = true;
  15592. std::string chunk(len, 'x');
  15593. sink.write(chunk.data(), chunk.size());
  15594. return true;
  15595. },
  15596. "application/octet-stream");
  15597. ASSERT_TRUE(res);
  15598. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15599. EXPECT_FALSE(body_sent);
  15600. }
  15601. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15602. Server svr;
  15603. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15604. return StatusCode::ExpectationFailed_417;
  15605. });
  15606. svr.Post("/p", [](const Request &, Response &res) {
  15607. res.set_content("ok", "text/plain");
  15608. });
  15609. auto port = svr.bind_to_any_port(HOST);
  15610. thread t = thread([&] { svr.listen_after_bind(); });
  15611. auto se = detail::scope_exit([&] {
  15612. svr.stop();
  15613. t.join();
  15614. });
  15615. svr.wait_until_ready();
  15616. std::string resp;
  15617. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15618. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15619. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15620. // Exactly one response: the route handler must not run after the 417.
  15621. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15622. }
  15623. #ifndef _WIN32
  15624. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15625. static constexpr char reject[] = "Unauthorized";
  15626. static constexpr char accept[] = "Upload accepted";
  15627. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15628. Server svr;
  15629. svr.set_expect_100_continue_handler(
  15630. [](const Request & /*req*/, Response &res) {
  15631. res.status = StatusCode::Unauthorized_401;
  15632. res.set_content(reject, "text/plain");
  15633. return res.status;
  15634. });
  15635. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15636. res.set_content(accept, "text/plain");
  15637. });
  15638. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15639. auto se = detail::scope_exit([&] {
  15640. svr.stop();
  15641. thread.join();
  15642. ASSERT_FALSE(svr.is_running());
  15643. });
  15644. svr.wait_until_ready();
  15645. {
  15646. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15647. curl_easy_init(), &curl_easy_cleanup};
  15648. ASSERT_NE(curl, nullptr);
  15649. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15650. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15651. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15652. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15653. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15654. &curl_slist_free_all};
  15655. ASSERT_NE(list, nullptr);
  15656. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15657. struct read_data {
  15658. size_t read_size;
  15659. size_t total_size;
  15660. } data = {0, total_size};
  15661. using read_callback_t =
  15662. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15663. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15664. void *userdata) -> size_t {
  15665. read_data *d = (read_data *)userdata;
  15666. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15667. std::fill_n(ptr, size * nmemb, 'A');
  15668. d->read_size += size * nmemb;
  15669. return size * nmemb;
  15670. };
  15671. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15672. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15673. std::vector<char> buffer;
  15674. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15675. using write_callback_t =
  15676. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15677. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15678. void *userdata) -> size_t {
  15679. std::vector<char> *buf = (std::vector<char> *)userdata;
  15680. buf->reserve(buf->size() + size * nmemb + 1);
  15681. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15682. return size * nmemb;
  15683. };
  15684. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15685. {
  15686. const auto res = curl_easy_perform(curl.get());
  15687. ASSERT_EQ(res, CURLE_OK);
  15688. }
  15689. {
  15690. auto response_code = long{};
  15691. const auto res =
  15692. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15693. ASSERT_EQ(res, CURLE_OK);
  15694. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15695. }
  15696. {
  15697. auto dl = curl_off_t{};
  15698. const auto res =
  15699. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15700. ASSERT_EQ(res, CURLE_OK);
  15701. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15702. }
  15703. {
  15704. buffer.push_back('\0');
  15705. ASSERT_STRCASEEQ(buffer.data(), reject);
  15706. }
  15707. }
  15708. }
  15709. #endif
  15710. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15711. // Regression test for #2458.
  15712. //
  15713. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15714. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15715. // ticket can make the client socket spuriously readable during the
  15716. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15717. // the client withholds the body and then blocks reading a response that never
  15718. // comes, failing with `Failed to read connection`.
  15719. //
  15720. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15721. // within the timeout. This raw OpenSSL server deliberately never sends
  15722. // `100 Continue`; the client must still deliver the body and receive 200.
  15723. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15724. signal(SIGPIPE, SIG_IGN);
  15725. const auto port = PORT + 4;
  15726. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15727. ASSERT_NE(srv, INVALID_SOCKET);
  15728. int opt = 1;
  15729. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15730. sockaddr_in addr{};
  15731. addr.sin_family = AF_INET;
  15732. addr.sin_port = htons(static_cast<uint16_t>(port));
  15733. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15734. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15735. ASSERT_EQ(0, ::listen(srv, 1));
  15736. std::atomic<size_t> server_body_bytes{0};
  15737. auto server_thread = std::thread([&] {
  15738. sockaddr_in cli_addr{};
  15739. socklen_t cli_len = sizeof(cli_addr);
  15740. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15741. if (cli == INVALID_SOCKET) { return; }
  15742. // Bound the lifetime of the server side so a buggy client (which never
  15743. // sends the body) cannot make this thread block forever on join.
  15744. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15745. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15746. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15747. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15748. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15749. SSL *ssl = SSL_new(ctx);
  15750. SSL_set_fd(ssl, static_cast<int>(cli));
  15751. if (SSL_accept(ssl) > 0) {
  15752. // Read the request headers. Reading here also flushes the TLS 1.3
  15753. // session tickets to the client. Deliberately do NOT send
  15754. // `100 Continue`.
  15755. std::string buf;
  15756. char tmp[1024];
  15757. while (buf.find("\r\n\r\n") == std::string::npos) {
  15758. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15759. if (n <= 0) { break; }
  15760. buf.append(tmp, static_cast<size_t>(n));
  15761. }
  15762. // A correct client sends the body now; count what arrives.
  15763. auto pos = buf.find("\r\n\r\n");
  15764. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15765. while (body < 4096) {
  15766. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15767. if (n <= 0) { break; }
  15768. body += static_cast<size_t>(n);
  15769. }
  15770. server_body_bytes = body;
  15771. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15772. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15773. SSL_shutdown(ssl);
  15774. }
  15775. SSL_free(ssl);
  15776. detail::close_socket(cli);
  15777. SSL_CTX_free(ctx);
  15778. });
  15779. auto se = detail::scope_exit([&] {
  15780. server_thread.join();
  15781. detail::close_socket(srv);
  15782. });
  15783. SSLClient cli("127.0.0.1", port);
  15784. cli.enable_server_certificate_verification(false);
  15785. cli.set_connection_timeout(5, 0);
  15786. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15787. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15788. std::string body(4096, 'A');
  15789. auto res = cli.Put("/api/test", body, "application/json");
  15790. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15791. EXPECT_EQ(StatusCode::OK_200, res->status);
  15792. EXPECT_EQ(body.size(), server_body_bytes.load());
  15793. }
  15794. #endif
  15795. template <typename S, typename C>
  15796. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15797. svr.Get("/stream", [&](const Request &, Response &res) {
  15798. auto data = new std::string("01234567890123456789");
  15799. res.set_content_provider(
  15800. data->size(), "text/plain",
  15801. [&, data](size_t offset, size_t length, DataSink &sink) {
  15802. const size_t DATA_CHUNK_SIZE = 4;
  15803. const auto &d = *data;
  15804. std::this_thread::sleep_for(std::chrono::seconds(1));
  15805. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15806. return true;
  15807. },
  15808. [data](bool success) {
  15809. EXPECT_FALSE(success);
  15810. delete data;
  15811. });
  15812. });
  15813. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15814. auto i = new size_t(0);
  15815. res.set_content_provider(
  15816. "text/plain",
  15817. [i](size_t, DataSink &sink) {
  15818. if (*i < 5) {
  15819. std::this_thread::sleep_for(std::chrono::seconds(1));
  15820. sink.write("abcd", 4);
  15821. (*i)++;
  15822. } else {
  15823. sink.done();
  15824. }
  15825. return true;
  15826. },
  15827. [i](bool success) {
  15828. EXPECT_FALSE(success);
  15829. delete i;
  15830. });
  15831. });
  15832. svr.Get("/chunked", [&](const Request &, Response &res) {
  15833. auto i = new size_t(0);
  15834. res.set_chunked_content_provider(
  15835. "text/plain",
  15836. [i](size_t, DataSink &sink) {
  15837. if (*i < 5) {
  15838. std::this_thread::sleep_for(std::chrono::seconds(1));
  15839. sink.os << "abcd";
  15840. (*i)++;
  15841. } else {
  15842. sink.done();
  15843. }
  15844. return true;
  15845. },
  15846. [i](bool success) {
  15847. EXPECT_FALSE(success);
  15848. delete i;
  15849. });
  15850. });
  15851. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15852. auto se = detail::scope_exit([&] {
  15853. svr.stop();
  15854. listen_thread.join();
  15855. ASSERT_FALSE(svr.is_running());
  15856. });
  15857. svr.wait_until_ready();
  15858. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15859. {
  15860. auto start = std::chrono::steady_clock::now();
  15861. auto res = cli.Get("/stream");
  15862. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15863. std::chrono::steady_clock::now() - start)
  15864. .count();
  15865. ASSERT_FALSE(res);
  15866. EXPECT_EQ(Error::Read, res.error());
  15867. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15868. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15869. }
  15870. {
  15871. auto start = std::chrono::steady_clock::now();
  15872. auto res = cli.Get("/stream_without_length");
  15873. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15874. std::chrono::steady_clock::now() - start)
  15875. .count();
  15876. ASSERT_FALSE(res);
  15877. EXPECT_EQ(Error::Read, res.error());
  15878. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15879. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15880. }
  15881. {
  15882. auto start = std::chrono::steady_clock::now();
  15883. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15884. EXPECT_EQ("abcd", string(data, data_length));
  15885. return true;
  15886. });
  15887. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15888. std::chrono::steady_clock::now() - start)
  15889. .count();
  15890. ASSERT_FALSE(res);
  15891. EXPECT_EQ(Error::Read, res.error());
  15892. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15893. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15894. }
  15895. }
  15896. TEST(MaxTimeoutTest, ContentStream) {
  15897. time_t timeout = 2000;
  15898. time_t threshold = 200;
  15899. Server svr;
  15900. Client cli("localhost", PORT);
  15901. max_timeout_test(svr, cli, timeout, threshold);
  15902. }
  15903. #ifdef CPPHTTPLIB_SSL_ENABLED
  15904. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15905. time_t timeout = 2000;
  15906. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15908. SSLClient cli("localhost", PORT);
  15909. cli.enable_server_certificate_verification(false);
  15910. max_timeout_test(svr, cli, timeout, threshold);
  15911. }
  15912. #endif
  15913. class EventDispatcher {
  15914. public:
  15915. EventDispatcher() {}
  15916. bool wait_event(DataSink *sink) {
  15917. unique_lock<mutex> lk(m_);
  15918. int id = id_;
  15919. // Wait with timeout to prevent hanging if client disconnects
  15920. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15921. [&] { return cid_ == id; })) {
  15922. return false; // Timeout occurred
  15923. }
  15924. sink->write(message_.data(), message_.size());
  15925. return true;
  15926. }
  15927. void send_event(const string &message) {
  15928. lock_guard<mutex> lk(m_);
  15929. cid_ = id_++;
  15930. message_ = message;
  15931. cv_.notify_all();
  15932. }
  15933. private:
  15934. mutex m_;
  15935. condition_variable cv_;
  15936. atomic_int id_{0};
  15937. atomic_int cid_{-1};
  15938. string message_;
  15939. };
  15940. TEST(ClientInThreadTest, Issue2068) {
  15941. EventDispatcher ed;
  15942. Server svr;
  15943. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15944. res.set_chunked_content_provider("text/event-stream",
  15945. [&](size_t /*offset*/, DataSink &sink) {
  15946. return ed.wait_event(&sink);
  15947. });
  15948. });
  15949. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15950. svr.wait_until_ready();
  15951. thread event_thread([&] {
  15952. int id = 0;
  15953. while (svr.is_running()) {
  15954. this_thread::sleep_for(chrono::milliseconds(500));
  15955. std::stringstream ss;
  15956. ss << "data: " << id << "\n\n";
  15957. ed.send_event(ss.str());
  15958. id++;
  15959. }
  15960. });
  15961. auto se = detail::scope_exit([&] {
  15962. svr.stop();
  15963. listen_thread.join();
  15964. event_thread.join();
  15965. ASSERT_FALSE(svr.is_running());
  15966. });
  15967. {
  15968. auto client = detail::make_unique<Client>(HOST, PORT);
  15969. client->set_read_timeout(std::chrono::minutes(10));
  15970. std::atomic<bool> stop{false};
  15971. std::thread t([&] {
  15972. client->Get("/event1",
  15973. [&](const char *, size_t) -> bool { return !stop; });
  15974. });
  15975. std::this_thread::sleep_for(std::chrono::seconds(2));
  15976. stop = true;
  15977. client->stop();
  15978. t.join();
  15979. // Reset client after thread has finished
  15980. client.reset();
  15981. }
  15982. }
  15983. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  15984. auto handled = false;
  15985. Server svr;
  15986. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15987. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15988. auto se = detail::scope_exit([&] {
  15989. svr.stop();
  15990. t.join();
  15991. ASSERT_FALSE(svr.is_running());
  15992. ASSERT_FALSE(handled);
  15993. });
  15994. svr.wait_until_ready();
  15995. // Two Content-Length headers with different values — must be rejected
  15996. auto req = "POST /test HTTP/1.1\r\n"
  15997. "Content-Length: 5\r\n"
  15998. "Content-Length: 10\r\n"
  15999. "\r\n"
  16000. "hello";
  16001. std::string response;
  16002. ASSERT_TRUE(send_request(1, req, &response));
  16003. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16004. response.substr(0, response.find("\r\n")));
  16005. }
  16006. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16007. auto handled = false;
  16008. Server svr;
  16009. svr.Post("/test", [&](const Request &, Response &res) {
  16010. handled = true;
  16011. res.set_content("ok", "text/plain");
  16012. });
  16013. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16014. auto se = detail::scope_exit([&] {
  16015. svr.stop();
  16016. t.join();
  16017. ASSERT_FALSE(svr.is_running());
  16018. ASSERT_TRUE(handled);
  16019. });
  16020. svr.wait_until_ready();
  16021. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16022. auto req = "POST /test HTTP/1.1\r\n"
  16023. "Content-Length: 5\r\n"
  16024. "Content-Length: 5\r\n"
  16025. "\r\n"
  16026. "hello";
  16027. std::string response;
  16028. ASSERT_TRUE(send_request(1, req, &response));
  16029. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16030. }
  16031. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16032. Server svr;
  16033. svr.Get("/", [](const Request &req, Response &res) {
  16034. EXPECT_EQ(2U, req.trailers.size());
  16035. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16036. // Denied
  16037. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16038. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16039. // Accepted
  16040. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16041. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16042. EXPECT_TRUE(req.has_trailer("X-World"));
  16043. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16044. res.set_content("ok", "text/plain");
  16045. });
  16046. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16047. auto se = detail::scope_exit([&] {
  16048. svr.stop();
  16049. t.join();
  16050. ASSERT_FALSE(svr.is_running());
  16051. });
  16052. svr.wait_until_ready();
  16053. const std::string req = "GET / HTTP/1.1\r\n"
  16054. "Transfer-Encoding: chunked\r\n"
  16055. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16056. "\r\n"
  16057. "0\r\n"
  16058. "Content-Length: 10\r\n"
  16059. "Host: internal.local\r\n"
  16060. "Content-Type: malicious/content\r\n"
  16061. "Cookie: any\r\n"
  16062. "Set-Cookie: any\r\n"
  16063. "X-Forwarded-For: attacker.com\r\n"
  16064. "X-Real-Ip: 1.1.1.1\r\n"
  16065. "X-Hello: hello\r\n"
  16066. "X-World: world\r\n"
  16067. "\r\n";
  16068. std::string res;
  16069. ASSERT_TRUE(send_request(1, req, &res));
  16070. }
  16071. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16072. // several field lines, and the combined value is what has to be parsed. A
  16073. // Trailer field split across lines therefore declares every name it lists;
  16074. // reading only the first line silently drops the trailers the later lines
  16075. // declare. The prohibited-trailer filter still applies to every line.
  16076. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16077. Server svr;
  16078. size_t observed_trailer_count = 0;
  16079. std::string observed_hello;
  16080. std::string observed_world;
  16081. bool observed_content_length = true;
  16082. svr.Get("/", [&](const Request &req, Response &res) {
  16083. observed_trailer_count = req.trailers.size();
  16084. observed_hello = req.get_trailer_value("X-Hello");
  16085. observed_world = req.get_trailer_value("X-World");
  16086. observed_content_length = req.has_trailer("Content-Length");
  16087. res.set_content("ok", "text/plain");
  16088. });
  16089. auto port = svr.bind_to_any_port(HOST);
  16090. thread t = thread([&]() { svr.listen_after_bind(); });
  16091. auto se = detail::scope_exit([&] {
  16092. svr.stop();
  16093. t.join();
  16094. ASSERT_FALSE(svr.is_running());
  16095. });
  16096. svr.wait_until_ready();
  16097. const std::string req = "GET / HTTP/1.1\r\n"
  16098. "Transfer-Encoding: chunked\r\n"
  16099. "Trailer: X-Hello\r\n"
  16100. "Trailer: X-World, Content-Length\r\n"
  16101. "\r\n"
  16102. "0\r\n"
  16103. "X-Hello: hello\r\n"
  16104. "X-World: world\r\n"
  16105. "Content-Length: 10\r\n"
  16106. "\r\n";
  16107. std::string res;
  16108. ASSERT_TRUE(send_request(1, req, &res, port));
  16109. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16110. // Accepted: both field lines contribute to the declared set
  16111. EXPECT_EQ(2U, observed_trailer_count);
  16112. EXPECT_EQ(observed_hello, "hello");
  16113. EXPECT_EQ(observed_world, "world");
  16114. // Denied: a prohibited name stays prohibited on a later field line
  16115. EXPECT_FALSE(observed_content_length);
  16116. }
  16117. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16118. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16119. // unbounded run of fields that are never declared, because the counter would
  16120. // only advance for declared fields.
  16121. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16122. Server svr;
  16123. bool handler_called = false;
  16124. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16125. handler_called = true;
  16126. res.set_content("ok", "text/plain");
  16127. });
  16128. auto port = svr.bind_to_any_port(HOST);
  16129. thread t = thread([&]() { svr.listen_after_bind(); });
  16130. auto se = detail::scope_exit([&] {
  16131. svr.stop();
  16132. t.join();
  16133. ASSERT_FALSE(svr.is_running());
  16134. });
  16135. svr.wait_until_ready();
  16136. // Declare nothing, then send far more undeclared trailer fields than the
  16137. // header-count limit. Parsing must stop and reject the request rather than
  16138. // read every line.
  16139. std::string req = "GET / HTTP/1.1\r\n"
  16140. "Transfer-Encoding: chunked\r\n"
  16141. "\r\n"
  16142. "0\r\n";
  16143. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16144. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16145. }
  16146. req += "\r\n";
  16147. std::string res;
  16148. ASSERT_TRUE(send_request(1, req, &res, port));
  16149. // The request is rejected before the handler runs.
  16150. EXPECT_FALSE(handler_called);
  16151. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16152. }
  16153. // The set of declared trailer names is capped so a peer cannot grow it without
  16154. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16155. // declared past the cap is not honored, even if the field is actually sent.
  16156. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16157. Server svr;
  16158. // One name inside the cap and one past it, so the test tracks the cap rather
  16159. // than a fixed count.
  16160. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16161. const std::string within_cap_name = "X-T-0";
  16162. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16163. bool observed_within_cap = false;
  16164. bool observed_past_cap = false;
  16165. svr.Get("/", [&](const Request &req, Response &res) {
  16166. observed_within_cap = req.has_trailer(within_cap_name);
  16167. observed_past_cap = req.has_trailer(past_cap_name);
  16168. res.set_content("ok", "text/plain");
  16169. });
  16170. auto port = svr.bind_to_any_port(HOST);
  16171. thread t = thread([&]() { svr.listen_after_bind(); });
  16172. auto se = detail::scope_exit([&] {
  16173. svr.stop();
  16174. t.join();
  16175. ASSERT_FALSE(svr.is_running());
  16176. });
  16177. svr.wait_until_ready();
  16178. // Declare more trailer names than the cap in a single Trailer field, then
  16179. // actually send the first (within the cap) and the last (past it).
  16180. std::string trailer_decl = "Trailer: ";
  16181. for (int i = 0; i < declared_count; i++) {
  16182. if (i != 0) { trailer_decl += ", "; }
  16183. trailer_decl += "X-T-" + std::to_string(i);
  16184. }
  16185. trailer_decl += "\r\n";
  16186. const std::string req = "GET / HTTP/1.1\r\n"
  16187. "Transfer-Encoding: chunked\r\n" +
  16188. trailer_decl +
  16189. "\r\n"
  16190. "0\r\n" +
  16191. within_cap_name + ": a\r\n" + past_cap_name +
  16192. ": b\r\n"
  16193. "\r\n";
  16194. std::string res;
  16195. ASSERT_TRUE(send_request(1, req, &res, port));
  16196. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16197. // A name within the cap is honored; one declared past the cap is dropped.
  16198. EXPECT_TRUE(observed_within_cap);
  16199. EXPECT_FALSE(observed_past_cap);
  16200. }
  16201. // A direct client that is not listed in trusted_proxies must not be able to
  16202. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16203. // the peer address on the actual TCP connection determines whether the
  16204. // header is honored.
  16205. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16206. Server svr;
  16207. // Deliberately does NOT include the loopback address the test client
  16208. // actually connects from, so the direct connection is not a trusted proxy.
  16209. svr.set_trusted_proxies({"203.0.113.66"});
  16210. std::string observed_remote_addr;
  16211. svr.Get("/ip", [&](const Request &req, Response &res) {
  16212. observed_remote_addr = req.remote_addr;
  16213. res.set_content("ok", "text/plain");
  16214. });
  16215. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16216. auto se = detail::scope_exit([&] {
  16217. svr.stop();
  16218. t.join();
  16219. ASSERT_FALSE(svr.is_running());
  16220. });
  16221. svr.wait_until_ready();
  16222. Client cli(HOST, PORT);
  16223. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16225. EXPECT_EQ(StatusCode::OK_200, res->status);
  16226. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16227. // ignored entirely and the real connection-level address retained.
  16228. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16229. observed_remote_addr == "127.0.0.1");
  16230. }
  16231. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16232. Server svr;
  16233. std::string observed_remote_addr;
  16234. std::string observed_xff;
  16235. svr.Get("/ip", [&](const Request &req, Response &res) {
  16236. observed_remote_addr = req.remote_addr;
  16237. observed_xff = req.get_header_value("X-Forwarded-For");
  16238. res.set_content("ok", "text/plain");
  16239. });
  16240. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16241. auto se = detail::scope_exit([&] {
  16242. svr.stop();
  16243. t.join();
  16244. ASSERT_FALSE(svr.is_running());
  16245. });
  16246. svr.wait_until_ready();
  16247. Client cli(HOST, PORT);
  16248. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16250. EXPECT_EQ(StatusCode::OK_200, res->status);
  16251. EXPECT_EQ(observed_xff, "203.0.113.66");
  16252. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16253. observed_remote_addr == "127.0.0.1");
  16254. }
  16255. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16256. Server svr;
  16257. svr.set_trusted_proxies({"203.0.113.66"});
  16258. std::string observed_remote_addr;
  16259. std::string observed_xff;
  16260. svr.Get("/ip", [&](const Request &req, Response &res) {
  16261. observed_remote_addr = req.remote_addr;
  16262. observed_xff = req.get_header_value("X-Forwarded-For");
  16263. res.set_content("ok", "text/plain");
  16264. });
  16265. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16266. auto se = detail::scope_exit([&] {
  16267. svr.stop();
  16268. t.join();
  16269. ASSERT_FALSE(svr.is_running());
  16270. });
  16271. svr.wait_until_ready();
  16272. Client cli(HOST, PORT);
  16273. auto res = cli.Get("/ip");
  16274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16275. EXPECT_EQ(StatusCode::OK_200, res->status);
  16276. EXPECT_EQ(observed_xff, "");
  16277. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16278. observed_remote_addr == "127.0.0.1");
  16279. }
  16280. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16281. Server svr;
  16282. // Include the loopback address the test client actually connects from, so
  16283. // the direct connection itself is recognized as the trusted proxy hop.
  16284. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16285. std::string observed_remote_addr;
  16286. std::string observed_xff;
  16287. svr.Get("/ip", [&](const Request &req, Response &res) {
  16288. observed_remote_addr = req.remote_addr;
  16289. observed_xff = req.get_header_value("X-Forwarded-For");
  16290. res.set_content("ok", "text/plain");
  16291. });
  16292. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16293. auto se = detail::scope_exit([&] {
  16294. svr.stop();
  16295. t.join();
  16296. ASSERT_FALSE(svr.is_running());
  16297. });
  16298. svr.wait_until_ready();
  16299. Client cli(HOST, PORT);
  16300. auto res = cli.Get(
  16301. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16303. EXPECT_EQ(StatusCode::OK_200, res->status);
  16304. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16305. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16306. }
  16307. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16308. Server svr;
  16309. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16310. std::string observed_remote_addr;
  16311. std::string observed_xff;
  16312. svr.Get("/ip", [&](const Request &req, Response &res) {
  16313. observed_remote_addr = req.remote_addr;
  16314. observed_xff = req.get_header_value("X-Forwarded-For");
  16315. res.set_content("ok", "text/plain");
  16316. });
  16317. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16318. auto se = detail::scope_exit([&] {
  16319. svr.stop();
  16320. t.join();
  16321. ASSERT_FALSE(svr.is_running());
  16322. });
  16323. svr.wait_until_ready();
  16324. Client cli(HOST, PORT);
  16325. auto res = cli.Get(
  16326. "/ip",
  16327. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16329. EXPECT_EQ(StatusCode::OK_200, res->status);
  16330. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16331. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16332. }
  16333. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16334. Server svr;
  16335. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16336. std::string observed_remote_addr;
  16337. std::string observed_xff;
  16338. svr.Get("/ip", [&](const Request &req, Response &res) {
  16339. observed_remote_addr = req.remote_addr;
  16340. observed_xff = req.get_header_value("X-Forwarded-For");
  16341. res.set_content("ok", "text/plain");
  16342. });
  16343. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16344. auto se = detail::scope_exit([&] {
  16345. svr.stop();
  16346. t.join();
  16347. ASSERT_FALSE(svr.is_running());
  16348. });
  16349. svr.wait_until_ready();
  16350. Client cli(HOST, PORT);
  16351. auto res = cli.Get(
  16352. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16354. EXPECT_EQ(StatusCode::OK_200, res->status);
  16355. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16356. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16357. // and must not be selected.
  16358. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16359. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16360. }
  16361. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16362. Server svr;
  16363. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16364. std::string observed_remote_addr;
  16365. svr.Get("/ip", [&](const Request &req, Response &res) {
  16366. observed_remote_addr = req.remote_addr;
  16367. res.set_content("ok", "text/plain");
  16368. });
  16369. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16370. auto se = detail::scope_exit([&] {
  16371. svr.stop();
  16372. t.join();
  16373. ASSERT_FALSE(svr.is_running());
  16374. });
  16375. svr.wait_until_ready();
  16376. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16377. // a forged address and the trusted proxy's own address; the forged value must
  16378. // not win over the address the trusted proxy actually recorded.
  16379. Client cli(HOST, PORT);
  16380. auto res = cli.Get(
  16381. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16383. EXPECT_EQ(StatusCode::OK_200, res->status);
  16384. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16385. }
  16386. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16387. Server svr;
  16388. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16389. std::string observed_remote_addr;
  16390. std::string observed_xff;
  16391. svr.Get("/ip", [&](const Request &req, Response &res) {
  16392. observed_remote_addr = req.remote_addr;
  16393. observed_xff = req.get_header_value("X-Forwarded-For");
  16394. res.set_content("ok", "text/plain");
  16395. });
  16396. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16397. auto se = detail::scope_exit([&] {
  16398. svr.stop();
  16399. t.join();
  16400. ASSERT_FALSE(svr.is_running());
  16401. });
  16402. svr.wait_until_ready();
  16403. Client cli(HOST, PORT);
  16404. auto res = cli.Get(
  16405. "/ip",
  16406. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16408. EXPECT_EQ(StatusCode::OK_200, res->status);
  16409. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16410. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16411. }
  16412. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16413. Server svr;
  16414. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16415. std::string observed_remote_addr;
  16416. std::string observed_xff;
  16417. svr.Get("/ip", [&](const Request &req, Response &res) {
  16418. observed_remote_addr = req.remote_addr;
  16419. observed_xff = req.get_header_value("X-Forwarded-For");
  16420. res.set_content("ok", "text/plain");
  16421. });
  16422. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16423. auto se = detail::scope_exit([&] {
  16424. svr.stop();
  16425. t.join();
  16426. ASSERT_FALSE(svr.is_running());
  16427. });
  16428. svr.wait_until_ready();
  16429. std::string raw_req =
  16430. "GET /ip HTTP/1.1\r\n"
  16431. "Host: localhost\r\n"
  16432. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16433. "Connection: close\r\n"
  16434. "\r\n";
  16435. std::string out;
  16436. ASSERT_TRUE(send_request(5, raw_req, &out));
  16437. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16438. // Header parser trims surrounding whitespace of the header value
  16439. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16440. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16441. }
  16442. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16443. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16444. // their own X-Forwarded-For as a separate field line rather than extending the
  16445. // one the client sent, so every occurrence has to be taken into account.
  16446. // Reading only the first one hands back the address the client chose.
  16447. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16448. Server svr;
  16449. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16450. std::string observed_remote_addr;
  16451. size_t observed_xff_count = 0;
  16452. svr.Get("/ip", [&](const Request &req, Response &res) {
  16453. observed_remote_addr = req.remote_addr;
  16454. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16455. res.set_content("ok", "text/plain");
  16456. });
  16457. auto port = svr.bind_to_any_port(HOST);
  16458. thread t = thread([&]() { svr.listen_after_bind(); });
  16459. auto se = detail::scope_exit([&] {
  16460. svr.stop();
  16461. t.join();
  16462. ASSERT_FALSE(svr.is_running());
  16463. });
  16464. svr.wait_until_ready();
  16465. // The client supplies the first field line; the trusted proxy appends the
  16466. // address it observed as a second one.
  16467. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16468. "Host: localhost\r\n"
  16469. "X-Forwarded-For: 1.2.3.4\r\n"
  16470. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16471. "Connection: close\r\n"
  16472. "\r\n";
  16473. std::string out;
  16474. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16475. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16476. EXPECT_EQ(observed_xff_count, 2U);
  16477. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16478. // The same chain spread over one field line per hop derives the same client
  16479. // address, i.e. the split and the comma-joined representations agree.
  16480. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16481. "Host: localhost\r\n"
  16482. "X-Forwarded-For: 1.2.3.4\r\n"
  16483. "X-Forwarded-For: 198.51.100.23\r\n"
  16484. "X-Forwarded-For: 192.0.2.45\r\n"
  16485. "Connection: close\r\n"
  16486. "\r\n";
  16487. out.clear();
  16488. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16489. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16490. EXPECT_EQ(observed_xff_count, 3U);
  16491. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16492. }
  16493. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16494. // crash the server (it used to call front() on an empty vector inside
  16495. // get_client_ip). The connection-level remote address must be retained instead.
  16496. static void run_malformed_xff_test(const std::string &xff_value) {
  16497. Server svr;
  16498. svr.set_trusted_proxies({"192.0.2.45"});
  16499. std::string observed_remote_addr;
  16500. svr.Get("/ip", [&](const Request &req, Response &res) {
  16501. observed_remote_addr = req.remote_addr;
  16502. res.set_content("ok", "text/plain");
  16503. });
  16504. int port = 0;
  16505. thread t = thread([&]() {
  16506. port = svr.bind_to_any_port(HOST);
  16507. svr.listen_after_bind();
  16508. });
  16509. auto se = detail::scope_exit([&] {
  16510. svr.stop();
  16511. t.join();
  16512. ASSERT_FALSE(svr.is_running());
  16513. });
  16514. svr.wait_until_ready();
  16515. Client cli(HOST, port);
  16516. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16518. EXPECT_EQ(StatusCode::OK_200, res->status);
  16519. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16520. observed_remote_addr == "127.0.0.1");
  16521. }
  16522. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16523. run_malformed_xff_test("");
  16524. }
  16525. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16526. run_malformed_xff_test(",");
  16527. }
  16528. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16529. run_malformed_xff_test(", , ,");
  16530. }
  16531. // The same rule applies to Accept: a request whose acceptable types are spread
  16532. // over several field lines must be negotiated against all of them.
  16533. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16534. // case-insensitive connection options. Comparing the whole field value against
  16535. // one option misses a client that sends several of them, and misses every
  16536. // casing but the one written in the comparison.
  16537. //
  16538. // Sends req, reads the response, then reuses the same socket for a second
  16539. // request to find out whether the server kept the connection.
  16540. static void probe_connection_reuse(int port, const std::string &req,
  16541. bool *announced_close, bool *reusable) {
  16542. auto error = Error::Success;
  16543. auto sock = detail::create_client_socket(
  16544. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16545. /*connection_timeout_sec=*/5, 0,
  16546. /*read_timeout_sec=*/1, 0,
  16547. /*write_timeout_sec=*/5, 0, std::string(), error);
  16548. ASSERT_NE(sock, INVALID_SOCKET);
  16549. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16550. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16551. "Host: localhost\r\n"
  16552. "Connection: close\r\n"
  16553. "\r\n";
  16554. std::string first_response;
  16555. std::string second_response;
  16556. detail::process_client_socket(
  16557. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16558. [&](Stream &strm) {
  16559. if (strm.write(req.data(), req.size()) !=
  16560. static_cast<ssize_t>(req.size())) {
  16561. return false;
  16562. }
  16563. char buf[512];
  16564. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16565. // Headers plus the two-byte body of the handler below
  16566. while (reader.getline()) {
  16567. first_response += reader.ptr();
  16568. if (first_response.find("ok") != std::string::npos) { break; }
  16569. }
  16570. if (strm.write(second.data(), second.size()) !=
  16571. static_cast<ssize_t>(second.size())) {
  16572. return true;
  16573. }
  16574. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16575. while (reader2.getline()) {
  16576. second_response += reader2.ptr();
  16577. if (second_response.find("ok") != std::string::npos) { break; }
  16578. }
  16579. return true;
  16580. });
  16581. *announced_close =
  16582. first_response.find("Connection: close") != std::string::npos;
  16583. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16584. }
  16585. class ConnectionTokenTest : public ::testing::Test {
  16586. protected:
  16587. void SetUp() override {
  16588. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16589. res.set_content("ok", "text/plain");
  16590. });
  16591. port_ = svr_.bind_to_any_port(HOST);
  16592. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16593. svr_.wait_until_ready();
  16594. }
  16595. void TearDown() override {
  16596. svr_.stop();
  16597. if (thread_.joinable()) { thread_.join(); }
  16598. }
  16599. Server svr_;
  16600. int port_ = 0;
  16601. thread thread_;
  16602. };
  16603. // "close" alongside another option still closes the connection, and the
  16604. // response says so rather than leaving the peer to discover it.
  16605. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16606. bool announced_close = false;
  16607. bool reusable = true;
  16608. probe_connection_reuse(port_,
  16609. "GET /keepalive HTTP/1.1\r\n"
  16610. "Host: localhost\r\n"
  16611. "Connection: keep-alive, close\r\n"
  16612. "\r\n",
  16613. &announced_close, &reusable);
  16614. EXPECT_TRUE(announced_close);
  16615. EXPECT_FALSE(reusable);
  16616. }
  16617. // "close" split over two field lines is the same list, so it is honored too.
  16618. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16619. bool announced_close = false;
  16620. bool reusable = true;
  16621. probe_connection_reuse(port_,
  16622. "GET /keepalive HTTP/1.1\r\n"
  16623. "Host: localhost\r\n"
  16624. "Connection: keep-alive\r\n"
  16625. "Connection: close\r\n"
  16626. "\r\n",
  16627. &announced_close, &reusable);
  16628. EXPECT_TRUE(announced_close);
  16629. EXPECT_FALSE(reusable);
  16630. }
  16631. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16632. // keep-alive in the spelling everyone actually sends keeps its connection.
  16633. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16634. bool announced_close = false;
  16635. bool reusable = false;
  16636. probe_connection_reuse(port_,
  16637. "GET /keepalive HTTP/1.0\r\n"
  16638. "Host: localhost\r\n"
  16639. "Connection: keep-alive\r\n"
  16640. "\r\n",
  16641. &announced_close, &reusable);
  16642. EXPECT_FALSE(announced_close);
  16643. EXPECT_TRUE(reusable);
  16644. }
  16645. // A token the value merely contains is not the token itself.
  16646. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16647. bool announced_close = false;
  16648. bool reusable = false;
  16649. probe_connection_reuse(port_,
  16650. "GET /keepalive HTTP/1.1\r\n"
  16651. "Host: localhost\r\n"
  16652. "Connection: notclose\r\n"
  16653. "\r\n",
  16654. &announced_close, &reusable);
  16655. EXPECT_FALSE(announced_close);
  16656. EXPECT_TRUE(reusable);
  16657. }
  16658. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16659. Server svr;
  16660. std::vector<std::string> observed_types;
  16661. svr.Get("/", [&](const Request &req, Response &res) {
  16662. observed_types = req.accept_content_types;
  16663. res.set_content("ok", "text/plain");
  16664. });
  16665. auto port = svr.bind_to_any_port(HOST);
  16666. thread t = thread([&]() { svr.listen_after_bind(); });
  16667. auto se = detail::scope_exit([&] {
  16668. svr.stop();
  16669. t.join();
  16670. ASSERT_FALSE(svr.is_running());
  16671. });
  16672. svr.wait_until_ready();
  16673. Client cli(HOST, port);
  16674. Headers headers;
  16675. headers.emplace("Accept", "text/plain;q=0.5");
  16676. headers.emplace("Accept", "application/json");
  16677. auto res = cli.Get("/", headers);
  16678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16679. EXPECT_EQ(StatusCode::OK_200, res->status);
  16680. // Sorted by q-value, so the second field line's type comes first
  16681. ASSERT_EQ(2U, observed_types.size());
  16682. EXPECT_EQ("application/json", observed_types[0]);
  16683. EXPECT_EQ("text/plain", observed_types[1]);
  16684. }
  16685. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16686. // empty field line must not contribute a bare comma to the combined value.
  16687. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16688. Server svr;
  16689. std::vector<std::string> observed_types;
  16690. svr.Get("/", [&](const Request &req, Response &res) {
  16691. observed_types = req.accept_content_types;
  16692. res.set_content("ok", "text/plain");
  16693. });
  16694. auto port = svr.bind_to_any_port(HOST);
  16695. thread t = thread([&]() { svr.listen_after_bind(); });
  16696. auto se = detail::scope_exit([&] {
  16697. svr.stop();
  16698. t.join();
  16699. ASSERT_FALSE(svr.is_running());
  16700. });
  16701. svr.wait_until_ready();
  16702. // Empty first field line, then a real one
  16703. std::string raw_req = "GET / HTTP/1.1\r\n"
  16704. "Host: localhost\r\n"
  16705. "Accept:\r\n"
  16706. "Accept: application/json\r\n"
  16707. "Connection: close\r\n"
  16708. "\r\n";
  16709. std::string out;
  16710. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16711. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16712. ASSERT_EQ(1U, observed_types.size());
  16713. EXPECT_EQ("application/json", observed_types[0]);
  16714. }
  16715. // The skip in get_combined_header_value() is what keeps an empty field line
  16716. // from contributing a bare comma. Only a trailing empty field line exercises
  16717. // it: a leading one is already covered by the "combined is still empty" check,
  16718. // and parse_accept_header() now ignores the empty element either way, so the
  16719. // request-level test above can no longer tell the two apart.
  16720. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16721. Headers headers;
  16722. headers.emplace("Accept", "text/html");
  16723. headers.emplace("Accept", "");
  16724. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16725. headers.clear();
  16726. headers.emplace("Accept", "");
  16727. headers.emplace("Accept", "application/json");
  16728. EXPECT_EQ("application/json",
  16729. detail::get_combined_header_value(headers, "Accept"));
  16730. }
  16731. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16732. // An encoding offered on a later Accept-Encoding field line is still offered.
  16733. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16734. Server svr;
  16735. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16736. res.set_content(std::string(1024, 'x'), "text/plain");
  16737. });
  16738. auto port = svr.bind_to_any_port(HOST);
  16739. thread t = thread([&]() { svr.listen_after_bind(); });
  16740. auto se = detail::scope_exit([&] {
  16741. svr.stop();
  16742. t.join();
  16743. ASSERT_FALSE(svr.is_running());
  16744. });
  16745. svr.wait_until_ready();
  16746. Client cli(HOST, port);
  16747. cli.set_decompress(false);
  16748. Headers headers;
  16749. headers.emplace("Accept-Encoding", "identity");
  16750. headers.emplace("Accept-Encoding", "gzip");
  16751. auto res = cli.Get("/", headers);
  16752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16753. EXPECT_EQ(StatusCode::OK_200, res->status);
  16754. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16755. }
  16756. #endif
  16757. #ifndef _WIN32
  16758. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16759. Server svr;
  16760. svr.Post("/post", [&](const Request &req, Response &res) {
  16761. res.set_content(req.body, "text/plain");
  16762. });
  16763. svr.Put("/put", [&](const Request &req, Response &res) {
  16764. res.set_content(req.body, "text/plain");
  16765. });
  16766. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16767. res.set_content(req.body, "text/plain");
  16768. });
  16769. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16770. res.set_content(req.body, "text/plain");
  16771. });
  16772. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16773. auto se = detail::scope_exit([&] {
  16774. svr.stop();
  16775. t.join();
  16776. ASSERT_FALSE(svr.is_running());
  16777. });
  16778. svr.wait_until_ready();
  16779. std::string resp;
  16780. // POST without Content-Length
  16781. ASSERT_TRUE(send_request(5,
  16782. "POST /post HTTP/1.1\r\n"
  16783. "Host: localhost\r\n"
  16784. "Connection: close\r\n"
  16785. "\r\n",
  16786. &resp));
  16787. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16788. // PUT without Content-Length
  16789. resp.clear();
  16790. ASSERT_TRUE(send_request(5,
  16791. "PUT /put HTTP/1.1\r\n"
  16792. "Host: localhost\r\n"
  16793. "Connection: close\r\n"
  16794. "\r\n",
  16795. &resp));
  16796. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16797. // PATCH without Content-Length
  16798. resp.clear();
  16799. ASSERT_TRUE(send_request(5,
  16800. "PATCH /patch HTTP/1.1\r\n"
  16801. "Host: localhost\r\n"
  16802. "Connection: close\r\n"
  16803. "\r\n",
  16804. &resp));
  16805. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16806. // DELETE without Content-Length
  16807. resp.clear();
  16808. ASSERT_TRUE(send_request(5,
  16809. "DELETE /delete HTTP/1.1\r\n"
  16810. "Host: localhost\r\n"
  16811. "Connection: close\r\n"
  16812. "\r\n",
  16813. &resp));
  16814. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16815. }
  16816. #endif
  16817. //==============================================================================
  16818. // open_stream() Tests
  16819. //==============================================================================
  16820. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16821. std::string result;
  16822. char buf[8192];
  16823. ssize_t n;
  16824. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16825. result.append(buf, static_cast<size_t>(n));
  16826. }
  16827. return result;
  16828. }
  16829. // Mock stream for unit tests
  16830. class MockStream : public Stream {
  16831. public:
  16832. std::string data;
  16833. size_t pos = 0;
  16834. ssize_t error_after = -1; // -1 = no error
  16835. explicit MockStream(const std::string &d, ssize_t err = -1)
  16836. : data(d), error_after(err) {}
  16837. bool is_readable() const override { return true; }
  16838. bool wait_readable() const override { return true; }
  16839. bool wait_writable() const override { return true; }
  16840. ssize_t read(char *ptr, size_t size) override {
  16841. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16842. if (pos >= data.size()) return 0;
  16843. size_t limit =
  16844. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16845. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16846. std::memcpy(ptr, data.data() + pos, to_read);
  16847. pos += to_read;
  16848. return static_cast<ssize_t>(to_read);
  16849. }
  16850. ssize_t write(const char *, size_t) override { return -1; }
  16851. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16852. ip = "127.0.0.1";
  16853. port = 0;
  16854. }
  16855. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16856. ip = "127.0.0.1";
  16857. port = 0;
  16858. }
  16859. socket_t socket() const override { return INVALID_SOCKET; }
  16860. time_t duration() const override { return 0; }
  16861. };
  16862. TEST(StreamHandleTest, Basic) {
  16863. ClientImpl::StreamHandle handle;
  16864. EXPECT_FALSE(handle.is_valid());
  16865. handle.response = detail::make_unique<Response>();
  16866. handle.error = Error::Connection;
  16867. EXPECT_FALSE(handle.is_valid());
  16868. handle.error = Error::Success;
  16869. EXPECT_TRUE(handle.is_valid());
  16870. }
  16871. TEST(BodyReaderTest, Basic) {
  16872. MockStream stream("Hello, World!");
  16873. detail::BodyReader reader;
  16874. reader.stream = &stream;
  16875. reader.content_length = 13;
  16876. char buf[32];
  16877. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16878. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16879. EXPECT_TRUE(reader.eof);
  16880. }
  16881. TEST(BodyReaderTest, NoStream) {
  16882. detail::BodyReader reader;
  16883. char buf[32];
  16884. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16885. EXPECT_EQ(Error::Connection, reader.last_error);
  16886. }
  16887. TEST(BodyReaderTest, Error) {
  16888. MockStream stream("Hello, World!", 5);
  16889. detail::BodyReader reader;
  16890. reader.stream = &stream;
  16891. reader.content_length = 13;
  16892. char buf[32];
  16893. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16894. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16895. EXPECT_EQ(Error::Read, reader.last_error);
  16896. }
  16897. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16898. // Mock-based StreamHandle tests relying on private internals are removed.
  16899. class OpenStreamTest : public ::testing::Test {
  16900. protected:
  16901. void SetUp() override {
  16902. svr_.Get("/hello", [](const Request &, Response &res) {
  16903. res.set_content("Hello World!", "text/plain");
  16904. });
  16905. svr_.Get("/large", [](const Request &, Response &res) {
  16906. res.set_content(std::string(10000, 'X'), "text/plain");
  16907. });
  16908. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16909. res.set_content("Hello World!", "image/jpeg");
  16910. res.set_header("Content-Encoding", "UTF-8");
  16911. });
  16912. svr_.Get("/chunked", [](const Request &, Response &res) {
  16913. res.set_chunked_content_provider("text/plain",
  16914. [](size_t offset, DataSink &sink) {
  16915. if (offset < 15) {
  16916. sink.write("chunk", 5);
  16917. return true;
  16918. }
  16919. sink.done();
  16920. return true;
  16921. });
  16922. });
  16923. svr_.Get("/compressible", [](const Request &, Response &res) {
  16924. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16925. DataSink &sink) {
  16926. if (offset < 100 * 1024) {
  16927. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16928. sink.write(chunk.data(), chunk.size());
  16929. return true;
  16930. }
  16931. sink.done();
  16932. return true;
  16933. });
  16934. });
  16935. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16936. [](const Request & /*req*/, Response &res) {
  16937. auto i = new int(0);
  16938. res.set_header("Trailer", "Content-Length, X-Allowed");
  16939. res.set_chunked_content_provider(
  16940. "text/plain",
  16941. [i](size_t /*offset*/, DataSink &sink) {
  16942. switch (*i) {
  16943. case 0: sink.os << "123"; break;
  16944. case 1: sink.os << "456"; break;
  16945. case 2: sink.os << "789"; break;
  16946. case 3: {
  16947. sink.done_with_trailer(
  16948. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16949. } break;
  16950. }
  16951. (*i)++;
  16952. return true;
  16953. },
  16954. [i](bool success) {
  16955. EXPECT_TRUE(success);
  16956. delete i;
  16957. });
  16958. });
  16959. // Echo headers endpoint for header-related tests
  16960. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16961. std::string body;
  16962. for (const auto &h : req.headers) {
  16963. body.append(h.first);
  16964. body.push_back(':');
  16965. body.append(h.second);
  16966. body.push_back('\n');
  16967. }
  16968. res.set_content(body, "text/plain");
  16969. });
  16970. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16971. std::string body;
  16972. for (const auto &h : req.headers) {
  16973. body.append(h.first);
  16974. body.push_back(':');
  16975. body.append(h.second);
  16976. body.push_back('\n');
  16977. }
  16978. res.set_content(body, "text/plain");
  16979. });
  16980. port_ = svr_.bind_to_any_port("127.0.0.1");
  16981. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16982. svr_.wait_until_ready();
  16983. }
  16984. void TearDown() override {
  16985. svr_.stop();
  16986. if (thread_.joinable()) thread_.join();
  16987. }
  16988. Server svr_;
  16989. std::thread thread_;
  16990. int port_ = 0;
  16991. };
  16992. TEST_F(OpenStreamTest, Basic) {
  16993. Client cli("127.0.0.1", port_);
  16994. auto handle = cli.open_stream("GET", "/hello");
  16995. EXPECT_TRUE(handle.is_valid());
  16996. EXPECT_EQ("Hello World!", read_all(handle));
  16997. }
  16998. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  16999. Client cli("127.0.0.1", port_);
  17000. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17001. ASSERT_TRUE(handle.is_valid());
  17002. EXPECT_EQ("Hello World!", read_all(handle));
  17003. }
  17004. TEST_F(OpenStreamTest, SmallBuffer) {
  17005. Client cli("127.0.0.1", port_);
  17006. auto handle = cli.open_stream("GET", "/hello");
  17007. std::string result;
  17008. char buf[4];
  17009. ssize_t n;
  17010. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17011. result.append(buf, static_cast<size_t>(n));
  17012. EXPECT_EQ("Hello World!", result);
  17013. }
  17014. TEST_F(OpenStreamTest, DefaultHeaders) {
  17015. Client cli("127.0.0.1", port_);
  17016. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17017. {
  17018. auto handle = cli.open_stream("GET", "/echo-headers");
  17019. ASSERT_TRUE(handle.is_valid());
  17020. auto body = read_all(handle);
  17021. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17022. std::string::npos);
  17023. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17024. std::string::npos);
  17025. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17026. }
  17027. // open_stream POST with body and no explicit content_type should NOT add
  17028. // text/plain Content-Type (behavior differs from non-streaming path), but
  17029. // should include Content-Length
  17030. {
  17031. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17032. ASSERT_TRUE(handle.is_valid());
  17033. auto body = read_all(handle);
  17034. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17035. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17036. }
  17037. // open_stream POST with explicit Content-Type should preserve it
  17038. {
  17039. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17040. {{"Content-Type", "application/custom"}},
  17041. "{}", "application/custom");
  17042. ASSERT_TRUE(handle.is_valid());
  17043. auto body = read_all(handle);
  17044. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17045. }
  17046. // User-specified User-Agent must not be overwritten for stream API
  17047. {
  17048. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17049. {{"User-Agent", "MyAgent/1.2"}});
  17050. ASSERT_TRUE(handle.is_valid());
  17051. auto body = read_all(handle);
  17052. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17053. }
  17054. }
  17055. TEST_F(OpenStreamTest, Large) {
  17056. Client cli("127.0.0.1", port_);
  17057. auto handle = cli.open_stream("GET", "/large");
  17058. EXPECT_EQ(10000u, read_all(handle).size());
  17059. }
  17060. TEST_F(OpenStreamTest, ConnectionError) {
  17061. Client cli("127.0.0.1", 9999);
  17062. auto handle = cli.open_stream("GET", "/hello");
  17063. EXPECT_FALSE(handle.is_valid());
  17064. }
  17065. TEST_F(OpenStreamTest, Chunked) {
  17066. Client cli("127.0.0.1", port_);
  17067. auto handle = cli.open_stream("GET", "/chunked");
  17068. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17069. "Transfer-Encoding") == "chunked");
  17070. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17071. }
  17072. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17073. Client cli("127.0.0.1", port_);
  17074. auto handle =
  17075. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17076. ASSERT_TRUE(handle.is_valid());
  17077. // Consume body to allow trailers to be received/parsed
  17078. auto body = read_all(handle);
  17079. // Explicitly parse trailers (ensure trailers are available for assertion)
  17080. handle.parse_trailers_if_needed();
  17081. EXPECT_EQ(std::string("123456789"), body);
  17082. // The response should include a Trailer header declaring both names
  17083. ASSERT_TRUE(handle.response);
  17084. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17085. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17086. handle.response->get_header_value("Trailer"));
  17087. // Prohibited trailer must not be present
  17088. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17089. // Allowed trailer should be present
  17090. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17091. EXPECT_EQ(std::string("yes"),
  17092. handle.response->get_trailer_value("X-Allowed"));
  17093. // Verify trailers are NOT present as regular headers
  17094. EXPECT_EQ(std::string(""),
  17095. handle.response->get_header_value("Content-Length"));
  17096. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17097. }
  17098. static std::thread serve_single_response(std::promise<int> &port_promise,
  17099. const std::string &response) {
  17100. return std::thread([&port_promise, response] {
  17101. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17102. default_socket_options(srv);
  17103. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17104. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17105. sockaddr_in addr{};
  17106. addr.sin_family = AF_INET;
  17107. addr.sin_port = htons(0); // Let OS assign a free port
  17108. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17109. int opt = 1;
  17110. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17111. #ifdef _WIN32
  17112. reinterpret_cast<const char *>(&opt),
  17113. #else
  17114. &opt,
  17115. #endif
  17116. sizeof(opt));
  17117. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17118. ::listen(srv, 1) != 0) {
  17119. port_promise.set_value(-1);
  17120. detail::close_socket(srv);
  17121. return;
  17122. }
  17123. socklen_t addr_len = sizeof(addr);
  17124. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17125. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17126. sockaddr_in cli_addr{};
  17127. socklen_t cli_len = sizeof(cli_addr);
  17128. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17129. if (cli != INVALID_SOCKET) {
  17130. // Read the complete HTTP request (until the blank line that terminates
  17131. // headers) before sending the response. If the server closes the socket
  17132. // while the client's request data is still unread in the kernel receive
  17133. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17134. // connection on both sides: it discards the client's receive buffer
  17135. // (which already holds our response) and causes any in-progress write on
  17136. // the client to fail with ECONNRESET. Reading all request data first
  17137. // ensures close() emits a graceful FIN.
  17138. {
  17139. char rbuf[256];
  17140. std::string req;
  17141. while (req.find("\r\n\r\n") == std::string::npos) {
  17142. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17143. if (n <= 0) { break; }
  17144. req.append(rbuf, static_cast<size_t>(n));
  17145. }
  17146. }
  17147. ::send(cli,
  17148. #ifdef _WIN32
  17149. static_cast<const char *>(response.c_str()),
  17150. static_cast<int>(response.size()),
  17151. #else
  17152. response.c_str(), response.size(),
  17153. #endif
  17154. 0);
  17155. detail::close_socket(cli);
  17156. }
  17157. detail::close_socket(srv);
  17158. });
  17159. }
  17160. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17161. #ifndef _WIN32
  17162. signal(SIGPIPE, SIG_IGN);
  17163. #endif
  17164. std::promise<int> port_promise;
  17165. auto port_future = port_promise.get_future();
  17166. auto server_thread =
  17167. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17168. "Content-Type: text/plain\r\n"
  17169. "Content-Length: not-a-number\r\n"
  17170. "Connection: close\r\n"
  17171. "\r\n"
  17172. "hello");
  17173. auto port = port_future.get();
  17174. ASSERT_GT(port, 0);
  17175. Client cli("127.0.0.1", port);
  17176. auto handle = cli.open_stream("GET", "/");
  17177. EXPECT_FALSE(handle.is_valid());
  17178. server_thread.join();
  17179. }
  17180. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17181. #ifndef _WIN32
  17182. signal(SIGPIPE, SIG_IGN);
  17183. #endif
  17184. std::promise<int> port_promise;
  17185. auto port_future = port_promise.get_future();
  17186. auto server_thread = serve_single_response(
  17187. port_promise, "HTTP/1.1 200 OK\r\n"
  17188. "Content-Type: text/plain\r\n"
  17189. "Content-Length: 99999999999999999999999999\r\n"
  17190. "Connection: close\r\n"
  17191. "\r\n"
  17192. "hello");
  17193. auto port = port_future.get();
  17194. ASSERT_GT(port, 0);
  17195. // Historically std::stoull would throw std::out_of_range here and crash
  17196. // the process, then parsing silently clamped to a bogus framing length and
  17197. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17198. // so the stream fails to open, matching the not-a-number case above. The
  17199. // process still must NOT terminate.
  17200. Client cli("127.0.0.1", port);
  17201. auto handle = cli.open_stream("GET", "/");
  17202. EXPECT_FALSE(handle.is_valid());
  17203. server_thread.join();
  17204. }
  17205. // Serves `response` to the single request `fn` makes with a fresh client.
  17206. template <typename Fn>
  17207. static void with_single_response(const std::string &response, Fn fn) {
  17208. #ifndef _WIN32
  17209. signal(SIGPIPE, SIG_IGN);
  17210. #endif
  17211. std::promise<int> port_promise;
  17212. auto port_future = port_promise.get_future();
  17213. auto server_thread = serve_single_response(port_promise, response);
  17214. auto se = detail::scope_exit([&] { server_thread.join(); });
  17215. auto port = port_future.get();
  17216. ASSERT_GT(port, 0);
  17217. Client cli("127.0.0.1", port);
  17218. fn(cli);
  17219. }
  17220. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17221. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17222. // the chunked coding and drop Content-Length, so a front-end that trusts
  17223. // Content-Length would disagree about where the body ends (response
  17224. // smuggling). The client must reject such a response.
  17225. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17226. for (const char *te : {"chunked", "gzip, chunked"}) {
  17227. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17228. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17229. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17230. "5\r\nhello\r\n0\r\n\r\n";
  17231. with_single_response(response, [&](Client &cli) {
  17232. auto res = cli.Get("/");
  17233. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17234. EXPECT_EQ(Error::Read, res.error()) << te;
  17235. });
  17236. with_single_response(response, [&](Client &cli) {
  17237. auto handle = cli.open_stream("GET", "/");
  17238. EXPECT_FALSE(handle.is_valid()) << te;
  17239. EXPECT_EQ(Error::Read, handle.error) << te;
  17240. });
  17241. }
  17242. }
  17243. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17244. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17245. // closing the connection (unlike a request, which must be rejected).
  17246. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17247. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17248. "Transfer-Encoding: chunked\r\n"
  17249. "Connection: close\r\n"
  17250. "\r\n"
  17251. "5\r\nhello\r\n0\r\n\r\n",
  17252. "HTTP/1.1 200 OK\r\n"
  17253. "Transfer-Encoding: gzip\r\n"
  17254. "Connection: close\r\n"
  17255. "\r\n"
  17256. "hello"}) {
  17257. with_single_response(response, [&](Client &cli) {
  17258. auto res = cli.Get("/");
  17259. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17260. EXPECT_EQ("hello", res->body);
  17261. });
  17262. with_single_response(response, [&](Client &cli) {
  17263. auto handle = cli.open_stream("GET", "/");
  17264. ASSERT_TRUE(handle.is_valid()) << response;
  17265. EXPECT_EQ("hello", read_all(handle));
  17266. });
  17267. }
  17268. }
  17269. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17270. // framing headers describe nothing to read and must not be rejected.
  17271. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17272. const std::string framing = "Content-Length: 5\r\n"
  17273. "Transfer-Encoding: chunked\r\n"
  17274. "Connection: close\r\n"
  17275. "\r\n";
  17276. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17277. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17278. });
  17279. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17280. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17281. });
  17282. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17283. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17284. with_single_response(response, [&](Client &cli) {
  17285. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17286. });
  17287. with_single_response(response, [&](Client &cli) {
  17288. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17289. });
  17290. }
  17291. }
  17292. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17293. TEST_F(OpenStreamTest, Gzip) {
  17294. Client cli("127.0.0.1", port_);
  17295. auto handle = cli.open_stream("GET", "/compressible", {},
  17296. {{"Accept-Encoding", "gzip"}});
  17297. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17298. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17299. }
  17300. #endif
  17301. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17302. TEST_F(OpenStreamTest, Brotli) {
  17303. Client cli("127.0.0.1", port_);
  17304. auto handle =
  17305. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17306. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17307. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17308. }
  17309. #endif
  17310. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17311. TEST_F(OpenStreamTest, Zstd) {
  17312. Client cli("127.0.0.1", port_);
  17313. auto handle = cli.open_stream("GET", "/compressible", {},
  17314. {{"Accept-Encoding", "zstd"}});
  17315. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17316. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17317. }
  17318. #endif
  17319. #ifdef CPPHTTPLIB_SSL_ENABLED
  17320. class SSLOpenStreamTest : public ::testing::Test {
  17321. protected:
  17322. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17323. void SetUp() override {
  17324. svr_.Get("/hello", [](const Request &, Response &res) {
  17325. res.set_content("Hello SSL World!", "text/plain");
  17326. });
  17327. svr_.Get("/chunked", [](const Request &, Response &res) {
  17328. res.set_chunked_content_provider("text/plain",
  17329. [](size_t offset, DataSink &sink) {
  17330. if (offset < 15) {
  17331. sink.write("chunk", 5);
  17332. return true;
  17333. }
  17334. sink.done();
  17335. return true;
  17336. });
  17337. });
  17338. svr_.Post("/echo", [](const Request &req, Response &res) {
  17339. res.set_content(req.body, req.get_header_value("Content-Type"));
  17340. });
  17341. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17342. std::string body = req.body;
  17343. res.set_chunked_content_provider(
  17344. "text/plain", [body](size_t offset, DataSink &sink) {
  17345. if (offset < body.size()) {
  17346. sink.write(body.data() + offset, body.size() - offset);
  17347. }
  17348. sink.done();
  17349. return true;
  17350. });
  17351. });
  17352. port_ = svr_.bind_to_any_port("127.0.0.1");
  17353. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17354. svr_.wait_until_ready();
  17355. }
  17356. void TearDown() override {
  17357. svr_.stop();
  17358. if (thread_.joinable()) thread_.join();
  17359. }
  17360. SSLServer svr_;
  17361. std::thread thread_;
  17362. int port_ = 0;
  17363. };
  17364. TEST_F(SSLOpenStreamTest, Basic) {
  17365. SSLClient cli("127.0.0.1", port_);
  17366. cli.enable_server_certificate_verification(false);
  17367. auto handle = cli.open_stream("GET", "/hello");
  17368. ASSERT_TRUE(handle.is_valid());
  17369. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17370. }
  17371. TEST_F(SSLOpenStreamTest, Chunked) {
  17372. SSLClient cli("127.0.0.1", port_);
  17373. cli.enable_server_certificate_verification(false);
  17374. auto handle = cli.open_stream("GET", "/chunked");
  17375. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17376. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17377. "Transfer-Encoding") == "chunked");
  17378. auto body = read_all(handle);
  17379. EXPECT_EQ("chunkchunkchunk", body);
  17380. }
  17381. TEST_F(SSLOpenStreamTest, Post) {
  17382. SSLClient cli("127.0.0.1", port_);
  17383. cli.enable_server_certificate_verification(false);
  17384. auto handle =
  17385. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17386. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17387. EXPECT_EQ(200, handle.response->status);
  17388. auto body = read_all(handle);
  17389. EXPECT_EQ("Hello SSL POST", body);
  17390. }
  17391. TEST_F(SSLOpenStreamTest, PostChunked) {
  17392. SSLClient cli("127.0.0.1", port_);
  17393. cli.enable_server_certificate_verification(false);
  17394. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17395. "Chunked SSL Data", "text/plain");
  17396. ASSERT_TRUE(handle.is_valid());
  17397. EXPECT_EQ(200, handle.response->status);
  17398. auto body = read_all(handle);
  17399. EXPECT_EQ("Chunked SSL Data", body);
  17400. }
  17401. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17402. // Content-Length is terminated by the server closing the connection. When the
  17403. // SSL peer sends a close_notify after the body, the client must treat it as a
  17404. // clean EOF and return a successful response rather than an error.
  17405. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17406. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17407. ASSERT_TRUE(svr.is_valid());
  17408. svr.set_keep_alive_max_count(1);
  17409. const std::string expected_body = "Hello from connection-close response!";
  17410. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17411. res.set_content_provider("text/plain",
  17412. [&](size_t offset, DataSink &sink) -> bool {
  17413. if (offset < expected_body.size()) {
  17414. sink.write(expected_body.data() + offset,
  17415. expected_body.size() - offset);
  17416. }
  17417. sink.done();
  17418. return true;
  17419. });
  17420. });
  17421. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17422. auto se = detail::scope_exit([&] {
  17423. svr.stop();
  17424. listen_thread.join();
  17425. ASSERT_FALSE(svr.is_running());
  17426. });
  17427. svr.wait_until_ready();
  17428. SSLClient cli(HOST, PORT);
  17429. cli.enable_server_certificate_verification(false);
  17430. auto res = cli.Get("/no-content-length");
  17431. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17432. EXPECT_EQ(StatusCode::OK_200, res->status);
  17433. EXPECT_EQ(expected_body, res->body);
  17434. }
  17435. #endif // CPPHTTPLIB_SSL_ENABLED
  17436. //==============================================================================
  17437. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17438. // results for various scenarios.
  17439. //==============================================================================
  17440. TEST(ParityTest, GetVsOpenStream) {
  17441. Server svr;
  17442. const std::string path = "/parity";
  17443. const std::string content = "Parity test content: hello world";
  17444. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17445. res.set_content(content, "text/plain");
  17446. });
  17447. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17448. auto se = detail::scope_exit([&] {
  17449. svr.stop();
  17450. t.join();
  17451. ASSERT_FALSE(svr.is_running());
  17452. });
  17453. svr.wait_until_ready();
  17454. Client cli(HOST, PORT);
  17455. // Non-stream path
  17456. auto r1 = cli.Get(path);
  17457. ASSERT_TRUE(r1);
  17458. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17459. // Stream path
  17460. auto h = cli.open_stream("GET", path);
  17461. ASSERT_TRUE(h.is_valid());
  17462. EXPECT_EQ(r1->body, read_all(h));
  17463. }
  17464. // Helper to compress data with provided compressor type T
  17465. template <typename Compressor>
  17466. static std::string compress_payload_for_parity(const std::string &in) {
  17467. std::string out;
  17468. Compressor compressor;
  17469. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17470. [&](const char *data, size_t n) {
  17471. out.append(data, n);
  17472. return true;
  17473. });
  17474. EXPECT_TRUE(ok);
  17475. return out;
  17476. }
  17477. // Helper function for compression parity tests
  17478. template <typename Compressor>
  17479. static void test_compression_parity(const std::string &original,
  17480. const std::string &path,
  17481. const std::string &encoding) {
  17482. const std::string compressed =
  17483. compress_payload_for_parity<Compressor>(original);
  17484. Server svr;
  17485. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17486. res.set_content(compressed, "application/octet-stream");
  17487. res.set_header("Content-Encoding", encoding);
  17488. });
  17489. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17490. auto se = detail::scope_exit([&] {
  17491. svr.stop();
  17492. t.join();
  17493. ASSERT_FALSE(svr.is_running());
  17494. });
  17495. svr.wait_until_ready();
  17496. Client cli(HOST, PORT);
  17497. // Non-streaming
  17498. {
  17499. auto res = cli.Get(path);
  17500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17501. EXPECT_EQ(StatusCode::OK_200, res->status);
  17502. EXPECT_EQ(original, res->body);
  17503. }
  17504. // Streaming
  17505. {
  17506. auto h = cli.open_stream("GET", path);
  17507. ASSERT_TRUE(h.is_valid());
  17508. EXPECT_EQ(original, read_all(h));
  17509. }
  17510. }
  17511. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17512. TEST(ParityTest, Gzip) {
  17513. test_compression_parity<detail::gzip_compressor>(
  17514. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17515. }
  17516. #endif
  17517. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17518. TEST(ParityTest, Brotli) {
  17519. test_compression_parity<detail::brotli_compressor>(
  17520. "Hello, brotli parity test payload", "/parity-br", "br");
  17521. }
  17522. #endif
  17523. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17524. TEST(ParityTest, Zstd) {
  17525. test_compression_parity<detail::zstd_compressor>(
  17526. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17527. }
  17528. #endif
  17529. //==============================================================================
  17530. // New Stream API Tests
  17531. //==============================================================================
  17532. inline std::string read_body(httplib::stream::Result &result) {
  17533. std::string body;
  17534. while (result.next()) {
  17535. body.append(result.data(), result.size());
  17536. }
  17537. return body;
  17538. }
  17539. TEST(ClientConnectionTest, Basic) {
  17540. httplib::ClientConnection conn;
  17541. EXPECT_FALSE(conn.is_open());
  17542. conn.sock = 1;
  17543. EXPECT_TRUE(conn.is_open());
  17544. httplib::ClientConnection conn2(std::move(conn));
  17545. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17546. conn2.sock = INVALID_SOCKET;
  17547. }
  17548. // Unified test server for all stream::* tests
  17549. class StreamApiTest : public ::testing::Test {
  17550. protected:
  17551. void SetUp() override {
  17552. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17553. res.set_content("Hello World!", "text/plain");
  17554. });
  17555. svr_.Get("/echo-params",
  17556. [](const httplib::Request &req, httplib::Response &res) {
  17557. std::string r;
  17558. for (const auto &p : req.params) {
  17559. if (!r.empty()) r += "&";
  17560. r += p.first + "=" + p.second;
  17561. }
  17562. res.set_content(r, "text/plain");
  17563. });
  17564. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17565. res.set_content(req.body, req.get_header_value("Content-Type"));
  17566. });
  17567. svr_.Post("/echo-headers",
  17568. [](const httplib::Request &req, httplib::Response &res) {
  17569. std::string r;
  17570. for (const auto &h : req.headers)
  17571. r += h.first + ": " + h.second + "\n";
  17572. res.set_content(r, "text/plain");
  17573. });
  17574. svr_.Post("/echo-params",
  17575. [](const httplib::Request &req, httplib::Response &res) {
  17576. std::string r = "params:";
  17577. for (const auto &p : req.params)
  17578. r += p.first + "=" + p.second + ";";
  17579. res.set_content(r + " body:" + req.body, "text/plain");
  17580. });
  17581. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17582. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17583. });
  17584. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17585. res.set_content("PUT:" + req.body, "text/plain");
  17586. });
  17587. svr_.Patch("/echo",
  17588. [](const httplib::Request &req, httplib::Response &res) {
  17589. res.set_content("PATCH:" + req.body, "text/plain");
  17590. });
  17591. svr_.Delete(
  17592. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17593. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17594. "text/plain");
  17595. });
  17596. svr_.Get("/head-test",
  17597. [](const httplib::Request &, httplib::Response &res) {
  17598. res.set_content("body for HEAD", "text/plain");
  17599. });
  17600. svr_.Options("/options",
  17601. [](const httplib::Request &, httplib::Response &res) {
  17602. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17603. });
  17604. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17605. svr_.wait_until_ready();
  17606. }
  17607. void TearDown() override {
  17608. svr_.stop();
  17609. if (thread_.joinable()) thread_.join();
  17610. }
  17611. httplib::Server svr_;
  17612. std::thread thread_;
  17613. };
  17614. // stream::Get tests
  17615. TEST_F(StreamApiTest, GetBasic) {
  17616. httplib::Client cli(HOST, PORT);
  17617. auto result = httplib::stream::Get(cli, "/hello");
  17618. ASSERT_TRUE(result.is_valid());
  17619. EXPECT_EQ(200, result.status());
  17620. EXPECT_EQ("Hello World!", read_body(result));
  17621. }
  17622. TEST_F(StreamApiTest, GetWithParams) {
  17623. httplib::Client cli(HOST, PORT);
  17624. httplib::Params params{{"foo", "bar"}};
  17625. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17626. ASSERT_TRUE(result.is_valid());
  17627. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17628. }
  17629. TEST_F(StreamApiTest, GetConnectionError) {
  17630. httplib::Client cli(HOST, 9999);
  17631. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17632. }
  17633. TEST_F(StreamApiTest, Get404) {
  17634. httplib::Client cli(HOST, PORT);
  17635. auto result = httplib::stream::Get(cli, "/nonexistent");
  17636. EXPECT_TRUE(result.is_valid());
  17637. EXPECT_EQ(404, result.status());
  17638. }
  17639. // stream::Post tests
  17640. TEST_F(StreamApiTest, PostBasic) {
  17641. httplib::Client cli(HOST, PORT);
  17642. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17643. "application/json");
  17644. ASSERT_TRUE(result.is_valid());
  17645. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17646. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17647. }
  17648. TEST_F(StreamApiTest, PostWithHeaders) {
  17649. httplib::Client cli(HOST, PORT);
  17650. httplib::Headers headers{{"X-Custom", "value"}};
  17651. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17652. "text/plain");
  17653. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17654. }
  17655. TEST_F(StreamApiTest, PostWithParams) {
  17656. httplib::Client cli(HOST, PORT);
  17657. httplib::Params params{{"k", "v"}};
  17658. auto result =
  17659. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17660. auto body = read_body(result);
  17661. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17662. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17663. }
  17664. TEST_F(StreamApiTest, PostLarge) {
  17665. httplib::Client cli(HOST, PORT);
  17666. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17667. size_t total = 0;
  17668. while (result.next()) {
  17669. total += result.size();
  17670. }
  17671. EXPECT_EQ(100u * 1024u, total);
  17672. }
  17673. // stream::Put/Patch tests
  17674. TEST_F(StreamApiTest, PutAndPatch) {
  17675. httplib::Client cli(HOST, PORT);
  17676. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17677. EXPECT_EQ("PUT:test", read_body(put));
  17678. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17679. EXPECT_EQ("PATCH:test", read_body(patch));
  17680. }
  17681. // stream::Delete tests
  17682. TEST_F(StreamApiTest, Delete) {
  17683. httplib::Client cli(HOST, PORT);
  17684. auto del1 = httplib::stream::Delete(cli, "/resource");
  17685. EXPECT_EQ("Deleted", read_body(del1));
  17686. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17687. EXPECT_EQ("Deleted:data", read_body(del2));
  17688. }
  17689. // stream::Head/Options tests
  17690. TEST_F(StreamApiTest, HeadAndOptions) {
  17691. httplib::Client cli(HOST, PORT);
  17692. auto head = httplib::stream::Head(cli, "/head-test");
  17693. EXPECT_TRUE(head.is_valid());
  17694. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17695. auto opts = httplib::stream::Options(cli, "/options");
  17696. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17697. }
  17698. // SSL stream::* tests
  17699. #ifdef CPPHTTPLIB_SSL_ENABLED
  17700. class SSLStreamApiTest : public ::testing::Test {
  17701. protected:
  17702. void SetUp() override {
  17703. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17704. res.set_content("Hello SSL!", "text/plain");
  17705. });
  17706. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17707. res.set_content(req.body, "text/plain");
  17708. });
  17709. port_ = svr_.bind_to_any_port("127.0.0.1");
  17710. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17711. svr_.wait_until_ready();
  17712. }
  17713. void TearDown() override {
  17714. svr_.stop();
  17715. if (thread_.joinable()) thread_.join();
  17716. }
  17717. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17718. std::thread thread_;
  17719. int port_ = 0;
  17720. };
  17721. TEST_F(SSLStreamApiTest, GetAndPost) {
  17722. httplib::SSLClient cli("127.0.0.1", port_);
  17723. cli.enable_server_certificate_verification(false);
  17724. auto get = httplib::stream::Get(cli, "/hello");
  17725. EXPECT_EQ("Hello SSL!", read_body(get));
  17726. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17727. EXPECT_EQ("test", read_body(post));
  17728. }
  17729. #endif
  17730. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17731. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17732. // BodyReader
  17733. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17734. // Test that read timeout during streaming is detected
  17735. // Use a large content-length response where server delays mid-stream
  17736. Server svr;
  17737. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17738. // Send a large response with delay in the middle
  17739. res.set_content_provider(
  17740. 1000, // content_length
  17741. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17742. if (offset < 100) {
  17743. // Send first 100 bytes immediately
  17744. std::string data(100, 'A');
  17745. sink.write(data.c_str(), data.size());
  17746. return true;
  17747. }
  17748. // Then delay longer than client timeout
  17749. std::this_thread::sleep_for(std::chrono::seconds(3));
  17750. std::string data(900, 'B');
  17751. sink.write(data.c_str(), data.size());
  17752. return true;
  17753. });
  17754. });
  17755. auto port = 8091;
  17756. std::thread t([&]() { svr.listen("localhost", port); });
  17757. svr.wait_until_ready();
  17758. Client cli("localhost", port);
  17759. cli.set_read_timeout(1, 0); // 1 second timeout
  17760. auto handle = cli.open_stream("GET", "/slow-stream");
  17761. ASSERT_TRUE(handle.is_valid());
  17762. char buf[256];
  17763. ssize_t total = 0;
  17764. ssize_t n;
  17765. bool got_error = false;
  17766. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17767. total += n;
  17768. }
  17769. if (n < 0) {
  17770. got_error = true;
  17771. // Should be timeout or read error
  17772. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17773. handle.get_read_error() == Error::Read)
  17774. << "Actual error: " << to_string(handle.get_read_error());
  17775. }
  17776. // Either we got an error, or we got less data than expected
  17777. EXPECT_TRUE(got_error || total < 1000)
  17778. << "Expected timeout but got all " << total << " bytes";
  17779. svr.stop();
  17780. t.join();
  17781. }
  17782. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17783. // Test connection closed detection via BodyReader
  17784. Server svr;
  17785. std::atomic<bool> close_now{false};
  17786. svr.Get("/will-close", [&](const Request &, Response &res) {
  17787. res.set_content_provider(
  17788. 10000, // Large content_length that we won't fully send
  17789. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17790. if (offset < 100) {
  17791. std::string data(100, 'X');
  17792. sink.write(data.c_str(), data.size());
  17793. return true;
  17794. }
  17795. // Wait for signal then abort
  17796. while (!close_now) {
  17797. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17798. }
  17799. return false; // Abort - server will close connection
  17800. });
  17801. });
  17802. auto port = 8092;
  17803. std::thread t([&]() { svr.listen("localhost", port); });
  17804. svr.wait_until_ready();
  17805. Client cli("localhost", port);
  17806. auto handle = cli.open_stream("GET", "/will-close");
  17807. ASSERT_TRUE(handle.is_valid());
  17808. char buf[256];
  17809. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17810. EXPECT_GT(n, 0) << "First read should succeed";
  17811. // Signal server to close
  17812. close_now = true;
  17813. // Keep reading until error or EOF
  17814. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17815. // Keep reading
  17816. }
  17817. // Should get an error since content_length wasn't satisfied
  17818. if (n < 0) {
  17819. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17820. handle.get_read_error() == Error::Read)
  17821. << "Actual error: " << to_string(handle.get_read_error());
  17822. }
  17823. svr.stop();
  17824. t.join();
  17825. }
  17826. #ifdef CPPHTTPLIB_SSL_ENABLED
  17827. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  17828. // Test that read timeout during SSL streaming is detected
  17829. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17830. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17831. res.set_content_provider(
  17832. 1000, "text/plain",
  17833. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17834. if (offset < 100) {
  17835. std::string data(100, 'A');
  17836. sink.write(data.c_str(), data.size());
  17837. return true;
  17838. }
  17839. std::this_thread::sleep_for(std::chrono::seconds(3));
  17840. std::string data(900, 'B');
  17841. sink.write(data.c_str(), data.size());
  17842. return true;
  17843. });
  17844. });
  17845. auto port = 8093;
  17846. std::thread t([&]() { svr.listen("localhost", port); });
  17847. svr.wait_until_ready();
  17848. SSLClient cli("localhost", port);
  17849. cli.enable_server_certificate_verification(false);
  17850. cli.set_read_timeout(1, 0); // 1 second timeout
  17851. auto handle = cli.open_stream("GET", "/slow-stream");
  17852. ASSERT_TRUE(handle.is_valid());
  17853. char buf[256];
  17854. ssize_t total = 0;
  17855. ssize_t n;
  17856. bool got_error = false;
  17857. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17858. total += n;
  17859. }
  17860. if (n < 0) {
  17861. got_error = true;
  17862. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17863. handle.get_read_error() == Error::Read)
  17864. << "Actual error: " << to_string(handle.get_read_error());
  17865. }
  17866. EXPECT_TRUE(got_error || total < 1000)
  17867. << "Expected timeout but got all " << total << " bytes";
  17868. svr.stop();
  17869. t.join();
  17870. }
  17871. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17872. // Test SSL connection closed detection
  17873. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17874. std::atomic<bool> close_now{false};
  17875. svr.Get("/will-close", [&](const Request &, Response &res) {
  17876. res.set_content_provider(
  17877. 10000, "text/plain",
  17878. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17879. if (offset < 100) {
  17880. std::string data(100, 'X');
  17881. sink.write(data.c_str(), data.size());
  17882. return true;
  17883. }
  17884. while (!close_now) {
  17885. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17886. }
  17887. return false;
  17888. });
  17889. });
  17890. auto port = 8094;
  17891. std::thread t([&]() { svr.listen("localhost", port); });
  17892. svr.wait_until_ready();
  17893. SSLClient cli("localhost", port);
  17894. cli.enable_server_certificate_verification(false);
  17895. auto handle = cli.open_stream("GET", "/will-close");
  17896. ASSERT_TRUE(handle.is_valid());
  17897. char buf[256];
  17898. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17899. EXPECT_GT(n, 0);
  17900. // Signal server to close
  17901. close_now = true;
  17902. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17903. // Keep reading
  17904. }
  17905. if (n < 0) {
  17906. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17907. handle.get_read_error() == Error::Read)
  17908. << "Actual error: " << to_string(handle.get_read_error());
  17909. }
  17910. svr.stop();
  17911. t.join();
  17912. }
  17913. #endif
  17914. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17915. using namespace httplib;
  17916. // Create a test file
  17917. const char *fname = "etag_testfile.txt";
  17918. const char *content = "etag-content";
  17919. {
  17920. std::ofstream ofs(fname);
  17921. ofs << content;
  17922. ASSERT_TRUE(ofs.good());
  17923. }
  17924. Server svr;
  17925. svr.set_mount_point("/static", ".");
  17926. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17927. svr.wait_until_ready();
  17928. Client cli(HOST, PORT);
  17929. // First request: should get 200 with ETag header
  17930. auto res1 = cli.Get("/static/etag_testfile.txt");
  17931. ASSERT_TRUE(res1);
  17932. ASSERT_EQ(200, res1->status);
  17933. ASSERT_TRUE(res1->has_header("ETag"));
  17934. std::string etag = res1->get_header_value("ETag");
  17935. EXPECT_FALSE(etag.empty());
  17936. // Verify ETag format: W/"hex-hex"
  17937. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17938. EXPECT_EQ('W', etag[0]);
  17939. EXPECT_EQ('/', etag[1]);
  17940. EXPECT_EQ('"', etag[2]);
  17941. EXPECT_EQ('"', etag.back());
  17942. // Exact match: expect 304 Not Modified
  17943. Headers h2 = {{"If-None-Match", etag}};
  17944. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17945. ASSERT_TRUE(res2);
  17946. EXPECT_EQ(304, res2->status);
  17947. // Wildcard match: expect 304 Not Modified
  17948. Headers h3 = {{"If-None-Match", "*"}};
  17949. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17950. ASSERT_TRUE(res3);
  17951. EXPECT_EQ(304, res3->status);
  17952. // Non-matching ETag: expect 200
  17953. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17954. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17955. ASSERT_TRUE(res4);
  17956. EXPECT_EQ(200, res4->status);
  17957. // Multiple ETags with one matching: expect 304
  17958. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17959. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17960. ASSERT_TRUE(res5);
  17961. EXPECT_EQ(304, res5->status);
  17962. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17963. // that equivalent to the single comma-separated list above, so the match on
  17964. // the second line must still be found.
  17965. Headers h6;
  17966. h6.emplace("If-None-Match", "W/\"other\"");
  17967. h6.emplace("If-None-Match", etag);
  17968. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17969. ASSERT_TRUE(res6);
  17970. EXPECT_EQ(304, res6->status);
  17971. svr.stop();
  17972. t.join();
  17973. std::remove(fname);
  17974. }
  17975. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  17976. using namespace httplib;
  17977. Server svr;
  17978. svr.set_mount_point("/static", ".");
  17979. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17980. svr.wait_until_ready();
  17981. Client cli(HOST, PORT);
  17982. // Send If-None-Match: * to a non-existent file
  17983. Headers h = {{"If-None-Match", "*"}};
  17984. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  17985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17986. EXPECT_EQ(404, res->status);
  17987. svr.stop();
  17988. t.join();
  17989. }
  17990. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  17991. using namespace httplib;
  17992. // Create a test file
  17993. const char *fname = "etag_boundary_testfile.txt";
  17994. const char *content = "boundary-test";
  17995. {
  17996. std::ofstream ofs(fname);
  17997. ofs << content;
  17998. ASSERT_TRUE(ofs.good());
  17999. }
  18000. Server svr;
  18001. svr.set_mount_point("/static", ".");
  18002. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18003. svr.wait_until_ready();
  18004. Client cli(HOST, PORT);
  18005. // Get the actual ETag
  18006. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18007. ASSERT_TRUE(res1);
  18008. ASSERT_EQ(200, res1->status);
  18009. ASSERT_TRUE(res1->has_header("ETag"));
  18010. std::string etag = res1->get_header_value("ETag");
  18011. // Test 1: Very long ETag value (longer than actual ETag)
  18012. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18013. Headers h1 = {{"If-None-Match", "W/"
  18014. "\"very-long-etag-value-that-is-much-longer-"
  18015. "than-the-actual-etag-value\""}};
  18016. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18017. ASSERT_TRUE(res2);
  18018. EXPECT_EQ(200, res2->status); // Should not match
  18019. // Test 2: Long string followed by wildcard
  18020. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18021. // string)
  18022. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18023. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18024. ASSERT_TRUE(res3);
  18025. EXPECT_EQ(304, res3->status); // Should match on "*"
  18026. // Test 3: Wildcard followed by long string
  18027. // Should match on "*" immediately and return 304
  18028. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18029. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18030. ASSERT_TRUE(res4);
  18031. EXPECT_EQ(304, res4->status); // Should match on "*"
  18032. // Test 4: Multiple long non-matching values
  18033. // Should NOT match and return 200 (test that all comparisons are safe)
  18034. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18035. "W/\"second-long-non-matching-value\", "
  18036. "W/\"third-long-non-matching-value\""}};
  18037. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18038. ASSERT_TRUE(res5);
  18039. EXPECT_EQ(200, res5->status); // Should not match
  18040. // Test 5: Single character that is not "*" (edge case)
  18041. Headers h5 = {{"If-None-Match", "X"}};
  18042. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18043. ASSERT_TRUE(res6);
  18044. EXPECT_EQ(200, res6->status); // Should not match
  18045. svr.stop();
  18046. t.join();
  18047. std::remove(fname);
  18048. }
  18049. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18050. using namespace httplib;
  18051. // Create a test file
  18052. const char *fname = "ims_testfile.txt";
  18053. const char *content = "if-modified-since-test";
  18054. {
  18055. std::ofstream ofs(fname);
  18056. ofs << content;
  18057. ASSERT_TRUE(ofs.good());
  18058. }
  18059. Server svr;
  18060. svr.set_mount_point("/static", ".");
  18061. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18062. svr.wait_until_ready();
  18063. Client cli(HOST, PORT);
  18064. // First request: should get 200 with Last-Modified header
  18065. auto res1 = cli.Get("/static/ims_testfile.txt");
  18066. ASSERT_TRUE(res1);
  18067. ASSERT_EQ(200, res1->status);
  18068. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18069. std::string last_modified = res1->get_header_value("Last-Modified");
  18070. EXPECT_FALSE(last_modified.empty());
  18071. // If-Modified-Since with same time: expect 304
  18072. Headers h2 = {{"If-Modified-Since", last_modified}};
  18073. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18074. ASSERT_TRUE(res2);
  18075. EXPECT_EQ(304, res2->status);
  18076. // If-Modified-Since with future time: expect 304
  18077. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18078. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18079. ASSERT_TRUE(res3);
  18080. EXPECT_EQ(304, res3->status);
  18081. // If-Modified-Since with past time: expect 200
  18082. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18083. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18084. ASSERT_TRUE(res4);
  18085. EXPECT_EQ(200, res4->status);
  18086. // If-None-Match takes precedence over If-Modified-Since
  18087. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18088. ASSERT_TRUE(res1->has_header("ETag"));
  18089. std::string etag = res1->get_header_value("ETag");
  18090. Headers h5 = {{"If-None-Match", etag},
  18091. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18092. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18093. ASSERT_TRUE(res5);
  18094. EXPECT_EQ(304, res5->status);
  18095. svr.stop();
  18096. t.join();
  18097. std::remove(fname);
  18098. }
  18099. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18100. using namespace httplib;
  18101. Server svr;
  18102. // Endpoint that returns compressible content
  18103. svr.Get("/compressible", [](const Request &, Response &res) {
  18104. // Return a large enough body to trigger compression
  18105. std::string body(1000, 'a');
  18106. res.set_content(body, "text/plain");
  18107. });
  18108. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18109. svr.wait_until_ready();
  18110. Client cli(HOST, PORT);
  18111. // Request with gzip support: should get Vary header when compressed
  18112. cli.set_compress(true);
  18113. auto res1 = cli.Get("/compressible");
  18114. ASSERT_TRUE(res1);
  18115. EXPECT_EQ(200, res1->status);
  18116. // If Content-Encoding is set, Vary should also be set
  18117. if (res1->has_header("Content-Encoding")) {
  18118. EXPECT_TRUE(res1->has_header("Vary"));
  18119. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18120. }
  18121. // Request without Accept-Encoding header: should not have compression
  18122. Headers h_no_compress;
  18123. auto res2 = cli.Get("/compressible", h_no_compress);
  18124. ASSERT_TRUE(res2);
  18125. EXPECT_EQ(200, res2->status);
  18126. // Verify Vary header is present when compression is applied
  18127. // (the exact behavior depends on server configuration)
  18128. svr.stop();
  18129. t.join();
  18130. }
  18131. TEST(ETagTest, IfRangeWithETag) {
  18132. using namespace httplib;
  18133. // Create a test file with known content
  18134. const char *fname = "if_range_testfile.txt";
  18135. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18136. {
  18137. std::ofstream ofs(fname);
  18138. ofs << content;
  18139. ASSERT_TRUE(ofs.good());
  18140. }
  18141. Server svr;
  18142. svr.set_mount_point("/static", ".");
  18143. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18144. svr.wait_until_ready();
  18145. Client cli(HOST, PORT);
  18146. // First request: get ETag
  18147. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18148. ASSERT_TRUE(res1);
  18149. ASSERT_EQ(200, res1->status);
  18150. ASSERT_TRUE(res1->has_header("ETag"));
  18151. std::string etag = res1->get_header_value("ETag");
  18152. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18153. // Since our server generates weak ETags (W/"..."), If-Range with our
  18154. // ETag should NOT result in partial content - it should return full content.
  18155. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18156. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18157. ASSERT_TRUE(res2);
  18158. // Weak ETag in If-Range -> full content (200), not partial (206)
  18159. EXPECT_EQ(200, res2->status);
  18160. EXPECT_EQ(content, res2->body);
  18161. EXPECT_FALSE(res2->has_header("Content-Range"));
  18162. // Range request with non-matching If-Range (ETag): should get 200 (full
  18163. // content)
  18164. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18165. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18166. ASSERT_TRUE(res3);
  18167. EXPECT_EQ(200, res3->status);
  18168. EXPECT_EQ(content, res3->body);
  18169. EXPECT_FALSE(res3->has_header("Content-Range"));
  18170. // Range request with strong ETag (hypothetical - our server doesn't generate
  18171. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18172. // should return full content)
  18173. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18174. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18175. ASSERT_TRUE(res4);
  18176. EXPECT_EQ(200, res4->status);
  18177. EXPECT_EQ(content, res4->body);
  18178. EXPECT_FALSE(res4->has_header("Content-Range"));
  18179. svr.stop();
  18180. t.join();
  18181. std::remove(fname);
  18182. }
  18183. TEST(ETagTest, IfRangeWithDate) {
  18184. using namespace httplib;
  18185. // Create a test file
  18186. const char *fname = "if_range_date_testfile.txt";
  18187. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18188. {
  18189. std::ofstream ofs(fname);
  18190. ofs << content;
  18191. ASSERT_TRUE(ofs.good());
  18192. }
  18193. Server svr;
  18194. svr.set_mount_point("/static", ".");
  18195. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18196. svr.wait_until_ready();
  18197. Client cli(HOST, PORT);
  18198. // First request: get Last-Modified
  18199. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18200. ASSERT_TRUE(res1);
  18201. ASSERT_EQ(200, res1->status);
  18202. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18203. std::string last_modified = res1->get_header_value("Last-Modified");
  18204. // Range request with matching If-Range (date): should get 206
  18205. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18206. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18207. ASSERT_TRUE(res2);
  18208. EXPECT_EQ(206, res2->status);
  18209. EXPECT_EQ("FGHIJ", res2->body);
  18210. // Range request with old If-Range date: should get 200 (full content)
  18211. Headers h3 = {{"Range", "bytes=5-9"},
  18212. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18213. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18214. ASSERT_TRUE(res3);
  18215. EXPECT_EQ(200, res3->status);
  18216. EXPECT_EQ(content, res3->body);
  18217. // Range request with future If-Range date: should get 206
  18218. Headers h4 = {{"Range", "bytes=0-4"},
  18219. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18220. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18221. ASSERT_TRUE(res4);
  18222. EXPECT_EQ(206, res4->status);
  18223. EXPECT_EQ("ABCDE", res4->body);
  18224. svr.stop();
  18225. t.join();
  18226. std::remove(fname);
  18227. }
  18228. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18229. using namespace httplib;
  18230. const char *fname = "etag_malformed.txt";
  18231. const char *content = "malformed-etag";
  18232. {
  18233. std::ofstream ofs(fname);
  18234. ofs << content;
  18235. ASSERT_TRUE(ofs.good());
  18236. }
  18237. Server svr;
  18238. svr.set_mount_point("/static", ".");
  18239. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18240. svr.wait_until_ready();
  18241. Client cli(HOST, PORT);
  18242. // baseline: should get 200 and an ETag
  18243. auto res1 = cli.Get("/static/etag_malformed.txt");
  18244. ASSERT_TRUE(res1);
  18245. ASSERT_EQ(200, res1->status);
  18246. ASSERT_TRUE(res1->has_header("ETag"));
  18247. // Malformed ETag value (missing quotes) should be treated as non-matching
  18248. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18249. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18250. ASSERT_TRUE(res_bad);
  18251. EXPECT_EQ(200, res_bad->status);
  18252. // Whitespace-only header value should be considered invalid / non-matching
  18253. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18254. "Host: localhost\r\n"
  18255. "If-None-Match: \r\n"
  18256. "Connection: close\r\n"
  18257. "\r\n";
  18258. std::string out;
  18259. ASSERT_TRUE(send_request(5, raw_req, &out));
  18260. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18261. svr.stop();
  18262. t.join();
  18263. std::remove(fname);
  18264. }
  18265. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18266. using namespace httplib;
  18267. const char *fname = "ims_invalid_format.txt";
  18268. const char *content = "ims-bad-format";
  18269. {
  18270. std::ofstream ofs(fname);
  18271. ofs << content;
  18272. ASSERT_TRUE(ofs.good());
  18273. }
  18274. Server svr;
  18275. svr.set_mount_point("/static", ".");
  18276. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18277. svr.wait_until_ready();
  18278. Client cli(HOST, PORT);
  18279. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18280. ASSERT_TRUE(res1);
  18281. ASSERT_EQ(200, res1->status);
  18282. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18283. // If-Modified-Since with invalid format should not result in 304
  18284. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18285. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18286. ASSERT_TRUE(res_bad);
  18287. EXPECT_EQ(200, res_bad->status);
  18288. // If-Range with invalid date format should be treated as mismatch -> full
  18289. // content (200)
  18290. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18291. {"If-Range", "invalid-date"}};
  18292. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18293. ASSERT_TRUE(res_ifrange);
  18294. EXPECT_EQ(200, res_ifrange->status);
  18295. svr.stop();
  18296. t.join();
  18297. std::remove(fname);
  18298. }
  18299. TEST(ETagTest, IfRangeWithMalformedETag) {
  18300. using namespace httplib;
  18301. const char *fname = "ifrange_malformed.txt";
  18302. const std::string content = "0123456789";
  18303. {
  18304. std::ofstream ofs(fname);
  18305. ofs << content;
  18306. ASSERT_TRUE(ofs.good());
  18307. }
  18308. Server svr;
  18309. svr.set_mount_point("/static", ".");
  18310. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18311. svr.wait_until_ready();
  18312. Client cli(HOST, PORT);
  18313. // First request: get ETag
  18314. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18315. ASSERT_TRUE(res1);
  18316. ASSERT_EQ(200, res1->status);
  18317. ASSERT_TRUE(res1->has_header("ETag"));
  18318. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18319. // full content (200)
  18320. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18321. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18322. ASSERT_TRUE(res2);
  18323. EXPECT_EQ(200, res2->status);
  18324. EXPECT_EQ(content, res2->body);
  18325. svr.stop();
  18326. t.join();
  18327. std::remove(fname);
  18328. }
  18329. TEST(ETagTest, ExtremeLargeDateValues) {
  18330. using namespace httplib;
  18331. const char *fname = "ims_extreme_date.txt";
  18332. const char *content = "ims-extreme-date";
  18333. {
  18334. std::ofstream ofs(fname);
  18335. ofs << content;
  18336. ASSERT_TRUE(ofs.good());
  18337. }
  18338. Server svr;
  18339. svr.set_mount_point("/static", ".");
  18340. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18341. svr.wait_until_ready();
  18342. Client cli(HOST, PORT);
  18343. auto res1 = cli.Get(std::string("/static/") + fname);
  18344. ASSERT_TRUE(res1);
  18345. ASSERT_EQ(200, res1->status);
  18346. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18347. // Extremely large year that may overflow date parsing routines.
  18348. Headers h_large_date = {
  18349. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18350. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18351. ASSERT_TRUE(res_bad);
  18352. // Expect server to treat this as invalid/mismatch and return full content
  18353. EXPECT_EQ(200, res_bad->status);
  18354. // If-Range with extremely large date should be treated as mismatch -> full
  18355. // content (200)
  18356. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18357. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18358. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18359. ASSERT_TRUE(res_ifrange);
  18360. EXPECT_EQ(200, res_ifrange->status);
  18361. svr.stop();
  18362. t.join();
  18363. std::remove(fname);
  18364. }
  18365. TEST(ETagTest, NegativeFileModificationTime) {
  18366. using namespace httplib;
  18367. const char *fname = "ims_negative_mtime.txt";
  18368. const std::string content = "negative-mtime";
  18369. {
  18370. std::ofstream ofs(fname);
  18371. ofs << content;
  18372. ASSERT_TRUE(ofs.good());
  18373. }
  18374. // Try to set file mtime to a negative value. This may fail on some
  18375. // platforms/filesystems; if it fails, the test will still verify server
  18376. // behaves safely by performing a regular conditional request.
  18377. #if defined(__APPLE__) || defined(__linux__)
  18378. bool set_negative = false;
  18379. do {
  18380. struct timeval times[2];
  18381. // access time: now
  18382. times[0].tv_sec = time(nullptr);
  18383. times[0].tv_usec = 0;
  18384. // modification time: negative (e.g., -1)
  18385. times[1].tv_sec = -1;
  18386. times[1].tv_usec = 0;
  18387. if (utimes(fname, times) == 0) { set_negative = true; }
  18388. } while (0);
  18389. #else
  18390. bool set_negative = false;
  18391. #endif
  18392. Server svr;
  18393. svr.set_mount_point("/static", ".");
  18394. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18395. svr.wait_until_ready();
  18396. Client cli(HOST, PORT);
  18397. auto res1 = cli.Get(std::string("/static/") + fname);
  18398. ASSERT_TRUE(res1);
  18399. ASSERT_EQ(200, res1->status);
  18400. bool has_last_modified = res1->has_header("Last-Modified");
  18401. std::string last_modified;
  18402. if (has_last_modified) {
  18403. last_modified = res1->get_header_value("Last-Modified");
  18404. }
  18405. if (set_negative) {
  18406. // If we successfully set a negative mtime, ensure server returns a
  18407. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18408. // with an old date and ensure server handles it without crash.
  18409. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18410. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18411. ASSERT_TRUE(res2);
  18412. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18413. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18414. } else {
  18415. // Could not set negative mtime on this platform; fall back to verifying
  18416. // that normal invalid/malformed dates are treated safely (non-304).
  18417. Headers h_bad_date = {
  18418. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18419. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18420. ASSERT_TRUE(res_bad);
  18421. EXPECT_EQ(200, res_bad->status);
  18422. }
  18423. svr.stop();
  18424. t.join();
  18425. std::remove(fname);
  18426. }
  18427. //==============================================================================
  18428. // SSE Parsing Tests
  18429. //==============================================================================
  18430. class SSEParsingTest : public ::testing::Test {
  18431. protected:
  18432. // Test helper that mimics SSE parsing behavior
  18433. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  18434. int &retry_ms) {
  18435. // Blank line signals end of event
  18436. if (line.empty() || line == "\r") { return true; }
  18437. // Lines starting with ':' are comments (ignored)
  18438. if (!line.empty() && line[0] == ':') { return false; }
  18439. // Find the colon separator
  18440. auto colon_pos = line.find(':');
  18441. if (colon_pos == std::string::npos) {
  18442. // Line with no colon is treated as field name with empty value
  18443. return false;
  18444. }
  18445. std::string field = line.substr(0, colon_pos);
  18446. std::string value;
  18447. // Value starts after colon, skip optional single space
  18448. if (colon_pos + 1 < line.size()) {
  18449. size_t value_start = colon_pos + 1;
  18450. if (line[value_start] == ' ') { value_start++; }
  18451. value = line.substr(value_start);
  18452. // Remove trailing \r if present
  18453. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  18454. }
  18455. // Handle known fields
  18456. if (field == "event") {
  18457. msg.event = value;
  18458. } else if (field == "data") {
  18459. // Multiple data lines are concatenated with newlines
  18460. if (!msg.data.empty()) { msg.data += "\n"; }
  18461. msg.data += value;
  18462. } else if (field == "id") {
  18463. // Empty id is valid (clears the last event ID)
  18464. msg.id = value;
  18465. } else if (field == "retry") {
  18466. // Parse retry interval in milliseconds
  18467. {
  18468. int v = 0;
  18469. auto res =
  18470. detail::from_chars(value.data(), value.data() + value.size(), v);
  18471. if (res.ec == std::errc{}) { retry_ms = v; }
  18472. }
  18473. }
  18474. // Unknown fields are ignored per SSE spec
  18475. return false;
  18476. }
  18477. };
  18478. // Test: Single-line data
  18479. TEST_F(SSEParsingTest, SingleLineData) {
  18480. sse::SSEMessage msg;
  18481. int retry_ms = 3000;
  18482. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  18483. EXPECT_EQ(msg.data, "hello");
  18484. EXPECT_EQ(msg.event, "message");
  18485. // Blank line ends event
  18486. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18487. }
  18488. // Test: Multi-line data
  18489. TEST_F(SSEParsingTest, MultiLineData) {
  18490. sse::SSEMessage msg;
  18491. int retry_ms = 3000;
  18492. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  18493. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  18494. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  18495. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  18496. }
  18497. // Test: Custom event types
  18498. TEST_F(SSEParsingTest, CustomEventType) {
  18499. sse::SSEMessage msg;
  18500. int retry_ms = 3000;
  18501. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  18502. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  18503. EXPECT_EQ(msg.event, "update");
  18504. EXPECT_EQ(msg.data, "payload");
  18505. }
  18506. // Test: Event ID handling
  18507. TEST_F(SSEParsingTest, EventIdHandling) {
  18508. sse::SSEMessage msg;
  18509. int retry_ms = 3000;
  18510. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  18511. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  18512. EXPECT_EQ(msg.id, "12345");
  18513. }
  18514. // Test: Empty event ID (clears last event ID)
  18515. TEST_F(SSEParsingTest, EmptyEventId) {
  18516. sse::SSEMessage msg;
  18517. msg.id = "previous";
  18518. int retry_ms = 3000;
  18519. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  18520. EXPECT_EQ(msg.id, "");
  18521. }
  18522. // Test: Retry field parsing
  18523. TEST_F(SSEParsingTest, RetryFieldParsing) {
  18524. sse::SSEMessage msg;
  18525. int retry_ms = 3000;
  18526. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  18527. EXPECT_EQ(retry_ms, 5000);
  18528. }
  18529. // Test: Invalid retry value
  18530. TEST_F(SSEParsingTest, InvalidRetryValue) {
  18531. sse::SSEMessage msg;
  18532. int retry_ms = 3000;
  18533. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  18534. EXPECT_EQ(retry_ms, 3000); // Unchanged
  18535. }
  18536. // Test: Comments (lines starting with :)
  18537. TEST_F(SSEParsingTest, CommentsIgnored) {
  18538. sse::SSEMessage msg;
  18539. int retry_ms = 3000;
  18540. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  18541. EXPECT_EQ(msg.data, "");
  18542. EXPECT_EQ(msg.event, "message");
  18543. }
  18544. // Test: Colon in value
  18545. TEST_F(SSEParsingTest, ColonInValue) {
  18546. sse::SSEMessage msg;
  18547. int retry_ms = 3000;
  18548. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  18549. EXPECT_EQ(msg.data, "hello:world:test");
  18550. }
  18551. // Test: Line with no colon (field name only)
  18552. TEST_F(SSEParsingTest, FieldNameOnly) {
  18553. sse::SSEMessage msg;
  18554. int retry_ms = 3000;
  18555. // According to SSE spec, this is treated as field name with empty value
  18556. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  18557. // Since we don't recognize "data" without colon, data should be empty
  18558. EXPECT_EQ(msg.data, "");
  18559. }
  18560. // Test: Trailing \r handling
  18561. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18562. sse::SSEMessage msg;
  18563. int retry_ms = 3000;
  18564. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  18565. EXPECT_EQ(msg.data, "hello");
  18566. }
  18567. // Test: Unknown fields ignored
  18568. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18569. sse::SSEMessage msg;
  18570. int retry_ms = 3000;
  18571. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  18572. EXPECT_EQ(msg.data, "");
  18573. EXPECT_EQ(msg.event, "message");
  18574. }
  18575. // Test: Space after colon is optional
  18576. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18577. sse::SSEMessage msg1, msg2;
  18578. int retry_ms = 3000;
  18579. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  18580. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  18581. EXPECT_EQ(msg1.data, "hello");
  18582. EXPECT_EQ(msg2.data, "hello");
  18583. }
  18584. // Test: SSEMessage clear
  18585. TEST_F(SSEParsingTest, MessageClear) {
  18586. sse::SSEMessage msg;
  18587. msg.event = "custom";
  18588. msg.data = "some data";
  18589. msg.id = "123";
  18590. msg.clear();
  18591. EXPECT_EQ(msg.event, "message");
  18592. EXPECT_EQ(msg.data, "");
  18593. EXPECT_EQ(msg.id, "");
  18594. }
  18595. // Test: Complete event parsing
  18596. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18597. sse::SSEMessage msg;
  18598. int retry_ms = 3000;
  18599. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  18600. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  18601. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  18602. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  18603. // Blank line ends event
  18604. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18605. EXPECT_EQ(msg.event, "notification");
  18606. EXPECT_EQ(msg.id, "evt-42");
  18607. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  18608. EXPECT_EQ(retry_ms, 1000);
  18609. }
  18610. //==============================================================================
  18611. // Integration Tests with Server
  18612. //==============================================================================
  18613. class SSEIntegrationTest : public ::testing::Test {
  18614. protected:
  18615. void SetUp() override {
  18616. stop_server_.store(false);
  18617. events_.clear();
  18618. server_ = httplib::detail::make_unique<Server>();
  18619. setup_server();
  18620. start_server();
  18621. }
  18622. void TearDown() override {
  18623. stop_server_.store(true);
  18624. event_cv_.notify_all();
  18625. server_->stop();
  18626. if (server_thread_.joinable()) { server_thread_.join(); }
  18627. }
  18628. void setup_server() {
  18629. // Simple SSE endpoint
  18630. server_->Get("/events", [this](const Request &req, Response &res) {
  18631. auto last_id = req.get_header_value("Last-Event-ID");
  18632. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18633. res.set_chunked_content_provider(
  18634. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18635. std::unique_lock<std::mutex> lock(event_mutex_);
  18636. if (event_cv_.wait_for(
  18637. lock, std::chrono::milliseconds(200), [this] {
  18638. return !events_.empty() || stop_server_.load();
  18639. })) {
  18640. if (stop_server_.load()) { return false; }
  18641. if (!events_.empty()) {
  18642. std::string event = events_.front();
  18643. events_.erase(events_.begin());
  18644. sink.write(event.data(), event.size());
  18645. return true;
  18646. }
  18647. }
  18648. return !stop_server_.load();
  18649. });
  18650. });
  18651. // Endpoint that returns error
  18652. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18653. res.status = 500;
  18654. res.set_content("Internal Server Error", "text/plain");
  18655. });
  18656. // Endpoint for custom event types
  18657. server_->Get("/custom-events", [](const Request &, Response &res) {
  18658. res.set_chunked_content_provider(
  18659. "text/event-stream", [](size_t offset, DataSink &sink) {
  18660. if (offset == 0) {
  18661. std::string event = "event: update\ndata: updated\n\n"
  18662. "event: delete\ndata: deleted\n\n";
  18663. sink.write(event.data(), event.size());
  18664. }
  18665. return false; // End stream after sending
  18666. });
  18667. });
  18668. }
  18669. void start_server() {
  18670. port_ = server_->bind_to_any_port(HOST);
  18671. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18672. // Wait for server to start
  18673. while (!server_->is_running()) {
  18674. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18675. }
  18676. }
  18677. int get_port() const { return port_; }
  18678. void send_event(const std::string &event) {
  18679. std::lock_guard<std::mutex> lock(event_mutex_);
  18680. events_.push_back(event);
  18681. event_cv_.notify_all();
  18682. }
  18683. std::unique_ptr<Server> server_;
  18684. std::thread server_thread_;
  18685. std::mutex event_mutex_;
  18686. std::condition_variable event_cv_;
  18687. std::vector<std::string> events_;
  18688. std::atomic<bool> stop_server_{false};
  18689. std::string last_received_event_id_;
  18690. int port_ = 0;
  18691. };
  18692. // Test: Successful connection and on_open callback
  18693. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18694. // Add a simple endpoint that sends one event and closes
  18695. server_->Get("/simple-event", [](const Request &, Response &res) {
  18696. res.set_chunked_content_provider(
  18697. "text/event-stream", [](size_t offset, DataSink &sink) {
  18698. if (offset == 0) {
  18699. std::string event = "data: hello\n\n";
  18700. sink.write(event.data(), event.size());
  18701. }
  18702. return false; // Close stream after sending
  18703. });
  18704. });
  18705. Client client("localhost", get_port());
  18706. sse::SSEClient sse(client, "/simple-event");
  18707. std::atomic<bool> open_called{false};
  18708. std::atomic<bool> message_received{false};
  18709. sse.on_open([&open_called]() { open_called.store(true); });
  18710. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18711. if (msg.data == "hello") { message_received.store(true); }
  18712. });
  18713. sse.set_reconnect_interval(100);
  18714. sse.set_max_reconnect_attempts(1);
  18715. // Start async
  18716. sse.start_async();
  18717. // Wait for message to be processed
  18718. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18719. sse.stop();
  18720. EXPECT_TRUE(open_called.load());
  18721. EXPECT_TRUE(message_received.load());
  18722. }
  18723. // Test: on_message callback
  18724. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18725. // Endpoint that sends multiple events then closes
  18726. server_->Get("/multi-event", [](const Request &, Response &res) {
  18727. res.set_chunked_content_provider(
  18728. "text/event-stream", [](size_t offset, DataSink &sink) {
  18729. if (offset == 0) {
  18730. std::string events = "data: message1\n\ndata: message2\n\n";
  18731. sink.write(events.data(), events.size());
  18732. }
  18733. return false;
  18734. });
  18735. });
  18736. Client client("localhost", get_port());
  18737. sse::SSEClient sse(client, "/multi-event");
  18738. std::vector<std::string> received_messages;
  18739. std::mutex messages_mutex;
  18740. sse.on_message([&](const sse::SSEMessage &msg) {
  18741. std::lock_guard<std::mutex> lock(messages_mutex);
  18742. received_messages.push_back(msg.data);
  18743. });
  18744. sse.set_reconnect_interval(100);
  18745. sse.set_max_reconnect_attempts(1);
  18746. sse.start_async();
  18747. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18748. sse.stop();
  18749. std::lock_guard<std::mutex> lock(messages_mutex);
  18750. EXPECT_GE(received_messages.size(), 2u);
  18751. if (received_messages.size() >= 2) {
  18752. EXPECT_EQ(received_messages[0], "message1");
  18753. EXPECT_EQ(received_messages[1], "message2");
  18754. }
  18755. }
  18756. // Test: on_event for specific types
  18757. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18758. Client client("localhost", get_port());
  18759. sse::SSEClient sse(client, "/custom-events");
  18760. std::atomic<bool> update_received{false};
  18761. std::atomic<bool> delete_received{false};
  18762. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18763. if (msg.data == "updated") { update_received.store(true); }
  18764. });
  18765. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18766. if (msg.data == "deleted") { delete_received.store(true); }
  18767. });
  18768. sse.set_max_reconnect_attempts(1);
  18769. sse.start_async();
  18770. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18771. sse.stop();
  18772. EXPECT_TRUE(update_received.load());
  18773. EXPECT_TRUE(delete_received.load());
  18774. }
  18775. // Test: on_error callback on connection failure
  18776. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18777. // Connect to a non-existent port
  18778. Client client("localhost", 59999);
  18779. sse::SSEClient sse(client, "/events");
  18780. std::atomic<bool> error_called{false};
  18781. Error received_error = Error::Success;
  18782. sse.on_error([&](Error err) {
  18783. error_called.store(true);
  18784. received_error = err;
  18785. });
  18786. sse.set_reconnect_interval(50);
  18787. sse.set_max_reconnect_attempts(1);
  18788. sse.start_async();
  18789. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18790. sse.stop();
  18791. EXPECT_TRUE(error_called.load());
  18792. EXPECT_NE(received_error, Error::Success);
  18793. }
  18794. // Test: Last-Event-ID header sent on reconnect
  18795. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18796. // Endpoint that sends event with ID
  18797. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18798. res.set_chunked_content_provider(
  18799. "text/event-stream", [](size_t offset, DataSink &sink) {
  18800. if (offset == 0) {
  18801. std::string event = "id: evt-123\ndata: test\n\n";
  18802. sink.write(event.data(), event.size());
  18803. }
  18804. return false;
  18805. });
  18806. });
  18807. Client client("localhost", get_port());
  18808. sse::SSEClient sse(client, "/event-with-id");
  18809. std::atomic<bool> id_received{false};
  18810. sse.on_message([&](const sse::SSEMessage &msg) {
  18811. if (!msg.id.empty()) { id_received.store(true); }
  18812. });
  18813. sse.set_reconnect_interval(100);
  18814. sse.set_max_reconnect_attempts(1);
  18815. sse.start_async();
  18816. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18817. sse.stop();
  18818. EXPECT_TRUE(id_received.load());
  18819. EXPECT_EQ(sse.last_event_id(), "evt-123");
  18820. }
  18821. // Test: Manual stop
  18822. TEST_F(SSEIntegrationTest, ManualStop) {
  18823. // Endpoint that sends one event and stays open briefly
  18824. std::atomic<bool> handler_running{true};
  18825. server_->Get("/stay-open", [&handler_running](const Request &,
  18826. Response &res) {
  18827. res.set_chunked_content_provider(
  18828. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  18829. if (offset == 0) {
  18830. std::string event = "data: connected\n\n";
  18831. sink.write(event.data(), event.size());
  18832. }
  18833. // Keep connection open while handler_running is true
  18834. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18835. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18836. }
  18837. return false;
  18838. });
  18839. });
  18840. Client client("localhost", get_port());
  18841. sse::SSEClient sse(client, "/stay-open");
  18842. std::atomic<bool> connected{false};
  18843. sse.on_open([&connected]() { connected.store(true); });
  18844. sse.set_reconnect_interval(100);
  18845. sse.set_max_reconnect_attempts(1);
  18846. sse.start_async();
  18847. // Wait for connection to establish
  18848. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18849. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18850. }
  18851. EXPECT_TRUE(connected.load());
  18852. EXPECT_TRUE(sse.is_connected());
  18853. // Signal handler to stop
  18854. handler_running.store(false);
  18855. // Stop SSE client
  18856. sse.stop();
  18857. EXPECT_FALSE(sse.is_connected());
  18858. }
  18859. // Test: SSEClient with custom headers
  18860. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18861. // Setup a server endpoint that checks for custom header
  18862. std::atomic<bool> header_received{false};
  18863. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18864. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18865. header_received.store(true);
  18866. }
  18867. res.set_chunked_content_provider("text/event-stream",
  18868. [](size_t, DataSink &) { return false; });
  18869. });
  18870. Client client("localhost", get_port());
  18871. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18872. sse::SSEClient sse(client, "/header-check", headers);
  18873. sse.set_max_reconnect_attempts(1);
  18874. sse.start_async();
  18875. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18876. sse.stop();
  18877. EXPECT_TRUE(header_received.load());
  18878. }
  18879. // Test: Reconnect interval configuration
  18880. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18881. Client client("localhost", get_port());
  18882. sse::SSEClient sse(client, "/events");
  18883. auto &result = sse.set_reconnect_interval(500);
  18884. // Builder pattern should return reference to self
  18885. EXPECT_EQ(&result, &sse);
  18886. }
  18887. // Test: Max reconnect attempts
  18888. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18889. // Connect to non-existent port to force reconnects
  18890. Client client("localhost", 59998);
  18891. sse::SSEClient sse(client, "/events");
  18892. std::atomic<int> error_count{0};
  18893. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18894. sse.set_reconnect_interval(50);
  18895. sse.set_max_reconnect_attempts(2);
  18896. auto start = std::chrono::steady_clock::now();
  18897. sse.start(); // Blocking call
  18898. auto end = std::chrono::steady_clock::now();
  18899. // Should have stopped after 2 failed attempts
  18900. EXPECT_GE(error_count.load(), 2);
  18901. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18902. auto duration =
  18903. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18904. #ifdef _WIN32
  18905. // Windows is much slower for socket connection failures
  18906. EXPECT_LT(duration.count(), 7000);
  18907. #else
  18908. EXPECT_LT(duration.count(), 1000);
  18909. #endif
  18910. }
  18911. // Test: Multi-line data in integration
  18912. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18913. // Endpoint with multi-line data
  18914. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18915. res.set_chunked_content_provider(
  18916. "text/event-stream", [](size_t offset, DataSink &sink) {
  18917. if (offset == 0) {
  18918. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18919. sink.write(event.data(), event.size());
  18920. }
  18921. return false;
  18922. });
  18923. });
  18924. Client client("localhost", get_port());
  18925. sse::SSEClient sse(client, "/multiline-data");
  18926. std::string received_data;
  18927. std::mutex data_mutex;
  18928. sse.on_message([&](const sse::SSEMessage &msg) {
  18929. std::lock_guard<std::mutex> lock(data_mutex);
  18930. received_data = msg.data;
  18931. });
  18932. sse.set_reconnect_interval(100);
  18933. sse.set_max_reconnect_attempts(1);
  18934. sse.start_async();
  18935. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18936. sse.stop();
  18937. std::lock_guard<std::mutex> lock(data_mutex);
  18938. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18939. }
  18940. // Test: Auto-reconnect after server disconnection
  18941. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18942. std::atomic<int> connection_count{0};
  18943. std::atomic<int> message_count{0};
  18944. // Endpoint that sends one event and closes, forcing reconnect
  18945. server_->Get("/reconnect-test",
  18946. [&connection_count](const Request &, Response &res) {
  18947. connection_count.fetch_add(1);
  18948. res.set_chunked_content_provider(
  18949. "text/event-stream", [](size_t offset, DataSink &sink) {
  18950. if (offset == 0) {
  18951. std::string event = "data: hello\n\n";
  18952. sink.write(event.data(), event.size());
  18953. }
  18954. return false; // Close connection after sending
  18955. });
  18956. });
  18957. Client client("localhost", get_port());
  18958. sse::SSEClient sse(client, "/reconnect-test");
  18959. sse.on_message([&message_count](const sse::SSEMessage &) {
  18960. message_count.fetch_add(1);
  18961. });
  18962. sse.set_reconnect_interval(100);
  18963. sse.set_max_reconnect_attempts(3);
  18964. sse.start_async();
  18965. // Wait long enough for multiple reconnects
  18966. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18967. sse.stop();
  18968. // Should have connected multiple times (initial + reconnects)
  18969. EXPECT_GE(connection_count.load(), 2);
  18970. // Should have received messages from multiple connections
  18971. EXPECT_GE(message_count.load(), 2);
  18972. }
  18973. // Test: A retry field that is not all ASCII digits is ignored
  18974. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  18975. std::atomic<int> connection_count{0};
  18976. server_->Get("/bad-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: -1\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, "/bad-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. EXPECT_EQ(connection_count.load(), 1);
  18995. }
  18996. // Test: A retry field of all ASCII digits sets the reconnection time
  18997. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  18998. std::atomic<int> connection_count{0};
  18999. server_->Get("/zero-retry",
  19000. [&connection_count](const Request &, Response &res) {
  19001. connection_count.fetch_add(1);
  19002. res.set_chunked_content_provider(
  19003. "text/event-stream", [](size_t offset, DataSink &sink) {
  19004. if (offset == 0) {
  19005. std::string event = "retry: 0\ndata: hello\n\n";
  19006. sink.write(event.data(), event.size());
  19007. }
  19008. return false;
  19009. });
  19010. });
  19011. Client client("localhost", get_port());
  19012. sse::SSEClient sse(client, "/zero-retry");
  19013. sse.set_reconnect_interval(10000);
  19014. sse.start_async();
  19015. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19016. sse.stop();
  19017. // The server-supplied interval is applied, but never below 100ms, so
  19018. // "retry: 0" does not cause a busy reconnect loop
  19019. EXPECT_GE(connection_count.load(), 2);
  19020. EXPECT_LE(connection_count.load(), 10);
  19021. }
  19022. // Test: Last-Event-ID sent on reconnect
  19023. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19024. std::atomic<int> connection_count{0};
  19025. std::vector<std::string> received_last_event_ids;
  19026. std::mutex id_mutex;
  19027. // Endpoint that checks Last-Event-ID header and sends event with ID
  19028. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19029. int conn = connection_count.fetch_add(1);
  19030. // Capture the Last-Event-ID header from each connection
  19031. {
  19032. std::lock_guard<std::mutex> lock(id_mutex);
  19033. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19034. }
  19035. res.set_chunked_content_provider(
  19036. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19037. if (offset == 0) {
  19038. std::string event =
  19039. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19040. sink.write(event.data(), event.size());
  19041. }
  19042. return false;
  19043. });
  19044. });
  19045. Client client("localhost", get_port());
  19046. sse::SSEClient sse(client, "/reconnect-with-id");
  19047. sse.set_reconnect_interval(100);
  19048. sse.set_max_reconnect_attempts(3);
  19049. sse.start_async();
  19050. // Wait for at least 2 connections
  19051. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19052. sse.stop();
  19053. // Verify behavior
  19054. std::lock_guard<std::mutex> lock(id_mutex);
  19055. EXPECT_GE(received_last_event_ids.size(), 2u);
  19056. // First connection should have no Last-Event-ID
  19057. if (!received_last_event_ids.empty()) {
  19058. EXPECT_EQ(received_last_event_ids[0], "");
  19059. }
  19060. // Second connection should have Last-Event-ID from first connection
  19061. if (received_last_event_ids.size() >= 2) {
  19062. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19063. }
  19064. }
  19065. // Test: set_headers updates headers used on reconnect
  19066. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19067. std::vector<std::string> received_tokens;
  19068. std::mutex token_mutex;
  19069. // Endpoint that captures Authorization header
  19070. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19071. {
  19072. std::lock_guard<std::mutex> lock(token_mutex);
  19073. received_tokens.push_back(req.get_header_value("Authorization"));
  19074. }
  19075. res.set_chunked_content_provider(
  19076. "text/event-stream", [](size_t offset, DataSink &sink) {
  19077. if (offset == 0) {
  19078. std::string event = "data: hello\n\n";
  19079. sink.write(event.data(), event.size());
  19080. }
  19081. return false; // Close connection to trigger reconnect
  19082. });
  19083. });
  19084. Client client("localhost", get_port());
  19085. Headers headers = {{"Authorization", "Bearer old-token"}};
  19086. sse::SSEClient sse(client, "/auth-check", headers);
  19087. // Update headers on each successful connection
  19088. sse.on_open(
  19089. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19090. sse.set_reconnect_interval(100);
  19091. sse.set_max_reconnect_attempts(3);
  19092. sse.start_async();
  19093. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19094. sse.stop();
  19095. std::lock_guard<std::mutex> lock(token_mutex);
  19096. ASSERT_GE(received_tokens.size(), 2u);
  19097. // First connection uses original header
  19098. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19099. // Second connection uses updated header from set_headers
  19100. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19101. }
  19102. // Test: 401 allows reconnection (so on_error can refresh headers)
  19103. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19104. std::atomic<int> connection_count{0};
  19105. // Endpoint: returns 401 on first attempt, 200 on second
  19106. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19107. int conn = connection_count.fetch_add(1);
  19108. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19109. res.status = StatusCode::Unauthorized_401;
  19110. res.set_content("Unauthorized", "text/plain");
  19111. return;
  19112. }
  19113. res.set_chunked_content_provider(
  19114. "text/event-stream", [](size_t offset, DataSink &sink) {
  19115. if (offset == 0) {
  19116. std::string event = "data: authenticated\n\n";
  19117. sink.write(event.data(), event.size());
  19118. }
  19119. return false;
  19120. });
  19121. });
  19122. Client client("localhost", get_port());
  19123. Headers headers = {{"Authorization", "Bearer expired"}};
  19124. sse::SSEClient sse(client, "/auth-retry", headers);
  19125. std::atomic<bool> message_received{false};
  19126. // Refresh token on error
  19127. sse.on_error(
  19128. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19129. sse.on_message([&](const sse::SSEMessage &msg) {
  19130. if (msg.data == "authenticated") { message_received.store(true); }
  19131. });
  19132. sse.set_reconnect_interval(100);
  19133. sse.set_max_reconnect_attempts(3);
  19134. sse.start_async();
  19135. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19136. sse.stop();
  19137. // Should have reconnected after 401 and succeeded with new token
  19138. EXPECT_GE(connection_count.load(), 2);
  19139. EXPECT_TRUE(message_received.load());
  19140. }
  19141. TEST(Issue2318Test, EmptyHostString) {
  19142. {
  19143. httplib::Client cli_empty("", PORT);
  19144. auto res = cli_empty.Get("/");
  19145. ASSERT_FALSE(res);
  19146. EXPECT_EQ(httplib::Error::Connection, res.error());
  19147. }
  19148. {
  19149. httplib::Client cli(" ", PORT);
  19150. auto res = cli.Get("/");
  19151. ASSERT_FALSE(res);
  19152. EXPECT_EQ(httplib::Error::Connection, res.error());
  19153. }
  19154. }
  19155. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19156. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19157. Server svr;
  19158. // Set a small payload limit (1KB)
  19159. svr.set_payload_max_length(1024);
  19160. svr.Post("/test", [&](const Request &req, Response &res) {
  19161. res.set_content("Body size: " + std::to_string(req.body.size()),
  19162. "text/plain");
  19163. });
  19164. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19165. auto se = detail::scope_exit([&] {
  19166. svr.stop();
  19167. listen_thread.join();
  19168. });
  19169. svr.wait_until_ready();
  19170. // Create data that compresses well but exceeds limit when decompressed
  19171. // 8KB of repeated null bytes compresses to a very small size
  19172. std::string original_data(8 * 1024, '\0');
  19173. // Compress the data using gzip
  19174. std::string compressed_data;
  19175. detail::gzip_compressor compressor;
  19176. compressor.compress(original_data.data(), original_data.size(), true,
  19177. [&](const char *data, size_t size) {
  19178. compressed_data.append(data, size);
  19179. return true;
  19180. });
  19181. // Verify compression worked (compressed should be much smaller)
  19182. ASSERT_LT(compressed_data.size(), original_data.size());
  19183. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19184. // Send compressed data with Content-Encoding: gzip
  19185. Client cli(HOST, PORT);
  19186. Headers headers = {{"Content-Encoding", "gzip"}};
  19187. auto res =
  19188. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19189. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19191. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19192. }
  19193. #endif
  19194. // ============================================================================
  19195. // OpenSSL-Specific Tests
  19196. // ============================================================================
  19197. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19198. X509 *readCertificate(const std::string &strFileName) {
  19199. std::ifstream inStream(strFileName);
  19200. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19201. std::istreambuf_iterator<char>());
  19202. if (strCertPEM.empty()) return (nullptr);
  19203. BIO *pbCert = BIO_new(BIO_s_mem());
  19204. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19205. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19206. BIO_free(pbCert);
  19207. return (pCert);
  19208. }
  19209. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19210. std::ifstream inStream(strFileName);
  19211. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19212. std::istreambuf_iterator<char>());
  19213. if (strPrivateKeyPEM.empty()) return (nullptr);
  19214. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19215. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19216. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19217. BIO_free(pbPrivKey);
  19218. return (pPrivateKey);
  19219. }
  19220. TEST(BindServerTest, UpdateCerts) {
  19221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19222. int port = svr.bind_to_any_port("0.0.0.0");
  19223. ASSERT_TRUE(svr.is_valid());
  19224. ASSERT_TRUE(port > 0);
  19225. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19226. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19227. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19228. ASSERT_TRUE(cert != nullptr);
  19229. ASSERT_TRUE(ca_cert != nullptr);
  19230. ASSERT_TRUE(key != nullptr);
  19231. X509_STORE *cert_store = X509_STORE_new();
  19232. X509_STORE_add_cert(cert_store, ca_cert);
  19233. // svr.update_certs(cert, key, cert_store); // deprecated
  19234. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19235. CLIENT_CA_CERT_FILE);
  19236. ASSERT_TRUE(svr.is_valid());
  19237. svr.stop();
  19238. X509_STORE_free(cert_store);
  19239. X509_free(cert);
  19240. X509_free(ca_cert);
  19241. EVP_PKEY_free(key);
  19242. }
  19243. // Test that update_certs() updates client CA list correctly
  19244. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19245. // Start with file-based constructor
  19246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19247. ASSERT_TRUE(svr.is_valid());
  19248. // Initially no client CA list should be set
  19249. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19250. ASSERT_TRUE(ssl_ctx != nullptr);
  19251. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19252. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19253. EXPECT_EQ(0, count_before);
  19254. // Now update with client CA (PEM string)
  19255. std::string cert_pem, key_pem, ca_pem;
  19256. read_file(SERVER_CERT_FILE, cert_pem);
  19257. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19258. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19259. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19260. ASSERT_TRUE(svr.is_valid());
  19261. // Now client CA list should be set
  19262. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19263. ASSERT_TRUE(ca_list_after != nullptr);
  19264. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19265. }
  19266. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19267. // Test that the file-path SSLServer constructor properly sets the client CA
  19268. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19269. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19270. ASSERT_TRUE(svr.is_valid());
  19271. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19272. ASSERT_TRUE(ssl_ctx != nullptr);
  19273. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19274. ASSERT_TRUE(ca_list != nullptr);
  19275. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19276. }
  19277. #endif
  19278. // ============================================================================
  19279. // MbedTLS-Specific Tests
  19280. // ============================================================================
  19281. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19282. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19283. using namespace httplib::tls;
  19284. // Track if callback was invoked
  19285. bool callback_invoked = false;
  19286. // The callback receives void* ctx which is actually MbedTlsContext*
  19287. // We can access the mbedtls_ssl_config via the context
  19288. auto setup_callback = [&callback_invoked](void *ctx) {
  19289. callback_invoked = true;
  19290. // Cast to MbedTlsContext* to access the ssl config
  19291. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19292. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19293. // Use static variables to hold certificate data (simplified for test)
  19294. static mbedtls_x509_crt own_cert;
  19295. static mbedtls_pk_context own_key;
  19296. static mbedtls_x509_crt ca_chain;
  19297. static bool initialized = false;
  19298. if (!initialized) {
  19299. mbedtls_x509_crt_init(&own_cert);
  19300. mbedtls_pk_init(&own_key);
  19301. mbedtls_x509_crt_init(&ca_chain);
  19302. // Load server certificate
  19303. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19304. return false;
  19305. }
  19306. // Load server private key.
  19307. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19308. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19309. #if MBEDTLS_VERSION_MAJOR == 3
  19310. ,
  19311. mbedtls_ctr_drbg_random, nullptr
  19312. #endif
  19313. ) != 0) {
  19314. return false;
  19315. }
  19316. // Load CA chain for client verification
  19317. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19318. return false;
  19319. }
  19320. initialized = true;
  19321. }
  19322. // Configure the SSL config
  19323. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19324. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19325. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19326. // Set minimum TLS version using mbedTLS native API
  19327. #if MBEDTLS_VERSION_MAJOR >= 3
  19328. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19329. #else
  19330. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19331. MBEDTLS_SSL_MINOR_VERSION_3);
  19332. #endif
  19333. return true;
  19334. };
  19335. SSLServer svr(setup_callback);
  19336. ASSERT_TRUE(svr.is_valid());
  19337. ASSERT_TRUE(callback_invoked);
  19338. svr.Get("/test", [&](const Request &req, Response &res) {
  19339. res.set_content("test", "text/plain");
  19340. auto cert = req.peer_cert();
  19341. ASSERT_TRUE(static_cast<bool>(cert));
  19342. auto common_name = cert.subject_cn();
  19343. EXPECT_EQ("Common Name", common_name);
  19344. });
  19345. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19346. auto se = detail::scope_exit([&] {
  19347. svr.stop();
  19348. t.join();
  19349. ASSERT_FALSE(svr.is_running());
  19350. });
  19351. svr.wait_until_ready();
  19352. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19353. cli.enable_server_certificate_verification(false);
  19354. cli.set_connection_timeout(30);
  19355. auto res = cli.Get("/test");
  19356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19357. ASSERT_EQ(StatusCode::OK_200, res->status);
  19358. }
  19359. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19360. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19361. // keep-alive SSL session, which reads through that config in
  19362. // mbedtls_ssl_close_notify.
  19363. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19365. ASSERT_TRUE(svr.is_valid());
  19366. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19367. res.set_content("test", "text/plain");
  19368. });
  19369. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19370. auto se = detail::scope_exit([&] {
  19371. svr.stop();
  19372. t.join();
  19373. ASSERT_FALSE(svr.is_running());
  19374. });
  19375. svr.wait_until_ready();
  19376. {
  19377. SSLClient cli(HOST, PORT);
  19378. cli.enable_server_certificate_verification(false);
  19379. cli.set_keep_alive(true);
  19380. auto res = cli.Get("/test");
  19381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19382. ASSERT_EQ(StatusCode::OK_200, res->status);
  19383. // cli is destructed here with the keep-alive SSL session still open.
  19384. }
  19385. }
  19386. #endif
  19387. // WebSocket Tests
  19388. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19389. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19390. // defining the meaning of these bits has been negotiated.
  19391. auto make_frame = [](uint8_t first_byte) {
  19392. std::string frame;
  19393. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19394. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19395. frame += "Hello";
  19396. return frame;
  19397. };
  19398. // RSV1 set (0x40)
  19399. {
  19400. detail::BufferStream strm;
  19401. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19402. ws::Opcode opcode;
  19403. std::string payload;
  19404. bool fin;
  19405. EXPECT_EQ(
  19406. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19407. ws::impl::FrameRead::Fail);
  19408. }
  19409. // RSV2 set (0x20)
  19410. {
  19411. detail::BufferStream strm;
  19412. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19413. ws::Opcode opcode;
  19414. std::string payload;
  19415. bool fin;
  19416. EXPECT_EQ(
  19417. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19418. ws::impl::FrameRead::Fail);
  19419. }
  19420. // RSV3 set (0x10)
  19421. {
  19422. detail::BufferStream strm;
  19423. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19424. ws::Opcode opcode;
  19425. std::string payload;
  19426. bool fin;
  19427. EXPECT_EQ(
  19428. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19429. ws::impl::FrameRead::Fail);
  19430. }
  19431. // No RSV bits set - should succeed
  19432. {
  19433. detail::BufferStream strm;
  19434. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19435. ws::Opcode opcode;
  19436. std::string payload;
  19437. bool fin;
  19438. EXPECT_EQ(
  19439. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19440. ws::impl::FrameRead::Ok);
  19441. EXPECT_EQ(ws::Opcode::Text, opcode);
  19442. EXPECT_EQ("Hello", payload);
  19443. EXPECT_TRUE(fin);
  19444. }
  19445. }
  19446. TEST(WebSocketTest, ControlFrameValidation) {
  19447. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19448. // payload length <= 125.
  19449. // Ping with FIN=0 - must be rejected
  19450. {
  19451. detail::BufferStream strm;
  19452. std::string frame;
  19453. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19454. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19455. strm.write(frame.data(), frame.size());
  19456. ws::Opcode opcode;
  19457. std::string payload;
  19458. bool fin;
  19459. EXPECT_EQ(
  19460. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19461. ws::impl::FrameRead::Fail);
  19462. }
  19463. // Close with FIN=0 - must be rejected
  19464. {
  19465. detail::BufferStream strm;
  19466. std::string frame;
  19467. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19468. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19469. strm.write(frame.data(), frame.size());
  19470. ws::Opcode opcode;
  19471. std::string payload;
  19472. bool fin;
  19473. EXPECT_EQ(
  19474. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19475. ws::impl::FrameRead::Fail);
  19476. }
  19477. // Ping with payload_len=126 (extended length) - must be rejected
  19478. {
  19479. detail::BufferStream strm;
  19480. std::string frame;
  19481. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19482. frame += static_cast<char>(126); // payload_len=126 (>125)
  19483. frame += static_cast<char>(0x00); // extended length high byte
  19484. frame += static_cast<char>(126); // extended length low byte
  19485. frame += std::string(126, 'x');
  19486. strm.write(frame.data(), frame.size());
  19487. ws::Opcode opcode;
  19488. std::string payload;
  19489. bool fin;
  19490. EXPECT_EQ(
  19491. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19492. ws::impl::FrameRead::Fail);
  19493. }
  19494. // Ping with FIN=1 and payload_len=125 - should succeed
  19495. {
  19496. detail::BufferStream strm;
  19497. std::string frame;
  19498. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19499. frame += static_cast<char>(125); // payload_len=125
  19500. frame += std::string(125, 'x');
  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::Ok);
  19508. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19509. EXPECT_EQ(125u, payload.size());
  19510. EXPECT_TRUE(fin);
  19511. }
  19512. }
  19513. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19514. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19515. // length MUST be 0.
  19516. // MSB set - must be rejected
  19517. {
  19518. detail::BufferStream strm;
  19519. std::string frame;
  19520. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19521. frame += static_cast<char>(127); // 64-bit extended length
  19522. frame += static_cast<char>(0x80); // MSB set (invalid)
  19523. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19524. strm.write(frame.data(), frame.size());
  19525. ws::Opcode opcode;
  19526. std::string payload;
  19527. bool fin;
  19528. EXPECT_EQ(
  19529. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19530. ws::impl::FrameRead::Fail);
  19531. }
  19532. // MSB clear - should pass length parsing (will be rejected by max_len,
  19533. // but that's a different check; use a small length to verify)
  19534. {
  19535. detail::BufferStream strm;
  19536. std::string frame;
  19537. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19538. frame += static_cast<char>(127); // 64-bit extended length
  19539. frame += std::string(7, '\0'); // high bytes = 0
  19540. frame += static_cast<char>(0x03); // length = 3
  19541. frame += "abc";
  19542. strm.write(frame.data(), frame.size());
  19543. ws::Opcode opcode;
  19544. std::string payload;
  19545. bool fin;
  19546. EXPECT_EQ(
  19547. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19548. ws::impl::FrameRead::Ok);
  19549. EXPECT_EQ(ws::Opcode::Text, opcode);
  19550. EXPECT_EQ("abc", payload);
  19551. }
  19552. }
  19553. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19554. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19555. // Valid UTF-8
  19556. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19557. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19558. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19559. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19560. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19561. // Invalid UTF-8
  19562. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19563. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19564. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19565. EXPECT_FALSE(
  19566. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19567. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19568. }
  19569. TEST(WebSocketTest, ConnectAndDisconnect) {
  19570. Server svr;
  19571. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19572. std::string msg;
  19573. while (ws.read(msg)) {}
  19574. });
  19575. auto port = svr.bind_to_any_port(HOST);
  19576. std::thread t([&]() { svr.listen_after_bind(); });
  19577. svr.wait_until_ready();
  19578. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19579. auto res = client.connect();
  19580. ASSERT_TRUE(res);
  19581. EXPECT_EQ(Error::Success, res.error());
  19582. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19583. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19584. EXPECT_TRUE(client.is_open());
  19585. client.close();
  19586. EXPECT_FALSE(client.is_open());
  19587. svr.stop();
  19588. t.join();
  19589. }
  19590. TEST(WebSocketTest, ValidURL) {
  19591. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19592. EXPECT_TRUE(ws1.is_valid());
  19593. ws::WebSocketClient ws2("ws://example.com/path");
  19594. EXPECT_TRUE(ws2.is_valid());
  19595. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19596. EXPECT_TRUE(ws3.is_valid());
  19597. #ifdef CPPHTTPLIB_SSL_ENABLED
  19598. ws::WebSocketClient wss1("wss://example.com/path");
  19599. EXPECT_TRUE(wss1.is_valid());
  19600. ws::WebSocketClient wss2("wss://example.com:443/path");
  19601. EXPECT_TRUE(wss2.is_valid());
  19602. #endif
  19603. }
  19604. TEST(WebSocketTest, InvalidURL) {
  19605. // No scheme
  19606. ws::WebSocketClient ws1("localhost:8080/path");
  19607. EXPECT_FALSE(ws1.is_valid());
  19608. // No path
  19609. ws::WebSocketClient ws2("ws://localhost:8080");
  19610. EXPECT_FALSE(ws2.is_valid());
  19611. // Empty string
  19612. ws::WebSocketClient ws3("");
  19613. EXPECT_FALSE(ws3.is_valid());
  19614. // Missing host
  19615. ws::WebSocketClient ws4("ws://:8080/path");
  19616. EXPECT_FALSE(ws4.is_valid());
  19617. // Port number overflow — should not crash
  19618. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19619. EXPECT_FALSE(ws5.is_valid());
  19620. // Port out of range
  19621. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19622. EXPECT_FALSE(ws6.is_valid());
  19623. }
  19624. TEST(WebSocketTest, UnsupportedScheme) {
  19625. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19626. ws::WebSocketClient ws1("http://localhost:8080/path");
  19627. EXPECT_FALSE(ws1.is_valid());
  19628. ws::WebSocketClient ws2("https://localhost:8080/path");
  19629. EXPECT_FALSE(ws2.is_valid());
  19630. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19631. EXPECT_FALSE(ws3.is_valid());
  19632. #else
  19633. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19634. std::invalid_argument);
  19635. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19636. std::invalid_argument);
  19637. #endif
  19638. }
  19639. TEST(WebSocketTest, ConnectWhenInvalid) {
  19640. ws::WebSocketClient ws("not a valid url");
  19641. EXPECT_FALSE(ws.is_valid());
  19642. auto res = ws.connect();
  19643. EXPECT_FALSE(res);
  19644. EXPECT_EQ(Error::Connection, res.error());
  19645. EXPECT_EQ(-1, res.status());
  19646. }
  19647. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19648. // Grab a port that is free, then close it again so nothing listens there
  19649. Server svr;
  19650. auto port = svr.bind_to_any_port(HOST);
  19651. svr.stop();
  19652. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19653. auto res = client.connect();
  19654. ASSERT_FALSE(res);
  19655. EXPECT_EQ(Error::Connection, res.error());
  19656. EXPECT_EQ(-1, res.status());
  19657. }
  19658. TEST(WebSocketTest, DefaultPort) {
  19659. ws::WebSocketClient ws1("ws://example.com/path");
  19660. EXPECT_TRUE(ws1.is_valid());
  19661. // ws:// defaults to port 80 (verified by successful parse)
  19662. #ifdef CPPHTTPLIB_SSL_ENABLED
  19663. ws::WebSocketClient ws2("wss://example.com/path");
  19664. EXPECT_TRUE(ws2.is_valid());
  19665. // wss:// defaults to port 443 (verified by successful parse)
  19666. #endif
  19667. }
  19668. TEST(WebSocketTest, IPv6LiteralAddress) {
  19669. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19670. EXPECT_TRUE(ws1.is_valid());
  19671. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  19672. EXPECT_TRUE(ws2.is_valid());
  19673. }
  19674. TEST(WebSocketTest, ComplexPath) {
  19675. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  19676. EXPECT_TRUE(ws1.is_valid());
  19677. ws::WebSocketClient ws2("ws://localhost:8080/");
  19678. EXPECT_TRUE(ws2.is_valid());
  19679. }
  19680. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  19681. Server svr;
  19682. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19683. std::string msg;
  19684. while (ws.read(msg)) {}
  19685. });
  19686. auto port = svr.bind_to_any_port(HOST);
  19687. std::thread t([&]() { svr.listen_after_bind(); });
  19688. svr.wait_until_ready();
  19689. auto another_host = "example.com";
  19690. auto wrong_ip = "192.0.2.1";
  19691. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19692. client.set_hostname_addr_map({{another_host, wrong_ip}});
  19693. ASSERT_TRUE(client.connect());
  19694. EXPECT_TRUE(client.is_open());
  19695. client.close();
  19696. svr.stop();
  19697. t.join();
  19698. }
  19699. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  19700. Server svr;
  19701. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19702. std::string msg;
  19703. while (ws.read(msg)) {}
  19704. });
  19705. auto port = svr.bind_to_any_port(HOST);
  19706. std::thread t([&]() { svr.listen_after_bind(); });
  19707. svr.wait_until_ready();
  19708. auto wrong_ip = "192.0.2.1";
  19709. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19710. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  19711. client.set_connection_timeout(1);
  19712. client.set_read_timeout(1);
  19713. client.set_write_timeout(1);
  19714. EXPECT_FALSE(client.connect());
  19715. EXPECT_FALSE(client.is_open());
  19716. svr.stop();
  19717. t.join();
  19718. }
  19719. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  19720. // A mapped value that is not an IP literal must be resolved. HOST resolves
  19721. // from the hosts file, so this test needs no external DNS. "target.invalid"
  19722. // (RFC 6761) is only a map key and the Host header value.
  19723. auto host = "target.invalid";
  19724. Server svr;
  19725. std::string received_host;
  19726. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19727. received_host = req.get_header_value("Host");
  19728. std::string msg;
  19729. while (ws.read(msg)) {}
  19730. });
  19731. auto port = svr.bind_to_any_port(HOST);
  19732. std::thread t([&]() { svr.listen_after_bind(); });
  19733. // ASSERT_* below returns from the test body, which would leave t joinable
  19734. // and make ~thread call std::terminate.
  19735. auto se = detail::scope_exit([&] {
  19736. svr.stop();
  19737. if (t.joinable()) { t.join(); }
  19738. });
  19739. svr.wait_until_ready();
  19740. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  19741. std::to_string(port) + "/ws");
  19742. client.set_hostname_addr_map({{host, HOST}});
  19743. ASSERT_TRUE(client.connect());
  19744. EXPECT_TRUE(client.is_open());
  19745. client.close();
  19746. svr.stop();
  19747. t.join();
  19748. // The mapping only redirects the connection; the identity stays host_.
  19749. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  19750. }
  19751. class WebSocketIntegrationTest : public ::testing::Test {
  19752. protected:
  19753. void SetUp() override {
  19754. server_ = httplib::detail::make_unique<Server>();
  19755. setup_server();
  19756. start_server();
  19757. }
  19758. void TearDown() override {
  19759. server_->stop();
  19760. if (server_thread_.joinable()) { server_thread_.join(); }
  19761. }
  19762. void setup_server() {
  19763. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19764. std::string msg;
  19765. ws::ReadResult ret;
  19766. while ((ret = ws.read(msg))) {
  19767. if (ret == ws::Binary) {
  19768. ws.send(msg.data(), msg.size());
  19769. } else {
  19770. ws.send(msg);
  19771. }
  19772. }
  19773. });
  19774. server_->WebSocket("/ws-echo-string",
  19775. [](const Request &, ws::WebSocket &ws) {
  19776. std::string msg;
  19777. while (ws.read(msg)) {
  19778. ws.send("echo: " + msg);
  19779. }
  19780. });
  19781. server_->WebSocket(
  19782. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19783. // Echo back request metadata
  19784. ws.send("path:" + req.path);
  19785. ws.send("header:" + req.get_header_value("X-Test-Header"));
  19786. std::string msg;
  19787. while (ws.read(msg)) {}
  19788. });
  19789. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  19790. std::string msg;
  19791. ws.read(msg); // wait for a message
  19792. ws.close();
  19793. });
  19794. server_->WebSocket("/ws-close-status",
  19795. [](const Request &, ws::WebSocket &ws) {
  19796. std::string msg;
  19797. ws.read(msg); // wait for a message
  19798. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  19799. });
  19800. server_->WebSocket(
  19801. "/ws-subprotocol",
  19802. [](const Request &, ws::WebSocket &ws) {
  19803. std::string msg;
  19804. while (ws.read(msg)) {
  19805. ws.send(msg);
  19806. }
  19807. },
  19808. [](const std::vector<std::string> &protocols) -> std::string {
  19809. for (const auto &p : protocols) {
  19810. if (p == "graphql-ws") { return p; }
  19811. }
  19812. return "";
  19813. });
  19814. }
  19815. void start_server() {
  19816. port_ = server_->bind_to_any_port(HOST);
  19817. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19818. server_->wait_until_ready();
  19819. }
  19820. std::unique_ptr<Server> server_;
  19821. std::thread server_thread_;
  19822. int port_ = 0;
  19823. };
  19824. TEST_F(WebSocketIntegrationTest, TextEcho) {
  19825. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19826. "/ws-echo");
  19827. ASSERT_TRUE(client.connect());
  19828. ASSERT_TRUE(client.is_open());
  19829. ASSERT_TRUE(client.send("Hello WebSocket"));
  19830. std::string msg;
  19831. EXPECT_EQ(ws::Text, client.read(msg));
  19832. EXPECT_EQ("Hello WebSocket", msg);
  19833. client.close();
  19834. }
  19835. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  19836. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19837. "/ws-echo");
  19838. ASSERT_TRUE(client.connect());
  19839. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  19840. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  19841. std::string msg;
  19842. EXPECT_EQ(ws::Binary, client.read(msg));
  19843. EXPECT_EQ(binary_data, msg);
  19844. client.close();
  19845. }
  19846. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  19847. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19848. "/ws-echo");
  19849. ASSERT_TRUE(client.connect());
  19850. for (int i = 0; i < 10; i++) {
  19851. auto text = "message " + std::to_string(i);
  19852. ASSERT_TRUE(client.send(text));
  19853. std::string msg;
  19854. ASSERT_TRUE(client.read(msg));
  19855. EXPECT_EQ(text, msg);
  19856. }
  19857. client.close();
  19858. }
  19859. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  19860. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19861. "/ws-close");
  19862. ASSERT_TRUE(client.connect());
  19863. // Send a message to trigger the server to close
  19864. ASSERT_TRUE(client.send("trigger close"));
  19865. // The server will close, so read should return false
  19866. std::string msg;
  19867. EXPECT_FALSE(client.read(msg));
  19868. EXPECT_FALSE(client.is_open());
  19869. }
  19870. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  19871. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19872. "/ws-echo");
  19873. ASSERT_TRUE(client.connect());
  19874. // 128KB message
  19875. std::string large_data(128 * 1024, 'X');
  19876. ASSERT_TRUE(client.send(large_data));
  19877. std::string msg;
  19878. ASSERT_TRUE(client.read(msg));
  19879. EXPECT_EQ(large_data, msg);
  19880. client.close();
  19881. }
  19882. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  19883. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19884. "/ws-echo");
  19885. ASSERT_TRUE(client.connect());
  19886. const int num_threads = 4;
  19887. std::vector<std::thread> threads;
  19888. std::atomic<int> send_count{0};
  19889. for (int t = 0; t < num_threads; t++) {
  19890. threads.emplace_back([&client, &send_count, t]() {
  19891. for (int i = 0; i < 5; i++) {
  19892. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19893. if (client.send(text)) { send_count++; }
  19894. }
  19895. });
  19896. }
  19897. for (auto &th : threads) {
  19898. th.join();
  19899. }
  19900. int received = 0;
  19901. std::string msg;
  19902. while (received < send_count.load()) {
  19903. if (!client.read(msg)) { break; }
  19904. received++;
  19905. }
  19906. EXPECT_EQ(send_count.load(), received);
  19907. client.close();
  19908. }
  19909. TEST_F(WebSocketIntegrationTest, ReadString) {
  19910. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19911. "/ws-echo-string");
  19912. ASSERT_TRUE(client.connect());
  19913. ASSERT_TRUE(client.send("hello"));
  19914. std::string msg;
  19915. ASSERT_TRUE(client.read(msg));
  19916. EXPECT_EQ("echo: hello", msg);
  19917. ASSERT_TRUE(client.send("world"));
  19918. ASSERT_TRUE(client.read(msg));
  19919. EXPECT_EQ("echo: world", msg);
  19920. client.close();
  19921. }
  19922. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19923. Headers headers = {{"X-Test-Header", "test-value"}};
  19924. ws::WebSocketClient client(
  19925. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19926. ASSERT_TRUE(client.connect());
  19927. std::string msg;
  19928. ASSERT_TRUE(client.read(msg));
  19929. EXPECT_EQ("path:/ws-request-info", msg);
  19930. ASSERT_TRUE(client.read(msg));
  19931. EXPECT_EQ("header:test-value", msg);
  19932. client.close();
  19933. }
  19934. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19935. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19936. "/ws-echo");
  19937. client.set_read_timeout(1, 0); // 1 second
  19938. ASSERT_TRUE(client.connect());
  19939. // Don't send anything — server echo handler waits for a message, so read()
  19940. // should time out. The connection survives it: nothing was consumed.
  19941. std::string msg;
  19942. EXPECT_EQ(client.read(msg), ws::Timeout);
  19943. EXPECT_TRUE(client.is_open());
  19944. // And it is still usable afterwards.
  19945. EXPECT_TRUE(client.send("after timeout"));
  19946. EXPECT_EQ(client.read(msg), ws::Text);
  19947. EXPECT_EQ(msg, "after timeout");
  19948. }
  19949. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  19950. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19951. "/ws-echo");
  19952. client.set_read_timeout(1, 0);
  19953. ASSERT_TRUE(client.connect());
  19954. ASSERT_TRUE(client.send("first"));
  19955. std::string msg;
  19956. ASSERT_EQ(client.read(msg), ws::Text);
  19957. ASSERT_EQ(msg, "first");
  19958. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  19959. // not be used with a read timeout: it would reprocess the previous message.
  19960. EXPECT_EQ(client.read(msg), ws::Timeout);
  19961. EXPECT_EQ(msg, "first");
  19962. }
  19963. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  19964. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19965. "/ws-echo");
  19966. ASSERT_TRUE(client.connect());
  19967. // Setting it once the connection is open reaches the live stream, not just
  19968. // the seed for the next connect().
  19969. client.set_read_timeout(1, 0);
  19970. std::string msg;
  19971. EXPECT_EQ(client.read(msg), ws::Timeout);
  19972. EXPECT_TRUE(client.is_open());
  19973. }
  19974. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  19975. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19976. "/ws-echo");
  19977. client.set_read_timeout(5, 0);
  19978. ASSERT_TRUE(client.connect());
  19979. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19980. // The server should reject it and close the connection.
  19981. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  19982. client.send(oversized);
  19983. // The server's read() should have failed due to payload limit,
  19984. // so our read() should return false (connection closed).
  19985. std::string msg;
  19986. EXPECT_FALSE(client.read(msg));
  19987. }
  19988. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  19989. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19990. "/ws-echo");
  19991. client.set_read_timeout(10, 0);
  19992. ASSERT_TRUE(client.connect());
  19993. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19994. // This should succeed.
  19995. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  19996. ASSERT_TRUE(client.send(at_limit));
  19997. std::string msg;
  19998. ASSERT_TRUE(client.read(msg));
  19999. EXPECT_EQ(at_limit.size(), msg.size());
  20000. client.close();
  20001. }
  20002. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20003. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20004. "/nonexistent");
  20005. auto res = client.connect();
  20006. EXPECT_FALSE(res);
  20007. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20008. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20009. EXPECT_FALSE(client.is_open());
  20010. }
  20011. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20012. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20013. "/ws-echo");
  20014. ASSERT_TRUE(client.connect());
  20015. ASSERT_TRUE(client.send(""));
  20016. std::string msg;
  20017. EXPECT_EQ(ws::Text, client.read(msg));
  20018. EXPECT_EQ("", msg);
  20019. client.close();
  20020. }
  20021. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20022. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20023. "/ws-echo");
  20024. // First connection
  20025. ASSERT_TRUE(client.connect());
  20026. ASSERT_TRUE(client.send("first"));
  20027. std::string msg;
  20028. ASSERT_TRUE(client.read(msg));
  20029. EXPECT_EQ("first", msg);
  20030. client.close();
  20031. EXPECT_FALSE(client.is_open());
  20032. // Reconnect using the same client object
  20033. ASSERT_TRUE(client.connect());
  20034. ASSERT_TRUE(client.is_open());
  20035. ASSERT_TRUE(client.send("second"));
  20036. ASSERT_TRUE(client.read(msg));
  20037. EXPECT_EQ("second", msg);
  20038. client.close();
  20039. }
  20040. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20041. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20042. "/ws-close-status");
  20043. ASSERT_TRUE(client.connect());
  20044. // Trigger the server to close with GoingAway status
  20045. ASSERT_TRUE(client.send("trigger"));
  20046. // read() should return false after receiving the close frame
  20047. std::string msg;
  20048. EXPECT_FALSE(client.read(msg));
  20049. EXPECT_FALSE(client.is_open());
  20050. }
  20051. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20052. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20053. "/ws-echo");
  20054. ASSERT_TRUE(client.connect());
  20055. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20056. EXPECT_FALSE(client.is_open());
  20057. }
  20058. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20059. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20060. ws::WebSocketClient client(
  20061. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20062. ASSERT_TRUE(client.connect());
  20063. // Server should have selected graphql-ws
  20064. EXPECT_EQ("graphql-ws", client.subprotocol());
  20065. client.close();
  20066. }
  20067. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20068. Headers headers;
  20069. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20070. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20071. ws::WebSocketClient client(
  20072. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20073. ASSERT_TRUE(client.connect());
  20074. // The offer on the second field line counts too, so graphql-ws is selected
  20075. EXPECT_EQ("graphql-ws", client.subprotocol());
  20076. client.close();
  20077. }
  20078. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20079. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20080. ws::WebSocketClient client(
  20081. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20082. ASSERT_TRUE(client.connect());
  20083. // Server should not have selected any subprotocol
  20084. EXPECT_TRUE(client.subprotocol().empty());
  20085. client.close();
  20086. }
  20087. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20088. // Connect without requesting any subprotocol
  20089. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20090. "/ws-subprotocol");
  20091. ASSERT_TRUE(client.connect());
  20092. EXPECT_TRUE(client.subprotocol().empty());
  20093. client.close();
  20094. }
  20095. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20096. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20097. "/ws-echo");
  20098. client.set_tcp_nodelay(true);
  20099. client.set_connection_timeout(3, 0);
  20100. bool socket_options_called = false;
  20101. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20102. ASSERT_TRUE(client.connect());
  20103. ASSERT_TRUE(client.is_open());
  20104. EXPECT_TRUE(socket_options_called);
  20105. ASSERT_TRUE(client.send("hello"));
  20106. std::string msg;
  20107. auto result = client.read(msg);
  20108. EXPECT_EQ(result, ws::ReadResult::Text);
  20109. EXPECT_EQ(msg, "hello");
  20110. client.close();
  20111. }
  20112. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20113. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20114. "/ws-echo");
  20115. client.set_connection_timeout(std::chrono::seconds(3));
  20116. client.set_write_timeout(std::chrono::seconds(3));
  20117. // A sub-second remainder exercises the seconds/microseconds split.
  20118. client.set_read_timeout(std::chrono::milliseconds(1500));
  20119. ASSERT_TRUE(client.connect());
  20120. auto start = std::chrono::steady_clock::now();
  20121. std::string msg;
  20122. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20123. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20124. std::chrono::steady_clock::now() - start)
  20125. .count();
  20126. // Above 1s so that dropping the microseconds half of the split fails here.
  20127. // Ignoring the setter altogether would not reach this line at all: a client
  20128. // waits forever by default.
  20129. EXPECT_GE(elapsed, 1400);
  20130. EXPECT_LT(elapsed, 30000);
  20131. }
  20132. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20133. Server svr;
  20134. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20135. if (!req.has_header("Authorization")) {
  20136. res.status = StatusCode::Unauthorized_401;
  20137. res.set_content("Unauthorized", "text/plain");
  20138. return Server::HandlerResponse::Handled;
  20139. }
  20140. return Server::HandlerResponse::Unhandled;
  20141. });
  20142. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20143. std::string msg;
  20144. while (ws.read(msg)) {
  20145. ws.send(msg);
  20146. }
  20147. });
  20148. auto port = svr.bind_to_any_port("localhost");
  20149. std::thread t([&]() { svr.listen_after_bind(); });
  20150. svr.wait_until_ready();
  20151. // Without Authorization header - should be rejected before upgrade
  20152. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20153. EXPECT_FALSE(client1.connect());
  20154. // The rejection is framed like any other HTTP response
  20155. {
  20156. Client cli("localhost", port);
  20157. Headers headers = {{"Upgrade", "websocket"},
  20158. {"Connection", "Upgrade"},
  20159. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20160. {"Sec-WebSocket-Version", "13"}};
  20161. auto res = cli.Get("/ws", headers);
  20162. ASSERT_TRUE(res);
  20163. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20164. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20165. EXPECT_EQ("Unauthorized", res->body);
  20166. }
  20167. // With Authorization header - should succeed
  20168. Headers headers = {{"Authorization", "Bearer token123"}};
  20169. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20170. headers);
  20171. ASSERT_TRUE(client2.connect());
  20172. ASSERT_TRUE(client2.send("hello"));
  20173. std::string msg;
  20174. ASSERT_TRUE(client2.read(msg));
  20175. EXPECT_EQ("hello", msg);
  20176. client2.close();
  20177. svr.stop();
  20178. t.join();
  20179. }
  20180. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20181. Server svr;
  20182. std::atomic<int> pre_request_calls{0};
  20183. std::atomic<bool> route_matched{false};
  20184. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20185. pre_request_calls++;
  20186. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20187. if (req.get_header_value("Authorization") != "Bearer token123") {
  20188. res.status = StatusCode::Unauthorized_401;
  20189. res.set_content("Unauthorized", "text/plain");
  20190. return Server::HandlerResponse::Handled;
  20191. }
  20192. return Server::HandlerResponse::Unhandled;
  20193. });
  20194. std::atomic<bool> handler_called{false};
  20195. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20196. handler_called = true;
  20197. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20198. });
  20199. auto port = svr.bind_to_any_port("localhost");
  20200. std::thread t([&]() { svr.listen_after_bind(); });
  20201. svr.wait_until_ready();
  20202. // Without Authorization header - should be rejected before upgrade
  20203. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20204. "/ws/1");
  20205. EXPECT_FALSE(client1.connect());
  20206. EXPECT_FALSE(handler_called);
  20207. EXPECT_EQ(1, pre_request_calls);
  20208. EXPECT_TRUE(route_matched);
  20209. // The rejection is an ordinary HTTP response, not a protocol switch
  20210. {
  20211. Client cli("localhost", port);
  20212. Headers headers = {{"Upgrade", "websocket"},
  20213. {"Connection", "Upgrade"},
  20214. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20215. {"Sec-WebSocket-Version", "13"}};
  20216. auto res = cli.Get("/ws/1", headers);
  20217. ASSERT_TRUE(res);
  20218. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20219. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20220. EXPECT_EQ("Unauthorized", res->body);
  20221. }
  20222. EXPECT_FALSE(handler_called);
  20223. // With Authorization header - should succeed
  20224. Headers headers = {{"Authorization", "Bearer token123"}};
  20225. ws::WebSocketClient client2(
  20226. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20227. ASSERT_TRUE(client2.connect());
  20228. std::string msg;
  20229. ASSERT_TRUE(client2.read(msg));
  20230. EXPECT_EQ("/ws/:id 2", msg);
  20231. EXPECT_TRUE(handler_called);
  20232. client2.close();
  20233. svr.stop();
  20234. t.join();
  20235. }
  20236. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20237. Server svr;
  20238. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20239. // A read timeout is how a handler gets control back. Without it, a handler
  20240. // parked in read() can never write on the connection it is reading.
  20241. ws.set_read_timeout(std::chrono::milliseconds(100));
  20242. std::string msg;
  20243. while (ws.is_open()) {
  20244. auto r = ws.read(msg);
  20245. if (r == httplib::ws::Timeout) {
  20246. ws.send("tick");
  20247. continue;
  20248. }
  20249. if (r == httplib::ws::Fail) { break; }
  20250. ws.send(msg);
  20251. }
  20252. });
  20253. auto port = svr.bind_to_any_port("localhost");
  20254. std::thread t([&]() { svr.listen_after_bind(); });
  20255. svr.wait_until_ready();
  20256. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20257. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20258. ASSERT_TRUE(client.connect());
  20259. // The client sends nothing, so anything it receives came out of the
  20260. // handler's timeout path.
  20261. std::string msg;
  20262. ASSERT_EQ(client.read(msg), ws::Text);
  20263. EXPECT_EQ("tick", msg);
  20264. client.close();
  20265. svr.stop();
  20266. t.join();
  20267. }
  20268. // Stream::read may return fewer bytes than asked for. This is that contract at
  20269. // its worst -- one byte per call -- which is what a frame header straddling a
  20270. // read buffer's boundary looks like to the frame parser.
  20271. class WsByteAtATimeStream : public Stream {
  20272. public:
  20273. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20274. bool is_readable() const override { return true; }
  20275. bool wait_readable() const override { return true; }
  20276. bool wait_writable() const override { return true; }
  20277. ssize_t read(char *ptr, size_t size) override {
  20278. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20279. *ptr = data_[pos_++];
  20280. return 1;
  20281. }
  20282. ssize_t write(const char *, size_t size) override {
  20283. return static_cast<ssize_t>(size);
  20284. }
  20285. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20286. ip = "127.0.0.1";
  20287. port = 0;
  20288. }
  20289. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20290. ip = "127.0.0.1";
  20291. port = 0;
  20292. }
  20293. socket_t socket() const override { return INVALID_SOCKET; }
  20294. time_t duration() const override { return 0; }
  20295. private:
  20296. std::string data_;
  20297. size_t pos_ = 0;
  20298. };
  20299. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20300. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20301. // length and the mask key are all multi-byte fields here. Each used to be
  20302. // read with a single read() call, which fails as soon as one is split.
  20303. std::string body(200, 'x');
  20304. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20305. std::string frame;
  20306. frame += static_cast<char>(0x81); // FIN + Text
  20307. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20308. frame += static_cast<char>(body.size() >> 8);
  20309. frame += static_cast<char>(body.size() & 0xff);
  20310. for (size_t i = 0; i < 4; i++) {
  20311. frame += static_cast<char>(mask[i]);
  20312. }
  20313. for (size_t i = 0; i < body.size(); i++) {
  20314. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20315. }
  20316. WsByteAtATimeStream strm(frame);
  20317. ws::Opcode opcode;
  20318. std::string payload;
  20319. bool fin = false;
  20320. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20321. /*expect_masked=*/true, 1024),
  20322. ws::impl::FrameRead::Ok);
  20323. EXPECT_TRUE(fin);
  20324. EXPECT_EQ(opcode, ws::Opcode::Text);
  20325. EXPECT_EQ(payload, body);
  20326. }
  20327. TEST(WebSocketTest, QueryStringInHandshake) {
  20328. Server svr;
  20329. std::mutex mtx;
  20330. std::string received_target;
  20331. std::string received_token;
  20332. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20333. {
  20334. std::lock_guard<std::mutex> lock(mtx);
  20335. received_target = req.target;
  20336. if (req.has_param("token")) {
  20337. received_token = req.get_param_value("token");
  20338. }
  20339. }
  20340. std::string msg;
  20341. while (ws.read(msg)) {
  20342. ws.send(msg);
  20343. }
  20344. });
  20345. auto port = svr.bind_to_any_port("localhost");
  20346. std::thread t([&]() { svr.listen_after_bind(); });
  20347. svr.wait_until_ready();
  20348. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20349. "/ws?token=ABC&session=123");
  20350. ASSERT_TRUE(client.connect());
  20351. // Round-trip ensures the handler has run and captured the request.
  20352. ASSERT_TRUE(client.send("hello"));
  20353. std::string msg;
  20354. ASSERT_TRUE(client.read(msg));
  20355. EXPECT_EQ("hello", msg);
  20356. client.close();
  20357. {
  20358. std::lock_guard<std::mutex> lock(mtx);
  20359. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20360. EXPECT_EQ("ABC", received_token);
  20361. }
  20362. svr.stop();
  20363. t.join();
  20364. }
  20365. // Run a handshake against a throwaway server and hand the request the server
  20366. // received back to the caller, so tests can assert on the headers the client
  20367. // actually put on the wire.
  20368. static void capture_websocket_handshake_request(
  20369. const Headers &client_headers,
  20370. std::function<void(const Request &, int port)> verify) {
  20371. Server svr;
  20372. std::mutex mtx;
  20373. Request received;
  20374. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20375. {
  20376. std::lock_guard<std::mutex> lock(mtx);
  20377. received = req;
  20378. }
  20379. std::string msg;
  20380. while (ws.read(msg)) {
  20381. ws.send(msg);
  20382. }
  20383. });
  20384. auto port = svr.bind_to_any_port("localhost");
  20385. std::thread t([&]() { svr.listen_after_bind(); });
  20386. auto se = detail::scope_exit([&] {
  20387. svr.stop();
  20388. t.join();
  20389. });
  20390. svr.wait_until_ready();
  20391. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20392. client_headers);
  20393. ASSERT_TRUE(client.connect());
  20394. ASSERT_TRUE(client.send("hello"));
  20395. std::string msg;
  20396. ASSERT_TRUE(client.read(msg));
  20397. client.close();
  20398. {
  20399. std::lock_guard<std::mutex> lock(mtx);
  20400. verify(received, port);
  20401. }
  20402. }
  20403. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20404. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20405. // Non-default port must be present in the Host header. Default ports
  20406. // (80/443) are omitted; that logic is covered by
  20407. // MakeHostAndPortStringTest.
  20408. EXPECT_EQ("localhost:" + std::to_string(port),
  20409. req.get_header_value("Host"));
  20410. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20411. req.get_header_value("User-Agent"));
  20412. EXPECT_FALSE(req.has_header("Accept"));
  20413. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20414. EXPECT_FALSE(req.has_header("Content-Length"));
  20415. });
  20416. }
  20417. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20418. capture_websocket_handshake_request(
  20419. {{"Host", "example.com"},
  20420. {"User-Agent", "custom-agent"},
  20421. {"X-Custom", "value"}},
  20422. [](const Request &req, int) {
  20423. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20424. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20425. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20426. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20427. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20428. });
  20429. }
  20430. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20431. capture_websocket_handshake_request(
  20432. {{"Upgrade", "bogus"},
  20433. {"Connection", "close"},
  20434. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20435. {"Sec-WebSocket-Version", "8"}},
  20436. [](const Request &req, int) {
  20437. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20438. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20439. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20440. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20441. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20442. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20443. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20444. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20445. req.get_header_value("Sec-WebSocket-Key"));
  20446. });
  20447. }
  20448. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20449. // A header the client refuses to send must abort the handshake before any
  20450. // part of it reaches the wire; a lone request line would otherwise sit in
  20451. // the peer's buffer as a truncated request.
  20452. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20453. ASSERT_NE(INVALID_SOCKET, srv);
  20454. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20455. sockaddr_in addr{};
  20456. addr.sin_family = AF_INET;
  20457. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20458. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20459. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20460. ASSERT_EQ(0, ::listen(srv, 1));
  20461. sockaddr_in bound{};
  20462. socklen_t bound_len = sizeof(bound);
  20463. ASSERT_EQ(
  20464. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20465. auto port = ntohs(bound.sin_port);
  20466. ssize_t received = -1;
  20467. std::thread t([&] {
  20468. // Bound every blocking call so a regression fails the test with a bad
  20469. // value instead of hanging the suite.
  20470. fd_set rfds;
  20471. FD_ZERO(&rfds);
  20472. FD_SET(srv, &rfds);
  20473. timeval tv{5, 0};
  20474. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20475. 0) {
  20476. return;
  20477. }
  20478. sockaddr_in cli_addr{};
  20479. socklen_t cli_len = sizeof(cli_addr);
  20480. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20481. if (cli == INVALID_SOCKET) { return; }
  20482. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20483. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20484. char buf[4096];
  20485. received = ::recv(cli, buf, sizeof(buf), 0);
  20486. });
  20487. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20488. // connect() has already shut the socket down by the time it returns false,
  20489. // so the peer sees EOF without waiting for the client to be destroyed.
  20490. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20491. {{"X-Bad", "a\r\nInjected: 1"}});
  20492. EXPECT_FALSE(client.connect());
  20493. t.join();
  20494. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20495. EXPECT_EQ(0, received);
  20496. }
  20497. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20498. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20499. // contains "upgrade" as a substring is a different token and must not
  20500. // start a WebSocket handshake.
  20501. auto make_request = [](const std::vector<std::string> &connection_values) {
  20502. Request req;
  20503. req.method = "GET";
  20504. req.headers.emplace("Upgrade", "websocket");
  20505. for (const auto &value : connection_values) {
  20506. req.headers.emplace("Connection", value);
  20507. }
  20508. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20509. req.headers.emplace("Sec-WebSocket-Version", "13");
  20510. return req;
  20511. };
  20512. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20513. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20514. EXPECT_TRUE(
  20515. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20516. EXPECT_TRUE(
  20517. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20518. EXPECT_TRUE(
  20519. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20520. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20521. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20522. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20523. EXPECT_FALSE(
  20524. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20525. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20526. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20527. }
  20528. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20529. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20530. // asks recipients to match each protocol-name case-insensitively, and RFC
  20531. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20532. // client naming websocket alongside another protocol, or on a second field
  20533. // line, is offering websocket; a value that merely contains "websocket" as a
  20534. // substring is a different protocol name and is not.
  20535. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20536. Request req;
  20537. req.method = "GET";
  20538. for (const auto &value : upgrade_values) {
  20539. req.headers.emplace("Upgrade", value);
  20540. }
  20541. req.headers.emplace("Connection", "Upgrade");
  20542. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20543. req.headers.emplace("Sec-WebSocket-Version", "13");
  20544. return req;
  20545. };
  20546. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20547. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20548. EXPECT_TRUE(
  20549. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20550. EXPECT_TRUE(
  20551. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20552. EXPECT_TRUE(
  20553. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20554. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20555. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20556. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20557. EXPECT_FALSE(
  20558. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20559. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20560. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20561. }
  20562. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20563. Server svr;
  20564. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20565. auto port = svr.bind_to_any_port("localhost");
  20566. std::thread t([&]() { svr.listen_after_bind(); });
  20567. auto se = detail::scope_exit([&] {
  20568. svr.stop();
  20569. t.join();
  20570. });
  20571. svr.wait_until_ready();
  20572. Headers headers = {{"Upgrade", "websocket"},
  20573. {"Connection", "notupgrade"},
  20574. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20575. {"Sec-WebSocket-Version", "13"}};
  20576. Client cli("localhost", port);
  20577. auto res = cli.Get("/ws", headers);
  20578. // The route exists only as a WebSocket route, so a request that fails the
  20579. // handshake check falls through to ordinary routing.
  20580. ASSERT_TRUE(res);
  20581. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20582. }
  20583. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20584. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20585. // Connection value is the only thing left for the client to reject.
  20586. Server svr;
  20587. svr.Get("/ws", [](const Request &req, Response &res) {
  20588. res.status = StatusCode::SwitchingProtocol_101;
  20589. res.set_header("Upgrade", "websocket");
  20590. res.set_header("Connection", "notupgrade");
  20591. res.set_header("Sec-WebSocket-Accept",
  20592. detail::websocket_accept_key(
  20593. req.get_header_value("Sec-WebSocket-Key")));
  20594. });
  20595. auto port = svr.bind_to_any_port("localhost");
  20596. std::thread t([&]() { svr.listen_after_bind(); });
  20597. auto se = detail::scope_exit([&] {
  20598. svr.stop();
  20599. t.join();
  20600. });
  20601. svr.wait_until_ready();
  20602. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20603. auto res = client.connect();
  20604. EXPECT_FALSE(res);
  20605. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20606. EXPECT_FALSE(client.is_open());
  20607. }
  20608. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20609. // The socket path doubles as the URL host, so it must not contain '/'.
  20610. const char *shard = getenv("GTEST_SHARD_INDEX");
  20611. const std::string sock_path =
  20612. shard ? std::string("httplib-ws-") + shard + ".sock"
  20613. : std::string("httplib-ws.sock");
  20614. std::remove(sock_path.c_str());
  20615. Server svr;
  20616. std::mutex mtx;
  20617. std::string received_host;
  20618. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20619. {
  20620. std::lock_guard<std::mutex> lock(mtx);
  20621. received_host = req.get_header_value("Host");
  20622. }
  20623. std::string msg;
  20624. while (ws.read(msg)) {
  20625. ws.send(msg);
  20626. }
  20627. });
  20628. svr.set_address_family(AF_UNIX);
  20629. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20630. auto se = detail::scope_exit([&] {
  20631. svr.stop();
  20632. t.join();
  20633. std::remove(sock_path.c_str());
  20634. });
  20635. svr.wait_until_ready();
  20636. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  20637. client.set_address_family(AF_UNIX);
  20638. ASSERT_TRUE(client.connect());
  20639. ASSERT_TRUE(client.send("hello"));
  20640. std::string msg;
  20641. ASSERT_TRUE(client.read(msg));
  20642. client.close();
  20643. {
  20644. std::lock_guard<std::mutex> lock(mtx);
  20645. // There is no host:port for a Unix socket, so the same "localhost"
  20646. // placeholder the HTTP client uses is expected.
  20647. EXPECT_EQ("localhost", received_host);
  20648. }
  20649. }
  20650. // Two threads must never parse WebSocket frames from the same stream.
  20651. // close() used to read the peer's Close reply with its own frame read, so it
  20652. // raced a reader thread that was in the middle of a payload: the payload loop
  20653. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  20654. // so bytes taken by close() were replaced with bytes from further along the
  20655. // stream. The message kept its length and silently changed content.
  20656. //
  20657. // The raw peer below sends a frame header plus part of the payload, waits for
  20658. // the handler to call close(), and only then sends the rest. Whichever thread
  20659. // would win the race for those bytes, the message must arrive intact, because
  20660. // close() must not touch the stream while read() owns it.
  20661. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  20662. #ifndef _WIN32
  20663. signal(SIGPIPE, SIG_IGN);
  20664. #endif
  20665. const size_t payload_len = 120; // fits the 7-bit length field
  20666. const size_t prefix_len = 8;
  20667. const int attempts = 8;
  20668. std::string expected(payload_len, '\0');
  20669. for (size_t i = 0; i < payload_len; i++) {
  20670. expected[i] = static_cast<char>('a' + i % 26);
  20671. }
  20672. std::atomic<bool> peer_stalled{false};
  20673. std::atomic<bool> handler_done{false};
  20674. std::mutex received_mutex;
  20675. std::vector<std::string> received;
  20676. // Bound every wait, so a regression fails the test instead of hanging the
  20677. // suite.
  20678. auto wait_for = [](const std::atomic<bool> &flag) {
  20679. for (int i = 0; i < 500 && !flag; i++) {
  20680. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20681. }
  20682. };
  20683. Server svr;
  20684. svr.set_websocket_ping_interval(0);
  20685. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  20686. std::thread reader([&]() {
  20687. std::string msg;
  20688. while (ws.read(msg)) {
  20689. std::lock_guard<std::mutex> guard(received_mutex);
  20690. received.push_back(msg);
  20691. }
  20692. });
  20693. // Wait until the peer stalls mid-payload, so the reader thread is parked
  20694. // inside read_websocket_frame() when close() runs.
  20695. wait_for(peer_stalled);
  20696. ws.close();
  20697. reader.join();
  20698. handler_done = true;
  20699. });
  20700. auto port = svr.bind_to_any_port("127.0.0.1");
  20701. std::thread t([&]() { svr.listen_after_bind(); });
  20702. auto se = detail::scope_exit([&] {
  20703. svr.stop();
  20704. t.join();
  20705. });
  20706. svr.wait_until_ready();
  20707. auto send_bytes = [](socket_t s, const std::string &data) {
  20708. #ifdef _WIN32
  20709. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  20710. #else
  20711. auto n = ::send(s, data.data(), data.size(), 0);
  20712. #endif
  20713. return n == static_cast<decltype(n)>(data.size());
  20714. };
  20715. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  20716. // Every length used here fits the 7-bit length field.
  20717. auto masked_header = [](uint8_t first_byte, size_t len) {
  20718. std::string h;
  20719. h += static_cast<char>(first_byte);
  20720. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  20721. h.append(4, '\0'); // mask key
  20722. return h;
  20723. };
  20724. for (int attempt = 0; attempt < attempts; attempt++) {
  20725. peer_stalled = false;
  20726. handler_done = false;
  20727. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  20728. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  20729. auto se_sock = detail::scope_exit([&] {
  20730. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  20731. });
  20732. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20733. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20734. sockaddr_in addr{};
  20735. addr.sin_family = AF_INET;
  20736. addr.sin_port = htons(static_cast<uint16_t>(port));
  20737. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20738. ASSERT_EQ(
  20739. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  20740. << "attempt " << attempt;
  20741. ASSERT_TRUE(send_bytes(sock,
  20742. "GET /ws HTTP/1.1\r\n"
  20743. "Host: 127.0.0.1\r\n"
  20744. "Upgrade: websocket\r\n"
  20745. "Connection: Upgrade\r\n"
  20746. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  20747. "Sec-WebSocket-Version: 13\r\n"
  20748. "\r\n"))
  20749. << "attempt " << attempt;
  20750. std::string response;
  20751. while (response.find("\r\n\r\n") == std::string::npos) {
  20752. char buf[512];
  20753. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  20754. if (n <= 0) { break; }
  20755. response.append(buf, static_cast<size_t>(n));
  20756. }
  20757. ASSERT_NE(std::string::npos, response.find(" 101 "))
  20758. << "attempt " << attempt;
  20759. // Send the header of a Binary message but only the first prefix_len bytes
  20760. // of its payload, leaving the reader thread stalled inside the payload.
  20761. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  20762. expected.substr(0, prefix_len)))
  20763. << "attempt " << attempt;
  20764. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20765. peer_stalled = true;
  20766. // Let close() send its Close frame and park in its own read before the
  20767. // rest of the payload arrives, so both threads are waiting for it.
  20768. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20769. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  20770. close_frame += static_cast<char>(0x03); // status 1000
  20771. close_frame += static_cast<char>(0xE8);
  20772. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  20773. << "attempt " << attempt;
  20774. // Closing the peer releases the reader thread even on the buggy path,
  20775. // where it waits for bytes another thread already consumed.
  20776. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20777. detail::close_socket(sock);
  20778. sock = INVALID_SOCKET;
  20779. wait_for(handler_done);
  20780. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  20781. }
  20782. std::lock_guard<std::mutex> guard(received_mutex);
  20783. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  20784. << "a message in flight when close() ran was dropped";
  20785. for (size_t i = 0; i < received.size(); i++) {
  20786. EXPECT_EQ(expected, received[i]) << "message " << i;
  20787. }
  20788. }
  20789. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20790. class WebSocketSSLIntegrationTest : public ::testing::Test {
  20791. protected:
  20792. void SetUp() override {
  20793. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  20794. SERVER_PRIVATE_KEY_FILE);
  20795. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20796. std::string msg;
  20797. ws::ReadResult ret;
  20798. while ((ret = ws.read(msg))) {
  20799. if (ret == ws::Binary) {
  20800. ws.send(msg.data(), msg.size());
  20801. } else {
  20802. ws.send(msg);
  20803. }
  20804. }
  20805. });
  20806. port_ = server_->bind_to_any_port(HOST);
  20807. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20808. server_->wait_until_ready();
  20809. }
  20810. void TearDown() override {
  20811. server_->stop();
  20812. if (server_thread_.joinable()) { server_thread_.join(); }
  20813. }
  20814. std::unique_ptr<SSLServer> server_;
  20815. std::thread server_thread_;
  20816. int port_ = 0;
  20817. };
  20818. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  20819. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20820. "/ws-echo");
  20821. client.enable_server_certificate_verification(false);
  20822. ASSERT_TRUE(client.connect());
  20823. ASSERT_TRUE(client.is_open());
  20824. ASSERT_TRUE(client.send("Hello WSS"));
  20825. std::string msg;
  20826. EXPECT_EQ(ws::Text, client.read(msg));
  20827. EXPECT_EQ("Hello WSS", msg);
  20828. client.close();
  20829. }
  20830. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  20831. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  20832. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  20833. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  20834. // client (without calling close() first) is the only path that runs
  20835. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  20836. // bug exactly.
  20837. //
  20838. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  20839. // when linked against an instrumented libssl; run under Valgrind to catch it
  20840. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  20841. // suite (the freed session otherwise stalls on the close handshake) — this test
  20842. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  20843. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  20844. {
  20845. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20846. "/ws-echo");
  20847. client.enable_server_certificate_verification(false);
  20848. client.set_read_timeout(2, 0);
  20849. client.set_write_timeout(2, 0);
  20850. ASSERT_TRUE(client.connect());
  20851. ASSERT_TRUE(client.is_open());
  20852. ASSERT_TRUE(client.send("still open"));
  20853. // Intentionally do NOT call client.close(): leaving scope runs
  20854. // shutdown_and_close() with the WebSocket still open, which must send the
  20855. // close frame while the TLS session is still alive.
  20856. }
  20857. }
  20858. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  20859. // shutdown_and_close() at the start of connect(), reproducing the same
  20860. // use-after-free within the test body rather than at scope exit. The second
  20861. // connect must succeed and echo, proving the close handshake ran over a live
  20862. // session. See the note above about memory-tool requirements.
  20863. TEST_F(WebSocketSSLIntegrationTest,
  20864. ReconnectWhileOpenSendsCloseOverLiveSession) {
  20865. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20866. "/ws-echo");
  20867. client.enable_server_certificate_verification(false);
  20868. client.set_read_timeout(2, 0);
  20869. client.set_write_timeout(2, 0);
  20870. ASSERT_TRUE(client.connect());
  20871. ASSERT_TRUE(client.is_open());
  20872. ASSERT_TRUE(client.send("still open"));
  20873. // Reconnect without closing first: connect() calls shutdown_and_close() on
  20874. // the still-open connection, which must not touch a freed TLS session.
  20875. ASSERT_TRUE(client.connect());
  20876. ASSERT_TRUE(client.is_open());
  20877. ASSERT_TRUE(client.send("after reconnect"));
  20878. std::string msg;
  20879. EXPECT_EQ(ws::Text, client.read(msg));
  20880. EXPECT_EQ("after reconnect", msg);
  20881. client.close();
  20882. }
  20883. #endif
  20884. #ifdef CPPHTTPLIB_SSL_ENABLED
  20885. class WebSocketSSLCATest : public ::testing::Test {
  20886. protected:
  20887. void SetUp() override {
  20888. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  20889. SERVER_PRIVATE_KEY_FILE);
  20890. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20891. std::string msg;
  20892. while (ws.read(msg)) {
  20893. ws.send(msg);
  20894. }
  20895. });
  20896. port_ = server_->bind_to_any_port("127.0.0.1");
  20897. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20898. server_->wait_until_ready();
  20899. }
  20900. void TearDown() override {
  20901. server_->stop();
  20902. if (server_thread_.joinable()) { server_thread_.join(); }
  20903. }
  20904. std::string url() const {
  20905. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  20906. }
  20907. std::unique_ptr<SSLServer> server_;
  20908. std::thread server_thread_;
  20909. int port_ = 0;
  20910. };
  20911. // A custom CA loaded as PEM verifies the server with full certificate
  20912. // verification enabled
  20913. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  20914. ws::WebSocketClient client(url());
  20915. std::string cert;
  20916. read_file(SERVER_CERT2_FILE, cert);
  20917. client.load_ca_cert_store(cert.c_str(), cert.size());
  20918. ASSERT_TRUE(client.connect());
  20919. ASSERT_TRUE(client.send("hello"));
  20920. std::string msg;
  20921. EXPECT_EQ(ws::Text, client.read(msg));
  20922. EXPECT_EQ("hello", msg);
  20923. client.close();
  20924. }
  20925. // A custom CA that does not cover the server must fail verification (the
  20926. // custom CA is exclusive; system certs are not loaded alongside it)
  20927. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  20928. ws::WebSocketClient client(url());
  20929. std::string cert;
  20930. read_file(CLIENT_CA_CERT_FILE, cert);
  20931. client.load_ca_cert_store(cert.c_str(), cert.size());
  20932. auto res = client.connect();
  20933. ASSERT_FALSE(res);
  20934. EXPECT_EQ(Error::SSLServerVerification, res.error());
  20935. EXPECT_EQ(-1, res.status());
  20936. EXPECT_NE(0u, res.ssl_backend_error());
  20937. }
  20938. // The same CA as a file path rather than PEM in memory
  20939. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  20940. ws::WebSocketClient client(url());
  20941. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20942. ASSERT_TRUE(client.connect());
  20943. ASSERT_TRUE(client.send("hello"));
  20944. std::string msg;
  20945. EXPECT_EQ(ws::Text, client.read(msg));
  20946. EXPECT_EQ("hello", msg);
  20947. client.close();
  20948. }
  20949. // ...and a CA file that does not cover the server still fails, so it is the
  20950. // path above that decides the outcome
  20951. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  20952. ws::WebSocketClient client(url());
  20953. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20954. ASSERT_FALSE(client.connect());
  20955. }
  20956. // Regression test: reconnecting with a native custom CA store used to reuse
  20957. // a store handle the previous TLS context had already freed (use-after-free
  20958. // under the OpenSSL backend). The context now lives as long as the client.
  20959. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  20960. ws::WebSocketClient client(url());
  20961. std::string cert;
  20962. read_file(SERVER_CERT2_FILE, cert);
  20963. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  20964. ASSERT_TRUE(client.connect());
  20965. client.close();
  20966. ASSERT_TRUE(client.connect());
  20967. ASSERT_TRUE(client.send("again"));
  20968. std::string msg;
  20969. EXPECT_EQ(ws::Text, client.read(msg));
  20970. EXPECT_EQ("again", msg);
  20971. client.close();
  20972. }
  20973. // Regression test: a certificate with a trusted chain but no identity match
  20974. // for the server IP must be rejected. The Mbed TLS backend used to skip
  20975. // verification entirely for IP hosts, so this connection succeeded there.
  20976. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  20977. // chain verification while the identity check must still fail.
  20978. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  20979. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20980. ASSERT_TRUE(svr.is_valid());
  20981. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20982. std::string msg;
  20983. while (ws.read(msg)) {
  20984. ws.send(msg);
  20985. }
  20986. });
  20987. auto port = svr.bind_to_any_port("127.0.0.1");
  20988. auto t = std::thread([&]() { svr.listen_after_bind(); });
  20989. auto se = detail::scope_exit([&] {
  20990. svr.stop();
  20991. t.join();
  20992. });
  20993. svr.wait_until_ready();
  20994. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  20995. "/echo");
  20996. std::string cert;
  20997. read_file(SERVER_CERT_FILE, cert);
  20998. client.load_ca_cert_store(cert.c_str(), cert.size());
  20999. ASSERT_FALSE(client.connect());
  21000. }
  21001. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21002. // SNI, so nothing binds the host name to the TLS session. These bind the
  21003. // server to "localhost" instead, the only shape that exercises the SNI and
  21004. // hostname-verification path with certificate verification left enabled.
  21005. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21006. protected:
  21007. void Start(const char *cert_file) {
  21008. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21009. SERVER_PRIVATE_KEY_FILE);
  21010. ASSERT_TRUE(server_->is_valid());
  21011. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21012. std::string msg;
  21013. while (ws.read(msg)) {
  21014. ws.send(msg);
  21015. }
  21016. });
  21017. port_ = server_->bind_to_any_port("localhost");
  21018. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21019. server_->wait_until_ready();
  21020. }
  21021. void TearDown() override {
  21022. if (server_) { server_->stop(); }
  21023. if (server_thread_.joinable()) { server_thread_.join(); }
  21024. }
  21025. std::string url() const {
  21026. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21027. }
  21028. std::unique_ptr<SSLServer> server_;
  21029. std::thread server_thread_;
  21030. int port_ = 0;
  21031. };
  21032. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21033. // out and the connection is usable
  21034. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21035. Start(SERVER_CERT2_FILE);
  21036. ws::WebSocketClient client(url());
  21037. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21038. ASSERT_TRUE(client.connect());
  21039. ASSERT_TRUE(client.send("hello"));
  21040. std::string msg;
  21041. EXPECT_EQ(ws::Text, client.read(msg));
  21042. EXPECT_EQ("hello", msg);
  21043. client.close();
  21044. }
  21045. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21046. // while the identity check must still reject "localhost"
  21047. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21048. Start(SERVER_CERT_FILE);
  21049. ws::WebSocketClient client(url());
  21050. client.set_ca_cert_path(SERVER_CERT_FILE);
  21051. auto res = client.connect();
  21052. ASSERT_FALSE(res);
  21053. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21054. EXPECT_EQ(-1, res.status());
  21055. }
  21056. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21057. // disabled: the chain is still checked, only the identity check is skipped
  21058. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21059. Start(SERVER_CERT_FILE);
  21060. ws::WebSocketClient client(url());
  21061. client.set_ca_cert_path(SERVER_CERT_FILE);
  21062. client.enable_server_hostname_verification(false);
  21063. ASSERT_TRUE(client.connect());
  21064. ASSERT_TRUE(client.send("hello"));
  21065. std::string msg;
  21066. EXPECT_EQ(ws::Text, client.read(msg));
  21067. EXPECT_EQ("hello", msg);
  21068. client.close();
  21069. }
  21070. // A CA that did not sign the server certificate fails the chain, even though
  21071. // the name would match
  21072. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21073. Start(SERVER_CERT2_FILE);
  21074. ws::WebSocketClient client(url());
  21075. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21076. ASSERT_FALSE(client.connect());
  21077. }
  21078. // With verification disabled, neither the chain nor the name is checked
  21079. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21080. Start(SERVER_CERT_FILE);
  21081. ws::WebSocketClient client(url());
  21082. client.enable_server_certificate_verification(false);
  21083. ASSERT_TRUE(client.connect());
  21084. ASSERT_TRUE(client.send("hello"));
  21085. std::string msg;
  21086. EXPECT_EQ(ws::Text, client.read(msg));
  21087. EXPECT_EQ("hello", msg);
  21088. client.close();
  21089. }
  21090. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21091. protected:
  21092. void SetUp() override {
  21093. server_ = httplib::detail::make_unique<SSLServer>(
  21094. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21095. ASSERT_TRUE(server_->is_valid());
  21096. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21097. std::string msg;
  21098. while (ws.read(msg)) {
  21099. ws.send(msg);
  21100. }
  21101. });
  21102. port_ = server_->bind_to_any_port("localhost");
  21103. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21104. server_->wait_until_ready();
  21105. }
  21106. void TearDown() override {
  21107. server_->stop();
  21108. if (server_thread_.joinable()) { server_thread_.join(); }
  21109. }
  21110. std::string url() const {
  21111. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21112. }
  21113. void ConnectWithClientCert(const std::string &client_cert_file,
  21114. const std::string &client_private_key_file,
  21115. const char *private_key_password) {
  21116. std::string cert_pem, key_pem;
  21117. read_file(client_cert_file, cert_pem);
  21118. read_file(client_private_key_file, key_pem);
  21119. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21120. key_pem.c_str(), key_pem.size(),
  21121. private_key_password};
  21122. ws::WebSocketClient client(url(), pem);
  21123. ASSERT_TRUE(client.is_valid());
  21124. client.enable_server_certificate_verification(false);
  21125. ASSERT_TRUE(client.connect());
  21126. ASSERT_TRUE(client.send("hello"));
  21127. std::string msg;
  21128. EXPECT_EQ(ws::Text, client.read(msg));
  21129. EXPECT_EQ("hello", msg);
  21130. client.close();
  21131. }
  21132. std::unique_ptr<SSLServer> server_;
  21133. std::thread server_thread_;
  21134. int port_ = 0;
  21135. };
  21136. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21137. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21138. }
  21139. // Control for the tests above: the fixture's server really does require a
  21140. // client certificate, so it is the PEM the constructor installed that decides
  21141. // the outcome.
  21142. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21143. ws::WebSocketClient client(url());
  21144. ASSERT_TRUE(client.is_valid());
  21145. client.enable_server_certificate_verification(false);
  21146. EXPECT_FALSE(client.connect());
  21147. }
  21148. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21149. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21150. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21151. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21152. }
  21153. #endif
  21154. #if !defined(_WIN32)
  21155. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21156. auto secret_dir = std::string("./symlink_test_secret");
  21157. auto served_dir = std::string("./symlink_test_served");
  21158. auto secret_file = secret_dir + "/secret.txt";
  21159. auto symlink_path = served_dir + "/escape";
  21160. // Setup: create directories and files
  21161. mkdir(secret_dir.c_str(), 0755);
  21162. mkdir(served_dir.c_str(), 0755);
  21163. {
  21164. std::ofstream ofs(secret_file);
  21165. ofs << "SECRET_DATA";
  21166. }
  21167. // Create symlink using absolute path so it resolves correctly
  21168. #ifdef PATH_MAX
  21169. char abs_secret[PATH_MAX];
  21170. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21171. #else
  21172. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21173. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21174. ASSERT_NE(nullptr, abs_secret);
  21175. #endif
  21176. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21177. auto se = detail::scope_exit([&] {
  21178. unlink(symlink_path.c_str());
  21179. unlink(secret_file.c_str());
  21180. rmdir(served_dir.c_str());
  21181. rmdir(secret_dir.c_str());
  21182. });
  21183. Server svr;
  21184. svr.set_mount_point("/", served_dir);
  21185. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21186. auto se2 = detail::scope_exit([&] {
  21187. svr.stop();
  21188. listen_thread.join();
  21189. });
  21190. svr.wait_until_ready();
  21191. Client cli("localhost", PORT);
  21192. // Symlink pointing outside base dir should be blocked
  21193. auto res = cli.Get("/escape/secret.txt");
  21194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21195. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21196. }
  21197. #endif
  21198. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  21199. // "GET /smuggled" request), reads the first response, and only then sends the
  21200. // embedded request as the body. Returns how many times /smuggled ran.
  21201. //
  21202. // The body is sent AFTER receiving the first response (as in the original
  21203. // PoC) so that the stream_line_reader cannot buffer it together with the
  21204. // headers of the first request.
  21205. static int count_smuggled_requests(const std::string &outer_head,
  21206. std::string &first_response) {
  21207. Server svr;
  21208. svr.set_mount_point("/", "./www");
  21209. std::atomic<int> smuggled_count(0);
  21210. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21211. smuggled_count++;
  21212. res.set_content("oops", "text/plain");
  21213. });
  21214. svr.Post("/post", [&](const Request &req, Response &res) {
  21215. res.set_content(req.body, "text/plain");
  21216. });
  21217. auto port = svr.bind_to_any_port("localhost");
  21218. thread t = thread([&] { svr.listen_after_bind(); });
  21219. auto se = detail::scope_exit([&] {
  21220. svr.stop();
  21221. t.join();
  21222. });
  21223. svr.wait_until_ready();
  21224. auto error = Error::Success;
  21225. auto sock = detail::create_client_socket(
  21226. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21227. /*connection_timeout_sec=*/2, 0,
  21228. /*read_timeout_sec=*/2, 0,
  21229. /*write_timeout_sec=*/2, 0, std::string(), error);
  21230. EXPECT_NE(INVALID_SOCKET, sock);
  21231. if (sock == INVALID_SOCKET) { return -1; }
  21232. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21233. // The "smuggled" request will be sent as the body of the outer request
  21234. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21235. "Host: localhost\r\n"
  21236. "Connection: close\r\n"
  21237. "\r\n";
  21238. auto head = outer_head;
  21239. auto len = std::to_string(smuggled.size());
  21240. for (auto pos = head.find("{len}"); pos != std::string::npos;
  21241. pos = head.find("{len}", pos + len.size())) {
  21242. head.replace(pos, 5, len);
  21243. }
  21244. // Step 1: Send only the outer request headers (no body yet)
  21245. auto sent = send(sock, head.data(), head.size(), 0);
  21246. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  21247. // Step 2: Read the first response
  21248. char buf[4096];
  21249. for (;;) {
  21250. auto n = recv(sock, buf, sizeof(buf), 0);
  21251. if (n <= 0) break;
  21252. first_response.append(buf, static_cast<size_t>(n));
  21253. // Stop once we have a complete response (headers + body)
  21254. auto hdr_end = first_response.find("\r\n\r\n");
  21255. if (hdr_end != std::string::npos) {
  21256. // Check for Content-Length to know when the body is complete
  21257. auto cl_pos = first_response.find("Content-Length:");
  21258. if (cl_pos != std::string::npos) {
  21259. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21260. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21261. auto cl = std::stoul(
  21262. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21263. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21264. } else {
  21265. break; // No Content-Length, assume headers-only response
  21266. }
  21267. }
  21268. }
  21269. // Step 3: Now send the body, which looks like a new HTTP request. On a
  21270. // vulnerable server the keep-alive loop reads this as a second request. The
  21271. // server may already have closed the connection, so the result is ignored.
  21272. send(sock, smuggled.data(), smuggled.size(), 0);
  21273. // Half-close so that a server which drained the body sees EOF and closes,
  21274. // instead of the read below waiting for the read timeout.
  21275. #ifdef _WIN32
  21276. ::shutdown(sock, SD_SEND);
  21277. #else
  21278. ::shutdown(sock, SHUT_WR);
  21279. #endif
  21280. // Step 4: Read until the server closes the connection
  21281. for (;;) {
  21282. auto n = recv(sock, buf, sizeof(buf), 0);
  21283. if (n <= 0) break;
  21284. }
  21285. return smuggled_count.load();
  21286. }
  21287. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21288. // A GET request with Content-Length to a static file handler must have its
  21289. // body drained before the keep-alive connection is reused. Otherwise the
  21290. // unread body bytes are interpreted as the next HTTP request.
  21291. std::string first_response;
  21292. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21293. "Host: localhost\r\n"
  21294. "Content-Length: {len}\r\n"
  21295. "\r\n",
  21296. first_response));
  21297. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  21298. }
  21299. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  21300. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  21301. // be answered with 400 and the connection closed. Treating it as "no body"
  21302. // leaves the body to be parsed as the next request.
  21303. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  21304. const char *targets[] = {
  21305. "GET /file", // handler that never reads the body
  21306. "GET /not-found", // no handler matches (404)
  21307. "POST /post", // handler that reads the body
  21308. };
  21309. for (auto target : targets) {
  21310. for (auto value : values) {
  21311. std::string first_response;
  21312. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  21313. " HTTP/1.1\r\n"
  21314. "Host: localhost\r\n"
  21315. "Content-Length: " +
  21316. value + "\r\n\r\n",
  21317. first_response))
  21318. << target << " with Content-Length: " << value;
  21319. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  21320. << target << " with Content-Length: " << value;
  21321. }
  21322. }
  21323. }
  21324. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  21325. // A 400 for an unparseable request line leaves the rest of the message
  21326. // unread, so the connection must be closed rather than reused.
  21327. std::string first_response;
  21328. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  21329. "Host: localhost\r\n"
  21330. "Content-Length: {len}\r\n"
  21331. "\r\n",
  21332. first_response));
  21333. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21334. }
  21335. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  21336. // Same as above for a header block that fails to parse.
  21337. std::string first_response;
  21338. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21339. "Host: localhost\r\n"
  21340. "Bad Header\r\n"
  21341. "Content-Length: {len}\r\n"
  21342. "\r\n",
  21343. first_response));
  21344. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21345. }
  21346. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  21347. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  21348. // server must not read another request on that connection, even when the
  21349. // request had no body to drain.
  21350. std::string first_response;
  21351. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  21352. "Host: localhost\r\n"
  21353. "\r\n",
  21354. first_response));
  21355. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  21356. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  21357. }
  21358. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21359. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21360. // must be rejected with 400 Bad Request.
  21361. Server svr;
  21362. svr.Post("/test", [&](const Request &, Response &res) {
  21363. res.set_content("ok", "text/plain");
  21364. });
  21365. thread t = thread([&] { svr.listen(HOST, PORT); });
  21366. auto se = detail::scope_exit([&] {
  21367. svr.stop();
  21368. t.join();
  21369. ASSERT_FALSE(svr.is_running());
  21370. });
  21371. svr.wait_until_ready();
  21372. // Exact "chunked"
  21373. {
  21374. auto req = "POST /test HTTP/1.1\r\n"
  21375. "Host: localhost\r\n"
  21376. "Content-Length: 5\r\n"
  21377. "Transfer-Encoding: chunked\r\n"
  21378. "Connection: close\r\n"
  21379. "\r\n"
  21380. "hello";
  21381. std::string response;
  21382. ASSERT_TRUE(send_request(1, req, &response));
  21383. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21384. response.substr(0, response.find("\r\n")));
  21385. }
  21386. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21387. {
  21388. auto req = "POST /test HTTP/1.1\r\n"
  21389. "Host: localhost\r\n"
  21390. "Content-Length: 5\r\n"
  21391. "Transfer-Encoding: gzip, chunked\r\n"
  21392. "Connection: close\r\n"
  21393. "\r\n"
  21394. "hello";
  21395. std::string response;
  21396. ASSERT_TRUE(send_request(1, req, &response));
  21397. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21398. response.substr(0, response.find("\r\n")));
  21399. }
  21400. }
  21401. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21402. Server svr;
  21403. svr.Post("/test", [&](const Request &, Response &res) {
  21404. res.set_content("ok", "text/plain");
  21405. });
  21406. thread t = thread([&] { svr.listen(HOST, PORT); });
  21407. auto se = detail::scope_exit([&] {
  21408. svr.stop();
  21409. t.join();
  21410. ASSERT_FALSE(svr.is_running());
  21411. });
  21412. svr.wait_until_ready();
  21413. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21414. // length cannot be determined, so the server must answer 400 and close
  21415. // rather than treat the request as bodyless and leave the body in the
  21416. // socket for the next request to pick up.
  21417. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21418. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21419. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21420. std::string response;
  21421. ASSERT_TRUE(send_request(1, req, &response));
  21422. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21423. response.substr(0, response.find("\r\n")))
  21424. << transfer_encoding;
  21425. }
  21426. // RFC 9110 5.3: the codings may also be split across several
  21427. // Transfer-Encoding lines, which combine in the order they were received.
  21428. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21429. // just like the single-line "chunked, gzip" above.
  21430. {
  21431. auto req = "POST /test HTTP/1.1\r\n"
  21432. "Host: localhost\r\n"
  21433. "Transfer-Encoding: chunked\r\n"
  21434. "Transfer-Encoding: gzip\r\n"
  21435. "\r\n"
  21436. "0\r\n\r\n";
  21437. std::string response;
  21438. ASSERT_TRUE(send_request(1, req, &response));
  21439. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21440. response.substr(0, response.find("\r\n")));
  21441. }
  21442. // A sequence ending in chunked stays valid.
  21443. auto req = "POST /test HTTP/1.1\r\n"
  21444. "Host: localhost\r\n"
  21445. "Transfer-Encoding: gzip, chunked\r\n"
  21446. "Connection: close\r\n"
  21447. "\r\n"
  21448. "0\r\n\r\n";
  21449. std::string response;
  21450. ASSERT_TRUE(send_request(1, req, &response));
  21451. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21452. // ...including when it is spread over several lines.
  21453. auto split_req = "POST /test HTTP/1.1\r\n"
  21454. "Host: localhost\r\n"
  21455. "Transfer-Encoding: gzip\r\n"
  21456. "Transfer-Encoding: chunked\r\n"
  21457. "Connection: close\r\n"
  21458. "\r\n"
  21459. "0\r\n\r\n";
  21460. std::string split_response;
  21461. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21462. EXPECT_EQ("HTTP/1.1 200 OK",
  21463. split_response.substr(0, split_response.find("\r\n")));
  21464. }
  21465. // Regression for issue #2450: a DELETE without Content-Length on a
  21466. // keep-alive connection must not let the post-response drain consume the
  21467. // next request's bytes.
  21468. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21469. Server svr;
  21470. std::atomic<int> delete_count(0);
  21471. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21472. delete_count++;
  21473. res.status = StatusCode::NoContent_204;
  21474. });
  21475. auto port = svr.bind_to_any_port(HOST);
  21476. thread t = thread([&] { svr.listen_after_bind(); });
  21477. auto se = detail::scope_exit([&] {
  21478. svr.stop();
  21479. t.join();
  21480. });
  21481. svr.wait_until_ready();
  21482. auto error = Error::Success;
  21483. auto sock = detail::create_client_socket(
  21484. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21485. /*connection_timeout_sec=*/2, 0,
  21486. /*read_timeout_sec=*/2, 0,
  21487. /*write_timeout_sec=*/2, 0, std::string(), error);
  21488. ASSERT_NE(INVALID_SOCKET, sock);
  21489. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21490. auto send_request_and_read_response = [&](const std::string &req,
  21491. std::string &out) -> bool {
  21492. auto sent = send(sock, req.data(), req.size(), 0);
  21493. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21494. char buf[4096];
  21495. for (;;) {
  21496. auto n = recv(sock, buf, sizeof(buf), 0);
  21497. if (n <= 0) { return !out.empty(); }
  21498. out.append(buf, static_cast<size_t>(n));
  21499. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21500. }
  21501. };
  21502. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21503. "Host: localhost\r\n"
  21504. "\r\n";
  21505. std::string resp1;
  21506. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21507. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21508. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21509. "Host: localhost\r\n"
  21510. "Connection: close\r\n"
  21511. "\r\n";
  21512. std::string resp2;
  21513. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21514. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21515. EXPECT_EQ(2, delete_count.load());
  21516. }
  21517. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21518. Server svr;
  21519. svr.Post("/ingest", [&](const Request &, Response &res,
  21520. const ContentReader &content_reader) {
  21521. auto consumed = content_reader([](const char *, size_t) { return false; });
  21522. EXPECT_FALSE(consumed);
  21523. res.status = StatusCode::Conflict_409;
  21524. res.set_header("Connection", "close");
  21525. });
  21526. auto port = svr.bind_to_any_port(HOST);
  21527. thread t = thread([&] { svr.listen_after_bind(); });
  21528. auto se = detail::scope_exit([&] {
  21529. svr.stop();
  21530. t.join();
  21531. });
  21532. svr.wait_until_ready();
  21533. auto error = Error::Success;
  21534. auto sock = detail::create_client_socket(
  21535. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21536. /*connection_timeout_sec=*/2, 0,
  21537. /*read_timeout_sec=*/1, 0,
  21538. /*write_timeout_sec=*/2, 0, std::string(), error);
  21539. ASSERT_NE(INVALID_SOCKET, sock);
  21540. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21541. std::string request = "POST /ingest HTTP/1.1\r\n"
  21542. "Host: localhost\r\n"
  21543. "Transfer-Encoding: chunked\r\n"
  21544. "\r\n"
  21545. "4\r\n"
  21546. "data\r\n";
  21547. auto sent = send(sock, request.data(), request.size(), 0);
  21548. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21549. std::string response;
  21550. ssize_t received = 0;
  21551. do {
  21552. char buf[4096];
  21553. received = recv(sock, buf, sizeof(buf), 0);
  21554. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21555. } while (received > 0);
  21556. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21557. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21558. EXPECT_EQ(0, received);
  21559. }
  21560. namespace no_proxy_test {
  21561. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21562. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21563. // calling listen().
  21564. class ScopedServer {
  21565. public:
  21566. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21567. ~ScopedServer() {
  21568. svr_.stop();
  21569. if (th_.joinable()) { th_.join(); }
  21570. }
  21571. Server &svr() { return svr_; }
  21572. int port() const { return port_; }
  21573. void listen() {
  21574. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21575. svr_.wait_until_ready();
  21576. }
  21577. private:
  21578. Server svr_;
  21579. std::thread th_;
  21580. int port_ = 0;
  21581. };
  21582. class ProxyAndTargetServers {
  21583. public:
  21584. ProxyAndTargetServers() {
  21585. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21586. proxy_hits_++;
  21587. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21588. res.set_content("via-proxy", "text/plain");
  21589. });
  21590. target_.Get(".*", [this](const Request &req, Response &res) {
  21591. target_hits_++;
  21592. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21593. res.set_content("direct", "text/plain");
  21594. });
  21595. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21596. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21597. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21598. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21599. proxy_mock_.wait_until_ready();
  21600. target_.wait_until_ready();
  21601. }
  21602. ~ProxyAndTargetServers() {
  21603. proxy_mock_.stop();
  21604. target_.stop();
  21605. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21606. if (target_thread_.joinable()) { target_thread_.join(); }
  21607. }
  21608. Server &proxy_mock() { return proxy_mock_; }
  21609. Server &target() { return target_; }
  21610. int proxy_port() const { return proxy_port_; }
  21611. int target_port() const { return target_port_; }
  21612. int proxy_hits() const { return proxy_hits_.load(); }
  21613. int target_hits() const { return target_hits_.load(); }
  21614. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21615. void reset_counters() {
  21616. proxy_hits_ = 0;
  21617. target_hits_ = 0;
  21618. last_had_proxy_authz_ = false;
  21619. }
  21620. private:
  21621. Server proxy_mock_;
  21622. Server target_;
  21623. std::thread proxy_thread_;
  21624. std::thread target_thread_;
  21625. int proxy_port_ = 0;
  21626. int target_port_ = 0;
  21627. std::atomic<int> proxy_hits_{0};
  21628. std::atomic<int> target_hits_{0};
  21629. std::atomic<bool> last_had_proxy_authz_{false};
  21630. };
  21631. inline std::unique_ptr<Client> make_client(const std::string &host,
  21632. ProxyAndTargetServers &s) {
  21633. auto cli = detail::make_unique<Client>(host, s.target_port());
  21634. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  21635. cli->set_proxy("127.0.0.1", s.proxy_port());
  21636. return cli;
  21637. }
  21638. } // namespace no_proxy_test
  21639. using no_proxy_test::make_client;
  21640. using no_proxy_test::ProxyAndTargetServers;
  21641. TEST(NoProxyTest, ExactHostnameBypasses) {
  21642. ProxyAndTargetServers s;
  21643. auto cli = make_client("example.com", s);
  21644. cli->set_no_proxy({"example.com"});
  21645. auto res = cli->Get("/");
  21646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21647. EXPECT_EQ(0, s.proxy_hits());
  21648. EXPECT_EQ(1, s.target_hits());
  21649. }
  21650. TEST(NoProxyTest, SubdomainBypasses) {
  21651. ProxyAndTargetServers s;
  21652. auto cli = make_client("foo.example.com", s);
  21653. cli->set_no_proxy({"example.com"});
  21654. auto res = cli->Get("/");
  21655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21656. EXPECT_EQ(0, s.proxy_hits());
  21657. EXPECT_EQ(1, s.target_hits());
  21658. }
  21659. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  21660. // Regression guard: "evilexample.com" must not be considered a subdomain
  21661. // of "example.com". Without the dot-boundary rule, a naive endsWith
  21662. // check would let traffic bypass the proxy and leak credentials direct
  21663. // to the attacker host.
  21664. ProxyAndTargetServers s;
  21665. auto cli = make_client("evilexample.com", s);
  21666. cli->set_no_proxy({"example.com"});
  21667. auto res = cli->Get("/");
  21668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21669. EXPECT_GE(s.proxy_hits(), 1);
  21670. EXPECT_EQ(0, s.target_hits());
  21671. }
  21672. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  21673. ProxyAndTargetServers s;
  21674. auto cli = make_client("example.com.evil.com", s);
  21675. cli->set_no_proxy({"example.com"});
  21676. auto res = cli->Get("/");
  21677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21678. EXPECT_GE(s.proxy_hits(), 1);
  21679. EXPECT_EQ(0, s.target_hits());
  21680. }
  21681. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  21682. ProxyAndTargetServers s;
  21683. auto cli = make_client("example.com", s);
  21684. cli->set_no_proxy({".example.com"});
  21685. auto res = cli->Get("/");
  21686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21687. EXPECT_EQ(0, s.proxy_hits());
  21688. EXPECT_EQ(1, s.target_hits());
  21689. }
  21690. TEST(NoProxyTest, CaseInsensitiveHostname) {
  21691. ProxyAndTargetServers s;
  21692. auto cli = make_client("Example.COM", s);
  21693. cli->set_no_proxy({"EXAMPLE.com"});
  21694. auto res = cli->Get("/");
  21695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21696. EXPECT_EQ(0, s.proxy_hits());
  21697. EXPECT_EQ(1, s.target_hits());
  21698. }
  21699. TEST(NoProxyTest, TrailingDotIsNormalized) {
  21700. ProxyAndTargetServers s;
  21701. auto cli = make_client("example.com.", s);
  21702. cli->set_no_proxy({"example.com"});
  21703. auto res = cli->Get("/");
  21704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21705. EXPECT_EQ(0, s.proxy_hits());
  21706. EXPECT_EQ(1, s.target_hits());
  21707. }
  21708. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  21709. // Trailing dots must be normalized on BOTH sides — host and entry.
  21710. // An implementation that only strips the host-side trailing dot would
  21711. // fail to match host "example.com" against entry "example.com." because
  21712. // a literal substring search would compare 11 chars against 12.
  21713. ProxyAndTargetServers s;
  21714. auto cli = make_client("example.com", s);
  21715. cli->set_no_proxy({"example.com."});
  21716. auto res = cli->Get("/");
  21717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21718. EXPECT_EQ(0, s.proxy_hits());
  21719. EXPECT_EQ(1, s.target_hits());
  21720. }
  21721. TEST(NoProxyTest, WildcardBypassesEverything) {
  21722. ProxyAndTargetServers s;
  21723. auto cli = make_client("anything.invalid.test", s);
  21724. cli->set_no_proxy({"*"});
  21725. auto res = cli->Get("/");
  21726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21727. EXPECT_EQ(0, s.proxy_hits());
  21728. EXPECT_EQ(1, s.target_hits());
  21729. }
  21730. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  21731. ProxyAndTargetServers s;
  21732. Client cli("127.0.0.1", s.target_port());
  21733. cli.set_proxy("127.0.0.1", s.proxy_port());
  21734. cli.set_no_proxy({"127.0.0.1"});
  21735. auto res = cli.Get("/");
  21736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21737. EXPECT_EQ(0, s.proxy_hits());
  21738. EXPECT_EQ(1, s.target_hits());
  21739. }
  21740. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  21741. ProxyAndTargetServers s;
  21742. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  21743. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  21744. cli.set_proxy("127.0.0.1", s.proxy_port());
  21745. cli.set_no_proxy({"::1"});
  21746. auto res = cli.Get("/");
  21747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21748. EXPECT_EQ(0, s.proxy_hits());
  21749. EXPECT_EQ(1, s.target_hits());
  21750. }
  21751. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  21752. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  21753. // must still be recognized as IPv6 for CIDR matching. Implementations
  21754. // that detect IPv6 only when the host begins with '[' would parse the
  21755. // host as a hostname and miss the match.
  21756. ProxyAndTargetServers s;
  21757. Client cli("fe80::1", s.target_port());
  21758. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21759. cli.set_proxy("127.0.0.1", s.proxy_port());
  21760. cli.set_no_proxy({"fe80::/10"});
  21761. auto res = cli.Get("/");
  21762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21763. EXPECT_EQ(0, s.proxy_hits());
  21764. EXPECT_EQ(1, s.target_hits());
  21765. }
  21766. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  21767. ProxyAndTargetServers s;
  21768. Client cli("::1", s.target_port());
  21769. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  21770. cli.set_proxy("127.0.0.1", s.proxy_port());
  21771. cli.set_no_proxy({"[::1]"});
  21772. auto res = cli.Get("/");
  21773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21774. EXPECT_EQ(0, s.proxy_hits());
  21775. EXPECT_EQ(1, s.target_hits());
  21776. }
  21777. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  21778. ProxyAndTargetServers s;
  21779. Client cli("fe80::1", s.target_port());
  21780. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21781. cli.set_proxy("127.0.0.1", s.proxy_port());
  21782. cli.set_no_proxy({"[fe80::]/10"});
  21783. auto res = cli.Get("/");
  21784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21785. EXPECT_EQ(0, s.proxy_hits());
  21786. EXPECT_EQ(1, s.target_hits());
  21787. }
  21788. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  21789. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  21790. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  21791. // tricks via address-family conversion.
  21792. ProxyAndTargetServers s;
  21793. Client cli("::ffff:127.0.0.1", s.target_port());
  21794. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  21795. cli.set_proxy("127.0.0.1", s.proxy_port());
  21796. cli.set_no_proxy({"127.0.0.1"});
  21797. auto res = cli.Get("/");
  21798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21799. EXPECT_GE(s.proxy_hits(), 1);
  21800. EXPECT_EQ(0, s.target_hits());
  21801. }
  21802. TEST(NoProxyTest, IPv4CidrMatch) {
  21803. ProxyAndTargetServers s;
  21804. Client cli("127.0.0.1", s.target_port());
  21805. cli.set_proxy("127.0.0.1", s.proxy_port());
  21806. cli.set_no_proxy({"127.0.0.0/8"});
  21807. auto res = cli.Get("/");
  21808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21809. EXPECT_EQ(0, s.proxy_hits());
  21810. EXPECT_EQ(1, s.target_hits());
  21811. }
  21812. TEST(NoProxyTest, IPv4CidrNonMatch) {
  21813. ProxyAndTargetServers s;
  21814. Client cli("127.0.0.1", s.target_port());
  21815. cli.set_proxy("127.0.0.1", s.proxy_port());
  21816. cli.set_no_proxy({"10.0.0.0/8"});
  21817. auto res = cli.Get("/");
  21818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21819. EXPECT_GE(s.proxy_hits(), 1);
  21820. EXPECT_EQ(0, s.target_hits());
  21821. }
  21822. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  21823. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  21824. // IPv4 target matches.
  21825. ProxyAndTargetServers s;
  21826. Client cli("127.0.0.1", s.target_port());
  21827. cli.set_proxy("127.0.0.1", s.proxy_port());
  21828. cli.set_no_proxy({"0.0.0.0/0"});
  21829. auto res = cli.Get("/");
  21830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21831. EXPECT_EQ(0, s.proxy_hits());
  21832. EXPECT_EQ(1, s.target_hits());
  21833. }
  21834. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  21835. ProxyAndTargetServers s;
  21836. Client cli("127.0.0.1", s.target_port());
  21837. cli.set_proxy("127.0.0.1", s.proxy_port());
  21838. cli.set_no_proxy({"127.0.0.1"});
  21839. auto res = cli.Get("/");
  21840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21841. EXPECT_EQ(0, s.proxy_hits());
  21842. EXPECT_EQ(1, s.target_hits());
  21843. }
  21844. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  21845. ProxyAndTargetServers s;
  21846. Client cli("127.0.0.1", s.target_port());
  21847. cli.set_proxy("127.0.0.1", s.proxy_port());
  21848. cli.set_no_proxy({"127.0.0.0/33"});
  21849. auto res = cli.Get("/");
  21850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21851. EXPECT_GE(s.proxy_hits(), 1);
  21852. EXPECT_EQ(0, s.target_hits());
  21853. }
  21854. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  21855. // Empty prefix after the slash must be rejected, not silently treated as /32.
  21856. ProxyAndTargetServers s;
  21857. Client cli("127.0.0.1", s.target_port());
  21858. cli.set_proxy("127.0.0.1", s.proxy_port());
  21859. cli.set_no_proxy({"127.0.0.1/"});
  21860. auto res = cli.Get("/");
  21861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21862. EXPECT_GE(s.proxy_hits(), 1);
  21863. EXPECT_EQ(0, s.target_hits());
  21864. }
  21865. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  21866. ProxyAndTargetServers s;
  21867. auto cli = make_client("internal.corp", s);
  21868. cli->set_proxy_basic_auth("u", "p");
  21869. cli->set_no_proxy({"internal.corp"});
  21870. auto res = cli->Get("/");
  21871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21872. EXPECT_EQ(1, s.target_hits());
  21873. EXPECT_EQ(0, s.proxy_hits());
  21874. EXPECT_FALSE(s.last_had_proxy_authz())
  21875. << "Proxy-Authorization must not be sent direct to the target";
  21876. }
  21877. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  21878. ProxyAndTargetServers s;
  21879. auto cli = make_client("public.example", s);
  21880. cli->set_proxy_basic_auth("u", "p");
  21881. cli->set_no_proxy({"internal.corp"}); // does not match
  21882. auto res = cli->Get("/");
  21883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21884. EXPECT_GE(s.proxy_hits(), 1);
  21885. EXPECT_TRUE(s.last_had_proxy_authz());
  21886. }
  21887. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  21888. ProxyAndTargetServers s;
  21889. auto cli = make_client("anything.test", s);
  21890. auto res = cli->Get("/");
  21891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21892. EXPECT_GE(s.proxy_hits(), 1);
  21893. EXPECT_EQ(0, s.target_hits());
  21894. }
  21895. TEST(NoProxyTest, PortSpecificEntryRejected) {
  21896. ProxyAndTargetServers s;
  21897. auto cli = make_client("example.com", s);
  21898. cli->set_no_proxy({"example.com:8080"});
  21899. auto res = cli->Get("/");
  21900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21901. EXPECT_GE(s.proxy_hits(), 1);
  21902. EXPECT_EQ(0, s.target_hits());
  21903. }
  21904. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  21905. ProxyAndTargetServers s;
  21906. auto cli = make_client("anything.test", s);
  21907. cli->set_no_proxy({"", " ", "\t"});
  21908. auto res = cli->Get("/");
  21909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21910. EXPECT_GE(s.proxy_hits(), 1);
  21911. EXPECT_EQ(0, s.target_hits());
  21912. }
  21913. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  21914. // An entry with leading/trailing whitespace must still match — env-style
  21915. // values are commonly pasted with stray spaces and an implementation
  21916. // that feeds the raw token directly to inet_pton would fail to match
  21917. // valid CIDRs because of the spaces.
  21918. ProxyAndTargetServers s;
  21919. Client cli("127.0.0.1", s.target_port());
  21920. cli.set_proxy("127.0.0.1", s.proxy_port());
  21921. cli.set_no_proxy({" 127.0.0.0/8 "});
  21922. auto res = cli.Get("/");
  21923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21924. EXPECT_EQ(0, s.proxy_hits());
  21925. EXPECT_EQ(1, s.target_hits());
  21926. }
  21927. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  21928. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  21929. // go direct and must NOT carry Proxy-Authorization.
  21930. std::atomic<int> proxy_hits{0};
  21931. std::atomic<int> target_hits{0};
  21932. std::atomic<bool> target_saw_authz{false};
  21933. no_proxy_test::ScopedServer proxy_mock, target;
  21934. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21935. proxy_hits++;
  21936. res.status = 302;
  21937. res.set_header("Location", "http://127.0.0.1:" +
  21938. std::to_string(target.port()) + "/landed");
  21939. });
  21940. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21941. target_hits++;
  21942. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  21943. res.set_content("direct", "text/plain");
  21944. });
  21945. proxy_mock.listen();
  21946. target.listen();
  21947. Client cli("public.example", target.port());
  21948. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21949. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21950. cli.set_proxy_basic_auth("u", "p");
  21951. cli.set_no_proxy({"127.0.0.1"});
  21952. cli.set_follow_location(true);
  21953. auto res = cli.Get("/redir");
  21954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21955. EXPECT_GE(proxy_hits.load(), 1);
  21956. EXPECT_GE(target_hits.load(), 1);
  21957. EXPECT_FALSE(target_saw_authz.load());
  21958. }
  21959. #ifdef CPPHTTPLIB_SSL_ENABLED
  21960. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  21961. // Direct origin replying 407 must not trigger the digest retry; otherwise
  21962. // proxy creds would be sent to the (possibly hostile) origin.
  21963. std::atomic<int> target_hits{0};
  21964. std::atomic<bool> target_saw_proxy_authz{false};
  21965. no_proxy_test::ScopedServer target;
  21966. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21967. target_hits++;
  21968. if (req.has_header("Proxy-Authorization")) {
  21969. target_saw_proxy_authz = true;
  21970. }
  21971. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21972. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  21973. "nonce=\"abc\", algorithm=MD5");
  21974. });
  21975. target.listen();
  21976. // The proxy address is set to the target's port: the bypass MUST kick in;
  21977. // if it doesn't, the test still routes "via proxy" to the same server and
  21978. // the Proxy-Authorization assertion below catches the leak.
  21979. Client cli("evil.example", target.port());
  21980. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  21981. cli.set_proxy("127.0.0.1", target.port());
  21982. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21983. cli.set_no_proxy({"evil.example"});
  21984. auto res = cli.Get("/x");
  21985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21986. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21987. EXPECT_EQ(1, target_hits.load());
  21988. EXPECT_FALSE(target_saw_proxy_authz.load());
  21989. }
  21990. #endif
  21991. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  21992. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  21993. std::atomic<int> proxy_hits{0};
  21994. std::atomic<int> bypass_hits{0};
  21995. std::atomic<bool> proxy_saw_c_url{false};
  21996. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  21997. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  21998. proxy_hits++;
  21999. if (req.path.find("/start") != std::string::npos) {
  22000. res.status = 302;
  22001. res.set_header("Location", "http://127.0.0.1:" +
  22002. std::to_string(bypass_server.port()) +
  22003. "/middle");
  22004. return;
  22005. }
  22006. if (req.path.find("/end") != std::string::npos) {
  22007. proxy_saw_c_url = true;
  22008. res.set_content("c-via-proxy", "text/plain");
  22009. return;
  22010. }
  22011. res.set_content("unexpected", "text/plain");
  22012. });
  22013. // public.example's "advertised" port is arbitrary (the request never lands
  22014. // there — it goes through the proxy), but use a dynamic value to stay
  22015. // friendly with sharded parallel runs.
  22016. int public_port = bypass_server.port();
  22017. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  22018. bypass_hits++;
  22019. res.status = 302;
  22020. res.set_header("Location", "http://public.example:" +
  22021. std::to_string(public_port) + "/end");
  22022. });
  22023. proxy_mock.listen();
  22024. bypass_server.listen();
  22025. Client cli("public.example", public_port);
  22026. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22027. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22028. cli.set_no_proxy({"127.0.0.1"});
  22029. cli.set_follow_location(true);
  22030. auto res = cli.Get("/start");
  22031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22032. EXPECT_EQ(StatusCode::OK_200, res->status);
  22033. EXPECT_EQ("c-via-proxy", res->body);
  22034. EXPECT_GE(proxy_hits.load(), 2);
  22035. EXPECT_GE(bypass_hits.load(), 1);
  22036. EXPECT_TRUE(proxy_saw_c_url.load());
  22037. }
  22038. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  22039. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  22040. // request reconnects to the correct endpoint.
  22041. std::atomic<int> proxy_hits{0};
  22042. std::atomic<int> target_hits{0};
  22043. no_proxy_test::ScopedServer proxy_mock, target;
  22044. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22045. proxy_hits++;
  22046. res.set_content("via-proxy", "text/plain");
  22047. });
  22048. target.svr().Get(".*", [&](const Request &, Response &res) {
  22049. target_hits++;
  22050. res.set_content("direct", "text/plain");
  22051. });
  22052. proxy_mock.listen();
  22053. target.listen();
  22054. Client cli("public.example", target.port());
  22055. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22056. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22057. cli.set_keep_alive(true);
  22058. auto res1 = cli.Get("/a");
  22059. ASSERT_TRUE(res1);
  22060. EXPECT_EQ("via-proxy", res1->body);
  22061. EXPECT_EQ(1, proxy_hits.load());
  22062. EXPECT_EQ(0, target_hits.load());
  22063. cli.set_no_proxy({"public.example"});
  22064. auto res2 = cli.Get("/b");
  22065. ASSERT_TRUE(res2);
  22066. EXPECT_EQ("direct", res2->body);
  22067. EXPECT_EQ(1, proxy_hits.load());
  22068. EXPECT_EQ(1, target_hits.load());
  22069. }
  22070. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  22071. namespace proxy_tunnel_test {
  22072. // SSLServer counterpart to no_proxy_test::ScopedServer.
  22073. class ScopedSSLServer {
  22074. public:
  22075. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  22076. port_ = svr_.bind_to_any_port("127.0.0.1");
  22077. }
  22078. ~ScopedSSLServer() {
  22079. svr_.stop();
  22080. if (th_.joinable()) { th_.join(); }
  22081. }
  22082. SSLServer &svr() { return svr_; }
  22083. int port() const { return port_; }
  22084. void listen() {
  22085. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22086. svr_.wait_until_ready();
  22087. }
  22088. private:
  22089. SSLServer svr_;
  22090. std::thread th_;
  22091. int port_ = 0;
  22092. };
  22093. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  22094. class ScopedConnectProxy {
  22095. public:
  22096. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  22097. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  22098. if (listen_fd_ < 0) { return; }
  22099. int yes = 1;
  22100. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  22101. sockaddr_in a{};
  22102. a.sin_family = AF_INET;
  22103. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22104. a.sin_port = 0;
  22105. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  22106. return;
  22107. }
  22108. socklen_t alen = sizeof(a);
  22109. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22110. 0) {
  22111. return;
  22112. }
  22113. port_ = ntohs(a.sin_port);
  22114. if (::listen(listen_fd_, 1) != 0) { return; }
  22115. th_ = std::thread([this] { run(); });
  22116. }
  22117. ~ScopedConnectProxy() {
  22118. stop_ = true;
  22119. if (listen_fd_ >= 0) {
  22120. ::shutdown(listen_fd_, SHUT_RDWR);
  22121. ::close(listen_fd_);
  22122. }
  22123. if (th_.joinable()) { th_.join(); }
  22124. }
  22125. int port() const { return port_; }
  22126. int connect_hits() const { return connect_hits_.load(); }
  22127. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22128. std::string connect_request() const {
  22129. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22130. return connect_request_;
  22131. }
  22132. private:
  22133. void run() {
  22134. while (!stop_.load()) {
  22135. fd_set rfds;
  22136. FD_ZERO(&rfds);
  22137. FD_SET(listen_fd_, &rfds);
  22138. timeval tv{0, 100 * 1000};
  22139. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22140. if (sel <= 0) { continue; }
  22141. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22142. if (client_fd < 0) { continue; }
  22143. std::string req;
  22144. char buf[2048];
  22145. while (req.find("\r\n\r\n") == std::string::npos) {
  22146. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22147. if (n <= 0) { break; }
  22148. req.append(buf, static_cast<size_t>(n));
  22149. }
  22150. if (req.compare(0, 7, "CONNECT") != 0) {
  22151. ::close(client_fd);
  22152. continue;
  22153. }
  22154. connect_hits_++;
  22155. {
  22156. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22157. connect_request_ = req;
  22158. }
  22159. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22160. ::send(client_fd, ok, std::strlen(ok), 0);
  22161. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22162. sockaddr_in o{};
  22163. o.sin_family = AF_INET;
  22164. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22165. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22166. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22167. 0) {
  22168. ::close(client_fd);
  22169. ::close(origin_fd);
  22170. continue;
  22171. }
  22172. auto forward = [](int from, int to) {
  22173. char b[8192];
  22174. for (;;) {
  22175. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22176. if (n <= 0) { break; }
  22177. ssize_t off = 0;
  22178. while (off < n) {
  22179. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22180. if (s <= 0) {
  22181. off = n;
  22182. break;
  22183. }
  22184. off += s;
  22185. }
  22186. }
  22187. ::shutdown(to, SHUT_WR);
  22188. };
  22189. std::thread t1([&] { forward(client_fd, origin_fd); });
  22190. std::thread t2([&] { forward(origin_fd, client_fd); });
  22191. t1.join();
  22192. t2.join();
  22193. ::close(client_fd);
  22194. ::close(origin_fd);
  22195. }
  22196. }
  22197. int forward_port_ = -1;
  22198. int listen_fd_ = -1;
  22199. int port_ = 0;
  22200. std::thread th_;
  22201. std::atomic<bool> stop_{false};
  22202. std::atomic<int> connect_hits_{0};
  22203. mutable std::mutex connect_request_mutex_;
  22204. std::string connect_request_;
  22205. };
  22206. // Sends one request through the CONNECT proxy to the TLS origin with a
  22207. // credential configured for each hop, and checks that each credential reaches
  22208. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22209. // origin's (every header in origin_headers) on the tunnelled request.
  22210. void CredentialsStayWithTheirHop(
  22211. const std::function<void(SSLClient &)> &set_credentials,
  22212. const std::string &scheme,
  22213. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22214. std::atomic<int> origin_hits{0};
  22215. std::atomic<bool> origin_saw_proxy_authz{false};
  22216. std::atomic<bool> origin_saw_headers{false};
  22217. ScopedSSLServer origin;
  22218. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22219. origin_hits++;
  22220. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22221. origin_saw_headers =
  22222. std::all_of(origin_headers.begin(), origin_headers.end(),
  22223. [&](const std::string &h) { return req.has_header(h); });
  22224. res.set_content("ok", "text/plain");
  22225. });
  22226. origin.listen();
  22227. ScopedConnectProxy proxy(origin.port());
  22228. ASSERT_NE(0, proxy.port());
  22229. // Pinned to 127.0.0.1 for the same reason as the test below.
  22230. SSLClient cli("127.0.0.1", origin.port());
  22231. cli.enable_server_certificate_verification(false);
  22232. cli.set_proxy("127.0.0.1", proxy.port());
  22233. set_credentials(cli);
  22234. auto res = cli.Get("/x");
  22235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22236. EXPECT_EQ(StatusCode::OK_200, res->status);
  22237. EXPECT_EQ(1, origin_hits.load());
  22238. EXPECT_EQ(1, proxy.connect_hits());
  22239. EXPECT_TRUE(origin_saw_headers.load());
  22240. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22241. << "Proxy-Authorization must not be sent inside the tunnel";
  22242. auto connect_req = proxy.connect_request();
  22243. EXPECT_NE(std::string::npos,
  22244. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22245. for (const auto &h : origin_headers) {
  22246. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22247. << h << " must not be sent to the proxy on CONNECT";
  22248. }
  22249. }
  22250. } // namespace proxy_tunnel_test
  22251. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22252. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22253. [](SSLClient &cli) {
  22254. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22255. cli.set_basic_auth("origin-user", "origin-pass");
  22256. },
  22257. "Basic");
  22258. }
  22259. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22260. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22261. [](SSLClient &cli) {
  22262. cli.set_proxy_bearer_token_auth("proxy-token");
  22263. cli.set_bearer_token_auth("origin-token");
  22264. },
  22265. "Bearer");
  22266. }
  22267. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22268. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22269. [](SSLClient &cli) {
  22270. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22271. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22272. {"Cookie", "sid=origin-session"},
  22273. {"X-Api-Key", "origin-key"}});
  22274. },
  22275. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22276. }
  22277. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22278. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22279. // retry; otherwise proxy creds would be sent to the origin.
  22280. std::atomic<int> origin_hits{0};
  22281. std::atomic<bool> origin_saw_proxy_authz{false};
  22282. proxy_tunnel_test::ScopedSSLServer origin;
  22283. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22284. origin_hits++;
  22285. if (req.has_header("Proxy-Authorization")) {
  22286. origin_saw_proxy_authz = true;
  22287. }
  22288. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22289. res.set_header("Proxy-Authenticate",
  22290. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22291. "algorithm=MD5");
  22292. });
  22293. origin.listen();
  22294. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22295. ASSERT_NE(0, proxy.port());
  22296. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22297. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22298. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22299. // and answer with its own status, making this test flaky.
  22300. SSLClient cli("127.0.0.1", origin.port());
  22301. cli.enable_server_certificate_verification(false);
  22302. cli.set_proxy("127.0.0.1", proxy.port());
  22303. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22304. auto res = cli.Get("/x");
  22305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22306. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22307. EXPECT_EQ(1, origin_hits.load());
  22308. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22309. EXPECT_EQ(1, proxy.connect_hits());
  22310. }
  22311. #endif