test.cc 937 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859
  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_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  396. // neighbours)
  397. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  398. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  399. }
  400. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  401. // A sign or whitespace inside the two-character escape window must not be
  402. // accepted as a valid percent-encoding; the sequence is passed through
  403. // literally, matching decode_uri_component / decode_path_component.
  404. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  405. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  406. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  407. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  408. // Well-formed escapes still decode.
  409. EXPECT_EQ("-", decode_query_component("%2D", false));
  410. EXPECT_EQ("A", decode_query_component("%41", false));
  411. }
  412. TEST(SanitizeFilenameTest, VariousPatterns) {
  413. // Path traversal
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  416. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  417. // Normal and edge cases
  418. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  419. EXPECT_EQ("filename.txt",
  420. httplib::sanitize_filename("/path/to/filename.txt"));
  421. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  422. EXPECT_EQ("", httplib::sanitize_filename(".."));
  423. EXPECT_EQ("", httplib::sanitize_filename(""));
  424. // Null bytes stripped
  425. EXPECT_EQ("safe.txt",
  426. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  427. // Whitespace-only rejected
  428. EXPECT_EQ("", httplib::sanitize_filename(" "));
  429. }
  430. // Forward declaration (see the base64_encode note below): split builds move the
  431. // definition into httplib.cc, so re-declaring it here lets the test link.
  432. namespace httplib {
  433. namespace detail {
  434. bool is_chunked_transfer_encoding(const Headers &headers);
  435. } // namespace detail
  436. } // namespace httplib
  437. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  438. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  439. auto make = [](std::initializer_list<const char *> lines) {
  440. Headers h;
  441. for (auto te : lines) {
  442. if (te) { h.emplace("Transfer-Encoding", te); }
  443. }
  444. return h;
  445. };
  446. // Sole coding, matched case-insensitively.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  450. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  454. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  459. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  460. // were received, into one list. Headers preserves that order, so the answer
  461. // is decided by the last coding of the last line and the order the lines
  462. // arrived in is significant.
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  466. // The split can fall anywhere in the list.
  467. EXPECT_TRUE(
  468. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  469. EXPECT_FALSE(
  470. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  471. // A trailing line naming no coding leaves the list ending in nothing, so it
  472. // must not inherit the chunked from the line before it.
  473. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  474. }
  475. // Forward declarations (see the base64_encode note below).
  476. namespace httplib {
  477. namespace detail {
  478. bool parse_status_line(const char *line, std::string &version, int &status,
  479. std::string &reason);
  480. std::string file_extension(const std::string &path);
  481. std::string
  482. find_content_type(const std::string &path,
  483. const std::map<std::string, std::string> &user_data,
  484. const std::string &default_content_type);
  485. bool can_compress_content_type(const std::string &content_type);
  486. bool is_prohibited_header_name(const std::string &name);
  487. #ifdef CPPHTTPLIB_SSL_ENABLED
  488. bool match_hostname(const std::string &pattern, const std::string &hostname);
  489. #endif
  490. } // namespace detail
  491. } // namespace httplib
  492. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  493. struct {
  494. const char *line;
  495. const char *version;
  496. int status;
  497. const char *reason;
  498. } cases[] = {
  499. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  500. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  501. // The reason phrase may be empty, or left out along with its space.
  502. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  503. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  504. };
  505. for (const auto &c : cases) {
  506. std::string version;
  507. int status = 0;
  508. std::string reason = "unset";
  509. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  510. << c.line;
  511. EXPECT_EQ(c.version, version);
  512. EXPECT_EQ(c.status, status);
  513. EXPECT_EQ(c.reason, reason);
  514. }
  515. }
  516. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  517. const char *lines[] = {
  518. "HTTP/2 200 OK\r\n",
  519. "HTTP/1.2 200 OK\r\n",
  520. "HTTP/1.1 20 OK\r\n",
  521. "HTTP/1.1 2000 OK\r\n",
  522. "HTTP/1.1 2x0 OK\r\n",
  523. "HTTP/1.1 200 OK\r\n",
  524. "HTTP/1.1 200OK\r\n",
  525. "HTTP/1.1 200 O\rK\r\n",
  526. "HTTP/1.1 200 OK",
  527. "HTTP/1.1 200 OK\r\nX",
  528. "",
  529. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  530. "HTTP/1.1 200 OK\n",
  531. #endif
  532. };
  533. for (auto line : lines) {
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  538. << line;
  539. }
  540. }
  541. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  542. // Long enough to overflow the stack when matched with std::regex.
  543. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  544. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  545. std::string version;
  546. int status = 0;
  547. std::string reason;
  548. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  549. EXPECT_EQ(200, status);
  550. EXPECT_EQ(long_reason, reason);
  551. }
  552. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  553. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  554. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  555. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  556. EXPECT_EQ("", detail::file_extension("noext"));
  557. EXPECT_EQ("", detail::file_extension("a."));
  558. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  559. EXPECT_EQ("", detail::file_extension("a.b-c"));
  560. // Long enough to overflow the stack when matched with std::regex.
  561. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  562. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  563. }
  564. #ifdef CPPHTTPLIB_SSL_ENABLED
  565. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  566. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  567. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  569. // A wildcard needs two labels after it, in the leftmost label only
  570. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  571. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  572. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  573. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  574. EXPECT_FALSE(
  575. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  576. // No name may have an empty label
  577. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  578. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  579. }
  580. #endif
  581. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  582. detail::case_ignore::hash hash;
  583. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  584. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  585. // Long enough to overflow the stack if hashed one call per character.
  586. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  587. }
  588. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  589. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  590. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  591. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  592. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  593. // Same 26-bit hash as html, svg and js.
  594. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  595. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  597. }
  598. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  599. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  600. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  601. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  602. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  603. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  604. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  605. // Same 26-bit hash as application/json.
  606. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  607. }
  608. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  609. Request req;
  610. req.set_header("Content-Type", "Multipart/Form-Data; boundary=x");
  611. EXPECT_TRUE(req.is_multipart_form_data());
  612. }
  613. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  614. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  615. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  616. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  617. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  618. // Same 26-bit hash as REMOTE_ADDR.
  619. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  620. }
  621. // Forward declaration: in split builds split.py strips `inline` and moves the
  622. // definition into httplib.cc, so detail::base64_encode is not visible from the
  623. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  624. // in both header-only and split builds.
  625. namespace httplib {
  626. namespace detail {
  627. std::string base64_encode(const std::string &in);
  628. } // namespace detail
  629. } // namespace httplib
  630. TEST(Base64EncodeTest, KnownAnswers) {
  631. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  632. // where the accumulator's top bit is already set before the next shift.
  633. EXPECT_EQ("", detail::base64_encode(""));
  634. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  635. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  636. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  637. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  638. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  639. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  640. // High bytes keep the top bit set across several rounds.
  641. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  642. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  643. }
  644. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  645. string unescapedCharacters = "-_.!~*'()";
  646. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  647. }
  648. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  649. string reservedCharacters = ";,/?:@&=+$";
  650. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  651. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  652. }
  653. TEST(ClientQueryOrder, PreserveOrder) {
  654. // This test reproduces Issue #2259: client may reorder query parameters
  655. // when sending a GET request. The expected behavior is that the client
  656. // preserves the original query string order when the caller supplied it
  657. // as part of the path.
  658. Server svr;
  659. svr.Get("/", [&](const Request &req, Response &res) {
  660. // Echo back the raw target so the test can assert ordering
  661. res.set_content(req.target, "text/plain");
  662. });
  663. std::thread t{[&] { svr.listen(HOST, PORT); }};
  664. auto se = detail::scope_exit([&] {
  665. svr.stop();
  666. t.join();
  667. ASSERT_FALSE(svr.is_running());
  668. });
  669. svr.wait_until_ready();
  670. Client cli(HOST, PORT);
  671. ASSERT_TRUE(cli.is_valid());
  672. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  673. auto res = cli.Get(original);
  674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  675. // Expect the echoed target to exactly match the original path (order
  676. // preserved)
  677. EXPECT_EQ(res->body, original);
  678. }
  679. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  680. string chineseCharacters = U8("中国語");
  681. string russianCharacters = U8("дом");
  682. string brazilianCharacters = U8("óculos");
  683. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  684. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  685. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  686. "%D0%B4%D0%BE%D0%BC");
  687. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  688. }
  689. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  690. string unescapedCharacters = "-_.!~*'()";
  691. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  692. }
  693. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  694. string reservedCharacters = ";,/?:@&=+$";
  695. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  696. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  697. }
  698. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  699. string chineseCharacters = U8("中国語");
  700. string russianCharacters = U8("дом");
  701. string brazilianCharacters = U8("óculos");
  702. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  703. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  704. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  705. "%D0%B4%D0%BE%D0%BC");
  706. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  707. }
  708. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  709. // Issue #2082 use case: encoding path component with ampersand
  710. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  711. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  712. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  713. }
  714. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  715. string unescapedCharacters = "-_.!~*'()";
  716. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  717. }
  718. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  719. string reservedCharacters = ";,/?:@&=+$#";
  720. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  721. }
  722. TEST(EncodeUriTest, TestUTF8Characters) {
  723. string chineseCharacters = U8("中国語");
  724. string russianCharacters = U8("дом");
  725. string brazilianCharacters = U8("óculos");
  726. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  727. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  728. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  729. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  730. }
  731. TEST(EncodeUriTest, TestCompleteUri) {
  732. string uri =
  733. "https://example.com/path/to/resource?query=value&param=test#fragment";
  734. EXPECT_EQ(
  735. httplib::encode_uri(uri),
  736. "https://example.com/path/to/resource?query=value&param=test#fragment");
  737. }
  738. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  739. string uri =
  740. "https://example.com/path with spaces/file name.html?q=hello world";
  741. EXPECT_EQ(httplib::encode_uri(uri),
  742. "https://example.com/path%20with%20spaces/"
  743. "file%20name.html?q=hello%20world");
  744. }
  745. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  746. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  747. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  748. }
  749. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  750. string unescapedCharacters = "-_.!~*'()";
  751. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  752. }
  753. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  754. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  755. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  756. string encodedBrazilian = "%C3%B3culos";
  757. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  758. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  759. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  760. }
  761. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  762. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  763. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  764. "Piri Tommy Villiers - on & on");
  765. }
  766. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  767. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  768. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  769. }
  770. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  771. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  772. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  773. }
  774. TEST(DecodeUriTest, TestUTF8Characters) {
  775. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  776. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  777. string encodedBrazilian = "%C3%B3culos";
  778. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  779. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  780. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  781. }
  782. TEST(DecodeUriTest, TestCompleteUri) {
  783. string encodedUri = "https://example.com/path%20with%20spaces/"
  784. "file%20name.html?q=hello%20world";
  785. EXPECT_EQ(
  786. httplib::decode_uri(encodedUri),
  787. "https://example.com/path with spaces/file name.html?q=hello world");
  788. }
  789. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  790. string original =
  791. "https://example.com/path with spaces/file name.html?q=hello world";
  792. string encoded = httplib::encode_uri(original);
  793. string decoded = httplib::decode_uri(encoded);
  794. EXPECT_EQ(decoded, original);
  795. }
  796. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  797. // decode_uri is the inverse of encode_uri: an escaped reserved character
  798. // stays encoded so it is not promoted into a real delimiter, while
  799. // non-reserved escapes still decode (like JS decodeURI).
  800. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  801. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  802. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  803. "%3F%3A%40%26%3D%2B%24%2C%3B");
  804. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  805. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  806. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  807. "http://example.com/a%2Fb");
  808. // decode_uri_component still decodes the reserved character.
  809. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  810. }
  811. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  812. string original = "Piri Tommy Villiers - on & on";
  813. string encoded = httplib::encode_uri_component(original);
  814. string decoded = httplib::decode_uri_component(encoded);
  815. EXPECT_EQ(decoded, original);
  816. }
  817. TEST(TrimTests, TrimStringTests) {
  818. EXPECT_EQ("abc", detail::trim_copy("abc"));
  819. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  820. EXPECT_TRUE(detail::trim_copy("").empty());
  821. }
  822. TEST(AsciiTest, LocaleIndependentClassification) {
  823. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  824. // which consult the global C locale: std::isalnum(0xC5) can return true
  825. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  826. // helpers must classify every byte by the ASCII grammar alone.
  827. for (int i = 0; i < 256; i++) {
  828. auto c = static_cast<char>(i);
  829. auto is_digit = i >= '0' && i <= '9';
  830. auto is_upper = i >= 'A' && i <= 'Z';
  831. auto is_lower = i >= 'a' && i <= 'z';
  832. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  833. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  834. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  835. << "byte " << i;
  836. }
  837. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  838. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  839. // Non-ASCII bytes must be percent-encoded, never passed through as
  840. // alphanumeric.
  841. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  842. }
  843. TEST(FromCharsTest, Double) {
  844. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  845. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  846. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  847. auto parse = [](const std::string &s, double &v) {
  848. return detail::from_chars(s.data(), s.data() + s.size(), v);
  849. };
  850. double v = -1.0;
  851. // Representative quality values.
  852. EXPECT_EQ(parse("0", v).ec, std::errc{});
  853. EXPECT_DOUBLE_EQ(v, 0.0);
  854. EXPECT_EQ(parse("1", v).ec, std::errc{});
  855. EXPECT_DOUBLE_EQ(v, 1.0);
  856. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 0.8);
  858. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  859. EXPECT_DOUBLE_EQ(v, 0.001);
  860. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 1.0);
  862. // A missing integer or fractional part is tolerated.
  863. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.5);
  865. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 5.0);
  867. // Values outside [0, 1] still parse; the caller range-checks them.
  868. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 123.456);
  870. // Stops at the first byte that is not part of the number and reports where.
  871. std::string trailing = "0.9, text/html";
  872. auto r = parse(trailing, v);
  873. EXPECT_EQ(r.ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 0.9);
  875. EXPECT_EQ(*r.ptr, ',');
  876. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  877. // outright, and an 'e'/'E' simply ends the number.
  878. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  879. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  880. std::string exp_input = "1.5e3";
  881. r = parse(exp_input, v);
  882. EXPECT_EQ(r.ec, std::errc{});
  883. EXPECT_DOUBLE_EQ(v, 1.5);
  884. EXPECT_EQ(*r.ptr, 'e');
  885. // Invalid inputs.
  886. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  887. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  888. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  889. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  890. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  891. // Pathological but well-formed inputs must stay bounded (no overflow, no
  892. // out-of-bounds table access) and stay within [0, 1] for the caller.
  893. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  894. std::errc{});
  895. EXPECT_DOUBLE_EQ(v, 0.0);
  896. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  897. std::errc{});
  898. EXPECT_GE(v, 0.0);
  899. EXPECT_LE(v, 1.0);
  900. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  901. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  902. }
  903. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  904. // Simple case without quality values
  905. std::vector<std::string> result1;
  906. EXPECT_TRUE(detail::parse_accept_header(
  907. "text/html,application/json,text/plain", result1));
  908. EXPECT_EQ(result1.size(), 3U);
  909. EXPECT_EQ(result1[0], "text/html");
  910. EXPECT_EQ(result1[1], "application/json");
  911. EXPECT_EQ(result1[2], "text/plain");
  912. // With quality values
  913. std::vector<std::string> result2;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  916. EXPECT_EQ(result2.size(), 3U);
  917. EXPECT_EQ(result2[0], "application/json"); // highest q value
  918. EXPECT_EQ(result2[1], "text/html");
  919. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  920. }
  921. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  922. // Mixed with and without quality values
  923. std::vector<std::string> result;
  924. EXPECT_TRUE(detail::parse_accept_header(
  925. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  926. EXPECT_EQ(result.size(), 3U);
  927. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  928. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  929. EXPECT_EQ(result[2], "application/json"); // q=0.5
  930. }
  931. TEST(ParseAcceptHeaderTest, EdgeCases) {
  932. // Empty header
  933. std::vector<std::string> empty_result;
  934. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  935. EXPECT_TRUE(empty_result.empty());
  936. // Single type
  937. std::vector<std::string> single_result;
  938. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  939. EXPECT_EQ(single_result.size(), 1U);
  940. EXPECT_EQ(single_result[0], "application/json");
  941. // Wildcard types
  942. std::vector<std::string> wildcard_result;
  943. EXPECT_TRUE(detail::parse_accept_header(
  944. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  945. EXPECT_EQ(wildcard_result.size(), 3U);
  946. EXPECT_EQ(wildcard_result[0], "application/json");
  947. EXPECT_EQ(wildcard_result[1], "text/*");
  948. EXPECT_EQ(wildcard_result[2], "*/*");
  949. }
  950. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  951. // Common browser Accept header
  952. std::vector<std::string> browser_result;
  953. EXPECT_TRUE(
  954. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  955. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  956. browser_result));
  957. EXPECT_EQ(browser_result.size(), 6U);
  958. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  959. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  960. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  961. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  962. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  963. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  964. // API client header
  965. std::vector<std::string> api_result;
  966. EXPECT_TRUE(detail::parse_accept_header(
  967. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  968. api_result));
  969. EXPECT_EQ(api_result.size(), 3U);
  970. EXPECT_EQ(api_result[0], "application/json");
  971. EXPECT_EQ(api_result[1], "application/xml");
  972. EXPECT_EQ(api_result[2], "text/plain");
  973. }
  974. TEST(ParseAcceptHeaderTest, SpecialCases) {
  975. // Quality value with 3 decimal places
  976. std::vector<std::string> decimal_result;
  977. EXPECT_TRUE(detail::parse_accept_header(
  978. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  979. EXPECT_EQ(decimal_result.size(), 2U);
  980. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  981. EXPECT_EQ(decimal_result[1], "text/html");
  982. // Zero quality (should still be included but with lowest priority)
  983. std::vector<std::string> zero_q_result;
  984. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  985. zero_q_result));
  986. EXPECT_EQ(zero_q_result.size(), 2U);
  987. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  988. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  989. // No spaces around commas
  990. std::vector<std::string> no_space_result;
  991. EXPECT_TRUE(detail::parse_accept_header(
  992. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  993. no_space_result));
  994. EXPECT_EQ(no_space_result.size(), 3U);
  995. EXPECT_EQ(no_space_result[0], "text/html");
  996. EXPECT_EQ(no_space_result[1], "application/json");
  997. EXPECT_EQ(no_space_result[2], "text/plain");
  998. }
  999. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1000. // Quality values always use '.' as the decimal separator, so parsing must
  1001. // not depend on the process locale. An embedding application may have
  1002. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1003. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1004. std::string saved = cur ? cur : "C";
  1005. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1006. "fr_FR.UTF-8"};
  1007. bool switched = false;
  1008. for (const auto loc : comma_locales) {
  1009. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1010. std::localeconv()->decimal_point[0] == ',') {
  1011. switched = true;
  1012. break;
  1013. }
  1014. }
  1015. if (!switched) {
  1016. std::setlocale(LC_NUMERIC, saved.c_str());
  1017. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1018. }
  1019. // The higher-weighted type appears later in the list, so a correct parse
  1020. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1021. // sensitive parse reads both weights as 0 and leaves the original order.
  1022. std::vector<std::string> result;
  1023. EXPECT_TRUE(detail::parse_accept_header(
  1024. "application/json;q=0.1,text/html;q=0.9", result));
  1025. ASSERT_EQ(result.size(), 2U);
  1026. EXPECT_EQ(result[0], "text/html");
  1027. EXPECT_EQ(result[1], "application/json");
  1028. std::setlocale(LC_NUMERIC, saved.c_str());
  1029. }
  1030. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1031. std::vector<std::string> result;
  1032. // Invalid quality value (> 1.0)
  1033. EXPECT_FALSE(
  1034. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1035. // Invalid quality value (< 0.0)
  1036. EXPECT_FALSE(
  1037. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1038. // Invalid quality value (not a number)
  1039. EXPECT_FALSE(detail::parse_accept_header(
  1040. "text/html;q=invalid,application/json", result));
  1041. // A valid numeric prefix does not make the entire quality value valid.
  1042. EXPECT_FALSE(detail::parse_accept_header(
  1043. "text/html;q=0.5junk,application/json", result));
  1044. // Empty quality value
  1045. EXPECT_FALSE(
  1046. detail::parse_accept_header("text/html;q=,application/json", result));
  1047. // Invalid media type format (no slash and not wildcard)
  1048. EXPECT_FALSE(
  1049. detail::parse_accept_header("invalidtype,application/json", result));
  1050. // Valid cases should still work
  1051. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1052. EXPECT_EQ(result.size(), 1U);
  1053. EXPECT_EQ(result[0], "*/*");
  1054. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1055. EXPECT_EQ(result.size(), 1U);
  1056. EXPECT_EQ(result[0], "*");
  1057. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1058. EXPECT_EQ(result.size(), 1U);
  1059. EXPECT_EQ(result[0], "text/*");
  1060. }
  1061. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1062. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1063. // and must not be answered with 400 Bad Request.
  1064. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1065. struct {
  1066. const char *value;
  1067. std::vector<std::string> expected;
  1068. } cases[] = {
  1069. {",application/json", {"application/json"}},
  1070. {"text/html,", {"text/html"}},
  1071. {"text/html,,*/*", {"text/html", "*/*"}},
  1072. // An empty element may be spelled with whitespace in it
  1073. {"text/html, , application/json", {"text/html", "application/json"}},
  1074. // Nothing but empty elements is an empty list, which means the same
  1075. // thing as no Accept header at all
  1076. {",,,", {}},
  1077. // Quality values still apply across ignored empty elements
  1078. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1079. };
  1080. for (const auto &c : cases) {
  1081. std::vector<std::string> result;
  1082. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1083. << "value: " << c.value;
  1084. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1085. }
  1086. // An invalid entry is still rejected when empty elements surround it
  1087. std::vector<std::string> result;
  1088. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1089. }
  1090. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1091. // or ';' inside one does not end the list element or the parameter. Section
  1092. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1093. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1094. struct {
  1095. const char *value;
  1096. std::vector<std::string> expected;
  1097. } cases[] = {
  1098. {"text/html;profile=\"a,b\",application/json",
  1099. {"text/html", "application/json"}},
  1100. // A "q=" inside a quoted value is not the weight
  1101. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1102. {"text/html", "application/json"}},
  1103. // The weight after a quoted value still applies
  1104. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1105. {"application/json", "text/html"}},
  1106. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1107. {"application/json", "text/html"}},
  1108. {"text/html;profile=\"a\\\"b\",application/json",
  1109. {"text/html", "application/json"}},
  1110. // An escaped backslash does not escape the '"' after it
  1111. {"text/html;profile=\"a\\\\\",application/json",
  1112. {"text/html", "application/json"}},
  1113. };
  1114. for (const auto &c : cases) {
  1115. std::vector<std::string> result;
  1116. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1117. << "value: " << c.value;
  1118. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1119. }
  1120. }
  1121. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1122. Server svr;
  1123. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1124. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1125. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1126. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1127. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1128. res.set_content("ok", "text/plain");
  1129. });
  1130. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1131. EXPECT_TRUE(false);
  1132. res.set_content("bad request", "text/plain");
  1133. });
  1134. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1135. auto se = detail::scope_exit([&] {
  1136. svr.stop();
  1137. listen_thread.join();
  1138. ASSERT_FALSE(svr.is_running());
  1139. });
  1140. svr.wait_until_ready();
  1141. Client cli("localhost", PORT);
  1142. {
  1143. auto res = cli.Get(
  1144. "/accept_ok",
  1145. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1147. EXPECT_EQ(StatusCode::OK_200, res->status);
  1148. }
  1149. {
  1150. auto res = cli.Get("/accept_bad_request",
  1151. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1153. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1154. }
  1155. }
  1156. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1157. Server svr;
  1158. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1159. res.set_content("ok", "text/plain");
  1160. });
  1161. std::atomic<int> start_count{0};
  1162. std::atomic<bool> running_when_called{false};
  1163. svr.set_start_handler([&]() {
  1164. running_when_called = svr.is_running();
  1165. start_count++;
  1166. });
  1167. auto port = svr.bind_to_any_port(HOST);
  1168. std::thread t([&]() { svr.listen_after_bind(); });
  1169. auto se = detail::scope_exit([&] {
  1170. svr.stop();
  1171. t.join();
  1172. ASSERT_FALSE(svr.is_running());
  1173. });
  1174. svr.wait_until_ready();
  1175. // A successful request proves the accept loop is running, which the start
  1176. // handler precedes; so by now the handler must have run exactly once.
  1177. Client cli(HOST, port);
  1178. cli.set_connection_timeout(std::chrono::seconds(5));
  1179. auto res = cli.Get("/");
  1180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1181. EXPECT_EQ(StatusCode::OK_200, res->status);
  1182. EXPECT_EQ(1, start_count.load());
  1183. EXPECT_TRUE(running_when_called.load());
  1184. }
  1185. TEST(DivideTest, DivideStringTests) {
  1186. auto divide = [](const std::string &str, char d) {
  1187. std::string lhs;
  1188. std::string rhs;
  1189. detail::divide(str, d,
  1190. [&](const char *lhs_data, std::size_t lhs_size,
  1191. const char *rhs_data, std::size_t rhs_size) {
  1192. lhs.assign(lhs_data, lhs_size);
  1193. rhs.assign(rhs_data, rhs_size);
  1194. });
  1195. return std::make_pair(std::move(lhs), std::move(rhs));
  1196. };
  1197. {
  1198. const auto res = divide("", '=');
  1199. EXPECT_EQ(res.first, "");
  1200. EXPECT_EQ(res.second, "");
  1201. }
  1202. {
  1203. const auto res = divide("=", '=');
  1204. EXPECT_EQ(res.first, "");
  1205. EXPECT_EQ(res.second, "");
  1206. }
  1207. {
  1208. const auto res = divide(" ", '=');
  1209. EXPECT_EQ(res.first, " ");
  1210. EXPECT_EQ(res.second, "");
  1211. }
  1212. {
  1213. const auto res = divide("a", '=');
  1214. EXPECT_EQ(res.first, "a");
  1215. EXPECT_EQ(res.second, "");
  1216. }
  1217. {
  1218. const auto res = divide("a=", '=');
  1219. EXPECT_EQ(res.first, "a");
  1220. EXPECT_EQ(res.second, "");
  1221. }
  1222. {
  1223. const auto res = divide("=b", '=');
  1224. EXPECT_EQ(res.first, "");
  1225. EXPECT_EQ(res.second, "b");
  1226. }
  1227. {
  1228. const auto res = divide("a=b", '=');
  1229. EXPECT_EQ(res.first, "a");
  1230. EXPECT_EQ(res.second, "b");
  1231. }
  1232. {
  1233. const auto res = divide("a=b=", '=');
  1234. EXPECT_EQ(res.first, "a");
  1235. EXPECT_EQ(res.second, "b=");
  1236. }
  1237. {
  1238. const auto res = divide("a=b=c", '=');
  1239. EXPECT_EQ(res.first, "a");
  1240. EXPECT_EQ(res.second, "b=c");
  1241. }
  1242. }
  1243. TEST(SplitTest, ParseQueryString) {
  1244. string s = "key1=val1&key2=val2&key3=val3";
  1245. Params dic;
  1246. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1247. [&](const char *b, const char *e) {
  1248. string key, val;
  1249. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1250. if (key.empty()) {
  1251. key.assign(b2, e2);
  1252. } else {
  1253. val.assign(b2, e2);
  1254. }
  1255. });
  1256. dic.emplace(key, val);
  1257. });
  1258. EXPECT_EQ("val1", dic.find("key1")->second);
  1259. EXPECT_EQ("val2", dic.find("key2")->second);
  1260. EXPECT_EQ("val3", dic.find("key3")->second);
  1261. }
  1262. TEST(SplitTest, ParseInvalidQueryTests) {
  1263. {
  1264. string s = " ";
  1265. Params dict;
  1266. detail::parse_query_text(s, dict);
  1267. EXPECT_TRUE(dict.empty());
  1268. }
  1269. {
  1270. string s = " = =";
  1271. Params dict;
  1272. detail::parse_query_text(s, dict);
  1273. EXPECT_TRUE(dict.empty());
  1274. }
  1275. }
  1276. TEST(ParseQueryTest, ParseQueryString) {
  1277. {
  1278. std::string s = "key1=val1&key2=val2&key3=val3";
  1279. Params dic;
  1280. detail::parse_query_text(s, dic);
  1281. EXPECT_EQ("val1", dic.find("key1")->second);
  1282. EXPECT_EQ("val2", dic.find("key2")->second);
  1283. EXPECT_EQ("val3", dic.find("key3")->second);
  1284. }
  1285. {
  1286. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1287. Params dic;
  1288. detail::parse_query_text(s, dic);
  1289. EXPECT_EQ("", dic.find("key1")->second);
  1290. EXPECT_EQ("val1", dic.find("key2")->second);
  1291. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1292. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1293. }
  1294. }
  1295. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1296. Params dic;
  1297. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1298. dic.emplace("key1", "val1");
  1299. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1300. dic.emplace("key2", "val2");
  1301. dic.emplace("key3", "val3");
  1302. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1303. }
  1304. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1305. Params params;
  1306. params.emplace("a", "1");
  1307. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1308. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1309. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1310. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1311. // Long enough to overflow the stack when matched with std::regex.
  1312. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1313. EXPECT_EQ("/p?" + long_query + "&a=1",
  1314. append_query_params("/p?" + long_query, params));
  1315. }
  1316. // Joins every entry of a Headers or Params into "key=value " so a whole
  1317. // traversal can be compared in one assertion. Both are instantiations of the
  1318. // same insertion-ordered container, so one helper serves both.
  1319. template <typename Map> static std::string entries_to_string(const Map &m) {
  1320. std::string s;
  1321. for (const auto &entry : m) {
  1322. s += entry.first + "=" + entry.second + " ";
  1323. }
  1324. return s;
  1325. }
  1326. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1327. // Params used to be a std::multimap, which sorted by name and handed the
  1328. // caller's query back alphabetised. A client signing its query string could
  1329. // not reproduce the order it asked for.
  1330. Params dic;
  1331. dic.emplace("zulu", "1");
  1332. dic.emplace("alpha", "2");
  1333. dic.emplace("mike", "3");
  1334. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1335. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1336. }
  1337. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1338. Params dic;
  1339. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1340. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1341. }
  1342. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1343. Request req;
  1344. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1345. req.params);
  1346. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1347. EXPECT_EQ("first", req.get_param_value("tag"));
  1348. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1349. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1350. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1351. EXPECT_EQ("", req.get_param_value("tag", 3));
  1352. }
  1353. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1354. // Params shares its container with Headers, which matches field names
  1355. // case-insensitively. Parameter names must not pick that up.
  1356. Params dic;
  1357. dic.emplace("Key", "upper");
  1358. dic.emplace("key", "lower");
  1359. EXPECT_EQ(2U, dic.size());
  1360. EXPECT_EQ(1U, dic.count("Key"));
  1361. EXPECT_EQ(1U, dic.count("key"));
  1362. EXPECT_EQ("upper", dic.find("Key")->second);
  1363. EXPECT_EQ("lower", dic.find("key")->second);
  1364. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1365. }
  1366. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1367. Server svr;
  1368. std::string order;
  1369. svr.Get("/order", [&](const Request &req, Response &res) {
  1370. order = entries_to_string(req.params);
  1371. res.set_content("ok", "text/plain");
  1372. });
  1373. auto port = svr.bind_to_any_port(HOST);
  1374. thread t = thread([&] { svr.listen_after_bind(); });
  1375. auto se = detail::scope_exit([&] {
  1376. svr.stop();
  1377. t.join();
  1378. ASSERT_FALSE(svr.is_running());
  1379. });
  1380. svr.wait_until_ready();
  1381. Client cli(HOST, port);
  1382. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1383. ASSERT_TRUE(res);
  1384. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1385. }
  1386. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1387. Server svr;
  1388. std::string field_order, file_order;
  1389. svr.Post("/order", [&](const Request &req, Response &res) {
  1390. for (const auto &field : req.form.fields) {
  1391. field_order += field.first + "=" + field.second.content + " ";
  1392. }
  1393. for (const auto &file : req.form.files) {
  1394. file_order += file.first + "=" + file.second.filename + " ";
  1395. }
  1396. res.set_content("ok", "text/plain");
  1397. });
  1398. auto port = svr.bind_to_any_port(HOST);
  1399. thread t = thread([&] { svr.listen_after_bind(); });
  1400. auto se = detail::scope_exit([&] {
  1401. svr.stop();
  1402. t.join();
  1403. ASSERT_FALSE(svr.is_running());
  1404. });
  1405. svr.wait_until_ready();
  1406. UploadFormDataItems items = {
  1407. {"zulu", "1", "", ""},
  1408. {"alpha", "2", "", ""},
  1409. {"mike", "3", "", ""},
  1410. {"zebra", "z", "z.txt", "text/plain"},
  1411. {"apple", "a", "a.txt", "text/plain"},
  1412. };
  1413. Client cli(HOST, port);
  1414. auto res = cli.Post("/order", items);
  1415. ASSERT_TRUE(res);
  1416. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1417. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1418. }
  1419. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1420. Server svr;
  1421. std::vector<std::string> values;
  1422. std::string first, second, out_of_range, order;
  1423. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1424. values = req.form.get_fields("tag");
  1425. first = req.form.get_field("tag", 0);
  1426. second = req.form.get_field("tag", 1);
  1427. out_of_range = req.form.get_field("tag", 2);
  1428. for (const auto &field : req.form.fields) {
  1429. order += field.first + "=" + field.second.content + " ";
  1430. }
  1431. res.set_content("ok", "text/plain");
  1432. });
  1433. auto port = svr.bind_to_any_port(HOST);
  1434. thread t = thread([&] { svr.listen_after_bind(); });
  1435. auto se = detail::scope_exit([&] {
  1436. svr.stop();
  1437. t.join();
  1438. ASSERT_FALSE(svr.is_running());
  1439. });
  1440. svr.wait_until_ready();
  1441. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1442. // not adjacent in the container.
  1443. UploadFormDataItems items = {
  1444. {"tag", "first", "", ""},
  1445. {"other", "x", "", ""},
  1446. {"tag", "second", "", ""},
  1447. };
  1448. Client cli(HOST, port);
  1449. auto res = cli.Post("/repeated", items);
  1450. ASSERT_TRUE(res);
  1451. ASSERT_EQ(2U, values.size());
  1452. EXPECT_EQ("first", values[0]);
  1453. EXPECT_EQ("second", values[1]);
  1454. EXPECT_EQ("first", first);
  1455. EXPECT_EQ("second", second);
  1456. // std::multimap already kept entries sharing a name in insertion order, so
  1457. // everything above passes without this change too. The whole traversal is
  1458. // what tells the two apart: sorting by name would hoist "other" to the front
  1459. // and the two "tag" parts would end up adjacent.
  1460. EXPECT_EQ("tag=first other=x tag=second ", order);
  1461. // Advancing past the last entry of a name used to run off the container;
  1462. // the container's saturating increment makes it return the default instead.
  1463. EXPECT_EQ("", out_of_range);
  1464. }
  1465. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1466. // Server::read_content() keeps a FormFields::iterator alive across the
  1467. // content callbacks that fill the part it points at. The container is
  1468. // vector-backed, so a later emplace can reallocate and invalidate an older
  1469. // iterator; 64 parts grow the vector through seven reallocations, which
  1470. // checks that every part's content still lands in its own entry.
  1471. const size_t part_count = 64;
  1472. // One formula for both the parts sent and the values expected back, so the
  1473. // two cannot drift apart.
  1474. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1475. auto content_of = [](size_t i) {
  1476. return std::string(64, static_cast<char>('a' + (i % 26)));
  1477. };
  1478. Server svr;
  1479. std::vector<std::pair<std::string, std::string>> received;
  1480. svr.Post("/many", [&](const Request &req, Response &res) {
  1481. for (const auto &field : req.form.fields) {
  1482. received.emplace_back(field.first, field.second.content);
  1483. }
  1484. res.set_content("ok", "text/plain");
  1485. });
  1486. auto port = svr.bind_to_any_port(HOST);
  1487. thread t = thread([&] { svr.listen_after_bind(); });
  1488. auto se = detail::scope_exit([&] {
  1489. svr.stop();
  1490. t.join();
  1491. ASSERT_FALSE(svr.is_running());
  1492. });
  1493. svr.wait_until_ready();
  1494. UploadFormDataItems items;
  1495. for (size_t i = 0; i < part_count; i++) {
  1496. items.push_back({name_of(i), content_of(i), "", ""});
  1497. }
  1498. Client cli(HOST, port);
  1499. auto res = cli.Post("/many", items);
  1500. ASSERT_TRUE(res);
  1501. ASSERT_EQ(part_count, received.size());
  1502. for (size_t i = 0; i < part_count; i++) {
  1503. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1504. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1505. }
  1506. }
  1507. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1508. string content_type = "multipart/form-data; boundary=something";
  1509. string boundary;
  1510. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1511. EXPECT_TRUE(ret);
  1512. EXPECT_EQ(boundary, "something");
  1513. }
  1514. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1515. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1516. string boundary;
  1517. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1518. EXPECT_TRUE(ret);
  1519. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1520. }
  1521. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1522. string content_type =
  1523. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1524. string boundary;
  1525. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1526. EXPECT_TRUE(ret);
  1527. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1528. }
  1529. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1530. string content_type =
  1531. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1532. string boundary;
  1533. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1534. EXPECT_TRUE(ret);
  1535. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1536. }
  1537. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1538. const string boundary(70, 'a');
  1539. string content_type = "multipart/form-data; boundary=" + boundary;
  1540. string parsed;
  1541. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1542. EXPECT_TRUE(ret);
  1543. EXPECT_EQ(parsed, boundary);
  1544. }
  1545. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1546. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1547. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1548. string parsed;
  1549. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1550. EXPECT_FALSE(ret);
  1551. }
  1552. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1553. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1554. // is 72 characters on the wire and still valid.
  1555. const string boundary(70, 'a');
  1556. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1557. string parsed;
  1558. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1559. EXPECT_EQ(parsed, boundary);
  1560. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1561. parsed.clear();
  1562. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1563. }
  1564. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1565. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1566. // The parameter parser must not treat that '=' as the key/value separator.
  1567. string content_type =
  1568. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1569. "charset=UTF-8";
  1570. string parsed;
  1571. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1572. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1573. }
  1574. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1575. // A ';' inside the quoted-string is part of the value, not a parameter
  1576. // separator, so it must not truncate the boundary.
  1577. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1578. string parsed;
  1579. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1580. EXPECT_EQ(parsed, "a;b");
  1581. }
  1582. TEST(ParseDispositionParamsTest, QuotedValues) {
  1583. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1584. // ';' and '=' are ordinary characters inside one.
  1585. struct {
  1586. const char *value;
  1587. std::vector<std::pair<const char *, const char *>> expected;
  1588. } cases[] = {
  1589. {"name=\"file1\"; filename=\"a.txt\"",
  1590. {{"name", "file1"}, {"filename", "a.txt"}}},
  1591. // Whitespace around '=' and ';' is still trimmed
  1592. {"name=\"file2\" ;filename = \"a.html\"",
  1593. {{"name", "file2"}, {"filename", "a.html"}}},
  1594. // '=' inside the value used to leave only the text after the last one
  1595. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1596. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1597. {"name=\"x=y\"", {{"name", "x=y"}}},
  1598. // ';' inside the value used to truncate the pair and leave a bogus one
  1599. {"name=\"file3\"; filename=\"a;b.txt\"",
  1600. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1601. // An unquoted value keeps working, and so does filename*
  1602. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1603. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1604. // A parameter with no key is dropped rather than turned into one whose
  1605. // key is the value
  1606. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1607. // An escaped quote does not end the value
  1608. {"name=\"a\\\"; filename=evil.php\"",
  1609. {{"name", "a\"; filename=evil.php"}}},
  1610. // Other backslashes, as in a Windows path, are kept
  1611. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1612. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1613. };
  1614. for (const auto &c : cases) {
  1615. Params params;
  1616. detail::parse_disposition_params(c.value, params);
  1617. for (const auto &kv : c.expected) {
  1618. auto it = params.find(kv.first);
  1619. ASSERT_NE(it, params.end())
  1620. << "value: " << c.value << ", key: " << kv.first;
  1621. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1622. }
  1623. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1624. }
  1625. }
  1626. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1627. Server svr;
  1628. std::string filename;
  1629. std::string content;
  1630. svr.Post("/upload", [&](const Request &req, Response &) {
  1631. const auto &file = req.form.get_file("file");
  1632. filename = file.filename;
  1633. content = file.content;
  1634. });
  1635. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1636. auto se = detail::scope_exit([&] {
  1637. svr.stop();
  1638. thread.join();
  1639. ASSERT_FALSE(svr.is_running());
  1640. });
  1641. svr.wait_until_ready();
  1642. std::string body = "--B\r\n"
  1643. "Content-Disposition: form-data; name=\"file\"; "
  1644. "filename=\"a.txt\"\r\n"
  1645. "Content-Type: text/plain\r\n"
  1646. "\r\n"
  1647. "hello\r\n"
  1648. "--B--\r\n";
  1649. Client cli(HOST, PORT);
  1650. auto res = cli.Post(
  1651. "/upload",
  1652. [&](size_t offset, DataSink &sink) {
  1653. if (offset < body.size()) {
  1654. sink.write(&body[offset], 1);
  1655. } else {
  1656. sink.done();
  1657. }
  1658. return true;
  1659. },
  1660. "multipart/form-data; boundary=B");
  1661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1662. EXPECT_EQ(StatusCode::OK_200, res->status);
  1663. EXPECT_EQ("a.txt", filename);
  1664. EXPECT_EQ("hello", content);
  1665. }
  1666. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1667. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1668. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1669. Server svr;
  1670. std::string field_value, file_name, file_filename;
  1671. bool has_field = false, has_file = false;
  1672. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1673. has_field = req.form.has_field("x=y");
  1674. field_value = req.form.get_field("x=y");
  1675. has_file = req.form.has_file("file1");
  1676. const auto &file = req.form.get_file("file1");
  1677. file_name = file.name;
  1678. file_filename = file.filename;
  1679. res.set_content("ok", "text/plain");
  1680. });
  1681. auto port = svr.bind_to_any_port(HOST);
  1682. thread t = thread([&] { svr.listen_after_bind(); });
  1683. auto se = detail::scope_exit([&] {
  1684. svr.stop();
  1685. t.join();
  1686. ASSERT_FALSE(svr.is_running());
  1687. });
  1688. svr.wait_until_ready();
  1689. UploadFormDataItems items = {
  1690. {"x=y", "field-value", "", ""},
  1691. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1692. };
  1693. Client cli(HOST, port);
  1694. auto res = cli.Post("/quoted", items);
  1695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1696. ASSERT_EQ(StatusCode::OK_200, res->status);
  1697. EXPECT_TRUE(has_field);
  1698. EXPECT_EQ("field-value", field_value);
  1699. EXPECT_TRUE(has_file);
  1700. EXPECT_EQ("file1", file_name);
  1701. EXPECT_EQ("a;b=report.pdf", file_filename);
  1702. }
  1703. TEST(GetHeaderValueTest, DefaultValue) {
  1704. Headers headers = {{"Dummy", "Dummy"}};
  1705. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1706. EXPECT_STREQ("text/plain", val);
  1707. }
  1708. TEST(GetHeaderValueTest, DefaultValueInt) {
  1709. Headers headers = {{"Dummy", "Dummy"}};
  1710. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1711. EXPECT_EQ(100ull, val);
  1712. }
  1713. TEST(GetHeaderValueTest, RegularValue) {
  1714. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1715. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1716. EXPECT_STREQ("text/html", val);
  1717. }
  1718. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1719. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1720. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1721. EXPECT_STREQ("text/html", val);
  1722. }
  1723. TEST(GetHeaderValueTest, SetContent) {
  1724. Response res;
  1725. res.set_content("html", "text/html");
  1726. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1727. res.set_content("text", "text/plain");
  1728. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1729. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1730. }
  1731. TEST(GetHeaderValueTest, RegularValueInt) {
  1732. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1733. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1734. EXPECT_EQ(100ull, val);
  1735. }
  1736. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1737. Headers headers = {{"Content-Length", "x"}};
  1738. auto is_invalid_value = false;
  1739. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1740. is_invalid_value);
  1741. EXPECT_EQ(0ull, val);
  1742. EXPECT_TRUE(is_invalid_value);
  1743. }
  1744. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1745. // An all-digit value that overflows size_t must be reported as invalid, not
  1746. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1747. // a large length to a small one on 32-bit builds, leaving the framing length
  1748. // wrong while is_invalid_value stayed false.
  1749. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1750. auto is_invalid_value = false;
  1751. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1752. is_invalid_value);
  1753. EXPECT_TRUE(is_invalid_value);
  1754. // A well-formed length is unaffected.
  1755. Headers ok = {{"Content-Length", "1234"}};
  1756. is_invalid_value = false;
  1757. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1758. is_invalid_value);
  1759. EXPECT_EQ(1234ull, val);
  1760. EXPECT_FALSE(is_invalid_value);
  1761. }
  1762. TEST(GetHeaderValueTest, Range) {
  1763. {
  1764. Headers headers = {make_range_header({{1, -1}})};
  1765. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1766. EXPECT_STREQ("bytes=1-", val);
  1767. }
  1768. {
  1769. Headers headers = {make_range_header({{-1, 1}})};
  1770. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1771. EXPECT_STREQ("bytes=-1", val);
  1772. }
  1773. {
  1774. Headers headers = {make_range_header({{1, 10}})};
  1775. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1776. EXPECT_STREQ("bytes=1-10", val);
  1777. }
  1778. {
  1779. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1780. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1781. EXPECT_STREQ("bytes=1-10, 100-", val);
  1782. }
  1783. {
  1784. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1785. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1786. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1787. }
  1788. {
  1789. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1790. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1791. EXPECT_STREQ("bytes=0-0, -1", val);
  1792. }
  1793. }
  1794. TEST(BearerTokenAuthTest, SchemeValidation) {
  1795. // A value shorter than "Bearer " must not throw from the fixed-length
  1796. // substr, and a non-Bearer scheme must not be reported as a token.
  1797. struct {
  1798. const char *value;
  1799. const char *expected;
  1800. } cases[] = {
  1801. {"x", ""},
  1802. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1803. {"Bearer abc123", "abc123"},
  1804. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1805. };
  1806. for (const auto &c : cases) {
  1807. Request req;
  1808. req.set_header("Authorization", c.value);
  1809. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1810. }
  1811. }
  1812. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1813. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1814. // to depend on the standard library (libstdc++ handed back duplicates in
  1815. // reverse insertion order, libc++ in insertion order).
  1816. Request req;
  1817. req.set_header("Accept-Encoding", "gzip");
  1818. req.set_header("Accept-Encoding", "deflate");
  1819. req.set_header("Accept-Encoding", "br");
  1820. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1821. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1822. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1823. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1824. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1825. }
  1826. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1827. Request req;
  1828. req.set_header("X-Test", "only");
  1829. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1830. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1831. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1832. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1833. }
  1834. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1835. Request req;
  1836. req.set_header("X-First", "1");
  1837. req.set_header("X-Test", "2");
  1838. req.params.emplace("first", "1");
  1839. req.params.emplace("test", "2");
  1840. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1841. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1842. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1843. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1844. // The second one is negative when read as a signed value
  1845. const auto max_id = (std::numeric_limits<size_t>::max)();
  1846. for (auto id : {max_id / 2, max_id}) {
  1847. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1848. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1849. EXPECT_EQ("", req.get_param_value("test", id));
  1850. EXPECT_EQ("", req.form.get_field("test", id));
  1851. EXPECT_EQ("", req.form.get_file("test", id).content);
  1852. }
  1853. }
  1854. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1855. Headers headers;
  1856. headers.emplace("Host", "example.com");
  1857. headers.emplace("Accept-Encoding", "gzip");
  1858. headers.emplace("User-Agent", "test");
  1859. headers.emplace("Accept-Encoding", "deflate");
  1860. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1861. "Accept-Encoding=deflate ",
  1862. entries_to_string(headers));
  1863. }
  1864. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1865. Headers headers = {{"Content-Type", "text/html"},
  1866. {"CONTENT-TYPE", "text/xml"}};
  1867. EXPECT_EQ(2U, headers.count("content-type"));
  1868. auto it = headers.find("content-type");
  1869. ASSERT_TRUE(it != headers.end());
  1870. EXPECT_EQ("text/html", it->second);
  1871. }
  1872. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1873. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1874. // drop only those fields and leave everything positioned between them.
  1875. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1876. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1877. auto rng = headers.equal_range("a");
  1878. headers.erase(rng.first, rng.second);
  1879. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1880. }
  1881. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1882. Headers headers = {
  1883. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1884. EXPECT_EQ(3U, headers.erase("A"));
  1885. EXPECT_EQ(0U, headers.count("A"));
  1886. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1887. }
  1888. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1889. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1890. headers.emplace_front("Host", "example.com");
  1891. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1892. entries_to_string(headers));
  1893. }
  1894. TEST(ParseHeaderValueTest, Range) {
  1895. {
  1896. Ranges ranges;
  1897. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1898. EXPECT_TRUE(ret);
  1899. EXPECT_EQ(1u, ranges.size());
  1900. EXPECT_EQ(1u, ranges[0].first);
  1901. EXPECT_EQ(-1, ranges[0].second);
  1902. }
  1903. {
  1904. Ranges ranges;
  1905. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1906. EXPECT_TRUE(ret);
  1907. EXPECT_EQ(1u, ranges.size());
  1908. EXPECT_EQ(-1, ranges[0].first);
  1909. EXPECT_EQ(1u, ranges[0].second);
  1910. }
  1911. {
  1912. Ranges ranges;
  1913. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1914. EXPECT_TRUE(ret);
  1915. EXPECT_EQ(1u, ranges.size());
  1916. EXPECT_EQ(1u, ranges[0].first);
  1917. EXPECT_EQ(10u, ranges[0].second);
  1918. }
  1919. {
  1920. Ranges ranges;
  1921. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1922. EXPECT_FALSE(ret);
  1923. }
  1924. {
  1925. Ranges ranges;
  1926. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1927. EXPECT_TRUE(ret);
  1928. EXPECT_EQ(2u, ranges.size());
  1929. EXPECT_EQ(1u, ranges[0].first);
  1930. EXPECT_EQ(10u, ranges[0].second);
  1931. EXPECT_EQ(100u, ranges[1].first);
  1932. EXPECT_EQ(-1, ranges[1].second);
  1933. }
  1934. {
  1935. Ranges ranges;
  1936. auto ret =
  1937. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1938. EXPECT_TRUE(ret);
  1939. EXPECT_EQ(3u, ranges.size());
  1940. EXPECT_EQ(1u, ranges[0].first);
  1941. EXPECT_EQ(10u, ranges[0].second);
  1942. EXPECT_EQ(100u, ranges[1].first);
  1943. EXPECT_EQ(200u, ranges[1].second);
  1944. EXPECT_EQ(300u, ranges[2].first);
  1945. EXPECT_EQ(400u, ranges[2].second);
  1946. }
  1947. {
  1948. Ranges ranges;
  1949. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1950. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1951. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1952. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1953. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1954. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1955. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1956. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1957. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1958. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1959. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1960. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1961. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1962. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1963. EXPECT_FALSE(
  1964. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1965. EXPECT_TRUE(ranges.empty());
  1966. }
  1967. {
  1968. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1969. // remainder of the representation, so it stays accepted.
  1970. Ranges ranges;
  1971. auto ret =
  1972. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1973. EXPECT_TRUE(ret);
  1974. ASSERT_EQ(1u, ranges.size());
  1975. EXPECT_EQ(0, ranges[0].first);
  1976. EXPECT_EQ(-1, ranges[0].second);
  1977. }
  1978. // RFC 9110 14.1: range unit names are case-insensitive.
  1979. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1980. Ranges ranges;
  1981. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1982. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1983. }
  1984. }
  1985. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1986. Request req;
  1987. req.set_header("Accept-Encoding", "gzip");
  1988. Response res;
  1989. res.set_header("Content-Type", "text/plain");
  1990. auto ret = detail::encoding_type(req, res);
  1991. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1992. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1993. #else
  1994. EXPECT_TRUE(ret == detail::EncodingType::None);
  1995. #endif
  1996. }
  1997. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1998. Request req;
  1999. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2000. Response res;
  2001. res.set_header("Content-Type", "text/plain");
  2002. auto ret = detail::encoding_type(req, res);
  2003. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2004. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2005. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2006. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2007. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2008. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2009. #else
  2010. EXPECT_TRUE(ret == detail::EncodingType::None);
  2011. #endif
  2012. }
  2013. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2014. Request req;
  2015. req.set_header("Accept-Encoding",
  2016. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2017. Response res;
  2018. res.set_header("Content-Type", "text/plain");
  2019. auto ret = detail::encoding_type(req, res);
  2020. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2021. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2022. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2023. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2024. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2025. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2026. #else
  2027. EXPECT_TRUE(ret == detail::EncodingType::None);
  2028. #endif
  2029. }
  2030. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2031. // All supported encodings rejected with q=0 should return None
  2032. Request req;
  2033. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2034. Response res;
  2035. res.set_header("Content-Type", "text/plain");
  2036. auto ret = detail::encoding_type(req, res);
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. }
  2039. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2040. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2041. Request req;
  2042. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2043. Response res;
  2044. res.set_header("Content-Type", "text/plain");
  2045. auto ret = detail::encoding_type(req, res);
  2046. EXPECT_TRUE(ret == detail::EncodingType::None);
  2047. }
  2048. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2049. Request req;
  2050. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2051. Response res;
  2052. res.set_header("Content-Type", "text/plain");
  2053. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2054. }
  2055. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2056. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2057. Request req;
  2058. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2059. Response res;
  2060. res.set_header("Content-Type", "text/plain");
  2061. auto ret = detail::encoding_type(req, res);
  2062. EXPECT_TRUE(ret == detail::EncodingType::None);
  2063. }
  2064. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2065. // RFC 7231: Accept-Encoding values are case-insensitive
  2066. Request req;
  2067. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2068. Response res;
  2069. res.set_header("Content-Type", "text/plain");
  2070. auto ret = detail::encoding_type(req, res);
  2071. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2072. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2073. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2074. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2075. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2076. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2077. #else
  2078. EXPECT_TRUE(ret == detail::EncodingType::None);
  2079. #endif
  2080. }
  2081. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2082. // q value should determine priority, not hardcoded order
  2083. Request req;
  2084. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2085. Response res;
  2086. res.set_header("Content-Type", "text/plain");
  2087. auto ret = detail::encoding_type(req, res);
  2088. // gzip has highest q=1.0, so it should be selected even though
  2089. // br and zstd are also supported
  2090. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2091. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2092. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2093. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2094. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2095. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2096. #else
  2097. EXPECT_TRUE(ret == detail::EncodingType::None);
  2098. #endif
  2099. }
  2100. TEST(BufferStreamTest, read) {
  2101. detail::BufferStream strm1;
  2102. Stream &strm = strm1;
  2103. EXPECT_EQ(5, strm.write("hello"));
  2104. char buf[512];
  2105. EXPECT_EQ(2, strm.read(buf, 2));
  2106. EXPECT_EQ('h', buf[0]);
  2107. EXPECT_EQ('e', buf[1]);
  2108. EXPECT_EQ(2, strm.read(buf, 2));
  2109. EXPECT_EQ('l', buf[0]);
  2110. EXPECT_EQ('l', buf[1]);
  2111. EXPECT_EQ(1, strm.read(buf, 1));
  2112. EXPECT_EQ('o', buf[0]);
  2113. EXPECT_EQ(0, strm.read(buf, 1));
  2114. }
  2115. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2116. auto host = "www.httpwatch.com";
  2117. auto ip = hosted_at(host);
  2118. EXPECT_EQ("23.96.13.243", ip);
  2119. std::vector<std::string> addrs;
  2120. hosted_at(host, addrs);
  2121. EXPECT_EQ(1u, addrs.size());
  2122. }
  2123. #if 0 // It depends on each test environment...
  2124. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2125. auto host = "www.youtube.com";
  2126. std::vector<std::string> addrs;
  2127. hosted_at(host, addrs);
  2128. EXPECT_EQ(20u, addrs.size());
  2129. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2130. EXPECT_TRUE(it != addrs.end());
  2131. }
  2132. #endif
  2133. class ChunkedEncodingTest : public ::testing::Test {
  2134. protected:
  2135. ChunkedEncodingTest()
  2136. : cli_(HOST, PORT)
  2137. #ifdef CPPHTTPLIB_SSL_ENABLED
  2138. ,
  2139. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2140. #endif
  2141. {
  2142. cli_.set_connection_timeout(2);
  2143. #ifdef CPPHTTPLIB_SSL_ENABLED
  2144. cli_.enable_server_certificate_verification(false);
  2145. #endif
  2146. }
  2147. virtual void SetUp() {
  2148. read_file("./image.jpg", image_data_);
  2149. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2150. res.set_content("Hello World!", "text/plain");
  2151. });
  2152. svr_.Get(
  2153. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2154. res.set_chunked_content_provider(
  2155. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2156. size_t remaining = image_data_.size() - offset;
  2157. if (remaining == 0) {
  2158. sink.done();
  2159. } else {
  2160. constexpr size_t CHUNK_SIZE = 1024;
  2161. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2162. sink.write(&image_data_[offset], send_size);
  2163. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2164. }
  2165. return true;
  2166. });
  2167. });
  2168. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2169. svr_.wait_until_ready();
  2170. }
  2171. virtual void TearDown() {
  2172. svr_.stop();
  2173. if (!request_threads_.empty()) {
  2174. std::this_thread::sleep_for(std::chrono::seconds(1));
  2175. for (auto &t : request_threads_) {
  2176. t.join();
  2177. }
  2178. }
  2179. t_.join();
  2180. }
  2181. #ifdef CPPHTTPLIB_SSL_ENABLED
  2182. SSLClient cli_;
  2183. SSLServer svr_;
  2184. #else
  2185. Client cli_;
  2186. Server svr_;
  2187. #endif
  2188. thread t_;
  2189. std::vector<thread> request_threads_;
  2190. std::string image_data_;
  2191. };
  2192. TEST_F(ChunkedEncodingTest, NormalGet) {
  2193. auto res = cli_.Get("/chunked");
  2194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2195. std::string out;
  2196. read_file("./image.jpg", out);
  2197. EXPECT_EQ(StatusCode::OK_200, res->status);
  2198. EXPECT_EQ(out, res->body);
  2199. }
  2200. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2201. std::string body;
  2202. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2203. body.append(data, data_length);
  2204. return true;
  2205. });
  2206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2207. std::string out;
  2208. read_file("./image.jpg", out);
  2209. EXPECT_EQ(StatusCode::OK_200, res->status);
  2210. EXPECT_EQ(out, body);
  2211. }
  2212. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2213. std::string body;
  2214. auto res = cli_.Get(
  2215. "/chunked",
  2216. [&](const Response &response) {
  2217. EXPECT_EQ(StatusCode::OK_200, response.status);
  2218. return true;
  2219. },
  2220. [&](const char *data, size_t data_length) {
  2221. body.append(data, data_length);
  2222. return true;
  2223. });
  2224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2225. std::string out;
  2226. read_file("./image.jpg", out);
  2227. EXPECT_EQ(StatusCode::OK_200, res->status);
  2228. EXPECT_EQ(out, body);
  2229. }
  2230. TEST(RangeTest, FromHTTPBin_Online) {
  2231. auto host = "httpbingo.org";
  2232. auto path = std::string{"/range/32"};
  2233. #ifdef CPPHTTPLIB_SSL_ENABLED
  2234. auto port = 443;
  2235. SSLClient cli(host, port);
  2236. #else
  2237. auto port = 80;
  2238. Client cli(host, port);
  2239. #endif
  2240. cli.set_connection_timeout(5);
  2241. {
  2242. auto res = cli.Get(path);
  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. {
  2248. Headers headers = {make_range_header({{1, -1}})};
  2249. auto res = cli.Get(path, headers);
  2250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2251. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2252. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2253. }
  2254. {
  2255. Headers headers = {make_range_header({{1, 10}})};
  2256. auto res = cli.Get(path, headers);
  2257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2258. EXPECT_EQ("bcdefghijk", res->body);
  2259. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2260. }
  2261. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2262. // entire resource, while the original httpbin returned 200. Both are
  2263. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2264. {
  2265. Headers headers = {make_range_header({{0, 31}})};
  2266. auto res = cli.Get(path, headers);
  2267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2268. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2269. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2270. res->status == StatusCode::PartialContent_206);
  2271. }
  2272. {
  2273. Headers headers = {make_range_header({{0, -1}})};
  2274. auto res = cli.Get(path, headers);
  2275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2276. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2277. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2278. res->status == StatusCode::PartialContent_206);
  2279. }
  2280. // go-httpbin returns 206 with clamped range for over-range requests,
  2281. // while the original httpbin returned 416. Both behaviors are observed
  2282. // in real servers, so we only verify the request succeeds.
  2283. {
  2284. Headers headers = {make_range_header({{0, 32}})};
  2285. auto res = cli.Get(path, headers);
  2286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2287. }
  2288. }
  2289. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2290. auto host = "unresolvableaddress.local";
  2291. auto path = std::string{"/"};
  2292. #ifdef CPPHTTPLIB_SSL_ENABLED
  2293. auto port = 443;
  2294. SSLClient cli(host, port);
  2295. #else
  2296. auto port = 80;
  2297. Client cli(host, port);
  2298. #endif
  2299. cli.set_connection_timeout(1);
  2300. {
  2301. auto res = cli.Get(path);
  2302. ASSERT_FALSE(res);
  2303. }
  2304. std::this_thread::sleep_for(std::chrono::seconds(8));
  2305. }
  2306. #if defined(__linux__) && defined(__GLIBC__) && \
  2307. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2308. // Forward declaration: in split builds split.py strips `inline` and moves the
  2309. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2310. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2311. // against the symbol in both header-only and split builds.
  2312. namespace httplib {
  2313. namespace detail {
  2314. int getaddrinfo_with_timeout(const char *node, const char *service,
  2315. const struct addrinfo *hints,
  2316. struct addrinfo **res, time_t timeout_sec);
  2317. } // namespace detail
  2318. } // namespace httplib
  2319. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2320. //
  2321. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2322. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2323. // gai_suspend() call hits the connection timeout the function calls
  2324. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2325. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2326. // still alive and still references the now-destroyed stack frame.
  2327. //
  2328. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2329. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2330. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2331. // and runs them in a container.
  2332. namespace {
  2333. bool should_run_issue_2431_tests() {
  2334. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2335. return v && *v && std::string(v) != "0";
  2336. }
  2337. std::string unique_unresolvable_host(int n) {
  2338. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2339. // glibc still asks the configured nameserver — which is exactly the path
  2340. // we want to exercise. A unique label per call avoids the resolver cache.
  2341. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2342. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2343. std::to_string(n) + ".invalid";
  2344. }
  2345. } // namespace
  2346. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2347. if (!should_run_issue_2431_tests()) {
  2348. GTEST_SKIP()
  2349. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2350. }
  2351. for (int i = 0; i < 8; ++i) {
  2352. struct addrinfo hints;
  2353. memset(&hints, 0, sizeof(hints));
  2354. hints.ai_family = AF_UNSPEC;
  2355. hints.ai_socktype = SOCK_STREAM;
  2356. auto host = unique_unresolvable_host(i);
  2357. struct addrinfo *result = nullptr;
  2358. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2359. &result, /*timeout_sec=*/1);
  2360. if (rc == 0 && result) { freeaddrinfo(result); }
  2361. }
  2362. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2363. // stack region they still believe holds their gaicb.
  2364. std::this_thread::sleep_for(std::chrono::seconds(3));
  2365. }
  2366. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2367. if (!should_run_issue_2431_tests()) {
  2368. GTEST_SKIP()
  2369. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2370. }
  2371. std::atomic<bool> stop{false};
  2372. std::vector<std::thread> threads;
  2373. for (int t = 0; t < 8; ++t) {
  2374. threads.emplace_back([t, &stop] {
  2375. int i = 0;
  2376. while (!stop.load(std::memory_order_relaxed)) {
  2377. struct addrinfo hints;
  2378. memset(&hints, 0, sizeof(hints));
  2379. hints.ai_family = AF_UNSPEC;
  2380. hints.ai_socktype = SOCK_STREAM;
  2381. auto host = unique_unresolvable_host(t * 100000 + i++);
  2382. struct addrinfo *result = nullptr;
  2383. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2384. &result, /*timeout_sec=*/1);
  2385. if (rc == 0 && result) { freeaddrinfo(result); }
  2386. }
  2387. });
  2388. }
  2389. std::this_thread::sleep_for(std::chrono::seconds(8));
  2390. stop.store(true, std::memory_order_relaxed);
  2391. for (auto &th : threads) {
  2392. th.join();
  2393. }
  2394. std::this_thread::sleep_for(std::chrono::seconds(3));
  2395. }
  2396. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2397. if (!should_run_issue_2431_tests()) {
  2398. GTEST_SKIP()
  2399. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2400. }
  2401. std::atomic<bool> stop{false};
  2402. std::vector<std::thread> threads;
  2403. for (int t = 0; t < 8; ++t) {
  2404. threads.emplace_back([t, &stop] {
  2405. int i = 0;
  2406. while (!stop.load(std::memory_order_relaxed)) {
  2407. auto host = unique_unresolvable_host(t * 100000 + i++);
  2408. Client cli(host, 80);
  2409. cli.set_connection_timeout(1, 0);
  2410. cli.set_read_timeout(1, 0);
  2411. cli.set_write_timeout(1, 0);
  2412. (void)cli.Get("/");
  2413. }
  2414. });
  2415. }
  2416. std::this_thread::sleep_for(std::chrono::seconds(8));
  2417. stop.store(true, std::memory_order_relaxed);
  2418. for (auto &th : threads) {
  2419. th.join();
  2420. }
  2421. std::this_thread::sleep_for(std::chrono::seconds(3));
  2422. }
  2423. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2424. TEST(ConnectionErrorTest, InvalidHost) {
  2425. auto host = "-abcde.com";
  2426. #ifdef CPPHTTPLIB_SSL_ENABLED
  2427. auto port = 443;
  2428. SSLClient cli(host, port);
  2429. #else
  2430. auto port = 80;
  2431. Client cli(host, port);
  2432. #endif
  2433. cli.set_connection_timeout(std::chrono::seconds(2));
  2434. auto res = cli.Get("/");
  2435. ASSERT_TRUE(!res);
  2436. EXPECT_EQ(Error::Connection, res.error());
  2437. }
  2438. TEST(ConnectionErrorTest, InvalidHost2) {
  2439. auto host = "httpcan.org/";
  2440. #ifdef CPPHTTPLIB_SSL_ENABLED
  2441. SSLClient cli(host);
  2442. #else
  2443. Client cli(host);
  2444. #endif
  2445. cli.set_connection_timeout(std::chrono::seconds(2));
  2446. auto res = cli.Get("/");
  2447. ASSERT_TRUE(!res);
  2448. EXPECT_EQ(Error::Connection, res.error());
  2449. }
  2450. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2451. auto host = "httpcan.org/";
  2452. #ifdef CPPHTTPLIB_SSL_ENABLED
  2453. SSLClient cli(host);
  2454. #else
  2455. Client cli(host);
  2456. #endif
  2457. cli.set_connection_timeout(std::chrono::seconds(2));
  2458. auto res = cli.Get("/");
  2459. ASSERT_TRUE(!res);
  2460. stringstream s;
  2461. s << "error code: " << res.error();
  2462. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2463. }
  2464. TEST(ConnectionErrorTest, InvalidPort) {
  2465. auto host = "localhost";
  2466. auto port = 44380;
  2467. #ifdef CPPHTTPLIB_SSL_ENABLED
  2468. SSLClient cli(host, port);
  2469. #else
  2470. Client cli(host, port);
  2471. #endif
  2472. cli.set_connection_timeout(std::chrono::seconds(2));
  2473. auto res = cli.Get("/");
  2474. ASSERT_TRUE(!res);
  2475. EXPECT_TRUE(Error::Connection == res.error() ||
  2476. Error::ConnectionTimeout == res.error());
  2477. }
  2478. TEST(ConnectionErrorTest, Timeout_Online) {
  2479. auto host = "google.com";
  2480. #ifdef CPPHTTPLIB_SSL_ENABLED
  2481. auto port = 44380;
  2482. SSLClient cli(host, port);
  2483. #else
  2484. auto port = 8080;
  2485. Client cli(host, port);
  2486. #endif
  2487. cli.set_connection_timeout(std::chrono::seconds(2));
  2488. // only probe one address type so that the error reason
  2489. // correlates to the timed-out IPv4, not the unsupported
  2490. // IPv6 connection attempt
  2491. cli.set_address_family(AF_INET);
  2492. auto res = cli.Get("/");
  2493. ASSERT_TRUE(!res);
  2494. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2495. }
  2496. TEST(CancelTest, NoCancel_Online) {
  2497. auto host = "httpbingo.org";
  2498. auto path = std::string{"/range/32"};
  2499. #ifdef CPPHTTPLIB_SSL_ENABLED
  2500. auto port = 443;
  2501. SSLClient cli(host, port);
  2502. #else
  2503. auto port = 80;
  2504. Client cli(host, port);
  2505. #endif
  2506. cli.set_connection_timeout(std::chrono::seconds(5));
  2507. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2509. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2510. EXPECT_EQ(StatusCode::OK_200, res->status);
  2511. }
  2512. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2513. // Use /bytes with a large payload so that the DownloadProgress callback
  2514. // (which only fires for Content-Length responses) is invoked before the
  2515. // entire body is received, giving cancellation a chance to fire.
  2516. auto host = "httpbingo.org";
  2517. auto path = std::string{"/bytes/524288"};
  2518. #ifdef CPPHTTPLIB_SSL_ENABLED
  2519. auto port = 443;
  2520. SSLClient cli(host, port);
  2521. #else
  2522. auto port = 80;
  2523. Client cli(host, port);
  2524. #endif
  2525. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2526. cli.set_connection_timeout(std::chrono::seconds(5));
  2527. ASSERT_TRUE(!res);
  2528. EXPECT_EQ(Error::Canceled, res.error());
  2529. }
  2530. TEST(CancelTest, WithCancelLargePayload_Online) {
  2531. auto host = "httpbingo.org";
  2532. auto path = std::string{"/bytes/524288"};
  2533. #ifdef CPPHTTPLIB_SSL_ENABLED
  2534. auto port = 443;
  2535. SSLClient cli(host, port);
  2536. #else
  2537. auto port = 80;
  2538. Client cli(host, port);
  2539. #endif
  2540. cli.set_connection_timeout(std::chrono::seconds(5));
  2541. uint32_t count = 0;
  2542. auto res =
  2543. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2544. ASSERT_TRUE(!res);
  2545. EXPECT_EQ(Error::Canceled, res.error());
  2546. }
  2547. TEST(CancelTest, NoCancelPost) {
  2548. Server svr;
  2549. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2550. res.set_content("Hello World!", "text/plain");
  2551. });
  2552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2553. auto se = detail::scope_exit([&] {
  2554. svr.stop();
  2555. thread.join();
  2556. ASSERT_FALSE(svr.is_running());
  2557. });
  2558. svr.wait_until_ready();
  2559. Client cli(HOST, PORT);
  2560. cli.set_connection_timeout(std::chrono::seconds(5));
  2561. auto res =
  2562. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2563. "application/json", [](uint64_t, uint64_t) { return true; });
  2564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2565. EXPECT_EQ("Hello World!", res->body);
  2566. EXPECT_EQ(StatusCode::OK_200, res->status);
  2567. }
  2568. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2569. Server svr;
  2570. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2571. res.set_content("Hello World!", "text/plain");
  2572. });
  2573. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2574. auto se = detail::scope_exit([&] {
  2575. svr.stop();
  2576. thread.join();
  2577. ASSERT_FALSE(svr.is_running());
  2578. });
  2579. svr.wait_until_ready();
  2580. Client cli(HOST, PORT);
  2581. cli.set_connection_timeout(std::chrono::seconds(5));
  2582. auto res =
  2583. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2584. "application/json", [](uint64_t, uint64_t) { return false; });
  2585. ASSERT_TRUE(!res);
  2586. EXPECT_EQ(Error::Canceled, res.error());
  2587. }
  2588. TEST(CancelTest, WithCancelLargePayloadPost) {
  2589. Server svr;
  2590. svr.set_payload_max_length(200 * 1024 * 1024);
  2591. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2592. res.set_content(LARGE_DATA, "text/plain");
  2593. });
  2594. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2595. auto se = detail::scope_exit([&] {
  2596. svr.stop();
  2597. thread.join();
  2598. ASSERT_FALSE(svr.is_running());
  2599. });
  2600. svr.wait_until_ready();
  2601. Client cli(HOST, PORT);
  2602. cli.set_payload_max_length(200 * 1024 * 1024);
  2603. cli.set_connection_timeout(std::chrono::seconds(5));
  2604. auto res =
  2605. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2606. "application/json", [](uint64_t, uint64_t) { return false; });
  2607. ASSERT_TRUE(!res);
  2608. EXPECT_EQ(Error::Canceled, res.error());
  2609. }
  2610. TEST(CancelTest, NoCancelPut) {
  2611. Server svr;
  2612. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2613. res.set_content("Hello World!", "text/plain");
  2614. });
  2615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2616. auto se = detail::scope_exit([&] {
  2617. svr.stop();
  2618. thread.join();
  2619. ASSERT_FALSE(svr.is_running());
  2620. });
  2621. svr.wait_until_ready();
  2622. Client cli(HOST, PORT);
  2623. cli.set_connection_timeout(std::chrono::seconds(5));
  2624. auto res =
  2625. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2626. "application/json", [](uint64_t, uint64_t) { return true; });
  2627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2628. EXPECT_EQ("Hello World!", res->body);
  2629. EXPECT_EQ(StatusCode::OK_200, res->status);
  2630. }
  2631. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2632. Server svr;
  2633. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2634. res.set_content("Hello World!", "text/plain");
  2635. });
  2636. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2637. auto se = detail::scope_exit([&] {
  2638. svr.stop();
  2639. thread.join();
  2640. ASSERT_FALSE(svr.is_running());
  2641. });
  2642. svr.wait_until_ready();
  2643. Client cli(HOST, PORT);
  2644. cli.set_connection_timeout(std::chrono::seconds(5));
  2645. auto res =
  2646. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2647. "application/json", [](uint64_t, uint64_t) { return false; });
  2648. ASSERT_TRUE(!res);
  2649. EXPECT_EQ(Error::Canceled, res.error());
  2650. }
  2651. TEST(CancelTest, WithCancelLargePayloadPut) {
  2652. Server svr;
  2653. svr.set_payload_max_length(200 * 1024 * 1024);
  2654. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2655. res.set_content(LARGE_DATA, "text/plain");
  2656. });
  2657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2658. auto se = detail::scope_exit([&] {
  2659. svr.stop();
  2660. thread.join();
  2661. ASSERT_FALSE(svr.is_running());
  2662. });
  2663. svr.wait_until_ready();
  2664. Client cli(HOST, PORT);
  2665. cli.set_payload_max_length(200 * 1024 * 1024);
  2666. cli.set_connection_timeout(std::chrono::seconds(5));
  2667. auto res =
  2668. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2669. "application/json", [](uint64_t, uint64_t) { return false; });
  2670. ASSERT_TRUE(!res);
  2671. EXPECT_EQ(Error::Canceled, res.error());
  2672. }
  2673. TEST(CancelTest, NoCancelPatch) {
  2674. Server svr;
  2675. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2676. res.set_content("Hello World!", "text/plain");
  2677. });
  2678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2679. auto se = detail::scope_exit([&] {
  2680. svr.stop();
  2681. thread.join();
  2682. ASSERT_FALSE(svr.is_running());
  2683. });
  2684. svr.wait_until_ready();
  2685. Client cli(HOST, PORT);
  2686. cli.set_connection_timeout(std::chrono::seconds(5));
  2687. auto res =
  2688. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2689. "application/json", [](uint64_t, uint64_t) { return true; });
  2690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2691. EXPECT_EQ("Hello World!", res->body);
  2692. EXPECT_EQ(StatusCode::OK_200, res->status);
  2693. }
  2694. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2695. Server svr;
  2696. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2697. res.set_content("Hello World!", "text/plain");
  2698. });
  2699. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2700. auto se = detail::scope_exit([&] {
  2701. svr.stop();
  2702. thread.join();
  2703. ASSERT_FALSE(svr.is_running());
  2704. });
  2705. svr.wait_until_ready();
  2706. Client cli(HOST, PORT);
  2707. cli.set_connection_timeout(std::chrono::seconds(5));
  2708. auto res =
  2709. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2710. "application/json", [](uint64_t, uint64_t) { return false; });
  2711. ASSERT_TRUE(!res);
  2712. EXPECT_EQ(Error::Canceled, res.error());
  2713. }
  2714. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2715. Server svr;
  2716. svr.set_payload_max_length(200 * 1024 * 1024);
  2717. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2718. res.set_content(LARGE_DATA, "text/plain");
  2719. });
  2720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2721. auto se = detail::scope_exit([&] {
  2722. svr.stop();
  2723. thread.join();
  2724. ASSERT_FALSE(svr.is_running());
  2725. });
  2726. svr.wait_until_ready();
  2727. Client cli(HOST, PORT);
  2728. cli.set_payload_max_length(200 * 1024 * 1024);
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. auto res =
  2731. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2732. "application/json", [](uint64_t, uint64_t) { return false; });
  2733. ASSERT_TRUE(!res);
  2734. EXPECT_EQ(Error::Canceled, res.error());
  2735. }
  2736. TEST(CancelTest, NoCancelDelete) {
  2737. Server svr;
  2738. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2739. res.set_content("Hello World!", "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. cli.set_connection_timeout(std::chrono::seconds(5));
  2750. auto res =
  2751. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2752. "application/json", [](uint64_t, uint64_t) { return true; });
  2753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2754. EXPECT_EQ("Hello World!", res->body);
  2755. EXPECT_EQ(StatusCode::OK_200, res->status);
  2756. }
  2757. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2758. Server svr;
  2759. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2760. res.set_content("Hello World!", "text/plain");
  2761. });
  2762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2763. auto se = detail::scope_exit([&] {
  2764. svr.stop();
  2765. thread.join();
  2766. ASSERT_FALSE(svr.is_running());
  2767. });
  2768. svr.wait_until_ready();
  2769. Client cli(HOST, PORT);
  2770. cli.set_connection_timeout(std::chrono::seconds(5));
  2771. auto res =
  2772. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2773. "application/json", [](uint64_t, uint64_t) { return false; });
  2774. ASSERT_TRUE(!res);
  2775. EXPECT_EQ(Error::Canceled, res.error());
  2776. }
  2777. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2778. Server svr;
  2779. svr.set_payload_max_length(200 * 1024 * 1024);
  2780. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2781. res.set_content(LARGE_DATA, "text/plain");
  2782. });
  2783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2784. auto se = detail::scope_exit([&] {
  2785. svr.stop();
  2786. thread.join();
  2787. ASSERT_FALSE(svr.is_running());
  2788. });
  2789. svr.wait_until_ready();
  2790. Client cli(HOST, PORT);
  2791. cli.set_payload_max_length(200 * 1024 * 1024);
  2792. cli.set_connection_timeout(std::chrono::seconds(5));
  2793. auto res =
  2794. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2795. "application/json", [](uint64_t, uint64_t) { return false; });
  2796. ASSERT_TRUE(!res);
  2797. EXPECT_EQ(Error::Canceled, res.error());
  2798. }
  2799. static std::string remove_whitespace(const std::string &input) {
  2800. std::string output;
  2801. output.reserve(input.size());
  2802. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2803. [](unsigned char c) { return !std::isspace(c); });
  2804. return output;
  2805. }
  2806. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2807. auto host = "httpbingo.org";
  2808. auto path = std::string{"/basic-auth/hello/world"};
  2809. #ifdef CPPHTTPLIB_SSL_ENABLED
  2810. auto port = 443;
  2811. SSLClient cli(host, port);
  2812. #else
  2813. auto port = 80;
  2814. Client cli(host, port);
  2815. #endif
  2816. {
  2817. auto res = cli.Get(path);
  2818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2819. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2820. }
  2821. {
  2822. auto res = cli.Get(
  2823. path, Headers{make_basic_authentication_header("hello", "world")});
  2824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2825. auto body = remove_whitespace(res->body);
  2826. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2827. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2828. EXPECT_EQ(StatusCode::OK_200, res->status);
  2829. }
  2830. {
  2831. cli.set_basic_auth("hello", "world");
  2832. auto res = cli.Get(path);
  2833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2834. auto body = remove_whitespace(res->body);
  2835. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2836. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2837. EXPECT_EQ(StatusCode::OK_200, res->status);
  2838. }
  2839. {
  2840. cli.set_basic_auth("hello", "bad");
  2841. auto res = cli.Get(path);
  2842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2843. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2844. }
  2845. {
  2846. cli.set_basic_auth("bad", "world");
  2847. auto res = cli.Get(path);
  2848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2849. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2850. }
  2851. }
  2852. #ifdef CPPHTTPLIB_SSL_ENABLED
  2853. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2854. auto host = "httpbingo.org";
  2855. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2856. auto paths = std::vector<std::string>{
  2857. "/digest-auth/auth/hello/world/MD5",
  2858. "/digest-auth/auth/hello/world/SHA-256",
  2859. };
  2860. auto port = 443;
  2861. SSLClient cli(host, port);
  2862. {
  2863. auto res = cli.Get(unauth_path);
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2866. }
  2867. {
  2868. cli.set_digest_auth("hello", "world");
  2869. for (const auto &path : paths) {
  2870. auto res = cli.Get(path.c_str());
  2871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2872. auto body = remove_whitespace(res->body);
  2873. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2874. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2875. EXPECT_EQ(StatusCode::OK_200, res->status);
  2876. }
  2877. cli.set_digest_auth("hello", "bad");
  2878. for (const auto &path : paths) {
  2879. auto res = cli.Get(path.c_str());
  2880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2881. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2882. }
  2883. }
  2884. }
  2885. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2886. // comma-separated list of challenges, and each challenge may itself carry a
  2887. // comma-separated auth-param list, so a server can legally offer Basic
  2888. // before Digest, either as two field lines or packed into one. Runs one 401
  2889. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2890. // value() joins them in receipt order) and checks that the retry carries a
  2891. // well-formed Digest Authorization header naming expected_realm.
  2892. static void
  2893. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2894. const std::string &expected_realm) {
  2895. std::atomic<int> hits{0};
  2896. Server svr;
  2897. svr.Get("/x", [&](const Request &req, Response &res) {
  2898. if (++hits == 1) {
  2899. res.status = StatusCode::Unauthorized_401;
  2900. for (const auto &challenge : challenges) {
  2901. res.set_header("WWW-Authenticate", challenge);
  2902. }
  2903. } else {
  2904. auto authorization = req.get_header_value("Authorization");
  2905. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2906. EXPECT_NE(std::string::npos,
  2907. authorization.find("realm=\"" + expected_realm + "\""));
  2908. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2909. res.set_content("ok", "text/plain");
  2910. }
  2911. });
  2912. auto port = svr.bind_to_any_port(HOST);
  2913. std::thread t([&]() { svr.listen_after_bind(); });
  2914. auto se = detail::scope_exit([&] {
  2915. svr.stop();
  2916. t.join();
  2917. });
  2918. svr.wait_until_ready();
  2919. Client cli(HOST, port);
  2920. cli.set_digest_auth("hello", "world");
  2921. auto res = cli.Get("/x");
  2922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2923. EXPECT_EQ(2, hits.load());
  2924. }
  2925. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2926. static const char *kDigestChallenge =
  2927. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2928. "algorithm=MD5";
  2929. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2930. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2931. "testrealm");
  2932. }
  2933. // Same challenge list with the schemes in the opposite order, to make sure
  2934. // the fix above didn't just special-case "Basic first".
  2935. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2936. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2937. "testrealm");
  2938. }
  2939. // A comma inside a quoted auth-param value must not be mistaken for the
  2940. // separator between two challenges (or two auth-params).
  2941. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2942. run_digest_challenge_list_test(
  2943. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2944. "algorithm=MD5"},
  2945. "test,realm");
  2946. }
  2947. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2948. // make_digest_authentication_header() dereferences both unconditionally, so
  2949. // a server sending a challenge missing either one must not be treated as
  2950. // usable -- doing so used to crash the client with std::out_of_range.
  2951. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2952. Server svr;
  2953. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2954. res.status = StatusCode::Unauthorized_401;
  2955. res.set_header("WWW-Authenticate", challenge);
  2956. });
  2957. auto port = svr.bind_to_any_port(HOST);
  2958. std::thread t([&]() { svr.listen_after_bind(); });
  2959. auto se = detail::scope_exit([&] {
  2960. svr.stop();
  2961. t.join();
  2962. });
  2963. svr.wait_until_ready();
  2964. Client cli(HOST, port);
  2965. cli.set_digest_auth("hello", "world");
  2966. auto res = cli.Get("/x");
  2967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2968. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2969. }
  2970. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2971. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2972. }
  2973. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2974. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2975. }
  2976. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2977. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2978. }
  2979. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2980. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2981. // when storing the values, so the header builder has to re-escape them (and
  2982. // keep algorithm a bare token); otherwise the value breaks out of its
  2983. // quoted-string and injects extra auth-params into the client's Authorization.
  2984. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2985. std::atomic<int> hits{0};
  2986. std::string authorization;
  2987. Server svr;
  2988. svr.Get("/x", [&](const Request &req, Response &res) {
  2989. if (++hits == 1) {
  2990. res.status = StatusCode::Unauthorized_401;
  2991. // On the wire the quotes embedded in the values are backslash-escaped.
  2992. res.set_header("WWW-Authenticate",
  2993. "Digest realm=\"testrealm\", "
  2994. "nonce=\"n\\\"; injected=\\\"x\", "
  2995. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2996. } else {
  2997. authorization = req.get_header_value("Authorization");
  2998. res.set_content("ok", "text/plain");
  2999. }
  3000. });
  3001. auto port = svr.bind_to_any_port(HOST);
  3002. std::thread t([&]() { svr.listen_after_bind(); });
  3003. auto se = detail::scope_exit([&] {
  3004. svr.stop();
  3005. t.join();
  3006. });
  3007. svr.wait_until_ready();
  3008. Client cli(HOST, port);
  3009. cli.set_digest_auth("hello", "world");
  3010. auto res = cli.Get("/x");
  3011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3012. EXPECT_EQ(2, hits.load());
  3013. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3014. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3015. // inside its quoted-string rather than starting an "injected" auth-param.
  3016. EXPECT_NE(std::string::npos,
  3017. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3018. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3019. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3020. }
  3021. #endif
  3022. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3023. auto host = "google.com";
  3024. auto another_host = "example.com";
  3025. auto wrong_ip = "0.0.0.0";
  3026. #ifdef CPPHTTPLIB_SSL_ENABLED
  3027. SSLClient cli(host);
  3028. #else
  3029. Client cli(host);
  3030. #endif
  3031. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3032. auto res = cli.Get("/");
  3033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3034. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3035. }
  3036. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3037. auto host = "google.com";
  3038. auto wrong_ip = "0.0.0.0";
  3039. #ifdef CPPHTTPLIB_SSL_ENABLED
  3040. SSLClient cli(host);
  3041. #else
  3042. Client cli(host);
  3043. #endif
  3044. cli.set_hostname_addr_map({{host, wrong_ip}});
  3045. auto res = cli.Get("/");
  3046. ASSERT_TRUE(!res);
  3047. EXPECT_EQ(Error::Connection, res.error());
  3048. }
  3049. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3050. // A mapped value that is not an IP literal must be resolved. "localhost"
  3051. // resolves from the hosts file, so this test needs no external DNS.
  3052. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3053. auto host = "target.invalid";
  3054. Server svr;
  3055. std::string received_host;
  3056. svr.Get("/hi", [&](const Request &req, Response &res) {
  3057. received_host = req.get_header_value("Host");
  3058. res.set_content("Hello World!", "text/plain");
  3059. });
  3060. auto port = svr.bind_to_any_port(HOST);
  3061. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3062. auto se = detail::scope_exit([&] {
  3063. svr.stop();
  3064. thread.join();
  3065. ASSERT_FALSE(svr.is_running());
  3066. });
  3067. svr.wait_until_ready();
  3068. Client cli(host, port);
  3069. cli.set_hostname_addr_map({{host, HOST}});
  3070. auto res = cli.Get("/hi");
  3071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3072. EXPECT_EQ(StatusCode::OK_200, res->status);
  3073. // The mapping only redirects the connection; the identity stays host_.
  3074. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3075. }
  3076. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3077. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3078. auto host = "target.invalid";
  3079. Server svr;
  3080. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3081. res.set_content("Hello World!", "text/plain");
  3082. });
  3083. auto port = svr.bind_to_any_port("127.0.0.1");
  3084. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3085. auto se = detail::scope_exit([&] {
  3086. svr.stop();
  3087. thread.join();
  3088. ASSERT_FALSE(svr.is_running());
  3089. });
  3090. svr.wait_until_ready();
  3091. Client cli(host, port);
  3092. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3093. auto res = cli.Get("/hi");
  3094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3095. EXPECT_EQ(StatusCode::OK_200, res->status);
  3096. }
  3097. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3098. // An empty mapped value must leave host_ as the connection target. Without
  3099. // that guard the empty value would become the host argument, getaddrinfo
  3100. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3101. // loopback - silently connecting somewhere the caller never asked for.
  3102. // The server listens on loopback, so such a fallback would succeed and is
  3103. // therefore observable as a failure of this test.
  3104. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3105. Server svr;
  3106. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3107. res.set_content("Hello World!", "text/plain");
  3108. });
  3109. auto port = svr.bind_to_any_port(HOST);
  3110. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3111. auto se = detail::scope_exit([&] {
  3112. svr.stop();
  3113. thread.join();
  3114. ASSERT_FALSE(svr.is_running());
  3115. });
  3116. svr.wait_until_ready();
  3117. Client cli(blackhole, port);
  3118. cli.set_hostname_addr_map({{blackhole, ""}});
  3119. cli.set_connection_timeout(1);
  3120. auto res = cli.Get("/hi");
  3121. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3122. }
  3123. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3124. auto host = "httpbingo.org";
  3125. auto path = std::string{"/absolute-redirect/3"};
  3126. #ifdef CPPHTTPLIB_SSL_ENABLED
  3127. SSLClient cli(host);
  3128. #else
  3129. Client cli(host);
  3130. #endif
  3131. cli.set_follow_location(true);
  3132. auto res = cli.Get(path);
  3133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3134. EXPECT_EQ(StatusCode::OK_200, res->status);
  3135. }
  3136. TEST(RedirectTest, Redirect_Online) {
  3137. auto host = "httpbingo.org";
  3138. auto path = std::string{"/redirect/3"};
  3139. #ifdef CPPHTTPLIB_SSL_ENABLED
  3140. SSLClient cli(host);
  3141. #else
  3142. Client cli(host);
  3143. #endif
  3144. cli.set_follow_location(true);
  3145. auto res = cli.Get(path);
  3146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3147. EXPECT_EQ(StatusCode::OK_200, res->status);
  3148. }
  3149. TEST(RelativeRedirectTest, Redirect_Online) {
  3150. auto host = "httpbingo.org";
  3151. auto path = std::string{"/relative-redirect/3"};
  3152. #ifdef CPPHTTPLIB_SSL_ENABLED
  3153. SSLClient cli(host);
  3154. #else
  3155. Client cli(host);
  3156. #endif
  3157. cli.set_follow_location(true);
  3158. auto res = cli.Get(path);
  3159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3160. EXPECT_EQ(StatusCode::OK_200, res->status);
  3161. }
  3162. TEST(TooManyRedirectTest, Redirect_Online) {
  3163. auto host = "httpbingo.org";
  3164. auto path = std::string{"/redirect/21"};
  3165. #ifdef CPPHTTPLIB_SSL_ENABLED
  3166. SSLClient cli(host);
  3167. #else
  3168. Client cli(host);
  3169. #endif
  3170. cli.set_follow_location(true);
  3171. auto res = cli.Get(path);
  3172. ASSERT_TRUE(!res);
  3173. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3174. }
  3175. #ifdef CPPHTTPLIB_SSL_ENABLED
  3176. TEST(YahooRedirectTest, Redirect_Online) {
  3177. Client cli("yahoo.com");
  3178. auto res = cli.Get("/");
  3179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3180. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3181. cli.set_follow_location(true);
  3182. res = cli.Get("/");
  3183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3184. EXPECT_EQ(StatusCode::OK_200, res->status);
  3185. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3186. }
  3187. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3188. #define REDIR_HOST "httpbingo.org"
  3189. #define REDIR_PATH "/redirect-to"
  3190. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3191. SSLClient cli(REDIR_HOST);
  3192. cli.set_follow_location(true);
  3193. auto res =
  3194. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3196. EXPECT_EQ(StatusCode::OK_200, res->status);
  3197. }
  3198. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3199. SSLClient cli(REDIR_HOST);
  3200. cli.set_follow_location(true);
  3201. Params params;
  3202. params.emplace("url", "http://example.com");
  3203. params.emplace("status_code", "302");
  3204. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. }
  3208. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3209. SSLClient cli(REDIR_HOST);
  3210. cli.set_follow_location(true);
  3211. Params params;
  3212. params.emplace("url", "http://example.com");
  3213. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3215. EXPECT_EQ(StatusCode::OK_200, res->status);
  3216. }
  3217. TEST(UrlWithSpace, Redirect_Online) {
  3218. SSLClient cli("edge.forgecdn.net");
  3219. cli.set_follow_location(true);
  3220. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3222. EXPECT_EQ(StatusCode::OK_200, res->status);
  3223. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3224. }
  3225. #endif
  3226. #if !defined(_WIN32) && !defined(_WIN64)
  3227. TEST(ReceiveSignals, Signal) {
  3228. auto setupSignalHandlers = []() {
  3229. struct sigaction act;
  3230. sigemptyset(&act.sa_mask);
  3231. act.sa_flags = SA_SIGINFO;
  3232. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3233. switch (sig) {
  3234. case SIGINT:
  3235. default: break;
  3236. }
  3237. };
  3238. ::sigaction(SIGINT, &act, nullptr);
  3239. };
  3240. Server svr;
  3241. int port = 0;
  3242. auto thread = std::thread([&]() {
  3243. setupSignalHandlers();
  3244. port = svr.bind_to_any_port(HOST);
  3245. svr.listen_after_bind();
  3246. });
  3247. auto se = detail::scope_exit([&] {
  3248. svr.stop();
  3249. thread.join();
  3250. ASSERT_FALSE(svr.is_running());
  3251. });
  3252. svr.wait_until_ready();
  3253. ASSERT_TRUE(svr.is_running());
  3254. pthread_kill(thread.native_handle(), SIGINT);
  3255. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3256. ASSERT_TRUE(svr.is_running());
  3257. }
  3258. #endif
  3259. TEST(RedirectToDifferentPort, Redirect) {
  3260. Server svr1;
  3261. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3262. res.set_content("Hello World!", "text/plain");
  3263. });
  3264. int svr1_port = 0;
  3265. auto thread1 = std::thread([&]() {
  3266. svr1_port = svr1.bind_to_any_port(HOST);
  3267. svr1.listen_after_bind();
  3268. });
  3269. Server svr2;
  3270. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3271. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3272. });
  3273. int svr2_port = 0;
  3274. auto thread2 = std::thread([&]() {
  3275. svr2_port = svr2.bind_to_any_port(HOST);
  3276. svr2.listen_after_bind();
  3277. });
  3278. auto se = detail::scope_exit([&] {
  3279. svr2.stop();
  3280. thread2.join();
  3281. svr1.stop();
  3282. thread1.join();
  3283. ASSERT_FALSE(svr2.is_running());
  3284. ASSERT_FALSE(svr1.is_running());
  3285. });
  3286. svr1.wait_until_ready();
  3287. svr2.wait_until_ready();
  3288. Client cli("localhost", svr2_port);
  3289. cli.set_follow_location(true);
  3290. auto res = cli.Get("/2");
  3291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3292. EXPECT_EQ(StatusCode::OK_200, res->status);
  3293. EXPECT_EQ("Hello World!", res->body);
  3294. }
  3295. // GET /redir on one server redirects to /target on another port, so the
  3296. // client follows it with a new client.
  3297. static Result
  3298. GetThroughRedirectToDifferentPort(Server::Handler target,
  3299. const std::function<void(Client &)> &setup,
  3300. const Headers &headers = Headers()) {
  3301. Server target_svr;
  3302. target_svr.Get("/target", target);
  3303. int target_port = 0;
  3304. auto target_thread = std::thread([&]() {
  3305. target_port = target_svr.bind_to_any_port(HOST);
  3306. target_svr.listen_after_bind();
  3307. });
  3308. Server origin_svr;
  3309. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3310. res.set_redirect(
  3311. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3312. });
  3313. int origin_port = 0;
  3314. auto origin_thread = std::thread([&]() {
  3315. origin_port = origin_svr.bind_to_any_port(HOST);
  3316. origin_svr.listen_after_bind();
  3317. });
  3318. auto se = detail::scope_exit([&] {
  3319. origin_svr.stop();
  3320. origin_thread.join();
  3321. target_svr.stop();
  3322. target_thread.join();
  3323. });
  3324. target_svr.wait_until_ready();
  3325. origin_svr.wait_until_ready();
  3326. Client cli("localhost", origin_port);
  3327. cli.set_follow_location(true);
  3328. setup(cli);
  3329. return cli.Get("/redir", headers);
  3330. }
  3331. static void
  3332. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3333. std::string captured_authorization;
  3334. auto result = GetThroughRedirectToDifferentPort(
  3335. [&](const Request &req, Response &res) {
  3336. captured_authorization = req.get_header_value("Authorization");
  3337. res.set_content("OK", "text/plain");
  3338. },
  3339. set_auth);
  3340. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3341. EXPECT_EQ(StatusCode::OK_200, result->status);
  3342. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3343. EXPECT_TRUE(captured_authorization.empty());
  3344. }
  3345. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3346. TestDoNotForwardCredentialsOnRedirect(
  3347. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3348. }
  3349. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3350. TestDoNotForwardCredentialsOnRedirect(
  3351. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3352. }
  3353. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3354. std::string captured_cookie;
  3355. auto result = GetThroughRedirectToDifferentPort(
  3356. [&](const Request &req, Response &res) {
  3357. captured_cookie = req.get_header_value("Cookie");
  3358. res.set_content("OK", "text/plain");
  3359. },
  3360. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3361. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3362. EXPECT_EQ(StatusCode::OK_200, result->status);
  3363. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3364. EXPECT_TRUE(captured_cookie.empty());
  3365. }
  3366. TEST(RedirectToSamePort, ForwardCookie) {
  3367. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3368. // header so that ordinary session flows keep working.
  3369. Server svr;
  3370. std::string captured_cookie;
  3371. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3372. res.set_redirect("/target", 302);
  3373. });
  3374. svr.Get("/target", [&](const Request &req, Response &res) {
  3375. captured_cookie = req.get_header_value("Cookie");
  3376. res.set_content("OK", "text/plain");
  3377. });
  3378. auto port = svr.bind_to_any_port(HOST);
  3379. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3380. auto se = detail::scope_exit([&] {
  3381. svr.stop();
  3382. thread.join();
  3383. ASSERT_FALSE(svr.is_running());
  3384. });
  3385. svr.wait_until_ready();
  3386. Client cli(HOST, port);
  3387. cli.set_follow_location(true);
  3388. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3389. auto res = cli.Get("/redir", headers);
  3390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3391. EXPECT_EQ(StatusCode::OK_200, res->status);
  3392. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3393. }
  3394. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3395. std::string authorization;
  3396. std::string trace_id;
  3397. auto result = GetThroughRedirectToDifferentPort(
  3398. [&](const Request &req, Response &res) {
  3399. authorization = req.get_header_value("Authorization");
  3400. trace_id = req.get_header_value("X-Trace-Id");
  3401. res.set_content("OK", "text/plain");
  3402. },
  3403. [](Client &cli) {
  3404. cli.set_default_headers(
  3405. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3406. });
  3407. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3408. EXPECT_EQ(StatusCode::OK_200, result->status);
  3409. // Like a header given with the request, a default one goes along unless it
  3410. // carries credentials (RFC 9110 15.4).
  3411. EXPECT_TRUE(authorization.empty());
  3412. EXPECT_EQ("42", trace_id);
  3413. }
  3414. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3415. auto result = GetThroughRedirectToDifferentPort(
  3416. [](const Request &, Response &res) {
  3417. res.set_content(std::string(2048, 'x'), "text/plain");
  3418. },
  3419. [](Client &cli) { cli.set_payload_max_length(1024); });
  3420. EXPECT_FALSE(result);
  3421. }
  3422. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3423. auto result = GetThroughRedirectToDifferentPort(
  3424. [](const Request &req, Response &res) {
  3425. // Answer after a second, or once the client gives up.
  3426. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3427. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3428. }
  3429. res.set_content("late", "text/plain");
  3430. },
  3431. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3432. ASSERT_FALSE(result);
  3433. EXPECT_EQ(Error::Read, result.error());
  3434. }
  3435. #ifdef CPPHTTPLIB_SSL_ENABLED
  3436. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3437. auto result = GetThroughRedirectToDifferentPort(
  3438. [](const Request &, Response &res) {
  3439. res.status = StatusCode::Unauthorized_401;
  3440. res.set_header("WWW-Authenticate",
  3441. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3442. },
  3443. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3444. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3445. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3446. }
  3447. #endif
  3448. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3449. Server svr;
  3450. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3451. // Port number that overflows int — should not crash
  3452. res.set_redirect("http://localhost:99999999999999999999/target");
  3453. });
  3454. auto port = svr.bind_to_any_port(HOST);
  3455. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3456. auto se = detail::scope_exit([&] {
  3457. svr.stop();
  3458. thread.join();
  3459. ASSERT_FALSE(svr.is_running());
  3460. });
  3461. svr.wait_until_ready();
  3462. Client cli(HOST, port);
  3463. cli.set_follow_location(true);
  3464. auto res = cli.Get("/redir");
  3465. // Should fail gracefully, not crash (no valid response due to bad port)
  3466. EXPECT_FALSE(res);
  3467. }
  3468. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3469. Server svr;
  3470. auto port = svr.bind_to_any_port(HOST);
  3471. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3472. // The server's own port followed by junk must not be followed
  3473. res.set_redirect("http://" + std::string(HOST) + ":" +
  3474. std::to_string(port) + "junk/target");
  3475. });
  3476. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3477. res.set_content("target", "text/plain");
  3478. });
  3479. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3480. auto se = detail::scope_exit([&] {
  3481. svr.stop();
  3482. thread.join();
  3483. ASSERT_FALSE(svr.is_running());
  3484. });
  3485. svr.wait_until_ready();
  3486. Client cli(HOST, port);
  3487. cli.set_follow_location(true);
  3488. auto res = cli.Get("/redir");
  3489. EXPECT_FALSE(res);
  3490. }
  3491. TEST(RedirectFromPageWithContent, Redirect) {
  3492. Server svr;
  3493. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3494. res.set_content("___", "text/plain");
  3495. res.set_redirect("/2");
  3496. });
  3497. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3498. res.set_content("Hello World!", "text/plain");
  3499. });
  3500. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3501. auto se = detail::scope_exit([&] {
  3502. svr.stop();
  3503. th.join();
  3504. ASSERT_FALSE(svr.is_running());
  3505. });
  3506. svr.wait_until_ready();
  3507. {
  3508. Client cli("localhost", PORT);
  3509. cli.set_follow_location(true);
  3510. std::string body;
  3511. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3512. body.append(data, data_length);
  3513. return true;
  3514. });
  3515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3516. EXPECT_EQ(StatusCode::OK_200, res->status);
  3517. EXPECT_EQ("Hello World!", body);
  3518. }
  3519. {
  3520. Client cli("localhost", PORT);
  3521. std::string body;
  3522. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3523. body.append(data, data_length);
  3524. return true;
  3525. });
  3526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3527. EXPECT_EQ(StatusCode::Found_302, res->status);
  3528. EXPECT_EQ("___", body);
  3529. }
  3530. }
  3531. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3532. Server svr;
  3533. auto port_str = std::to_string(PORT);
  3534. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3535. auto expected_host = "[::1]:" + port_str;
  3536. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3537. res.set_content("___", "text/plain");
  3538. // res.set_redirect("/2");
  3539. res.set_redirect(redirect_url);
  3540. });
  3541. svr.Get("/2", [&](const Request &req, Response &res) {
  3542. auto host_header = req.headers.find("Host");
  3543. ASSERT_TRUE(host_header != req.headers.end());
  3544. EXPECT_EQ(expected_host, host_header->second);
  3545. res.set_content("Hello World!", "text/plain");
  3546. });
  3547. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3548. auto se = detail::scope_exit([&] {
  3549. svr.stop();
  3550. th.join();
  3551. ASSERT_FALSE(svr.is_running());
  3552. });
  3553. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3554. // actually starts anything, so the condition !svr.is_running() will
  3555. // always remain true, and the loop never stops.
  3556. // This basically counts how many milliseconds have passed since the
  3557. // call to svr.listen(), and if after 5 seconds nothing started yet
  3558. // aborts the test.
  3559. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3560. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3561. ASSERT_LT(milliseconds, 5000U);
  3562. }
  3563. {
  3564. Client cli("::1", PORT);
  3565. cli.set_follow_location(true);
  3566. std::string body;
  3567. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3568. body.append(data, data_length);
  3569. return true;
  3570. });
  3571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3572. EXPECT_EQ(StatusCode::OK_200, res->status);
  3573. EXPECT_EQ("Hello World!", body);
  3574. }
  3575. {
  3576. Client cli("::1", PORT);
  3577. std::string body;
  3578. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3579. body.append(data, data_length);
  3580. return true;
  3581. });
  3582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3583. EXPECT_EQ(StatusCode::Found_302, res->status);
  3584. EXPECT_EQ("___", body);
  3585. }
  3586. }
  3587. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3588. Server svr;
  3589. svr.Get("/foo", [](const Request &req, Response &res) {
  3590. auto a = req.params.find("a");
  3591. if (a != req.params.end()) {
  3592. res.set_content((*a).second, "text/plain");
  3593. res.status = StatusCode::OK_200;
  3594. } else {
  3595. res.status = StatusCode::BadRequest_400;
  3596. }
  3597. });
  3598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3599. auto se = detail::scope_exit([&] {
  3600. svr.stop();
  3601. thread.join();
  3602. ASSERT_FALSE(svr.is_running());
  3603. });
  3604. svr.wait_until_ready();
  3605. {
  3606. Client cli(HOST, PORT);
  3607. cli.set_path_encode(false);
  3608. auto res = cli.Get("/foo?a=explicitly+encoded");
  3609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3610. EXPECT_EQ(StatusCode::OK_200, res->status);
  3611. // This expects it back with a space, as the `+` won't have been
  3612. // url-encoded, and server-side the params get decoded turning `+`
  3613. // into spaces.
  3614. EXPECT_EQ("explicitly encoded", res->body);
  3615. }
  3616. }
  3617. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3618. // When path encoding is disabled the client must transmit the supplied
  3619. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3620. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3621. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3622. // than a space (0x20). Assert on the raw wire target to catch this.
  3623. Server svr;
  3624. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3625. svr.Get("/foo", [&](const Request &req, Response &res) {
  3626. EXPECT_EQ(expected_target, req.target);
  3627. res.status = StatusCode::OK_200;
  3628. });
  3629. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3630. auto se = detail::scope_exit([&] {
  3631. svr.stop();
  3632. thread.join();
  3633. ASSERT_FALSE(svr.is_running());
  3634. });
  3635. svr.wait_until_ready();
  3636. {
  3637. Client cli(HOST, PORT);
  3638. cli.set_path_encode(false);
  3639. auto res = cli.Get(expected_target.c_str());
  3640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3641. EXPECT_EQ(StatusCode::OK_200, res->status);
  3642. }
  3643. }
  3644. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3645. // `open_stream()` used to skip the path encoding that the buffered send
  3646. // path applies, so the same `path` produced different bytes in the request
  3647. // line depending on which API was used. Assert the two agree.
  3648. Server svr;
  3649. std::string target;
  3650. svr.Get(".*", [&](const Request &req, Response &res) {
  3651. target = req.target;
  3652. res.status = StatusCode::OK_200;
  3653. });
  3654. auto port = svr.bind_to_any_port(HOST);
  3655. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3656. auto se = detail::scope_exit([&] {
  3657. svr.stop();
  3658. thread.join();
  3659. ASSERT_FALSE(svr.is_running());
  3660. });
  3661. svr.wait_until_ready();
  3662. struct {
  3663. const char *path;
  3664. const char *expected;
  3665. } cases[] = {
  3666. {"/a b?x=1", "/a%20b?x=1"},
  3667. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3668. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3669. };
  3670. for (const auto &c : cases) {
  3671. Client cli(HOST, port);
  3672. target.clear();
  3673. auto res = cli.Get(c.path);
  3674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3675. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3676. auto buffered_target = target;
  3677. target.clear();
  3678. auto handle = cli.open_stream("GET", c.path);
  3679. EXPECT_TRUE(handle.is_valid())
  3680. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3681. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3682. }
  3683. }
  3684. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3685. // The `set_path_encode(false)` contract — transmit the supplied target
  3686. // verbatim — must hold for the streaming API too.
  3687. Server svr;
  3688. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3689. std::string target;
  3690. svr.Get("/foo", [&](const Request &req, Response &res) {
  3691. target = req.target;
  3692. res.status = StatusCode::OK_200;
  3693. });
  3694. auto port = svr.bind_to_any_port(HOST);
  3695. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3696. auto se = detail::scope_exit([&] {
  3697. svr.stop();
  3698. thread.join();
  3699. ASSERT_FALSE(svr.is_running());
  3700. });
  3701. svr.wait_until_ready();
  3702. {
  3703. Client cli(HOST, port);
  3704. cli.set_path_encode(false);
  3705. auto handle = cli.open_stream("GET", expected_target);
  3706. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3707. EXPECT_EQ(expected_target, target);
  3708. }
  3709. }
  3710. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3711. // With path encoding enabled a CR/LF in the target is percent-encoded
  3712. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3713. // write_request_line still backstops `set_path_encode(false)`, which is
  3714. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3715. Server svr;
  3716. // Captured before routing: the decoded path contains a newline, which a
  3717. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3718. std::string target;
  3719. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3720. target = req.target;
  3721. res.status = StatusCode::OK_200;
  3722. return Server::HandlerResponse::Handled;
  3723. });
  3724. auto port = svr.bind_to_any_port(HOST);
  3725. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3726. auto se = detail::scope_exit([&] {
  3727. svr.stop();
  3728. thread.join();
  3729. ASSERT_FALSE(svr.is_running());
  3730. });
  3731. svr.wait_until_ready();
  3732. {
  3733. Client cli(HOST, port);
  3734. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3735. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3736. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3737. }
  3738. }
  3739. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3740. // Every control character is percent-encoded, not just CR/LF, so the target
  3741. // passes the request-target check in write_request_line.
  3742. Server svr;
  3743. std::string target;
  3744. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3745. target = req.target;
  3746. res.status = StatusCode::OK_200;
  3747. return Server::HandlerResponse::Handled;
  3748. });
  3749. auto port = svr.bind_to_any_port(HOST);
  3750. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3751. auto se = detail::scope_exit([&] {
  3752. svr.stop();
  3753. thread.join();
  3754. ASSERT_FALSE(svr.is_running());
  3755. });
  3756. svr.wait_until_ready();
  3757. {
  3758. Client cli(HOST, port);
  3759. auto res = cli.Get("/a\tb\x1b\x7f");
  3760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3761. EXPECT_EQ("/a%09b%1B%7F", target);
  3762. }
  3763. }
  3764. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3765. // Nothing may reach the wire: a raw CR/LF target would split the request
  3766. // line and inject headers.
  3767. Server svr;
  3768. // Pre-routing so that "not called" means nothing reached the server at all,
  3769. // rather than merely failing to match a handler pattern.
  3770. auto handler_called = false;
  3771. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3772. handler_called = true;
  3773. res.status = StatusCode::OK_200;
  3774. return Server::HandlerResponse::Handled;
  3775. });
  3776. auto port = svr.bind_to_any_port(HOST);
  3777. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3778. auto se = detail::scope_exit([&] {
  3779. svr.stop();
  3780. thread.join();
  3781. ASSERT_FALSE(svr.is_running());
  3782. });
  3783. svr.wait_until_ready();
  3784. {
  3785. Client cli(HOST, port);
  3786. cli.set_path_encode(false);
  3787. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3788. EXPECT_FALSE(handle.is_valid());
  3789. EXPECT_EQ(Error::Write, handle.error);
  3790. EXPECT_FALSE(handler_called);
  3791. }
  3792. }
  3793. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3794. // Which of the two branches runs is decided by whether the query component
  3795. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3796. // an empty query and must still fall back to building one from
  3797. // `req.params`, while a non-empty query must win over `req.params`.
  3798. Server svr;
  3799. std::string target;
  3800. svr.Get("/foo", [&](const Request &req, Response &res) {
  3801. target = req.target;
  3802. res.status = StatusCode::OK_200;
  3803. });
  3804. auto port = svr.bind_to_any_port(HOST);
  3805. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3806. auto se = detail::scope_exit([&] {
  3807. svr.stop();
  3808. thread.join();
  3809. ASSERT_FALSE(svr.is_running());
  3810. });
  3811. svr.wait_until_ready();
  3812. {
  3813. // Trailing `?` -> empty query component -> `req.params` is used.
  3814. Client cli(HOST, port);
  3815. Request req;
  3816. req.method = "GET";
  3817. req.path = "/foo?";
  3818. req.params.emplace("a", "1");
  3819. target.clear();
  3820. auto res = cli.send(req);
  3821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3822. EXPECT_EQ("/foo?a=1", target);
  3823. }
  3824. {
  3825. // Non-empty query in `req.path` -> `req.params` is not appended.
  3826. Client cli(HOST, port);
  3827. Request req;
  3828. req.method = "GET";
  3829. req.path = "/foo?b=2";
  3830. req.params.emplace("a", "1");
  3831. target.clear();
  3832. auto res = cli.send(req);
  3833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3834. EXPECT_EQ("/foo?b=2", target);
  3835. }
  3836. }
  3837. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3838. Server svr;
  3839. svr.Get("/", [](const Request &req, Response &) {
  3840. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3841. });
  3842. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3843. auto se = detail::scope_exit([&] {
  3844. svr.stop();
  3845. thread.join();
  3846. ASSERT_FALSE(svr.is_running());
  3847. });
  3848. svr.wait_until_ready();
  3849. {
  3850. Client cli(HOST, PORT);
  3851. cli.set_path_encode(false);
  3852. auto res = cli.Get("/?something=%0A");
  3853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3854. EXPECT_EQ(StatusCode::OK_200, res->status);
  3855. }
  3856. }
  3857. TEST(BindServerTest, BindDualStack) {
  3858. Server svr;
  3859. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3860. res.set_content("Hello World!", "text/plain");
  3861. });
  3862. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3863. auto se = detail::scope_exit([&] {
  3864. svr.stop();
  3865. thread.join();
  3866. ASSERT_FALSE(svr.is_running());
  3867. });
  3868. svr.wait_until_ready();
  3869. {
  3870. Client cli("127.0.0.1", PORT);
  3871. auto res = cli.Get("/1");
  3872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3873. EXPECT_EQ(StatusCode::OK_200, res->status);
  3874. EXPECT_EQ("Hello World!", res->body);
  3875. }
  3876. {
  3877. Client cli("::1", PORT);
  3878. auto res = cli.Get("/1");
  3879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3880. EXPECT_EQ(StatusCode::OK_200, res->status);
  3881. EXPECT_EQ("Hello World!", res->body);
  3882. }
  3883. }
  3884. TEST(BindServerTest, BindAndListenSeparately) {
  3885. Server svr;
  3886. int port = svr.bind_to_any_port("0.0.0.0");
  3887. ASSERT_TRUE(svr.is_valid());
  3888. ASSERT_TRUE(port > 0);
  3889. svr.stop();
  3890. }
  3891. // Reports whether anything is still listening on a loopback port. A plain
  3892. // connect() is used instead of a Client request because a socket left bound by
  3893. // mistake accepts the connection into its backlog and never answers, which
  3894. // would hang the test instead of failing it.
  3895. static bool is_loopback_port_accepting(int port) {
  3896. sockaddr_in addr{};
  3897. addr.sin_family = AF_INET;
  3898. addr.sin_port = htons(static_cast<uint16_t>(port));
  3899. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3900. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3901. EXPECT_NE(sock, INVALID_SOCKET);
  3902. if (sock == INVALID_SOCKET) { return false; }
  3903. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3904. static_cast<socklen_t>(sizeof(addr)));
  3905. detail::close_socket(sock);
  3906. return ret == 0;
  3907. }
  3908. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3909. Server svr;
  3910. auto port = svr.bind_to_any_port("127.0.0.1");
  3911. ASSERT_TRUE(port > 0);
  3912. svr.stop();
  3913. // bind_to_any_port() already called listen(2), so until stop() closed the
  3914. // descriptor the port kept accepting connections into the backlog. ASSERT
  3915. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3916. // below blocks forever in the accept loop.
  3917. ASSERT_FALSE(is_loopback_port_accepting(port));
  3918. // Nothing is left to accept on, so listen_after_bind() must report failure
  3919. // instead of returning success without ever serving.
  3920. EXPECT_FALSE(svr.listen_after_bind());
  3921. // The failed listen marks the server decommissioned, so a waiter returns
  3922. // instead of spinning forever.
  3923. svr.wait_until_ready();
  3924. }
  3925. #ifdef CPPHTTPLIB_SSL_ENABLED
  3926. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3928. CLIENT_CA_CERT_DIR);
  3929. int port = svr.bind_to_any_port("0.0.0.0");
  3930. ASSERT_TRUE(svr.is_valid());
  3931. ASSERT_TRUE(port > 0);
  3932. svr.stop();
  3933. }
  3934. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3935. // or a rejected CustomRoute() registration would not stop the server binding.
  3936. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3937. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3938. CLIENT_CA_CERT_DIR);
  3939. ASSERT_TRUE(svr.is_valid());
  3940. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3941. EXPECT_FALSE(svr.is_valid());
  3942. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3943. }
  3944. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3945. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3946. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3947. int port = svr.bind_to_any_port("0.0.0.0");
  3948. ASSERT_TRUE(svr.is_valid());
  3949. ASSERT_TRUE(port > 0);
  3950. svr.stop();
  3951. }
  3952. TEST(BindServerTest, UpdateCertsPem) {
  3953. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3954. int port = svr.bind_to_any_port("0.0.0.0");
  3955. ASSERT_TRUE(svr.is_valid());
  3956. ASSERT_TRUE(port > 0);
  3957. // Read PEM files
  3958. std::string cert_pem, key_pem, ca_pem;
  3959. read_file(SERVER_CERT_FILE, cert_pem);
  3960. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3961. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3962. // Update server certificates using PEM API
  3963. ASSERT_TRUE(
  3964. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3965. ASSERT_TRUE(svr.is_valid());
  3966. svr.stop();
  3967. }
  3968. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3969. // Start server with client CA (enables client auth)
  3970. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3971. ASSERT_TRUE(svr.is_valid());
  3972. bool handler_called = false;
  3973. svr.Get("/test", [&](const Request &req, Response &res) {
  3974. handler_called = true;
  3975. // Verify client certificate is present
  3976. auto cert = req.peer_cert();
  3977. EXPECT_TRUE(static_cast<bool>(cert));
  3978. res.set_content("ok", "text/plain");
  3979. });
  3980. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3981. auto se = detail::scope_exit([&] {
  3982. svr.stop();
  3983. t.join();
  3984. ASSERT_FALSE(svr.is_running());
  3985. });
  3986. svr.wait_until_ready();
  3987. // Read PEM files
  3988. std::string cert_pem, key_pem, ca_pem;
  3989. read_file(SERVER_CERT_FILE, cert_pem);
  3990. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3991. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3992. // Update server certificates and client CA using PEM API while server running
  3993. ASSERT_TRUE(
  3994. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3995. // Connect with client certificate
  3996. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3997. cli.enable_server_certificate_verification(false);
  3998. cli.set_connection_timeout(30);
  3999. auto res = cli.Get("/test");
  4000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4001. ASSERT_EQ(StatusCode::OK_200, res->status);
  4002. ASSERT_TRUE(handler_called);
  4003. EXPECT_EQ("ok", res->body);
  4004. }
  4005. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4006. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4007. ASSERT_TRUE(svr.is_valid());
  4008. svr.Get("/test", [](const Request &, Response &res) {
  4009. res.set_content("ok", "text/plain");
  4010. });
  4011. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4012. auto se = detail::scope_exit([&] {
  4013. svr.stop();
  4014. t.join();
  4015. ASSERT_FALSE(svr.is_running());
  4016. });
  4017. svr.wait_until_ready();
  4018. auto get = [] {
  4019. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4020. cli.enable_server_certificate_verification(false);
  4021. return cli.Get("/test");
  4022. };
  4023. ASSERT_TRUE(get());
  4024. // A CA that did not sign the client's certificate takes the old one's place.
  4025. std::string cert_pem, key_pem, ca_pem;
  4026. read_file(SERVER_CERT_FILE, cert_pem);
  4027. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4028. read_file(SERVER_CERT2_FILE, ca_pem);
  4029. ASSERT_TRUE(
  4030. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4031. EXPECT_FALSE(get());
  4032. }
  4033. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4035. ASSERT_TRUE(svr.is_valid());
  4036. svr.Get("/test", [](const Request &, Response &res) {
  4037. res.set_content("ok", "text/plain");
  4038. });
  4039. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4040. auto se = detail::scope_exit([&] {
  4041. svr.stop();
  4042. t.join();
  4043. ASSERT_FALSE(svr.is_running());
  4044. });
  4045. svr.wait_until_ready();
  4046. // A connection that sends no ClientHello keeps its handshake in progress,
  4047. // once the server has had a moment to start it.
  4048. auto error = Error::Success;
  4049. auto sock = detail::create_client_socket(
  4050. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4051. /*connection_timeout_sec=*/5, 0,
  4052. /*read_timeout_sec=*/5, 0,
  4053. /*write_timeout_sec=*/5, 0, std::string(), error);
  4054. ASSERT_NE(INVALID_SOCKET, sock);
  4055. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4056. std::string cert_pem, key_pem;
  4057. read_file(SERVER_CERT_FILE, cert_pem);
  4058. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4059. auto update = std::async(std::launch::async, [&]() {
  4060. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4061. });
  4062. EXPECT_EQ(std::future_status::timeout,
  4063. update.wait_for(std::chrono::milliseconds(200)));
  4064. detail::close_socket(sock);
  4065. EXPECT_TRUE(update.get());
  4066. SSLClient cli(HOST, PORT);
  4067. cli.enable_server_certificate_verification(false);
  4068. auto res = cli.Get("/test");
  4069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4070. EXPECT_EQ(StatusCode::OK_200, res->status);
  4071. }
  4072. #endif
  4073. TEST(ErrorHandlerTest, ContentLength) {
  4074. Server svr;
  4075. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4076. res.status = StatusCode::OK_200;
  4077. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4078. "text/html"); // <= Content-Length still 13
  4079. });
  4080. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4081. res.set_content("Hello World!\n", "text/plain");
  4082. res.status = 524;
  4083. });
  4084. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4085. auto se = detail::scope_exit([&] {
  4086. svr.stop();
  4087. thread.join();
  4088. ASSERT_FALSE(svr.is_running());
  4089. });
  4090. svr.wait_until_ready();
  4091. {
  4092. Client cli(HOST, PORT);
  4093. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4095. EXPECT_EQ(StatusCode::OK_200, res->status);
  4096. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4097. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4098. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4099. }
  4100. }
  4101. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4102. TEST(ExceptionTest, WithoutExceptionHandler) {
  4103. Server svr;
  4104. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4105. throw std::runtime_error("exception...");
  4106. });
  4107. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4108. throw std::runtime_error("exception\r\n...");
  4109. });
  4110. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4111. auto se = detail::scope_exit([&] {
  4112. svr.stop();
  4113. listen_thread.join();
  4114. ASSERT_FALSE(svr.is_running());
  4115. });
  4116. svr.wait_until_ready();
  4117. Client cli("localhost", PORT);
  4118. {
  4119. auto res = cli.Get("/exception");
  4120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4121. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4122. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4123. }
  4124. {
  4125. auto res = cli.Get("/unknown");
  4126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4127. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4128. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4129. }
  4130. }
  4131. TEST(ExceptionTest, WithExceptionHandler) {
  4132. Server svr;
  4133. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4134. std::exception_ptr ep) {
  4135. EXPECT_FALSE(ep == nullptr);
  4136. try {
  4137. std::rethrow_exception(ep);
  4138. } catch (std::exception &e) {
  4139. EXPECT_EQ("abc", std::string(e.what()));
  4140. } catch (...) {}
  4141. res.status = StatusCode::InternalServerError_500;
  4142. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4143. "text/html"); // <= Content-Length still 13 at this point
  4144. });
  4145. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4146. res.set_content("Hello World!\n", "text/plain");
  4147. throw std::runtime_error("abc");
  4148. });
  4149. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4150. auto se = detail::scope_exit([&] {
  4151. svr.stop();
  4152. thread.join();
  4153. ASSERT_FALSE(svr.is_running());
  4154. });
  4155. svr.wait_until_ready();
  4156. for (size_t i = 0; i < 10; i++) {
  4157. Client cli(HOST, PORT);
  4158. for (size_t j = 0; j < 100; j++) {
  4159. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4161. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4162. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4163. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4164. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4165. }
  4166. cli.set_keep_alive(true);
  4167. for (size_t j = 0; j < 100; j++) {
  4168. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4170. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4171. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4172. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4173. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4174. }
  4175. }
  4176. }
  4177. TEST(ExceptionTest, AndErrorHandler) {
  4178. Server svr;
  4179. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4180. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4181. });
  4182. svr.set_exception_handler(
  4183. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4184. EXPECT_FALSE(ep == nullptr);
  4185. try {
  4186. std::rethrow_exception(ep);
  4187. } catch (std::exception &e) {
  4188. res.set_content(e.what(), "text/html");
  4189. } catch (...) {}
  4190. res.status = StatusCode::InternalServerError_500;
  4191. });
  4192. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4193. throw std::runtime_error("EXCEPTION");
  4194. });
  4195. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4196. res.set_content("ERROR", "text/html");
  4197. res.status = StatusCode::InternalServerError_500;
  4198. });
  4199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4200. auto se = detail::scope_exit([&] {
  4201. svr.stop();
  4202. thread.join();
  4203. ASSERT_FALSE(svr.is_running());
  4204. });
  4205. svr.wait_until_ready();
  4206. Client cli(HOST, PORT);
  4207. {
  4208. auto res = cli.Get("/exception");
  4209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4210. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4211. EXPECT_EQ("EXCEPTION", res->body);
  4212. }
  4213. {
  4214. auto res = cli.Get("/error");
  4215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4216. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4217. EXPECT_EQ("ERROR", res->body);
  4218. }
  4219. {
  4220. auto res = cli.Get("/invalid");
  4221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4223. EXPECT_EQ("NOT_FOUND", res->body);
  4224. }
  4225. }
  4226. #endif
  4227. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4228. // process_request() wraps only routing() in a try/catch, so an exception from
  4229. // any other user callback used to unwind into the task queue - which does not
  4230. // catch - and terminate the process. Each test below runs the server on a
  4231. // single worker thread: a guard that catches the exception but still loses the
  4232. // thread would otherwise be hidden by a spare worker serving the follow-up
  4233. // request. Note that a regression here aborts the whole test binary rather
  4234. // than failing one test.
  4235. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4236. Server svr;
  4237. svr.new_task_queue = [] { return new ThreadPool(1); };
  4238. std::atomic<int> reported{0};
  4239. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4240. if (err == Error::UserCallbackException) { reported++; }
  4241. });
  4242. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4243. res.set_content_provider(
  4244. 1024, "text/plain",
  4245. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4246. sink.write("hello", 5);
  4247. throw std::runtime_error("from the content provider");
  4248. });
  4249. });
  4250. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4251. res.set_content("ok", "text/plain");
  4252. });
  4253. auto port = svr.bind_to_any_port(HOST);
  4254. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4255. auto se = detail::scope_exit([&] {
  4256. svr.stop();
  4257. listen_thread.join();
  4258. ASSERT_FALSE(svr.is_running());
  4259. });
  4260. svr.wait_until_ready();
  4261. {
  4262. Client cli(HOST, port);
  4263. cli.set_read_timeout(5, 0);
  4264. EXPECT_FALSE(cli.Get("/throw"));
  4265. }
  4266. EXPECT_TRUE(svr.is_running());
  4267. EXPECT_EQ(1, reported.load());
  4268. // A request on a fresh connection is still served.
  4269. {
  4270. Client cli(HOST, port);
  4271. auto res = cli.Get("/ok");
  4272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4273. EXPECT_EQ(StatusCode::OK_200, res->status);
  4274. EXPECT_EQ("ok", res->body);
  4275. }
  4276. }
  4277. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4278. Server svr;
  4279. svr.new_task_queue = [] { return new ThreadPool(1); };
  4280. std::atomic<bool> should_throw{true};
  4281. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4282. res.set_content("hi", "text/plain");
  4283. });
  4284. svr.set_post_routing_handler(
  4285. [&](const Request & /*req*/, Response & /*res*/) {
  4286. if (should_throw) {
  4287. throw std::runtime_error("from the post-routing handler");
  4288. }
  4289. });
  4290. auto port = svr.bind_to_any_port(HOST);
  4291. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4292. auto se = detail::scope_exit([&] {
  4293. svr.stop();
  4294. listen_thread.join();
  4295. ASSERT_FALSE(svr.is_running());
  4296. });
  4297. svr.wait_until_ready();
  4298. {
  4299. Client cli(HOST, port);
  4300. cli.set_read_timeout(5, 0);
  4301. EXPECT_FALSE(cli.Get("/hi"));
  4302. }
  4303. EXPECT_TRUE(svr.is_running());
  4304. should_throw = false;
  4305. {
  4306. Client cli(HOST, port);
  4307. auto res = cli.Get("/hi");
  4308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4309. EXPECT_EQ(StatusCode::OK_200, res->status);
  4310. EXPECT_EQ("hi", res->body);
  4311. }
  4312. }
  4313. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4314. // The guard reports the caught exception through the error logger, which is
  4315. // a user callback too. A logger that throws has to be contained as well, or
  4316. // the process would terminate from inside the catch.
  4317. Server svr;
  4318. svr.new_task_queue = [] { return new ThreadPool(1); };
  4319. std::atomic<int> reported{0};
  4320. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4321. if (err == Error::UserCallbackException) {
  4322. reported++;
  4323. throw std::runtime_error("from the error logger");
  4324. }
  4325. });
  4326. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4327. res.set_content_provider(
  4328. 1024, "text/plain",
  4329. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4330. sink.write("hello", 5);
  4331. throw std::runtime_error("from the content provider");
  4332. });
  4333. });
  4334. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4335. res.set_content("ok", "text/plain");
  4336. });
  4337. auto port = svr.bind_to_any_port(HOST);
  4338. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4339. auto se = detail::scope_exit([&] {
  4340. svr.stop();
  4341. listen_thread.join();
  4342. ASSERT_FALSE(svr.is_running());
  4343. });
  4344. svr.wait_until_ready();
  4345. {
  4346. Client cli(HOST, port);
  4347. cli.set_read_timeout(5, 0);
  4348. EXPECT_FALSE(cli.Get("/throw"));
  4349. }
  4350. EXPECT_TRUE(svr.is_running());
  4351. EXPECT_EQ(1, reported.load());
  4352. {
  4353. Client cli(HOST, port);
  4354. auto res = cli.Get("/ok");
  4355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4356. EXPECT_EQ(StatusCode::OK_200, res->status);
  4357. EXPECT_EQ("ok", res->body);
  4358. }
  4359. }
  4360. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4361. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4362. // so the exception unwinds through the ws::WebSocket object on its way to
  4363. // the guard. None of the HTTP cases above cross that.
  4364. Server svr;
  4365. svr.new_task_queue = [] { return new ThreadPool(1); };
  4366. std::atomic<int> reported{0};
  4367. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4368. if (err == Error::UserCallbackException) { reported++; }
  4369. });
  4370. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4371. throw std::runtime_error("from the WebSocket handler");
  4372. });
  4373. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4374. res.set_content("ok", "text/plain");
  4375. });
  4376. auto port = svr.bind_to_any_port(HOST);
  4377. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4378. auto se = detail::scope_exit([&] {
  4379. svr.stop();
  4380. listen_thread.join();
  4381. ASSERT_FALSE(svr.is_running());
  4382. });
  4383. svr.wait_until_ready();
  4384. {
  4385. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4386. "/ws");
  4387. auto res = client.connect();
  4388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4389. // The server dropped the connection instead of dying.
  4390. std::string msg;
  4391. EXPECT_FALSE(client.read(msg));
  4392. client.close();
  4393. }
  4394. EXPECT_TRUE(svr.is_running());
  4395. EXPECT_EQ(1, reported.load());
  4396. {
  4397. Client cli(HOST, port);
  4398. auto res = cli.Get("/ok");
  4399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. EXPECT_EQ("ok", res->body);
  4402. }
  4403. }
  4404. #ifdef CPPHTTPLIB_SSL_ENABLED
  4405. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4406. // SSLServer::process_and_close_socket() is a separate overload with its own
  4407. // guard, so it is exercised on its own.
  4408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4409. ASSERT_TRUE(svr.is_valid());
  4410. svr.new_task_queue = [] { return new ThreadPool(1); };
  4411. std::atomic<int> reported{0};
  4412. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4413. if (err == Error::UserCallbackException) { reported++; }
  4414. });
  4415. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4416. res.set_content_provider(
  4417. 1024, "text/plain",
  4418. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4419. sink.write("hello", 5);
  4420. throw std::runtime_error("from the content provider");
  4421. });
  4422. });
  4423. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4424. res.set_content("ok", "text/plain");
  4425. });
  4426. auto port = svr.bind_to_any_port(HOST);
  4427. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4428. auto se = detail::scope_exit([&] {
  4429. svr.stop();
  4430. listen_thread.join();
  4431. ASSERT_FALSE(svr.is_running());
  4432. });
  4433. svr.wait_until_ready();
  4434. {
  4435. SSLClient cli(HOST, port);
  4436. cli.enable_server_certificate_verification(false);
  4437. cli.set_read_timeout(5, 0);
  4438. EXPECT_FALSE(cli.Get("/throw"));
  4439. }
  4440. EXPECT_TRUE(svr.is_running());
  4441. EXPECT_EQ(1, reported.load());
  4442. {
  4443. SSLClient cli(HOST, port);
  4444. cli.enable_server_certificate_verification(false);
  4445. auto res = cli.Get("/ok");
  4446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4447. EXPECT_EQ(StatusCode::OK_200, res->status);
  4448. EXPECT_EQ("ok", res->body);
  4449. }
  4450. }
  4451. #endif
  4452. #endif
  4453. TEST(NoContentTest, ContentLength) {
  4454. Server svr;
  4455. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4456. res.status = StatusCode::NoContent_204;
  4457. });
  4458. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4459. auto se = detail::scope_exit([&] {
  4460. svr.stop();
  4461. thread.join();
  4462. ASSERT_FALSE(svr.is_running());
  4463. });
  4464. svr.wait_until_ready();
  4465. {
  4466. Client cli(HOST, PORT);
  4467. auto res = cli.Get("/hi");
  4468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4469. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4470. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4471. }
  4472. }
  4473. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4474. #ifdef CPPHTTPLIB_SSL_ENABLED
  4475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4476. ASSERT_TRUE(svr.is_valid());
  4477. #else
  4478. Server svr;
  4479. #endif
  4480. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4481. if (req.path == "/routing_handler") {
  4482. res.set_header("PRE_ROUTING", "on");
  4483. res.set_content("Routing Handler", "text/plain");
  4484. return httplib::Server::HandlerResponse::Handled;
  4485. }
  4486. return httplib::Server::HandlerResponse::Unhandled;
  4487. });
  4488. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4489. res.set_content("Error", "text/html");
  4490. });
  4491. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4492. if (req.path == "/routing_handler") {
  4493. res.set_header("POST_ROUTING", "on");
  4494. }
  4495. });
  4496. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4497. res.set_content("Hello World!\n", "text/plain");
  4498. });
  4499. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4500. auto se = detail::scope_exit([&] {
  4501. svr.stop();
  4502. thread.join();
  4503. ASSERT_FALSE(svr.is_running());
  4504. });
  4505. svr.wait_until_ready();
  4506. {
  4507. #ifdef CPPHTTPLIB_SSL_ENABLED
  4508. SSLClient cli(HOST, PORT);
  4509. cli.enable_server_certificate_verification(false);
  4510. #else
  4511. Client cli(HOST, PORT);
  4512. #endif
  4513. auto res = cli.Get("/routing_handler");
  4514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4515. EXPECT_EQ(StatusCode::OK_200, res->status);
  4516. EXPECT_EQ("Routing Handler", res->body);
  4517. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4518. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4519. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4520. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4521. }
  4522. {
  4523. #ifdef CPPHTTPLIB_SSL_ENABLED
  4524. SSLClient cli(HOST, PORT);
  4525. cli.enable_server_certificate_verification(false);
  4526. #else
  4527. Client cli(HOST, PORT);
  4528. #endif
  4529. auto res = cli.Get("/hi");
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ(StatusCode::OK_200, res->status);
  4532. EXPECT_EQ("Hello World!\n", res->body);
  4533. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4534. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4535. }
  4536. {
  4537. #ifdef CPPHTTPLIB_SSL_ENABLED
  4538. SSLClient cli(HOST, PORT);
  4539. cli.enable_server_certificate_verification(false);
  4540. #else
  4541. Client cli(HOST, PORT);
  4542. #endif
  4543. auto res = cli.Get("/aaa");
  4544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4545. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4546. EXPECT_EQ("Error", res->body);
  4547. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4548. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4549. }
  4550. }
  4551. TEST(RequestHandlerTest, PreRequestHandler) {
  4552. auto route_path = "/user/:user";
  4553. Server svr;
  4554. svr.Get("/hi", [](const Request &, Response &res) {
  4555. res.set_content("hi", "text/plain");
  4556. });
  4557. svr.Get(route_path, [](const Request &req, Response &res) {
  4558. res.set_content(req.path_params.at("user"), "text/plain");
  4559. });
  4560. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4561. if (req.matched_route == route_path) {
  4562. auto user = req.path_params.at("user");
  4563. if (user != "john") {
  4564. res.status = StatusCode::Forbidden_403;
  4565. res.set_content("error", "text/html");
  4566. return Server::HandlerResponse::Handled;
  4567. }
  4568. }
  4569. return Server::HandlerResponse::Unhandled;
  4570. });
  4571. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4572. auto se = detail::scope_exit([&] {
  4573. svr.stop();
  4574. thread.join();
  4575. ASSERT_FALSE(svr.is_running());
  4576. });
  4577. svr.wait_until_ready();
  4578. Client cli(HOST, PORT);
  4579. {
  4580. auto res = cli.Get("/hi");
  4581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4582. EXPECT_EQ(StatusCode::OK_200, res->status);
  4583. EXPECT_EQ("hi", res->body);
  4584. }
  4585. {
  4586. auto res = cli.Get("/user/john");
  4587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4588. EXPECT_EQ(StatusCode::OK_200, res->status);
  4589. EXPECT_EQ("john", res->body);
  4590. }
  4591. {
  4592. auto res = cli.Get("/user/invalid-user");
  4593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4594. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4595. EXPECT_EQ("error", res->body);
  4596. }
  4597. }
  4598. // The pre-request handler must run before the request body is read, so a
  4599. // rejected request never forces the server to buffer a (potentially large)
  4600. // body. Here the posted body is larger than the payload limit: if the body
  4601. // were read first the server would answer 413, but because the pre-request
  4602. // handler runs first it answers 403 and the body is never read.
  4603. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4604. Server svr;
  4605. svr.set_payload_max_length(8);
  4606. auto handler_ran = false;
  4607. svr.Post("/reject", [&](const Request &req, Response &res) {
  4608. handler_ran = true;
  4609. res.set_content(req.body, "text/plain");
  4610. });
  4611. svr.Post("/accept", [](const Request &req, Response &res) {
  4612. res.set_content(req.body, "text/plain");
  4613. });
  4614. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4615. if (req.matched_route == "/reject") {
  4616. res.status = StatusCode::Forbidden_403;
  4617. res.set_content("denied", "text/plain");
  4618. return Server::HandlerResponse::Handled;
  4619. }
  4620. return Server::HandlerResponse::Unhandled;
  4621. });
  4622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4623. auto se = detail::scope_exit([&] {
  4624. svr.stop();
  4625. thread.join();
  4626. ASSERT_FALSE(svr.is_running());
  4627. });
  4628. svr.wait_until_ready();
  4629. Client cli(HOST, PORT);
  4630. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4631. // rejects with 403 before the body is read, so 413 is never reached.
  4632. {
  4633. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4635. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4636. EXPECT_EQ("denied", res->body);
  4637. EXPECT_FALSE(handler_ran);
  4638. }
  4639. // An approved route still reads the body and enforces the payload limit.
  4640. {
  4641. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4643. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4644. }
  4645. }
  4646. TEST(UserDataTest, BasicOperations) {
  4647. httplib::UserData ud;
  4648. // Initially empty
  4649. EXPECT_FALSE(ud.has("key"));
  4650. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4651. // set and get
  4652. ud.set("key", 42);
  4653. EXPECT_TRUE(ud.has("key"));
  4654. auto *p = ud.get<int>("key");
  4655. ASSERT_NE(nullptr, p);
  4656. EXPECT_EQ(42, *p);
  4657. // Type mismatch → nullptr
  4658. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4659. // Overwrite with different type
  4660. ud.set("key", std::string("hello"));
  4661. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4662. auto *s = ud.get<std::string>("key");
  4663. ASSERT_NE(nullptr, s);
  4664. EXPECT_EQ("hello", *s);
  4665. // erase
  4666. ud.erase("key");
  4667. EXPECT_FALSE(ud.has("key"));
  4668. // clear
  4669. ud.set("a", 1);
  4670. ud.set("b", 2);
  4671. ud.clear();
  4672. EXPECT_FALSE(ud.has("a"));
  4673. EXPECT_FALSE(ud.has("b"));
  4674. }
  4675. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4676. struct AuthCtx {
  4677. std::string user_id;
  4678. };
  4679. Server svr;
  4680. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4681. res.user_data.set("auth", AuthCtx{"alice"});
  4682. return Server::HandlerResponse::Unhandled;
  4683. });
  4684. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4685. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4686. ASSERT_NE(nullptr, ctx);
  4687. res.set_content("Hello " + ctx->user_id, "text/plain");
  4688. });
  4689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4690. auto se = detail::scope_exit([&] {
  4691. svr.stop();
  4692. thread.join();
  4693. ASSERT_FALSE(svr.is_running());
  4694. });
  4695. svr.wait_until_ready();
  4696. Client cli(HOST, PORT);
  4697. auto res = cli.Get("/me");
  4698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4699. EXPECT_EQ(StatusCode::OK_200, res->status);
  4700. EXPECT_EQ("Hello alice", res->body);
  4701. }
  4702. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4703. struct RoleCtx {
  4704. std::string role;
  4705. };
  4706. Server svr;
  4707. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4708. res.user_data.set("role", RoleCtx{"admin"});
  4709. return Server::HandlerResponse::Unhandled;
  4710. });
  4711. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4712. auto *ctx = res.user_data.get<RoleCtx>("role");
  4713. ASSERT_NE(nullptr, ctx);
  4714. res.set_content(ctx->role, "text/plain");
  4715. });
  4716. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4717. auto se = detail::scope_exit([&] {
  4718. svr.stop();
  4719. thread.join();
  4720. ASSERT_FALSE(svr.is_running());
  4721. });
  4722. svr.wait_until_ready();
  4723. Client cli(HOST, PORT);
  4724. auto res = cli.Get("/role");
  4725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4726. EXPECT_EQ(StatusCode::OK_200, res->status);
  4727. EXPECT_EQ("admin", res->body);
  4728. }
  4729. TEST(InvalidFormatTest, StatusCode) {
  4730. Server svr;
  4731. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4732. res.set_content("Hello World!\n", "text/plain");
  4733. res.status = 9999; // Status should be a three-digit code...
  4734. });
  4735. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4736. auto se = detail::scope_exit([&] {
  4737. svr.stop();
  4738. thread.join();
  4739. ASSERT_FALSE(svr.is_running());
  4740. });
  4741. svr.wait_until_ready();
  4742. {
  4743. Client cli(HOST, PORT);
  4744. auto res = cli.Get("/hi");
  4745. ASSERT_FALSE(res);
  4746. }
  4747. }
  4748. TEST(URLFragmentTest, WithFragment) {
  4749. Server svr;
  4750. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4751. EXPECT_TRUE(req.target == "/hi");
  4752. });
  4753. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4754. auto se = detail::scope_exit([&] {
  4755. svr.stop();
  4756. thread.join();
  4757. ASSERT_FALSE(svr.is_running());
  4758. });
  4759. svr.wait_until_ready();
  4760. {
  4761. Client cli(HOST, PORT);
  4762. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4763. EXPECT_TRUE(res);
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. res = cli.Get("/hi%23key1=val1=key2=val2");
  4766. EXPECT_TRUE(res);
  4767. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4768. }
  4769. }
  4770. TEST(HeaderWriter, SetHeaderWriter) {
  4771. Server svr;
  4772. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4773. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4774. return detail::write_headers(strm, hdrs);
  4775. });
  4776. svr.Get("/hi", [](const Request &req, Response &res) {
  4777. auto it = req.headers.find("CustomClientHeader");
  4778. EXPECT_TRUE(it != req.headers.end());
  4779. EXPECT_EQ(it->second, "CustomClientValue");
  4780. res.set_content("Hello World!\n", "text/plain");
  4781. });
  4782. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4783. auto se = detail::scope_exit([&] {
  4784. svr.stop();
  4785. thread.join();
  4786. ASSERT_FALSE(svr.is_running());
  4787. });
  4788. svr.wait_until_ready();
  4789. {
  4790. Client cli(HOST, PORT);
  4791. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4792. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4793. return detail::write_headers(strm, hdrs);
  4794. });
  4795. auto res = cli.Get("/hi");
  4796. EXPECT_TRUE(res);
  4797. EXPECT_EQ(StatusCode::OK_200, res->status);
  4798. auto it = res->headers.find("CustomServerHeader");
  4799. EXPECT_TRUE(it != res->headers.end());
  4800. EXPECT_EQ(it->second, "CustomServerValue");
  4801. }
  4802. }
  4803. class ServerTest : public ::testing::Test {
  4804. protected:
  4805. ServerTest()
  4806. : cli_(HOST, PORT)
  4807. #ifdef CPPHTTPLIB_SSL_ENABLED
  4808. ,
  4809. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4810. #endif
  4811. {
  4812. #ifdef CPPHTTPLIB_SSL_ENABLED
  4813. cli_.enable_server_certificate_verification(false);
  4814. #endif
  4815. // Allow LARGE_DATA (100MB) responses
  4816. cli_.set_payload_max_length(200 * 1024 * 1024);
  4817. }
  4818. virtual void SetUp() {
  4819. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4820. svr_.set_payload_max_length(200 * 1024 * 1024);
  4821. svr_.set_mount_point("/", "./www");
  4822. svr_.set_mount_point("/mount", "./www2");
  4823. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4824. svr_.Get("/hi",
  4825. [&](const Request & /*req*/, Response &res) {
  4826. res.set_content("Hello World!", "text/plain");
  4827. })
  4828. .Get("/file_content",
  4829. [&](const Request & /*req*/, Response &res) {
  4830. res.set_file_content("./www/dir/test.html");
  4831. })
  4832. .Get("/file_content_with_content_type",
  4833. [&](const Request & /*req*/, Response &res) {
  4834. res.set_file_content("./www/file", "text/plain");
  4835. })
  4836. .Get("/invalid_file_content",
  4837. [&](const Request & /*req*/, Response &res) {
  4838. res.set_file_content("./www/dir/invalid_file_path");
  4839. })
  4840. .Get("/http_response_splitting",
  4841. [&](const Request & /*req*/, Response &res) {
  4842. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4843. EXPECT_EQ(0U, res.headers.size());
  4844. EXPECT_FALSE(res.has_header("a"));
  4845. res.set_header("a", "1\nSet-Cookie: a=1");
  4846. EXPECT_EQ(0U, res.headers.size());
  4847. EXPECT_FALSE(res.has_header("a"));
  4848. res.set_header("a", "1\rSet-Cookie: a=1");
  4849. EXPECT_EQ(0U, res.headers.size());
  4850. EXPECT_FALSE(res.has_header("a"));
  4851. res.set_header("a\r\nb", "0");
  4852. EXPECT_EQ(0U, res.headers.size());
  4853. EXPECT_FALSE(res.has_header("a"));
  4854. res.set_header("a\rb", "0");
  4855. EXPECT_EQ(0U, res.headers.size());
  4856. EXPECT_FALSE(res.has_header("a"));
  4857. res.set_header("a\nb", "0");
  4858. EXPECT_EQ(0U, res.headers.size());
  4859. EXPECT_FALSE(res.has_header("a"));
  4860. res.set_redirect("1\r\nSet-Cookie: a=1");
  4861. EXPECT_EQ(0U, res.headers.size());
  4862. EXPECT_FALSE(res.has_header("Location"));
  4863. })
  4864. .Get("/slow",
  4865. [&](const Request & /*req*/, Response &res) {
  4866. std::this_thread::sleep_for(std::chrono::seconds(4));
  4867. res.set_content("slow", "text/plain");
  4868. })
  4869. #if 0
  4870. .Post("/slowpost",
  4871. [&](const Request & /*req*/, Response &res) {
  4872. std::this_thread::sleep_for(std::chrono::seconds(2));
  4873. res.set_content("slow", "text/plain");
  4874. })
  4875. #endif
  4876. .Get("/remote_addr",
  4877. [&](const Request &req, Response &res) {
  4878. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4879. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4880. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4881. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4882. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4883. #endif
  4884. res.set_content(req.remote_addr, "text/plain");
  4885. })
  4886. .Get("/local_addr",
  4887. [&](const Request &req, Response &res) {
  4888. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4889. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4890. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4891. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4892. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4893. #endif
  4894. auto local_addr = req.local_addr;
  4895. auto local_port = std::to_string(req.local_port);
  4896. res.set_content(local_addr.append(":").append(local_port),
  4897. "text/plain");
  4898. })
  4899. .Get("/endwith%",
  4900. [&](const Request & /*req*/, Response &res) {
  4901. res.set_content("Hello World!", "text/plain");
  4902. })
  4903. .Get("/a\\+\\+b",
  4904. [&](const Request &req, Response &res) {
  4905. ASSERT_TRUE(req.has_param("a +b"));
  4906. auto val = req.get_param_value("a +b");
  4907. res.set_content(val, "text/plain");
  4908. })
  4909. .Get("/", [&](const Request & /*req*/,
  4910. Response &res) { res.set_redirect("/hi"); })
  4911. .Post("/1",
  4912. [](const Request & /*req*/, Response &res) {
  4913. res.set_redirect("/2", StatusCode::SeeOther_303);
  4914. })
  4915. .Get("/2",
  4916. [](const Request & /*req*/, Response &res) {
  4917. res.set_content("redirected.", "text/plain");
  4918. res.status = StatusCode::OK_200;
  4919. })
  4920. .Post("/person",
  4921. [&](const Request &req, Response &res) {
  4922. if (req.has_param("name") && req.has_param("note")) {
  4923. persons_[req.get_param_value("name")] =
  4924. req.get_param_value("note");
  4925. } else {
  4926. res.status = StatusCode::BadRequest_400;
  4927. }
  4928. })
  4929. .Put("/person",
  4930. [&](const Request &req, Response &res) {
  4931. if (req.has_param("name") && req.has_param("note")) {
  4932. persons_[req.get_param_value("name")] =
  4933. req.get_param_value("note");
  4934. } else {
  4935. res.status = StatusCode::BadRequest_400;
  4936. }
  4937. })
  4938. .Get("/person/(.*)",
  4939. [&](const Request &req, Response &res) {
  4940. string name = req.matches[1];
  4941. if (persons_.find(name) != persons_.end()) {
  4942. auto note = persons_[name];
  4943. res.set_content(note, "text/plain");
  4944. } else {
  4945. res.status = StatusCode::NotFound_404;
  4946. }
  4947. })
  4948. .Delete("/person",
  4949. [&](const Request &req, Response &res) {
  4950. if (req.has_param("name")) {
  4951. string name = req.get_param_value("name");
  4952. if (persons_.find(name) != persons_.end()) {
  4953. persons_.erase(name);
  4954. res.set_content("DELETED", "text/plain");
  4955. } else {
  4956. res.status = StatusCode::NotFound_404;
  4957. }
  4958. } else {
  4959. res.status = StatusCode::BadRequest_400;
  4960. }
  4961. })
  4962. .Post("/x-www-form-urlencoded-json",
  4963. [&](const Request &req, Response &res) {
  4964. auto json = req.get_param_value("json");
  4965. ASSERT_EQ(JSON_DATA, json);
  4966. res.set_content(json, "appliation/json");
  4967. res.status = StatusCode::OK_200;
  4968. })
  4969. .Get("/streamed-chunked",
  4970. [&](const Request & /*req*/, Response &res) {
  4971. res.set_chunked_content_provider(
  4972. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4973. sink.os << "123";
  4974. sink.os << "456";
  4975. sink.os << "789";
  4976. sink.done();
  4977. return true;
  4978. });
  4979. })
  4980. .Get("/streamed-chunked-with-prohibited-trailer",
  4981. [&](const Request & /*req*/, Response &res) {
  4982. auto i = new int(0);
  4983. // Declare both a prohibited trailer (Content-Length) and an
  4984. // allowed one
  4985. res.set_header("Trailer", "Content-Length, X-Allowed");
  4986. res.set_chunked_content_provider(
  4987. "text/plain",
  4988. [i](size_t /*offset*/, DataSink &sink) {
  4989. switch (*i) {
  4990. case 0: sink.os << "123"; break;
  4991. case 1: sink.os << "456"; break;
  4992. case 2: sink.os << "789"; break;
  4993. case 3: {
  4994. sink.done_with_trailer(
  4995. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4996. } break;
  4997. }
  4998. (*i)++;
  4999. return true;
  5000. },
  5001. [i](bool success) {
  5002. EXPECT_TRUE(success);
  5003. delete i;
  5004. });
  5005. })
  5006. .Get("/streamed-chunked2",
  5007. [&](const Request & /*req*/, Response &res) {
  5008. auto i = new int(0);
  5009. res.set_chunked_content_provider(
  5010. "text/plain",
  5011. [i](size_t /*offset*/, DataSink &sink) {
  5012. switch (*i) {
  5013. case 0: sink.os << "123"; break;
  5014. case 1: sink.os << "456"; break;
  5015. case 2: sink.os << "789"; break;
  5016. case 3: sink.done(); break;
  5017. }
  5018. (*i)++;
  5019. return true;
  5020. },
  5021. [i](bool success) {
  5022. EXPECT_TRUE(success);
  5023. delete i;
  5024. });
  5025. })
  5026. .Get("/streamed-chunked-with-trailer",
  5027. [&](const Request & /*req*/, Response &res) {
  5028. auto i = new int(0);
  5029. res.set_header("Trailer", "Dummy1, Dummy2");
  5030. res.set_chunked_content_provider(
  5031. "text/plain",
  5032. [i](size_t /*offset*/, DataSink &sink) {
  5033. switch (*i) {
  5034. case 0: sink.os << "123"; break;
  5035. case 1: sink.os << "456"; break;
  5036. case 2: sink.os << "789"; break;
  5037. case 3: {
  5038. sink.done_with_trailer(
  5039. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5040. } break;
  5041. }
  5042. (*i)++;
  5043. return true;
  5044. },
  5045. [i](bool success) {
  5046. EXPECT_TRUE(success);
  5047. delete i;
  5048. });
  5049. })
  5050. .Get("/streamed",
  5051. [&](const Request & /*req*/, Response &res) {
  5052. res.set_content_provider(
  5053. 6, "text/plain",
  5054. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5055. sink.os << (offset < 3 ? "a" : "b");
  5056. return true;
  5057. });
  5058. })
  5059. .Get("/streamed-without-length",
  5060. [&](const Request & /*req*/, Response &res) {
  5061. auto data = new std::string("abcdefg");
  5062. res.set_content_provider(
  5063. "text/plain",
  5064. [data](size_t offset, DataSink &sink) {
  5065. if (offset < data->size()) {
  5066. sink.os << data->substr(offset);
  5067. }
  5068. sink.done();
  5069. return true;
  5070. },
  5071. [data](bool success) {
  5072. EXPECT_TRUE(success);
  5073. delete data;
  5074. });
  5075. })
  5076. .Get("/streamed-with-range",
  5077. [&](const Request &req, Response &res) {
  5078. auto data = new std::string("abcdefg");
  5079. // An explicit status keeps the server from picking the 206 it
  5080. // would otherwise choose for a ranged request, so the response
  5081. // is not a partial representation.
  5082. auto status = req.get_param_value("status");
  5083. if (status == "200") {
  5084. res.status = StatusCode::OK_200;
  5085. } else if (status == "403") {
  5086. res.status = StatusCode::Forbidden_403;
  5087. }
  5088. res.set_content_provider(
  5089. data->size(), "text/plain",
  5090. [data](size_t offset, size_t length, DataSink &sink) {
  5091. size_t DATA_CHUNK_SIZE = 4;
  5092. const auto &d = *data;
  5093. auto out_len =
  5094. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5095. auto ret =
  5096. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5097. EXPECT_TRUE(ret);
  5098. return true;
  5099. },
  5100. [data, &req](bool success) {
  5101. EXPECT_EQ(success, !req.has_param("error"));
  5102. delete data;
  5103. });
  5104. })
  5105. .Get("/streamed-cancel",
  5106. [&](const Request & /*req*/, Response &res) {
  5107. res.set_content_provider(
  5108. size_t(-1), "text/plain",
  5109. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5110. sink.os << "data_chunk";
  5111. return true;
  5112. });
  5113. })
  5114. .Get("/regex-with-delimiter",
  5115. [&](const Request &req, Response & /*res*/) {
  5116. ASSERT_TRUE(req.has_param("key"));
  5117. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5118. })
  5119. .Get("/with-range",
  5120. [&](const Request & /*req*/, Response &res) {
  5121. res.set_content("abcdefg", "text/plain");
  5122. })
  5123. .Get("/test-start-time",
  5124. [&](const Request &req, Response & /*res*/) {
  5125. EXPECT_NE(req.start_time_,
  5126. std::chrono::steady_clock::time_point::min());
  5127. })
  5128. .Get("/with-range-customized-response",
  5129. [&](const Request & /*req*/, Response &res) {
  5130. res.status = StatusCode::BadRequest_400;
  5131. res.set_content(JSON_DATA, "application/json");
  5132. })
  5133. .Post("/chunked",
  5134. [&](const Request &req, Response & /*res*/) {
  5135. EXPECT_EQ(req.body, "dechunked post body");
  5136. })
  5137. .Post("/large-chunked",
  5138. [&](const Request &req, Response & /*res*/) {
  5139. std::string expected(6 * 30 * 1024u, 'a');
  5140. EXPECT_EQ(req.body, expected);
  5141. })
  5142. .Post("/multipart",
  5143. [&](const Request &req, Response & /*res*/) {
  5144. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5145. req.form.get_field_count("text2") +
  5146. req.form.get_field_count("file3") +
  5147. req.form.get_field_count("file4"));
  5148. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5149. req.form.get_file_count("file2"));
  5150. ASSERT_TRUE(!req.form.has_file("???"));
  5151. ASSERT_TRUE(!req.form.has_field("???"));
  5152. ASSERT_TRUE(req.body.empty());
  5153. {
  5154. const auto &text = req.form.get_field("text1");
  5155. EXPECT_EQ("text default", text);
  5156. }
  5157. {
  5158. const auto &text = req.form.get_field("text2");
  5159. EXPECT_EQ("aωb", text);
  5160. }
  5161. {
  5162. const auto &file = req.form.get_file("file1");
  5163. EXPECT_EQ("hello.txt", file.filename);
  5164. EXPECT_EQ("text/plain", file.content_type);
  5165. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5166. }
  5167. {
  5168. const auto &file = req.form.get_file("file2");
  5169. EXPECT_EQ("world.json", file.filename);
  5170. EXPECT_EQ("application/json", file.content_type);
  5171. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5172. }
  5173. {
  5174. const auto &text = req.form.get_field("file3");
  5175. EXPECT_EQ(0u, text.size());
  5176. }
  5177. {
  5178. const auto &text = req.form.get_field("file4");
  5179. EXPECT_EQ(0u, text.size());
  5180. }
  5181. })
  5182. .Post("/multipart/multi_file_values",
  5183. [&](const Request &req, Response & /*res*/) {
  5184. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5185. req.form.get_field_count("multi_text1"));
  5186. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5187. ASSERT_TRUE(!req.form.has_file("???"));
  5188. ASSERT_TRUE(!req.form.has_field("???"));
  5189. ASSERT_TRUE(req.body.empty());
  5190. {
  5191. const auto &text = req.form.get_field("text");
  5192. EXPECT_EQ("default text", text);
  5193. }
  5194. {
  5195. const auto &text1_values = req.form.get_fields("multi_text1");
  5196. EXPECT_EQ(2u, text1_values.size());
  5197. EXPECT_EQ("aaaaa", text1_values[0]);
  5198. EXPECT_EQ("bbbbb", text1_values[1]);
  5199. }
  5200. {
  5201. const auto &file1_values = req.form.get_files("multi_file1");
  5202. EXPECT_EQ(2u, file1_values.size());
  5203. auto file1 = file1_values[0];
  5204. EXPECT_EQ(file1.filename, "hello.txt");
  5205. EXPECT_EQ(file1.content_type, "text/plain");
  5206. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5207. auto file2 = file1_values[1];
  5208. EXPECT_EQ(file2.filename, "world.json");
  5209. EXPECT_EQ(file2.content_type, "application/json");
  5210. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5211. }
  5212. })
  5213. .Post("/empty",
  5214. [&](const Request &req, Response &res) {
  5215. EXPECT_EQ(req.body, "");
  5216. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5217. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5218. res.set_content("empty", "text/plain");
  5219. })
  5220. .Post("/empty-no-content-type",
  5221. [&](const Request &req, Response &res) {
  5222. EXPECT_EQ(req.body, "");
  5223. EXPECT_FALSE(req.has_header("Content-Type"));
  5224. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5225. res.set_content("empty-no-content-type", "text/plain");
  5226. })
  5227. .Post("/path-only",
  5228. [&](const Request &req, Response &res) {
  5229. EXPECT_EQ(req.body, "");
  5230. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5231. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5232. res.set_content("path-only", "text/plain");
  5233. })
  5234. .Post("/path-headers-only",
  5235. [&](const Request &req, Response &res) {
  5236. EXPECT_EQ(req.body, "");
  5237. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5238. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5239. EXPECT_EQ("world", req.get_header_value("hello"));
  5240. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5241. res.set_content("path-headers-only", "text/plain");
  5242. })
  5243. .Post("/post-large",
  5244. [&](const Request &req, Response &res) {
  5245. EXPECT_EQ(req.body, LARGE_DATA);
  5246. res.set_content(req.body, "text/plain");
  5247. })
  5248. .Post("/post-loopback",
  5249. [&](const Request &, Response &res,
  5250. ContentReader const &content_reader) {
  5251. std::string body;
  5252. content_reader([&](const char *data, size_t data_length) {
  5253. body.append(data, data_length);
  5254. return true;
  5255. });
  5256. res.set_content(body, "text/plain");
  5257. })
  5258. .Put("/put-loopback",
  5259. [&](const Request &, Response &res,
  5260. ContentReader const &content_reader) {
  5261. std::string body;
  5262. content_reader([&](const char *data, size_t data_length) {
  5263. body.append(data, data_length);
  5264. return true;
  5265. });
  5266. res.set_content(body, "text/plain");
  5267. })
  5268. .Patch("/patch-loopback",
  5269. [&](const Request &, Response &res,
  5270. ContentReader const &content_reader) {
  5271. std::string body;
  5272. content_reader([&](const char *data, size_t data_length) {
  5273. body.append(data, data_length);
  5274. return true;
  5275. });
  5276. res.set_content(body, "text/plain");
  5277. })
  5278. .Put("/empty-no-content-type",
  5279. [&](const Request &req, Response &res) {
  5280. EXPECT_EQ(req.body, "");
  5281. EXPECT_FALSE(req.has_header("Content-Type"));
  5282. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5283. res.set_content("empty-no-content-type", "text/plain");
  5284. })
  5285. .Put("/put",
  5286. [&](const Request &req, Response &res) {
  5287. EXPECT_EQ(req.body, "PUT");
  5288. res.set_content(req.body, "text/plain");
  5289. })
  5290. .Put("/put-large",
  5291. [&](const Request &req, Response &res) {
  5292. EXPECT_EQ(req.body, LARGE_DATA);
  5293. res.set_content(req.body, "text/plain");
  5294. })
  5295. .Patch("/patch",
  5296. [&](const Request &req, Response &res) {
  5297. EXPECT_EQ(req.body, "PATCH");
  5298. res.set_content(req.body, "text/plain");
  5299. })
  5300. .Delete("/delete",
  5301. [&](const Request & /*req*/, Response &res) {
  5302. res.set_content("DELETE", "text/plain");
  5303. })
  5304. .Delete("/delete-body",
  5305. [&](const Request &req, Response &res) {
  5306. EXPECT_EQ(req.body, "content");
  5307. res.set_content(req.body, "text/plain");
  5308. })
  5309. .Options(R"(\*)",
  5310. [&](const Request & /*req*/, Response &res) {
  5311. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5312. })
  5313. .CustomRoute("PROPFIND", "/dav/:id",
  5314. [&](const Request &req, Response &res) {
  5315. res.set_header("x-body-size",
  5316. std::to_string(req.body.size()));
  5317. res.set_header("x-matched-route", req.matched_route);
  5318. res.set_header("x-dav-id", req.path_params.at("id"));
  5319. res.status = StatusCode::MultiStatus_207;
  5320. res.set_content(req.body, "application/xml");
  5321. })
  5322. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5323. [&](const Request &req, Response &res) {
  5324. res.set_header("x-dav-match", req.matches[1]);
  5325. res.status = StatusCode::MultiStatus_207;
  5326. })
  5327. .CustomRoute("MKCOL", "/dav-mkcol",
  5328. [&](const Request &req, Response &res) {
  5329. EXPECT_TRUE(req.body.empty());
  5330. res.status = StatusCode::Created_201;
  5331. })
  5332. .CustomRoute(
  5333. "REPORT", "/dav-report",
  5334. [&](const Request & /*req*/, Response &res,
  5335. const ContentReader &content_reader) {
  5336. std::string body;
  5337. content_reader([&](const char *data, size_t data_length) {
  5338. body.append(data, data_length);
  5339. return true;
  5340. });
  5341. res.set_header("x-body-size", std::to_string(body.size()));
  5342. res.status = StatusCode::MultiStatus_207;
  5343. res.set_content(body, "application/xml");
  5344. })
  5345. .Get("/request-target",
  5346. [&](const Request &req, Response & /*res*/) {
  5347. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5348. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5349. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5350. })
  5351. .Get("/long-query-value",
  5352. [&](const Request &req, Response & /*res*/) {
  5353. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5354. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5355. })
  5356. .Get("/too-long-query-value",
  5357. [&](const Request &req, Response & /*res*/) {
  5358. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5359. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5360. })
  5361. .Get("/array-param",
  5362. [&](const Request &req, Response & /*res*/) {
  5363. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5364. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5365. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5366. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5367. })
  5368. .Get("/array-param-values",
  5369. [&](const Request &req, Response & /*res*/) {
  5370. auto values = req.get_param_values("array");
  5371. EXPECT_EQ(3u, values.size());
  5372. EXPECT_EQ("value1", values[0]);
  5373. EXPECT_EQ("value2", values[1]);
  5374. EXPECT_EQ("value3", values[2]);
  5375. auto empty = req.get_param_values("nonexistent");
  5376. EXPECT_TRUE(empty.empty());
  5377. })
  5378. .Post("/validate-no-multiple-headers",
  5379. [&](const Request &req, Response & /*res*/) {
  5380. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5381. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5382. })
  5383. .Post("/content_receiver",
  5384. [&](const Request &req, Response &res,
  5385. const ContentReader &content_reader) {
  5386. if (req.is_multipart_form_data()) {
  5387. std::vector<FormData> items;
  5388. content_reader(
  5389. [&](const FormData &file) {
  5390. items.push_back(file);
  5391. return true;
  5392. },
  5393. [&](const char *data, size_t data_length) {
  5394. items.back().content.append(data, data_length);
  5395. return true;
  5396. });
  5397. EXPECT_EQ(5u, items.size());
  5398. {
  5399. const auto &file = get_file_value(items, "text1");
  5400. EXPECT_TRUE(file.filename.empty());
  5401. EXPECT_EQ("text default", file.content);
  5402. }
  5403. {
  5404. const auto &file = get_file_value(items, "text2");
  5405. EXPECT_TRUE(file.filename.empty());
  5406. EXPECT_EQ("aωb", file.content);
  5407. }
  5408. {
  5409. const auto &file = get_file_value(items, "file1");
  5410. EXPECT_EQ("hello.txt", file.filename);
  5411. EXPECT_EQ("text/plain", file.content_type);
  5412. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5413. }
  5414. {
  5415. const auto &file = get_file_value(items, "file2");
  5416. EXPECT_EQ("world.json", file.filename);
  5417. EXPECT_EQ("application/json", file.content_type);
  5418. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5419. }
  5420. {
  5421. const auto &file = get_file_value(items, "file3");
  5422. EXPECT_TRUE(file.filename.empty());
  5423. EXPECT_EQ("application/octet-stream", file.content_type);
  5424. EXPECT_EQ(0u, file.content.size());
  5425. }
  5426. } else {
  5427. std::string body;
  5428. content_reader([&](const char *data, size_t data_length) {
  5429. EXPECT_EQ(7U, data_length);
  5430. body.append(data, data_length);
  5431. return true;
  5432. });
  5433. EXPECT_EQ(body, "content");
  5434. res.set_content(body, "text/plain");
  5435. }
  5436. })
  5437. .Put("/content_receiver",
  5438. [&](const Request & /*req*/, Response &res,
  5439. const ContentReader &content_reader) {
  5440. std::string body;
  5441. content_reader([&](const char *data, size_t data_length) {
  5442. body.append(data, data_length);
  5443. return true;
  5444. });
  5445. EXPECT_EQ(body, "content");
  5446. res.set_content(body, "text/plain");
  5447. })
  5448. .Patch("/content_receiver",
  5449. [&](const Request & /*req*/, Response &res,
  5450. const ContentReader &content_reader) {
  5451. std::string body;
  5452. content_reader([&](const char *data, size_t data_length) {
  5453. body.append(data, data_length);
  5454. return true;
  5455. });
  5456. EXPECT_EQ(body, "content");
  5457. res.set_content(body, "text/plain");
  5458. })
  5459. .Post("/query-string-and-body",
  5460. [&](const Request &req, Response & /*res*/) {
  5461. ASSERT_TRUE(req.has_param("key"));
  5462. EXPECT_EQ(req.get_param_value("key"), "value");
  5463. EXPECT_EQ(req.body, "content");
  5464. })
  5465. .Get("/last-request",
  5466. [&](const Request &req, Response & /*res*/) {
  5467. EXPECT_EQ("close", req.get_header_value("Connection"));
  5468. })
  5469. .Get(R"(/redirect/(\d+))",
  5470. [&](const Request &req, Response &res) {
  5471. auto num = std::stoi(req.matches[1]) + 1;
  5472. std::string url = "/redirect/" + std::to_string(num);
  5473. res.set_redirect(url);
  5474. })
  5475. .Post("/binary",
  5476. [&](const Request &req, Response &res) {
  5477. EXPECT_EQ(4U, req.body.size());
  5478. EXPECT_EQ("application/octet-stream",
  5479. req.get_header_value("Content-Type"));
  5480. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5481. res.set_content(req.body, "application/octet-stream");
  5482. })
  5483. .Put("/binary",
  5484. [&](const Request &req, Response &res) {
  5485. EXPECT_EQ(4U, req.body.size());
  5486. EXPECT_EQ("application/octet-stream",
  5487. req.get_header_value("Content-Type"));
  5488. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5489. res.set_content(req.body, "application/octet-stream");
  5490. })
  5491. .Patch("/binary",
  5492. [&](const Request &req, Response &res) {
  5493. EXPECT_EQ(4U, req.body.size());
  5494. EXPECT_EQ("application/octet-stream",
  5495. req.get_header_value("Content-Type"));
  5496. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5497. res.set_content(req.body, "application/octet-stream");
  5498. })
  5499. .Delete("/binary",
  5500. [&](const Request &req, Response &res) {
  5501. EXPECT_EQ(4U, req.body.size());
  5502. EXPECT_EQ("application/octet-stream",
  5503. req.get_header_value("Content-Type"));
  5504. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5505. res.set_content(req.body, "application/octet-stream");
  5506. })
  5507. .Get("/issue1772",
  5508. [&](const Request & /*req*/, Response &res) {
  5509. res.status = 401;
  5510. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5511. })
  5512. .Delete("/issue609",
  5513. [](const httplib::Request &, httplib::Response &res,
  5514. const httplib::ContentReader &) {
  5515. res.set_content("ok", "text/plain");
  5516. })
  5517. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5518. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5519. .Get("/compress",
  5520. [&](const Request & /*req*/, Response &res) {
  5521. res.set_content(
  5522. "12345678901234567890123456789012345678901234567890123456789"
  5523. "01234567890123456789012345678901234567890",
  5524. "text/plain");
  5525. })
  5526. .Get("/compress-with-charset",
  5527. [&](const Request & /*req*/, Response &res) {
  5528. res.set_content(
  5529. "12345678901234567890123456789012345678901234567890123456789"
  5530. "01234567890123456789012345678901234567890",
  5531. "application/json; charset=utf-8");
  5532. })
  5533. .Get("/nocompress",
  5534. [&](const Request & /*req*/, Response &res) {
  5535. res.set_content(
  5536. "12345678901234567890123456789012345678901234567890123456789"
  5537. "01234567890123456789012345678901234567890",
  5538. "application/octet-stream");
  5539. })
  5540. .Post("/compress-multipart",
  5541. [&](const Request &req, Response & /*res*/) {
  5542. EXPECT_EQ(2u, req.form.fields.size());
  5543. ASSERT_TRUE(!req.form.has_field("???"));
  5544. {
  5545. const auto &text = req.form.get_field("key1");
  5546. EXPECT_EQ("test", text);
  5547. }
  5548. {
  5549. const auto &text = req.form.get_field("key2");
  5550. EXPECT_EQ("--abcdefg123", text);
  5551. }
  5552. })
  5553. #endif
  5554. ;
  5555. persons_["john"] = "programmer";
  5556. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5557. svr_.wait_until_ready();
  5558. }
  5559. virtual void TearDown() {
  5560. svr_.stop();
  5561. if (!request_threads_.empty()) {
  5562. std::this_thread::sleep_for(std::chrono::seconds(1));
  5563. for (auto &t : request_threads_) {
  5564. t.join();
  5565. }
  5566. }
  5567. t_.join();
  5568. }
  5569. map<string, string> persons_;
  5570. #ifdef CPPHTTPLIB_SSL_ENABLED
  5571. SSLClient cli_;
  5572. SSLServer svr_;
  5573. #else
  5574. Client cli_;
  5575. Server svr_;
  5576. #endif
  5577. thread t_;
  5578. std::vector<thread> request_threads_;
  5579. };
  5580. TEST_F(ServerTest, GetMethod200) {
  5581. auto res = cli_.Get("/hi");
  5582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5583. EXPECT_EQ("HTTP/1.1", res->version);
  5584. EXPECT_EQ(StatusCode::OK_200, res->status);
  5585. EXPECT_EQ("OK", res->reason);
  5586. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5587. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5588. EXPECT_EQ("Hello World!", res->body);
  5589. }
  5590. TEST_F(ServerTest, GetEmptyFile) {
  5591. auto res = cli_.Get("/empty_file");
  5592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5593. EXPECT_EQ(StatusCode::OK_200, res->status);
  5594. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5595. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5596. EXPECT_EQ("", res->body);
  5597. }
  5598. TEST_F(ServerTest, GetFileContent) {
  5599. auto res = cli_.Get("/file_content");
  5600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5601. EXPECT_EQ(StatusCode::OK_200, res->status);
  5602. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5603. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5604. EXPECT_EQ("test.html", res->body);
  5605. }
  5606. TEST_F(ServerTest, GetFileContentWithRange) {
  5607. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5609. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5610. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5611. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5612. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5613. EXPECT_EQ("est", res->body);
  5614. }
  5615. TEST_F(ServerTest, GetFileContentWithContentType) {
  5616. auto res = cli_.Get("/file_content_with_content_type");
  5617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5618. EXPECT_EQ(StatusCode::OK_200, res->status);
  5619. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5620. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5621. EXPECT_EQ("file\n", res->body);
  5622. }
  5623. TEST_F(ServerTest, GetInvalidFileContent) {
  5624. auto res = cli_.Get("/invalid_file_content");
  5625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5626. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5627. }
  5628. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5629. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ("HTTP/1.1", res->version);
  5632. EXPECT_EQ(StatusCode::OK_200, res->status);
  5633. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5634. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5635. EXPECT_EQ("Hello World!", res->body);
  5636. }
  5637. TEST_F(ServerTest, GetMethod302) {
  5638. auto res = cli_.Get("/");
  5639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5640. EXPECT_EQ(StatusCode::Found_302, res->status);
  5641. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5642. }
  5643. TEST_F(ServerTest, GetMethod302Redirect) {
  5644. cli_.set_follow_location(true);
  5645. auto res = cli_.Get("/");
  5646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5647. EXPECT_EQ(StatusCode::OK_200, res->status);
  5648. EXPECT_EQ("Hello World!", res->body);
  5649. EXPECT_EQ("/hi", res->location);
  5650. }
  5651. TEST_F(ServerTest, GetMethod404) {
  5652. auto res = cli_.Get("/invalid");
  5653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5654. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5655. }
  5656. TEST_F(ServerTest, HeadMethod200) {
  5657. auto res = cli_.Head("/hi");
  5658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5659. EXPECT_EQ(StatusCode::OK_200, res->status);
  5660. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5661. EXPECT_TRUE(res->body.empty());
  5662. }
  5663. TEST_F(ServerTest, HeadMethod200Static) {
  5664. auto res = cli_.Head("/mount/dir/index.html");
  5665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5666. EXPECT_EQ(StatusCode::OK_200, res->status);
  5667. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5668. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5669. EXPECT_TRUE(res->body.empty());
  5670. }
  5671. TEST_F(ServerTest, HeadMethod404) {
  5672. auto res = cli_.Head("/invalid");
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5675. EXPECT_TRUE(res->body.empty());
  5676. }
  5677. TEST_F(ServerTest, GetMethodPersonJohn) {
  5678. auto res = cli_.Get("/person/john");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. EXPECT_EQ(StatusCode::OK_200, res->status);
  5681. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5682. EXPECT_EQ("programmer", res->body);
  5683. }
  5684. TEST_F(ServerTest, PostMethod1) {
  5685. auto res = cli_.Get("/person/john1");
  5686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5687. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5688. res = cli_.Post("/person", "name=john1&note=coder",
  5689. "application/x-www-form-urlencoded");
  5690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5691. ASSERT_EQ(StatusCode::OK_200, res->status);
  5692. res = cli_.Get("/person/john1");
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. ASSERT_EQ(StatusCode::OK_200, res->status);
  5695. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5696. ASSERT_EQ("coder", res->body);
  5697. }
  5698. TEST_F(ServerTest, PostMethod2) {
  5699. auto res = cli_.Get("/person/john2");
  5700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5701. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5702. Params params;
  5703. params.emplace("name", "john2");
  5704. params.emplace("note", "coder");
  5705. res = cli_.Post("/person", params);
  5706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5707. ASSERT_EQ(StatusCode::OK_200, res->status);
  5708. res = cli_.Get("/person/john2");
  5709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5710. ASSERT_EQ(StatusCode::OK_200, res->status);
  5711. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5712. ASSERT_EQ("coder", res->body);
  5713. }
  5714. TEST_F(ServerTest, PutMethod3) {
  5715. auto res = cli_.Get("/person/john3");
  5716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5717. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5718. Params params;
  5719. params.emplace("name", "john3");
  5720. params.emplace("note", "coder");
  5721. res = cli_.Put("/person", params);
  5722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5723. ASSERT_EQ(StatusCode::OK_200, res->status);
  5724. res = cli_.Get("/person/john3");
  5725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5726. ASSERT_EQ(StatusCode::OK_200, res->status);
  5727. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5728. ASSERT_EQ("coder", res->body);
  5729. }
  5730. TEST_F(ServerTest, DeleteMethod1) {
  5731. auto res = cli_.Get("/person/john4");
  5732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5733. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5734. Params params;
  5735. params.emplace("name", "john4");
  5736. params.emplace("note", "coder");
  5737. res = cli_.Post("/person", params);
  5738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5739. ASSERT_EQ(StatusCode::OK_200, res->status);
  5740. res = cli_.Get("/person/john4");
  5741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5742. ASSERT_EQ(StatusCode::OK_200, res->status);
  5743. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5744. ASSERT_EQ("coder", res->body);
  5745. Params delete_params;
  5746. delete_params.emplace("name", "john4");
  5747. res = cli_.Delete("/person", delete_params);
  5748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5749. ASSERT_EQ(StatusCode::OK_200, res->status);
  5750. ASSERT_EQ("DELETED", res->body);
  5751. res = cli_.Get("/person/john4");
  5752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5753. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5754. }
  5755. TEST_F(ServerTest, DeleteMethod2) {
  5756. auto res = cli_.Get("/person/john5");
  5757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5758. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5759. Params params;
  5760. params.emplace("name", "john5");
  5761. params.emplace("note", "developer");
  5762. res = cli_.Post("/person", params);
  5763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5764. ASSERT_EQ(StatusCode::OK_200, res->status);
  5765. res = cli_.Get("/person/john5");
  5766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5767. ASSERT_EQ(StatusCode::OK_200, res->status);
  5768. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5769. ASSERT_EQ("developer", res->body);
  5770. Params delete_params;
  5771. delete_params.emplace("name", "john5");
  5772. Headers headers;
  5773. headers.emplace("Custom-Header", "test-value");
  5774. res = cli_.Delete("/person", headers, delete_params);
  5775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5776. ASSERT_EQ(StatusCode::OK_200, res->status);
  5777. ASSERT_EQ("DELETED", res->body);
  5778. res = cli_.Get("/person/john5");
  5779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5780. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5781. }
  5782. TEST_F(ServerTest, DeleteMethod3) {
  5783. auto res = cli_.Get("/person/john6");
  5784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5785. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5786. Params params;
  5787. params.emplace("name", "john6");
  5788. params.emplace("note", "tester");
  5789. res = cli_.Post("/person", params);
  5790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5791. ASSERT_EQ(StatusCode::OK_200, res->status);
  5792. res = cli_.Get("/person/john6");
  5793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5794. ASSERT_EQ(StatusCode::OK_200, res->status);
  5795. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5796. ASSERT_EQ("tester", res->body);
  5797. Params delete_params;
  5798. delete_params.emplace("name", "john6");
  5799. Headers headers;
  5800. headers.emplace("Custom-Header", "test-value");
  5801. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5803. ASSERT_EQ(StatusCode::OK_200, res->status);
  5804. ASSERT_EQ("DELETED", res->body);
  5805. res = cli_.Get("/person/john6");
  5806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5807. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5808. }
  5809. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5810. Params params;
  5811. params.emplace("json", JSON_DATA);
  5812. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5814. ASSERT_EQ(StatusCode::OK_200, res->status);
  5815. ASSERT_EQ(JSON_DATA, res->body);
  5816. }
  5817. TEST_F(ServerTest, PostEmptyContent) {
  5818. auto res = cli_.Post("/empty", "", "text/plain");
  5819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5820. ASSERT_EQ(StatusCode::OK_200, res->status);
  5821. ASSERT_EQ("empty", res->body);
  5822. }
  5823. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5824. auto res = cli_.Post("/empty-no-content-type");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. ASSERT_EQ(StatusCode::OK_200, res->status);
  5827. ASSERT_EQ("empty-no-content-type", res->body);
  5828. }
  5829. TEST_F(ServerTest, PostPathOnly) {
  5830. auto res = cli_.Post("/path-only");
  5831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5832. ASSERT_EQ(StatusCode::OK_200, res->status);
  5833. ASSERT_EQ("path-only", res->body);
  5834. }
  5835. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5836. auto res = cli_.Post("/path-headers-only",
  5837. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5839. ASSERT_EQ(StatusCode::OK_200, res->status);
  5840. ASSERT_EQ("path-headers-only", res->body);
  5841. }
  5842. TEST_F(ServerTest, PostLarge) {
  5843. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5845. ASSERT_EQ(StatusCode::OK_200, res->status);
  5846. EXPECT_EQ(LARGE_DATA, res->body);
  5847. }
  5848. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5849. auto res = cli_.Put("/empty-no-content-type");
  5850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5851. ASSERT_EQ(StatusCode::OK_200, res->status);
  5852. ASSERT_EQ("empty-no-content-type", res->body);
  5853. }
  5854. TEST_F(ServerTest, GetMethodDir) {
  5855. auto res = cli_.Get("/dir/");
  5856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5857. EXPECT_EQ(StatusCode::OK_200, res->status);
  5858. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5859. auto body = R"(<html>
  5860. <head>
  5861. </head>
  5862. <body>
  5863. <a href="/dir/test.html">Test</a>
  5864. <a href="/hi">hi</a>
  5865. </body>
  5866. </html>
  5867. )";
  5868. EXPECT_EQ(body, res->body);
  5869. }
  5870. TEST_F(ServerTest, GetMethodDirTest) {
  5871. auto res = cli_.Get("/dir/test.html");
  5872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5873. EXPECT_EQ(StatusCode::OK_200, res->status);
  5874. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5875. EXPECT_EQ("test.html", res->body);
  5876. }
  5877. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5878. auto res = cli_.Get("/dir/../dir/test.html");
  5879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5880. EXPECT_EQ(StatusCode::OK_200, res->status);
  5881. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5882. EXPECT_EQ("test.html", res->body);
  5883. }
  5884. TEST_F(ServerTest, GetMethodInvalidPath) {
  5885. auto res = cli_.Get("/dir/../test.html");
  5886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5887. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5888. }
  5889. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5890. auto res = cli_.Get("/../www/dir/test.html");
  5891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5892. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5893. }
  5894. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5895. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5897. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5898. }
  5899. TEST_F(ServerTest, GetMethodDirMountTest) {
  5900. auto res = cli_.Get("/mount/dir/test.html");
  5901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5902. EXPECT_EQ(StatusCode::OK_200, res->status);
  5903. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5904. EXPECT_EQ("test.html", res->body);
  5905. }
  5906. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5907. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5909. EXPECT_EQ(StatusCode::OK_200, res->status);
  5910. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5911. EXPECT_EQ("test.html", res->body);
  5912. }
  5913. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5914. auto res = cli_.Get("/mount/dir/../test.html");
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5917. }
  5918. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5919. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5921. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5922. }
  5923. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5924. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5926. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5927. }
  5928. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5929. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5931. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5932. }
  5933. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5934. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5936. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5937. }
  5938. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5939. auto res = cli_.Get("/mount/dir");
  5940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5941. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5942. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5943. }
  5944. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5945. auto res = cli_.Get("//dir");
  5946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5947. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5948. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5949. }
  5950. TEST_F(ServerTest, PostMethod303) {
  5951. auto res = cli_.Post("/1", "body", "text/plain");
  5952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5953. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5954. EXPECT_EQ("/2", res->get_header_value("Location"));
  5955. }
  5956. TEST_F(ServerTest, PostMethod303Redirect) {
  5957. cli_.set_follow_location(true);
  5958. auto res = cli_.Post("/1", "body", "text/plain");
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. EXPECT_EQ(StatusCode::OK_200, res->status);
  5961. EXPECT_EQ("redirected.", res->body);
  5962. EXPECT_EQ("/2", res->location);
  5963. }
  5964. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5965. auto res = cli_.Get("/dir/test.abcde");
  5966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5967. EXPECT_EQ(StatusCode::OK_200, res->status);
  5968. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5969. EXPECT_EQ("abcde", res->body);
  5970. }
  5971. TEST_F(ServerTest, StaticFileRange) {
  5972. auto res =
  5973. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5975. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5976. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5977. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5978. EXPECT_EQ(true, res->has_header("Content-Range"));
  5979. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5980. EXPECT_EQ(std::string("cd"), res->body);
  5981. }
  5982. TEST_F(ServerTest, StaticFileRanges) {
  5983. auto res = cli_.Get("/dir/test.abcde",
  5984. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5986. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5987. EXPECT_TRUE(
  5988. res->get_header_value("Content-Type")
  5989. .find(
  5990. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5991. 0);
  5992. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5993. }
  5994. TEST_F(ServerTest, StaticFileRangeHead) {
  5995. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5998. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5999. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6000. EXPECT_EQ(true, res->has_header("Content-Range"));
  6001. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6002. }
  6003. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6004. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6006. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6007. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6008. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6009. EXPECT_EQ(true, res->has_header("Content-Range"));
  6010. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6011. res->get_header_value("Content-Range"));
  6012. EXPECT_EQ("LAST\n", res->body);
  6013. }
  6014. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6015. auto res =
  6016. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6019. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6020. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6021. EXPECT_EQ(true, res->has_header("Content-Range"));
  6022. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6023. }
  6024. TEST_F(ServerTest, StaticFileBigFile) {
  6025. auto res = cli_.Get("/dir/1MB.txt");
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::OK_200, res->status);
  6028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6029. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6030. }
  6031. TEST_F(ServerTest, InvalidBaseDirMount) {
  6032. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6033. }
  6034. TEST_F(ServerTest, Binary) {
  6035. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6036. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6037. "application/octet-stream");
  6038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6039. ASSERT_EQ(StatusCode::OK_200, res->status);
  6040. ASSERT_EQ(4U, res->body.size());
  6041. res = cli_.Put("/binary", binary.data(), binary.size(),
  6042. "application/octet-stream");
  6043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6044. ASSERT_EQ(StatusCode::OK_200, res->status);
  6045. ASSERT_EQ(4U, res->body.size());
  6046. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6047. "application/octet-stream");
  6048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6049. ASSERT_EQ(StatusCode::OK_200, res->status);
  6050. ASSERT_EQ(4U, res->body.size());
  6051. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6052. "application/octet-stream");
  6053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6054. ASSERT_EQ(StatusCode::OK_200, res->status);
  6055. ASSERT_EQ(4U, res->body.size());
  6056. }
  6057. TEST_F(ServerTest, BinaryString) {
  6058. auto binary = std::string("\x00\x01\x02\x03", 4);
  6059. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6061. ASSERT_EQ(StatusCode::OK_200, res->status);
  6062. ASSERT_EQ(4U, res->body.size());
  6063. res = cli_.Put("/binary", binary, "application/octet-stream");
  6064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6065. ASSERT_EQ(StatusCode::OK_200, res->status);
  6066. ASSERT_EQ(4U, res->body.size());
  6067. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. ASSERT_EQ(StatusCode::OK_200, res->status);
  6070. ASSERT_EQ(4U, res->body.size());
  6071. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6073. ASSERT_EQ(StatusCode::OK_200, res->status);
  6074. ASSERT_EQ(4U, res->body.size());
  6075. }
  6076. TEST_F(ServerTest, EmptyRequest) {
  6077. auto res = cli_.Get("");
  6078. ASSERT_TRUE(!res);
  6079. EXPECT_EQ(Error::Connection, res.error());
  6080. }
  6081. TEST_F(ServerTest, LongRequest) {
  6082. std::string request;
  6083. for (size_t i = 0; i < 545; i++) {
  6084. request += "/TooLongRequest";
  6085. }
  6086. request += "OK";
  6087. auto res = cli_.Get(request.c_str());
  6088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6089. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6090. }
  6091. TEST_F(ServerTest, TooLongRequest) {
  6092. std::string request;
  6093. for (size_t i = 0; i < 546; i++) {
  6094. request += "/TooLongRequest";
  6095. }
  6096. request += "_NG";
  6097. auto start = std::chrono::high_resolution_clock::now();
  6098. cli_.set_keep_alive(true);
  6099. auto res = cli_.Get(request.c_str());
  6100. auto end = std::chrono::high_resolution_clock::now();
  6101. auto elapsed =
  6102. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6103. .count();
  6104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6105. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6106. EXPECT_LE(elapsed, 1000);
  6107. EXPECT_EQ("close", res->get_header_value("Connection"));
  6108. EXPECT_FALSE(cli_.is_socket_open());
  6109. }
  6110. TEST_F(ServerTest, AlmostTooLongRequest) {
  6111. // test for #2046 - URI length check shouldn't include other content on req
  6112. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6113. // leading /, space, HTTP/1.1)
  6114. std::string request =
  6115. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6116. auto res = cli_.Get(request.c_str());
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6119. }
  6120. TEST_F(ServerTest, LongHeader) {
  6121. Request req;
  6122. req.method = "GET";
  6123. req.path = "/hi";
  6124. std::string host_and_port;
  6125. host_and_port += HOST;
  6126. host_and_port += ":";
  6127. host_and_port += std::to_string(PORT);
  6128. req.headers.emplace("Host", host_and_port.c_str());
  6129. req.headers.emplace("Accept", "*/*");
  6130. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6131. req.headers.emplace(
  6132. "Header-Name",
  6133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6161. "@@@@@@@@@@@@@@@@");
  6162. auto res = std::make_shared<Response>();
  6163. auto error = Error::Success;
  6164. auto ret = cli_.send(req, *res, error);
  6165. ASSERT_TRUE(ret);
  6166. EXPECT_EQ(StatusCode::OK_200, res->status);
  6167. }
  6168. TEST_F(ServerTest, LongQueryValue) {
  6169. auto start = std::chrono::high_resolution_clock::now();
  6170. cli_.set_keep_alive(true);
  6171. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6172. auto end = std::chrono::high_resolution_clock::now();
  6173. auto elapsed =
  6174. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6175. .count();
  6176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6177. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6178. EXPECT_LE(elapsed, 1000);
  6179. EXPECT_EQ("close", res->get_header_value("Connection"));
  6180. EXPECT_FALSE(cli_.is_socket_open());
  6181. }
  6182. TEST_F(ServerTest, TooLongQueryValue) {
  6183. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6184. ASSERT_FALSE(res);
  6185. EXPECT_EQ(Error::Read, res.error());
  6186. }
  6187. TEST_F(ServerTest, TooLongHeader) {
  6188. Request req;
  6189. req.method = "GET";
  6190. req.path = "/hi";
  6191. std::string host_and_port;
  6192. host_and_port += HOST;
  6193. host_and_port += ":";
  6194. host_and_port += std::to_string(PORT);
  6195. req.headers.emplace("Host", host_and_port.c_str());
  6196. req.headers.emplace("Accept", "*/*");
  6197. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6198. req.headers.emplace(
  6199. "Header-Name",
  6200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6223. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6224. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6225. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6226. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6227. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6228. "@@@@@@@@@@@@@@@@@");
  6229. auto res = std::make_shared<Response>();
  6230. auto error = Error::Success;
  6231. auto ret = cli_.send(req, *res, error);
  6232. ASSERT_TRUE(ret);
  6233. EXPECT_EQ(StatusCode::OK_200, res->status);
  6234. }
  6235. TEST_F(ServerTest, HeaderCountAtLimit) {
  6236. // Test with headers just under the 100 limit
  6237. httplib::Headers headers;
  6238. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6239. // This should keep us just under the 100 header limit
  6240. for (int i = 0; i < 95; i++) {
  6241. std::string name = "X-Test-Header-" + std::to_string(i);
  6242. std::string value = "value" + std::to_string(i);
  6243. headers.emplace(name, value);
  6244. }
  6245. // This should work fine as we're under the limit
  6246. auto res = cli_.Get("/hi", headers);
  6247. EXPECT_TRUE(res);
  6248. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6249. }
  6250. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6251. // Test with many headers to exceed the 100 limit
  6252. httplib::Headers headers;
  6253. // Add 150 headers to definitely exceed the 100 limit
  6254. for (int i = 0; i < 150; i++) {
  6255. std::string name = "X-Test-Header-" + std::to_string(i);
  6256. std::string value = "value" + std::to_string(i);
  6257. headers.emplace(name, value);
  6258. }
  6259. // This should fail due to exceeding header count limit
  6260. cli_.set_keep_alive(true);
  6261. auto res = cli_.Get("/hi", headers);
  6262. // The server should respond with 400 Bad Request
  6263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6264. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6265. EXPECT_EQ("close", res->get_header_value("Connection"));
  6266. EXPECT_FALSE(cli_.is_socket_open());
  6267. }
  6268. TEST_F(ServerTest, PercentEncoding) {
  6269. auto res = cli_.Get("/e%6edwith%");
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. EXPECT_EQ(StatusCode::OK_200, res->status);
  6272. }
  6273. TEST_F(ServerTest, PercentEncodingUnicode) {
  6274. auto res = cli_.Get("/e%u006edwith%");
  6275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. }
  6278. TEST_F(ServerTest, InvalidPercentEncoding) {
  6279. auto res = cli_.Get("/%endwith%");
  6280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6282. }
  6283. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6284. auto res = cli_.Get("/%uendwith%");
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6287. }
  6288. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6289. auto res = cli_.Get("/hello?aaa=bbb%");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6292. }
  6293. TEST_F(ServerTest, PlusSignEncoding) {
  6294. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. EXPECT_EQ(StatusCode::OK_200, res->status);
  6297. EXPECT_EQ("a +b", res->body);
  6298. }
  6299. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6300. // This test simulates a potential DoS attack using many headers
  6301. // to verify our security fix prevents memory exhaustion
  6302. httplib::Headers attack_headers;
  6303. // Attempt to add many headers like an attacker would (200 headers to far
  6304. // exceed limit)
  6305. for (int i = 0; i < 200; i++) {
  6306. std::string name = "X-Attack-Header-" + std::to_string(i);
  6307. std::string value = "attack_payload_" + std::to_string(i);
  6308. attack_headers.emplace(name, value);
  6309. }
  6310. // Try to POST with excessive headers
  6311. cli_.set_keep_alive(true);
  6312. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6313. // Should either fail or return 400 Bad Request due to security limit
  6314. if (res) {
  6315. // If we get a response, it should be 400 Bad Request
  6316. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6317. EXPECT_EQ("close", res->get_header_value("Connection"));
  6318. }
  6319. EXPECT_FALSE(cli_.is_socket_open());
  6320. }
  6321. TEST_F(ServerTest, MultipartFormData) {
  6322. UploadFormDataItems items = {
  6323. {"text1", "text default", "", ""},
  6324. {"text2", "aωb", "", ""},
  6325. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6326. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6327. {"file3", "", "", "application/octet-stream"},
  6328. {"file4", "", "", " application/json tmp-string "}};
  6329. auto res = cli_.Post("/multipart", items);
  6330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6331. EXPECT_EQ(StatusCode::OK_200, res->status);
  6332. }
  6333. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6334. UploadFormDataItems items = {
  6335. {"text", "default text", "", ""},
  6336. {"multi_text1", "aaaaa", "", ""},
  6337. {"multi_text1", "bbbbb", "", ""},
  6338. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6339. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6340. "application/json"},
  6341. };
  6342. auto res = cli_.Post("/multipart/multi_file_values", items);
  6343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6344. EXPECT_EQ(StatusCode::OK_200, res->status);
  6345. }
  6346. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6347. auto res = cli_.Get("/hi");
  6348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6349. EXPECT_EQ(StatusCode::OK_200, res->status);
  6350. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6351. EXPECT_EQ("Hello World!", res->body);
  6352. }
  6353. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6354. Request req;
  6355. req.method = "POST";
  6356. req.path = "/chunked";
  6357. std::string host_and_port;
  6358. host_and_port += HOST;
  6359. host_and_port += ":";
  6360. host_and_port += std::to_string(PORT);
  6361. req.headers.emplace("Host", host_and_port.c_str());
  6362. req.headers.emplace("Accept", "*/*");
  6363. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6364. req.headers.emplace("Content-Type", "text/plain");
  6365. req.headers.emplace("Content-Length", "0");
  6366. req.headers.emplace(
  6367. "Transfer-Encoding",
  6368. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6369. // Client does not chunk, so make a chunked body manually.
  6370. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6371. auto res = std::make_shared<Response>();
  6372. auto error = Error::Success;
  6373. auto ret = cli_.send(req, *res, error);
  6374. ASSERT_TRUE(ret);
  6375. EXPECT_EQ(StatusCode::OK_200, res->status);
  6376. }
  6377. template <typename ClientT>
  6378. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6379. int expected_status) {
  6380. Request req;
  6381. req.method = "POST";
  6382. req.path = "/chunked";
  6383. std::string host_and_port;
  6384. host_and_port += HOST;
  6385. host_and_port += ":";
  6386. host_and_port += std::to_string(PORT);
  6387. req.headers.emplace("Host", host_and_port.c_str());
  6388. req.headers.emplace("Content-Length", "0");
  6389. req.headers.emplace("Transfer-Encoding", "chunked");
  6390. req.body = body;
  6391. auto res = std::make_shared<Response>();
  6392. auto error = Error::Success;
  6393. ASSERT_TRUE(cli.send(req, *res, error));
  6394. EXPECT_EQ(expected_status, res->status);
  6395. }
  6396. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6397. // rather than treat them as valid lengths.
  6398. template <typename ClientT>
  6399. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6400. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6401. }
  6402. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6403. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6404. }
  6405. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6406. expect_chunked_body_rejected(
  6407. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6408. }
  6409. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6410. // chunk-size line carries no CR, LF or other control character ahead of its
  6411. // terminator. Such a line must be refused rather than read as extension text.
  6412. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6413. expect_chunked_body_rejected(
  6414. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6415. }
  6416. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6417. expect_chunked_body_rejected(
  6418. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6419. }
  6420. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6421. expect_chunked_body_rejected(
  6422. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6423. }
  6424. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6425. // The literal stays split: a hex escape consumes every hex digit that
  6426. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6427. expect_chunked_body_rejected(
  6428. cli_, "4;a\x01"
  6429. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6430. }
  6431. TEST_F(ServerTest, AcceptsChunkExtension) {
  6432. expect_chunked_body_status(cli_,
  6433. "4;name=value\r\ndech\r\n"
  6434. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6435. "0;last\r\n\r\n",
  6436. StatusCode::OK_200);
  6437. }
  6438. TEST_F(ServerTest, GetStreamed2) {
  6439. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6442. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6443. EXPECT_EQ(true, res->has_header("Content-Range"));
  6444. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6445. EXPECT_EQ(std::string("ab"), res->body);
  6446. }
  6447. TEST_F(ServerTest, GetStreamed) {
  6448. auto res = cli_.Get("/streamed");
  6449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6450. EXPECT_EQ(StatusCode::OK_200, res->status);
  6451. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6452. EXPECT_EQ(std::string("aaabbb"), res->body);
  6453. }
  6454. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6455. auto res = cli_.Get("/streamed-without-length",
  6456. Headers{make_range_header({{0, -1}})});
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. EXPECT_EQ(StatusCode::OK_200, res->status);
  6459. EXPECT_EQ(false, res->has_header("Content-Length"));
  6460. EXPECT_EQ(false, res->has_header("Content-Range"));
  6461. EXPECT_EQ(std::string("abcdefg"), res->body);
  6462. }
  6463. TEST_F(ServerTest, GetStreamedWithRange1) {
  6464. auto res =
  6465. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6468. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6469. EXPECT_EQ(true, res->has_header("Content-Range"));
  6470. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6471. EXPECT_EQ(std::string("def"), res->body);
  6472. }
  6473. TEST_F(ServerTest, GetStreamedWithRange2) {
  6474. auto res =
  6475. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6478. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6479. EXPECT_EQ(true, res->has_header("Content-Range"));
  6480. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6481. EXPECT_EQ(std::string("bcdefg"), res->body);
  6482. }
  6483. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6484. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6487. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6488. EXPECT_EQ(true, res->has_header("Content-Range"));
  6489. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6490. EXPECT_EQ(std::string("efg"), res->body);
  6491. }
  6492. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6493. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6494. // the entire representation.
  6495. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6496. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6499. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6500. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6501. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6502. }
  6503. }
  6504. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6505. auto res =
  6506. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6508. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6509. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6510. EXPECT_EQ(false, res->has_header("Content-Range"));
  6511. EXPECT_EQ(0U, res->body.size());
  6512. }
  6513. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6514. // Only a 206 is served as a partial representation. Under any other status
  6515. // `apply_ranges()` reported the full content length, so the body must match
  6516. // that header, and the content provider must never be asked for an offset
  6517. // outside the representation.
  6518. auto check = [&](int status, const char *range) {
  6519. auto path =
  6520. std::string("/streamed-with-range?status=") + std::to_string(status);
  6521. auto ctx = path + " Range: " + range;
  6522. auto res = cli_.Get(path, Headers{{"Range", range}});
  6523. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6524. EXPECT_EQ(status, res->status) << ctx;
  6525. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6526. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6527. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6528. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6529. };
  6530. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6531. check(403, "bytes=3-5");
  6532. // The offset is far past the representation.
  6533. check(403, "bytes=100000-100200");
  6534. // `first_pos` is still -1 here, and the bounds asserts in
  6535. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6536. check(403, "bytes=-3");
  6537. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6538. // multipart branch would have written one that is empty.
  6539. check(403, "bytes=1-2, 4-5");
  6540. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6541. // covers the whole representation.
  6542. check(200, "bytes=3-5");
  6543. check(200, "bytes=1-2, 4-5");
  6544. }
  6545. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6546. auto res =
  6547. cli_.Get("/streamed-with-range",
  6548. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6549. "92233720368547758079223372036854775807"}});
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6552. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6553. EXPECT_EQ(false, res->has_header("Content-Range"));
  6554. EXPECT_EQ(0U, res->body.size());
  6555. }
  6556. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6557. auto res = cli_.Get(
  6558. "/with-range",
  6559. Headers{{"Range",
  6560. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6561. {"Accept-Encoding", ""}});
  6562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6563. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6564. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6565. EXPECT_EQ(true, res->has_header("Content-Range"));
  6566. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6567. EXPECT_EQ(std::string("abcdefg"), res->body);
  6568. }
  6569. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6570. auto res = cli_.Get("/with-range", Headers{
  6571. {"Range", "bytes=0-"},
  6572. {"Accept-Encoding", ""},
  6573. });
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6576. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6577. EXPECT_EQ(true, res->has_header("Content-Range"));
  6578. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6579. EXPECT_EQ(std::string("abcdefg"), res->body);
  6580. }
  6581. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6582. auto res = cli_.Get("/streamed-with-range",
  6583. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6585. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6586. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6587. EXPECT_EQ(false, res->has_header("Content-Range"));
  6588. EXPECT_EQ(267U, res->body.size());
  6589. // Check that both range contents are present
  6590. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6591. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6592. // Check that Content-Range headers are present for both ranges
  6593. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6594. std::string::npos);
  6595. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6596. std::string::npos);
  6597. }
  6598. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6599. Ranges ranges;
  6600. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6601. ranges.emplace_back(0, -1);
  6602. }
  6603. auto res = cli_.Get("/streamed-with-range?error",
  6604. Headers{{make_range_header(ranges)}});
  6605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6606. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6607. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6608. EXPECT_EQ(false, res->has_header("Content-Range"));
  6609. EXPECT_EQ(0U, res->body.size());
  6610. }
  6611. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6612. auto res = cli_.Get("/streamed-with-range",
  6613. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6616. EXPECT_EQ(5U, res->body.size());
  6617. // Check that overlapping ranges are coalesced into a single range
  6618. EXPECT_EQ("bcdef", res->body);
  6619. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6620. // Should be single range, not multipart
  6621. EXPECT_TRUE(res->has_header("Content-Range"));
  6622. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6623. }
  6624. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6625. auto res = cli_.Get("/streamed-with-range",
  6626. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6628. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6629. EXPECT_EQ(268U, res->body.size());
  6630. // Check that both range contents are present
  6631. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6632. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6633. // Check that Content-Range headers are present for both ranges
  6634. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6635. std::string::npos);
  6636. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6637. std::string::npos);
  6638. }
  6639. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6640. auto res = cli_.Get("/streamed-with-range",
  6641. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6644. EXPECT_EQ(269U, res->body.size());
  6645. // Check that both duplicate range contents are present
  6646. size_t first_abc = res->body.find("abc\r\n");
  6647. EXPECT_TRUE(first_abc != std::string::npos);
  6648. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6649. EXPECT_TRUE(second_abc != std::string::npos);
  6650. // Check that Content-Range headers are present for both ranges
  6651. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6652. EXPECT_TRUE(first_range != std::string::npos);
  6653. size_t second_range =
  6654. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6655. EXPECT_TRUE(second_range != std::string::npos);
  6656. }
  6657. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6658. auto res =
  6659. cli_.Get("/streamed-with-range?error",
  6660. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6662. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6663. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6664. EXPECT_EQ(false, res->has_header("Content-Range"));
  6665. EXPECT_EQ(0U, res->body.size());
  6666. }
  6667. TEST_F(ServerTest, GetStreamedEndless) {
  6668. uint64_t offset = 0;
  6669. auto res = cli_.Get("/streamed-cancel",
  6670. [&](const char * /*data*/, uint64_t data_length) {
  6671. if (offset < 100) {
  6672. offset += data_length;
  6673. return true;
  6674. }
  6675. return false;
  6676. });
  6677. ASSERT_TRUE(!res);
  6678. EXPECT_EQ(Error::Canceled, res.error());
  6679. }
  6680. TEST_F(ServerTest, ClientStop) {
  6681. std::atomic_size_t count{4};
  6682. std::vector<std::thread> threads;
  6683. for (auto i = count.load(); i != 0; --i) {
  6684. threads.emplace_back([&]() {
  6685. auto res = cli_.Get("/streamed-cancel",
  6686. [&](const char *, uint64_t) { return true; });
  6687. --count;
  6688. ASSERT_TRUE(!res);
  6689. EXPECT_TRUE(res.error() == Error::Canceled ||
  6690. res.error() == Error::Read || res.error() == Error::Write);
  6691. });
  6692. }
  6693. std::this_thread::sleep_for(std::chrono::seconds(2));
  6694. while (count != 0) {
  6695. cli_.stop();
  6696. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6697. }
  6698. for (auto &t : threads) {
  6699. t.join();
  6700. }
  6701. }
  6702. TEST_F(ServerTest, GetWithRange1) {
  6703. auto res = cli_.Get("/with-range", Headers{
  6704. make_range_header({{3, 5}}),
  6705. {"Accept-Encoding", ""},
  6706. });
  6707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6708. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6709. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6710. EXPECT_EQ(true, res->has_header("Content-Range"));
  6711. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6712. EXPECT_EQ(std::string("def"), res->body);
  6713. }
  6714. TEST_F(ServerTest, GetWithRange2) {
  6715. auto res = cli_.Get("/with-range", Headers{
  6716. make_range_header({{1, -1}}),
  6717. {"Accept-Encoding", ""},
  6718. });
  6719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6720. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6721. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6722. EXPECT_EQ(true, res->has_header("Content-Range"));
  6723. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6724. EXPECT_EQ(std::string("bcdefg"), res->body);
  6725. }
  6726. TEST_F(ServerTest, GetWithRange3) {
  6727. auto res = cli_.Get("/with-range", Headers{
  6728. make_range_header({{0, 0}}),
  6729. {"Accept-Encoding", ""},
  6730. });
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6733. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6734. EXPECT_EQ(true, res->has_header("Content-Range"));
  6735. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6736. EXPECT_EQ(std::string("a"), res->body);
  6737. }
  6738. TEST_F(ServerTest, GetWithRange4) {
  6739. auto res = cli_.Get("/with-range", Headers{
  6740. make_range_header({{-1, 2}}),
  6741. {"Accept-Encoding", ""},
  6742. });
  6743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6744. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6745. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6746. EXPECT_EQ(true, res->has_header("Content-Range"));
  6747. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6748. EXPECT_EQ(std::string("fg"), res->body);
  6749. }
  6750. TEST_F(ServerTest, GetWithRange5) {
  6751. auto res = cli_.Get("/with-range", Headers{
  6752. make_range_header({{0, 5}}),
  6753. {"Accept-Encoding", ""},
  6754. });
  6755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6756. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6757. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6758. EXPECT_EQ(true, res->has_header("Content-Range"));
  6759. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6760. EXPECT_EQ(std::string("abcdef"), res->body);
  6761. }
  6762. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6763. auto res =
  6764. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6767. }
  6768. TEST_F(ServerTest, GetWithRangeMultipart) {
  6769. auto res =
  6770. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6773. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6774. EXPECT_EQ(false, res->has_header("Content-Range"));
  6775. EXPECT_EQ(267U, res->body.size());
  6776. }
  6777. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6778. auto res = cli_.Get("/with-range",
  6779. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6781. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6782. }
  6783. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6784. auto res = cli_.Get("/with-range-customized-response",
  6785. Headers{{make_range_header({{1, 2}})}});
  6786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6787. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6788. EXPECT_EQ(true, res->has_header("Content-Length"));
  6789. EXPECT_EQ(false, res->has_header("Content-Range"));
  6790. EXPECT_EQ(JSON_DATA, res->body);
  6791. }
  6792. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6793. auto res = cli_.Get("/with-range-customized-response",
  6794. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6796. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6797. EXPECT_EQ(true, res->has_header("Content-Length"));
  6798. EXPECT_EQ(false, res->has_header("Content-Range"));
  6799. EXPECT_EQ(JSON_DATA, res->body);
  6800. }
  6801. TEST_F(ServerTest, Issue1772) {
  6802. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6804. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6805. }
  6806. TEST_F(ServerTest, Issue609) {
  6807. auto res = cli_.Delete("/issue609");
  6808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6809. EXPECT_EQ(StatusCode::OK_200, res->status);
  6810. EXPECT_EQ(std::string("ok"), res->body);
  6811. }
  6812. TEST_F(ServerTest, GetStreamedChunked) {
  6813. auto res = cli_.Get("/streamed-chunked");
  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, GetStreamedChunked2) {
  6819. auto res = cli_.Get("/streamed-chunked2");
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. EXPECT_EQ(std::string("123456789"), res->body);
  6823. }
  6824. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6825. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. EXPECT_EQ(std::string("123456789"), res->body);
  6829. EXPECT_TRUE(res->has_header("Trailer"));
  6830. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6831. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6832. // Trailers are now stored separately from headers (security fix)
  6833. EXPECT_EQ(2U, res->trailers.size());
  6834. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6835. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6836. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6837. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6838. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6839. // Verify trailers are NOT in headers (security verification)
  6840. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6841. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6842. }
  6843. TEST_F(ServerTest, LargeChunkedPost) {
  6844. Request req;
  6845. req.method = "POST";
  6846. req.path = "/large-chunked";
  6847. std::string host_and_port;
  6848. host_and_port += HOST;
  6849. host_and_port += ":";
  6850. host_and_port += std::to_string(PORT);
  6851. req.headers.emplace("Host", host_and_port.c_str());
  6852. req.headers.emplace("Accept", "*/*");
  6853. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6854. req.headers.emplace("Content-Type", "text/plain");
  6855. req.headers.emplace("Content-Length", "0");
  6856. req.headers.emplace("Transfer-Encoding", "chunked");
  6857. std::string long_string(30 * 1024u, 'a');
  6858. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6859. // Attempt to make a large enough post to exceed OS buffers, to test that
  6860. // the server handles short reads if the full chunk data isn't available.
  6861. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6862. auto res = std::make_shared<Response>();
  6863. auto error = Error::Success;
  6864. auto ret = cli_.send(req, *res, error);
  6865. ASSERT_TRUE(ret);
  6866. EXPECT_EQ(StatusCode::OK_200, res->status);
  6867. }
  6868. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6869. auto res = cli_.Get("/remote_addr");
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. EXPECT_EQ(StatusCode::OK_200, res->status);
  6872. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6873. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6874. }
  6875. TEST_F(ServerTest, GetMethodLocalAddr) {
  6876. auto res = cli_.Get("/local_addr");
  6877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6878. EXPECT_EQ(StatusCode::OK_200, res->status);
  6879. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6880. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6881. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6882. }
  6883. TEST_F(ServerTest, HTTPResponseSplitting) {
  6884. auto res = cli_.Get("/http_response_splitting");
  6885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6886. EXPECT_EQ(StatusCode::OK_200, res->status);
  6887. }
  6888. TEST_F(ServerTest, SlowRequest) {
  6889. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6890. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6891. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6892. }
  6893. #if 0
  6894. TEST_F(ServerTest, SlowPost) {
  6895. char buffer[64 * 1024];
  6896. memset(buffer, 0x42, sizeof(buffer));
  6897. auto res = cli_.Post(
  6898. "/slowpost", 64 * 1024 * 1024,
  6899. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6900. auto ret = sink.write(buffer, sizeof(buffer));
  6901. EXPECT_TRUE(ret);
  6902. return true;
  6903. },
  6904. "text/plain");
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::OK_200, res->status);
  6907. }
  6908. TEST_F(ServerTest, SlowPostFail) {
  6909. char buffer[64 * 1024];
  6910. memset(buffer, 0x42, sizeof(buffer));
  6911. cli_.set_write_timeout(std::chrono::seconds(0));
  6912. auto res = cli_.Post(
  6913. "/slowpost", 64 * 1024 * 1024,
  6914. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6915. sink.write(buffer, sizeof(buffer));
  6916. return true;
  6917. },
  6918. "text/plain");
  6919. ASSERT_TRUE(!res);
  6920. EXPECT_EQ(Error::Write, res.error());
  6921. }
  6922. #endif
  6923. TEST_F(ServerTest, Put) {
  6924. auto res = cli_.Put("/put", "PUT", "text/plain");
  6925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6926. EXPECT_EQ(StatusCode::OK_200, res->status);
  6927. EXPECT_EQ("PUT", res->body);
  6928. }
  6929. TEST_F(ServerTest, PutWithContentProvider) {
  6930. auto res = cli_.Put(
  6931. "/put", 3,
  6932. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6933. sink.os << "PUT";
  6934. return true;
  6935. },
  6936. "text/plain");
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. EXPECT_EQ(StatusCode::OK_200, res->status);
  6939. EXPECT_EQ("PUT", res->body);
  6940. }
  6941. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6942. auto res = cli_.Post(
  6943. "/post", 42,
  6944. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6945. return false;
  6946. },
  6947. "text/plain");
  6948. ASSERT_TRUE(!res);
  6949. EXPECT_EQ(Error::Canceled, res.error());
  6950. }
  6951. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6952. auto res = cli_.Put(
  6953. "/put",
  6954. [](size_t /*offset*/, DataSink &sink) {
  6955. sink.os << "PUT";
  6956. sink.done();
  6957. return true;
  6958. },
  6959. "text/plain");
  6960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6961. EXPECT_EQ(StatusCode::OK_200, res->status);
  6962. EXPECT_EQ("PUT", res->body);
  6963. }
  6964. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6965. auto res = cli_.Post(
  6966. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6967. "text/plain");
  6968. ASSERT_TRUE(!res);
  6969. EXPECT_EQ(Error::Canceled, res.error());
  6970. }
  6971. TEST_F(ServerTest, PostLoopBack) {
  6972. std::string body;
  6973. auto res = cli_.Post(
  6974. "/post-loopback", 9,
  6975. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6976. EXPECT_EQ(9u, length);
  6977. sink.write("123", 3);
  6978. sink.write("456", 3);
  6979. sink.write("789", 3);
  6980. return true;
  6981. },
  6982. "text/plain",
  6983. [&body](const char *data, size_t data_length) {
  6984. body.append(data, data_length);
  6985. return true;
  6986. });
  6987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6988. EXPECT_EQ(StatusCode::OK_200, res->status);
  6989. EXPECT_EQ("123456789", body);
  6990. }
  6991. TEST_F(ServerTest, PutLoopBack) {
  6992. std::string body;
  6993. auto res = cli_.Put(
  6994. "/put-loopback", 9,
  6995. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6996. EXPECT_EQ(9u, length);
  6997. sink.write("123", 3);
  6998. sink.write("456", 3);
  6999. sink.write("789", 3);
  7000. return true;
  7001. },
  7002. "text/plain",
  7003. [&body](const char *data, size_t data_length) {
  7004. body.append(data, data_length);
  7005. return true;
  7006. });
  7007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7008. EXPECT_EQ(StatusCode::OK_200, res->status);
  7009. EXPECT_EQ("123456789", body);
  7010. }
  7011. TEST_F(ServerTest, PatchLoopBack) {
  7012. std::string body;
  7013. auto res = cli_.Patch(
  7014. "/patch-loopback", 9,
  7015. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7016. EXPECT_EQ(9u, length);
  7017. sink.write("123", 3);
  7018. sink.write("456", 3);
  7019. sink.write("789", 3);
  7020. return true;
  7021. },
  7022. "text/plain",
  7023. [&body](const char *data, size_t data_length) {
  7024. body.append(data, data_length);
  7025. return true;
  7026. });
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. EXPECT_EQ(StatusCode::OK_200, res->status);
  7029. EXPECT_EQ("123456789", body);
  7030. }
  7031. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7032. std::string body;
  7033. auto res = cli_.Post(
  7034. "/post-loopback",
  7035. [](size_t /*offset*/, DataSink &sink) {
  7036. sink.write("123", 3);
  7037. sink.write("456", 3);
  7038. sink.write("789", 3);
  7039. sink.done();
  7040. return true;
  7041. },
  7042. "text/plain",
  7043. [&body](const char *data, size_t data_length) {
  7044. body.append(data, data_length);
  7045. return true;
  7046. });
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. EXPECT_EQ("123456789", body);
  7050. }
  7051. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7052. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7053. cli_.set_compress(true);
  7054. auto res = cli_.Put(
  7055. "/put", 3,
  7056. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7057. sink.os << "PUT";
  7058. return true;
  7059. },
  7060. "text/plain");
  7061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7062. EXPECT_EQ(StatusCode::OK_200, res->status);
  7063. EXPECT_EQ("PUT", res->body);
  7064. }
  7065. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7066. cli_.set_compress(true);
  7067. auto res = cli_.Post(
  7068. "/post", 42,
  7069. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7070. return false;
  7071. },
  7072. "text/plain");
  7073. ASSERT_TRUE(!res);
  7074. EXPECT_EQ(Error::Canceled, res.error());
  7075. }
  7076. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7077. cli_.set_compress(true);
  7078. auto res = cli_.Put(
  7079. "/put",
  7080. [](size_t /*offset*/, DataSink &sink) {
  7081. sink.os << "PUT";
  7082. sink.done();
  7083. return true;
  7084. },
  7085. "text/plain");
  7086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7087. EXPECT_EQ(StatusCode::OK_200, res->status);
  7088. EXPECT_EQ("PUT", res->body);
  7089. }
  7090. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7091. cli_.set_compress(true);
  7092. auto res = cli_.Post(
  7093. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7094. "text/plain");
  7095. ASSERT_TRUE(!res);
  7096. EXPECT_EQ(Error::Canceled, res.error());
  7097. }
  7098. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7099. cli_.set_compress(true);
  7100. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7102. EXPECT_EQ(StatusCode::OK_200, res->status);
  7103. EXPECT_EQ(LARGE_DATA, res->body);
  7104. }
  7105. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7106. #ifdef CPPHTTPLIB_SSL_ENABLED
  7107. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7108. Client cli(s.c_str());
  7109. cli.enable_server_certificate_verification(false);
  7110. #else
  7111. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7112. Client cli(s.c_str());
  7113. #endif
  7114. cli.set_compress(true);
  7115. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7117. EXPECT_EQ(StatusCode::OK_200, res->status);
  7118. EXPECT_EQ(LARGE_DATA, res->body);
  7119. // The compressed size should be less than a 10th of the original. May vary
  7120. // depending on the zlib library.
  7121. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7122. static_cast<uint64_t>(10 * 1024 * 1024));
  7123. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7124. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7125. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7126. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7127. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7128. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7129. #endif
  7130. }
  7131. TEST_F(ServerTest, PutContentWithDeflate) {
  7132. cli_.set_compress(false);
  7133. Headers headers;
  7134. headers.emplace("Content-Encoding", "deflate");
  7135. // PUT in deflate format:
  7136. auto res = cli_.Put("/put", headers,
  7137. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7139. EXPECT_EQ(StatusCode::OK_200, res->status);
  7140. EXPECT_EQ("PUT", res->body);
  7141. }
  7142. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7143. Headers headers;
  7144. headers.emplace("Accept-Encoding", "gzip, deflate");
  7145. auto res = cli_.Get("/streamed-chunked", headers);
  7146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7147. EXPECT_EQ(StatusCode::OK_200, res->status);
  7148. EXPECT_EQ(std::string("123456789"), res->body);
  7149. }
  7150. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7151. Headers headers;
  7152. headers.emplace("Accept-Encoding", "gzip, deflate");
  7153. auto res = cli_.Get("/streamed-chunked2", headers);
  7154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7155. EXPECT_EQ(StatusCode::OK_200, res->status);
  7156. EXPECT_EQ(std::string("123456789"), res->body);
  7157. }
  7158. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7159. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7161. EXPECT_EQ(StatusCode::OK_200, res->status);
  7162. }
  7163. TEST(GzipDecompressor, ChunkedDecompression) {
  7164. std::string data;
  7165. for (size_t i = 0; i < 32 * 1024; ++i) {
  7166. data.push_back(static_cast<char>('a' + i % 26));
  7167. }
  7168. std::string compressed_data;
  7169. {
  7170. httplib::detail::gzip_compressor compressor;
  7171. bool result = compressor.compress(
  7172. data.data(), data.size(),
  7173. /*last=*/true,
  7174. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7175. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7176. compressed_data_size);
  7177. return true;
  7178. });
  7179. ASSERT_TRUE(result);
  7180. }
  7181. std::string decompressed_data;
  7182. {
  7183. httplib::detail::gzip_decompressor decompressor;
  7184. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7185. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7186. size_t chunk_size = 130;
  7187. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7188. chunk_begin += chunk_size) {
  7189. size_t current_chunk_size =
  7190. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7191. bool result = decompressor.decompress(
  7192. compressed_data.data() + chunk_begin, current_chunk_size,
  7193. [&](const char *decompressed_data_chunk,
  7194. size_t decompressed_data_chunk_size) {
  7195. decompressed_data.insert(decompressed_data.size(),
  7196. decompressed_data_chunk,
  7197. decompressed_data_chunk_size);
  7198. return true;
  7199. });
  7200. ASSERT_TRUE(result);
  7201. }
  7202. }
  7203. ASSERT_EQ(data, decompressed_data);
  7204. }
  7205. TEST(GzipDecompressor, DeflateDecompression) {
  7206. std::string original_text = "Raw deflate without gzip";
  7207. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7208. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7209. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7210. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7211. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7212. std::string decompressed_data;
  7213. {
  7214. httplib::detail::gzip_decompressor decompressor;
  7215. bool result = decompressor.decompress(
  7216. compressed_data.data(), compressed_data.size(),
  7217. [&](const char *decompressed_data_chunk,
  7218. size_t decompressed_data_chunk_size) {
  7219. decompressed_data.insert(decompressed_data.size(),
  7220. decompressed_data_chunk,
  7221. decompressed_data_chunk_size);
  7222. return true;
  7223. });
  7224. ASSERT_TRUE(result);
  7225. }
  7226. ASSERT_EQ(original_text, decompressed_data);
  7227. }
  7228. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7229. std::string original_text = "Raw deflate without gzip";
  7230. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7231. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7232. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7233. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7234. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7235. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7236. std::string decompressed_data;
  7237. {
  7238. httplib::detail::gzip_decompressor decompressor;
  7239. bool result = decompressor.decompress(
  7240. compressed_data.data(), compressed_data.size(),
  7241. [&](const char *decompressed_data_chunk,
  7242. size_t decompressed_data_chunk_size) {
  7243. decompressed_data.insert(decompressed_data.size(),
  7244. decompressed_data_chunk,
  7245. decompressed_data_chunk_size);
  7246. return true;
  7247. });
  7248. ASSERT_TRUE(result);
  7249. }
  7250. ASSERT_EQ(original_text, decompressed_data);
  7251. }
  7252. #endif
  7253. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7254. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7255. Headers headers;
  7256. headers.emplace("Accept-Encoding", "br");
  7257. auto res = cli_.Get("/streamed-chunked", headers);
  7258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7259. EXPECT_EQ(StatusCode::OK_200, res->status);
  7260. EXPECT_EQ(std::string("123456789"), res->body);
  7261. }
  7262. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7263. Headers headers;
  7264. headers.emplace("Accept-Encoding", "br");
  7265. auto res = cli_.Get("/streamed-chunked2", headers);
  7266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7267. EXPECT_EQ(StatusCode::OK_200, res->status);
  7268. EXPECT_EQ(std::string("123456789"), res->body);
  7269. }
  7270. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7271. cli_.set_compress(true);
  7272. auto res = cli_.Put(
  7273. "/put", 3,
  7274. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7275. sink.os << "PUT";
  7276. return true;
  7277. },
  7278. "text/plain");
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::OK_200, res->status);
  7281. EXPECT_EQ("PUT", res->body);
  7282. }
  7283. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7284. cli_.set_compress(true);
  7285. auto res = cli_.Put(
  7286. "/put",
  7287. [](size_t /*offset*/, DataSink &sink) {
  7288. sink.os << "PUT";
  7289. sink.done();
  7290. return true;
  7291. },
  7292. "text/plain");
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ(StatusCode::OK_200, res->status);
  7295. EXPECT_EQ("PUT", res->body);
  7296. }
  7297. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7298. cli_.set_compress(true);
  7299. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::OK_200, res->status);
  7302. EXPECT_EQ(LARGE_DATA, res->body);
  7303. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7304. }
  7305. #endif
  7306. TEST_F(ServerTest, Patch) {
  7307. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7309. EXPECT_EQ(StatusCode::OK_200, res->status);
  7310. EXPECT_EQ("PATCH", res->body);
  7311. }
  7312. TEST_F(ServerTest, Delete) {
  7313. auto res = cli_.Delete("/delete");
  7314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7315. EXPECT_EQ(StatusCode::OK_200, res->status);
  7316. EXPECT_EQ("DELETE", res->body);
  7317. }
  7318. TEST_F(ServerTest, DeleteContentReceiver) {
  7319. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7321. EXPECT_EQ(StatusCode::OK_200, res->status);
  7322. EXPECT_EQ("content", res->body);
  7323. }
  7324. TEST_F(ServerTest, Options) {
  7325. auto res = cli_.Options("*");
  7326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7327. EXPECT_EQ(StatusCode::OK_200, res->status);
  7328. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7329. EXPECT_TRUE(res->body.empty());
  7330. }
  7331. TEST_F(ServerTest, URL) {
  7332. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. EXPECT_EQ(StatusCode::OK_200, res->status);
  7335. }
  7336. TEST_F(ServerTest, ArrayParam) {
  7337. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7339. EXPECT_EQ(StatusCode::OK_200, res->status);
  7340. }
  7341. TEST_F(ServerTest, ArrayParamValues) {
  7342. auto res =
  7343. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7345. EXPECT_EQ(StatusCode::OK_200, res->status);
  7346. }
  7347. TEST_F(ServerTest, NoMultipleHeaders) {
  7348. Headers headers = {{"Content-Length", "5"}};
  7349. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7350. "text/plain");
  7351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7352. EXPECT_EQ(StatusCode::OK_200, res->status);
  7353. }
  7354. TEST_F(ServerTest, PostContentReceiver) {
  7355. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7357. ASSERT_EQ(StatusCode::OK_200, res->status);
  7358. ASSERT_EQ("content", res->body);
  7359. }
  7360. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7361. UploadFormDataItems items = {
  7362. {"text1", "text default", "", ""},
  7363. {"text2", "aωb", "", ""},
  7364. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7365. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7366. {"file3", "", "", "application/octet-stream"},
  7367. };
  7368. auto res = cli_.Post("/content_receiver", items);
  7369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7370. EXPECT_EQ(StatusCode::OK_200, res->status);
  7371. }
  7372. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7373. UploadFormDataItems items = {
  7374. {"text1", "text default", "", ""},
  7375. {"text2", "aωb", "", ""},
  7376. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7377. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7378. {"file3", "", "", "application/octet-stream"},
  7379. };
  7380. auto boundary = std::string("+++++");
  7381. std::string body;
  7382. for (const auto &item : items) {
  7383. body += "--" + boundary + "\r\n";
  7384. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7385. if (!item.filename.empty()) {
  7386. body += "; filename=\"" + item.filename + "\"";
  7387. }
  7388. body += "\r\n";
  7389. if (!item.content_type.empty()) {
  7390. body += "Content-Type: " + item.content_type + "\r\n";
  7391. }
  7392. body += "\r\n";
  7393. body += item.content + "\r\n";
  7394. }
  7395. body += "--" + boundary + "--\r\n";
  7396. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7397. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7399. EXPECT_EQ(StatusCode::OK_200, res->status);
  7400. }
  7401. TEST(MultipartFormDataTest, FieldEscaping) {
  7402. Server svr;
  7403. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7404. const ContentReader &content_reader) {
  7405. ASSERT_TRUE(req.is_multipart_form_data());
  7406. std::vector<FormData> received;
  7407. content_reader(
  7408. [&](const FormData &file) {
  7409. received.push_back(file);
  7410. return true;
  7411. },
  7412. [&](const char *data, size_t data_length) {
  7413. received.back().content.append(data, data_length);
  7414. return true;
  7415. });
  7416. // '"', CR and LF in names and filenames are escaped following the
  7417. // WHATWG HTML standard, so each part still parses as a single part
  7418. // with no injected headers. Content types get CR/LF escaped too,
  7419. // while '"' (legal there, e.g. quoted charset) is preserved.
  7420. ASSERT_EQ(4U, received.size());
  7421. EXPECT_EQ("na%22me", received[0].name);
  7422. EXPECT_EQ("quoted name", received[0].content);
  7423. EXPECT_EQ("file", received[1].name);
  7424. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7425. received[1].filename);
  7426. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7427. EXPECT_EQ("injected", received[1].content);
  7428. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7429. EXPECT_EQ("my%22file.txt", received[2].filename);
  7430. EXPECT_EQ("cr lf name", received[2].content);
  7431. EXPECT_EQ("typed", received[3].name);
  7432. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7433. received[3].content_type);
  7434. EXPECT_EQ("typed content", received[3].content);
  7435. });
  7436. auto port = svr.bind_to_any_port("localhost");
  7437. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7438. auto se = detail::scope_exit([&] {
  7439. svr.stop();
  7440. t.join();
  7441. ASSERT_FALSE(svr.is_running());
  7442. });
  7443. svr.wait_until_ready();
  7444. Client cli("localhost", port);
  7445. UploadFormDataItems items = {
  7446. {"na\"me", "quoted name", "", ""},
  7447. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7448. "application/octet-stream"},
  7449. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7450. {"typed", "typed content", "",
  7451. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7452. };
  7453. auto res = cli.Post("/post", items);
  7454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7455. EXPECT_EQ(StatusCode::OK_200, res->status);
  7456. }
  7457. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7458. const UploadFormDataItems items = {
  7459. {"name1", "Content 1", "", ""},
  7460. {"name2", "Content 2", "file2.txt", "text/plain"},
  7461. };
  7462. Server svr;
  7463. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7464. const ContentReader &content_reader) {
  7465. ASSERT_TRUE(req.is_multipart_form_data());
  7466. std::vector<FormData> received;
  7467. content_reader(
  7468. [&](const FormData &file) {
  7469. received.push_back(file);
  7470. return true;
  7471. },
  7472. [&](const char *data, size_t data_length) {
  7473. received.back().content.append(data, data_length);
  7474. return true;
  7475. });
  7476. ASSERT_EQ(2U, received.size());
  7477. EXPECT_EQ("name1", received[0].name);
  7478. EXPECT_EQ("Content 1", received[0].content);
  7479. EXPECT_EQ("name2", received[1].name);
  7480. EXPECT_EQ("Content 2", received[1].content);
  7481. EXPECT_EQ("file2.txt", received[1].filename);
  7482. EXPECT_EQ("text/plain", received[1].content_type);
  7483. });
  7484. auto port = svr.bind_to_any_port("localhost");
  7485. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7486. auto se = detail::scope_exit([&] {
  7487. svr.stop();
  7488. t.join();
  7489. ASSERT_FALSE(svr.is_running());
  7490. });
  7491. svr.wait_until_ready();
  7492. Client cli("localhost", port);
  7493. // Whole-body serialization with a generated boundary
  7494. {
  7495. MultipartFormDataWriter writer;
  7496. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7497. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7498. writer.content_type());
  7499. auto body = writer.serialize(items);
  7500. EXPECT_EQ(body.size(), writer.content_length(items));
  7501. auto res = cli.Post("/post", body, writer.content_type());
  7502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7503. EXPECT_EQ(StatusCode::OK_200, res->status);
  7504. }
  7505. // Per-part framing with a custom boundary via a content provider
  7506. {
  7507. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7508. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7509. MultipartFormDataWriter writer("custom-boundary_123");
  7510. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7511. std::string body;
  7512. for (const auto &item : items) {
  7513. body += writer.item_begin(item);
  7514. body += item.content;
  7515. body += MultipartFormDataWriter::item_end();
  7516. }
  7517. body += writer.finish();
  7518. EXPECT_EQ(body.size(), writer.content_length(items));
  7519. auto res = cli.Post(
  7520. "/post", body.size(),
  7521. [&](size_t offset, size_t length, DataSink &sink) {
  7522. sink.write(body.data() + offset, length);
  7523. return true;
  7524. },
  7525. writer.content_type());
  7526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7527. EXPECT_EQ(StatusCode::OK_200, res->status);
  7528. }
  7529. }
  7530. TEST_F(ServerTest, PostContentReceiverGzip) {
  7531. cli_.set_compress(true);
  7532. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. ASSERT_EQ(StatusCode::OK_200, res->status);
  7535. ASSERT_EQ("content", res->body);
  7536. }
  7537. TEST_F(ServerTest, PutContentReceiver) {
  7538. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7540. ASSERT_EQ(StatusCode::OK_200, res->status);
  7541. ASSERT_EQ("content", res->body);
  7542. }
  7543. TEST_F(ServerTest, PatchContentReceiver) {
  7544. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7546. ASSERT_EQ(StatusCode::OK_200, res->status);
  7547. ASSERT_EQ("content", res->body);
  7548. }
  7549. template <typename ClientType>
  7550. void TestWithHeadersAndContentReceiver(
  7551. ClientType &cli,
  7552. std::function<Result(ClientType &, const std::string &, const Headers &,
  7553. const std::string &, const std::string &,
  7554. ContentReceiver, DownloadProgress)>
  7555. request_func) {
  7556. Headers headers;
  7557. headers.emplace("X-Custom-Header", "test-value");
  7558. std::string received_body;
  7559. auto res = request_func(
  7560. cli, "/content_receiver", headers, "content", "application/json",
  7561. [&](const char *data, size_t data_length) {
  7562. received_body.append(data, data_length);
  7563. return true;
  7564. },
  7565. nullptr);
  7566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7567. EXPECT_EQ(StatusCode::OK_200, res->status);
  7568. EXPECT_EQ("content", received_body);
  7569. }
  7570. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7571. #ifdef CPPHTTPLIB_SSL_ENABLED
  7572. using ClientT = SSLClient;
  7573. #else
  7574. using ClientT = Client;
  7575. #endif
  7576. TestWithHeadersAndContentReceiver<ClientT>(
  7577. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7578. const std::string &body, const std::string &content_type,
  7579. ContentReceiver receiver, DownloadProgress progress) {
  7580. return cli.Post(path, headers, body, content_type, receiver, progress);
  7581. });
  7582. }
  7583. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7584. #ifdef CPPHTTPLIB_SSL_ENABLED
  7585. using ClientT = SSLClient;
  7586. #else
  7587. using ClientT = Client;
  7588. #endif
  7589. TestWithHeadersAndContentReceiver<ClientT>(
  7590. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7591. const std::string &body, const std::string &content_type,
  7592. ContentReceiver receiver, DownloadProgress progress) {
  7593. return cli.Put(path, headers, body, content_type, receiver, progress);
  7594. });
  7595. }
  7596. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7597. #ifdef CPPHTTPLIB_SSL_ENABLED
  7598. using ClientT = SSLClient;
  7599. #else
  7600. using ClientT = Client;
  7601. #endif
  7602. TestWithHeadersAndContentReceiver<ClientT>(
  7603. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7604. const std::string &body, const std::string &content_type,
  7605. ContentReceiver receiver, DownloadProgress progress) {
  7606. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7607. });
  7608. }
  7609. template <typename ClientType>
  7610. void TestWithHeadersAndContentReceiverWithProgress(
  7611. ClientType &cli,
  7612. std::function<Result(ClientType &, const std::string &, const Headers &,
  7613. const std::string &, const std::string &,
  7614. ContentReceiver, DownloadProgress)>
  7615. request_func) {
  7616. Headers headers;
  7617. headers.emplace("X-Test-Header", "progress-test");
  7618. std::string received_body;
  7619. auto progress_called = false;
  7620. auto res = request_func(
  7621. cli, "/content_receiver", headers, "content", "text/plain",
  7622. [&](const char *data, size_t data_length) {
  7623. received_body.append(data, data_length);
  7624. return true;
  7625. },
  7626. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7627. progress_called = true;
  7628. return true;
  7629. });
  7630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7631. EXPECT_EQ(StatusCode::OK_200, res->status);
  7632. EXPECT_EQ("content", received_body);
  7633. EXPECT_TRUE(progress_called);
  7634. }
  7635. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7636. #ifdef CPPHTTPLIB_SSL_ENABLED
  7637. using ClientT = SSLClient;
  7638. #else
  7639. using ClientT = Client;
  7640. #endif
  7641. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7642. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7643. const std::string &body, const std::string &content_type,
  7644. ContentReceiver receiver, DownloadProgress progress) {
  7645. return cli.Post(path, headers, body, content_type, receiver, progress);
  7646. });
  7647. }
  7648. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7649. #ifdef CPPHTTPLIB_SSL_ENABLED
  7650. using ClientT = SSLClient;
  7651. #else
  7652. using ClientT = Client;
  7653. #endif
  7654. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7655. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7656. const std::string &body, const std::string &content_type,
  7657. ContentReceiver receiver, DownloadProgress progress) {
  7658. return cli.Put(path, headers, body, content_type, receiver, progress);
  7659. });
  7660. }
  7661. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7662. #ifdef CPPHTTPLIB_SSL_ENABLED
  7663. using ClientT = SSLClient;
  7664. #else
  7665. using ClientT = Client;
  7666. #endif
  7667. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7668. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7669. const std::string &body, const std::string &content_type,
  7670. ContentReceiver receiver, DownloadProgress progress) {
  7671. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7672. });
  7673. }
  7674. template <typename ClientType>
  7675. void TestWithHeadersAndContentReceiverError(
  7676. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7677. const Headers &, const std::string &,
  7678. const std::string &, ContentReceiver)>
  7679. request_func) {
  7680. Headers headers;
  7681. headers.emplace("X-Error-Test", "true");
  7682. std::string received_body;
  7683. auto receiver_failed = false;
  7684. auto res =
  7685. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7686. [&](const char *data, size_t data_length) {
  7687. received_body.append(data, data_length);
  7688. receiver_failed = true;
  7689. return false;
  7690. });
  7691. ASSERT_FALSE(res);
  7692. EXPECT_TRUE(receiver_failed);
  7693. }
  7694. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7695. #ifdef CPPHTTPLIB_SSL_ENABLED
  7696. using ClientT = SSLClient;
  7697. #else
  7698. using ClientT = Client;
  7699. #endif
  7700. TestWithHeadersAndContentReceiverError<ClientT>(
  7701. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7702. const std::string &body, const std::string &content_type,
  7703. ContentReceiver receiver) {
  7704. return cli.Post(path, headers, body, content_type, receiver);
  7705. });
  7706. }
  7707. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7708. #ifdef CPPHTTPLIB_SSL_ENABLED
  7709. using ClientT = SSLClient;
  7710. #else
  7711. using ClientT = Client;
  7712. #endif
  7713. TestWithHeadersAndContentReceiverError<ClientT>(
  7714. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7715. const std::string &body, const std::string &content_type,
  7716. ContentReceiver receiver) {
  7717. return cli.Put(path, headers, body, content_type, receiver);
  7718. });
  7719. }
  7720. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7721. #ifdef CPPHTTPLIB_SSL_ENABLED
  7722. using ClientT = SSLClient;
  7723. #else
  7724. using ClientT = Client;
  7725. #endif
  7726. TestWithHeadersAndContentReceiverError<ClientT>(
  7727. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7728. const std::string &body, const std::string &content_type,
  7729. ContentReceiver receiver) {
  7730. return cli.Patch(path, headers, body, content_type, receiver);
  7731. });
  7732. }
  7733. TEST_F(ServerTest, PostQueryStringAndBody) {
  7734. auto res =
  7735. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7737. ASSERT_EQ(StatusCode::OK_200, res->status);
  7738. }
  7739. TEST_F(ServerTest, HTTP2Magic) {
  7740. Request req;
  7741. req.method = "PRI";
  7742. req.path = "*";
  7743. req.body = "SM";
  7744. auto res = std::make_shared<Response>();
  7745. auto error = Error::Success;
  7746. auto ret = cli_.send(req, *res, error);
  7747. ASSERT_TRUE(ret);
  7748. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7749. }
  7750. TEST_F(ServerTest, KeepAlive) {
  7751. auto res = cli_.Get("/hi");
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7755. EXPECT_EQ("Hello World!", res->body);
  7756. res = cli_.Get("/hi");
  7757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7758. EXPECT_EQ(StatusCode::OK_200, res->status);
  7759. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7760. EXPECT_EQ("Hello World!", res->body);
  7761. res = cli_.Get("/hi");
  7762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7763. EXPECT_EQ(StatusCode::OK_200, res->status);
  7764. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7765. EXPECT_EQ("Hello World!", res->body);
  7766. res = cli_.Get("/not-exist");
  7767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7768. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7769. res = cli_.Post("/empty", "", "text/plain");
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. EXPECT_EQ(StatusCode::OK_200, res->status);
  7772. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7773. EXPECT_EQ("empty", res->body);
  7774. EXPECT_EQ("close", res->get_header_value("Connection"));
  7775. res = cli_.Post(
  7776. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7777. "text/plain");
  7778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7779. EXPECT_EQ(StatusCode::OK_200, res->status);
  7780. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7781. EXPECT_EQ("empty", res->body);
  7782. cli_.set_keep_alive(false);
  7783. res = cli_.Get("/last-request");
  7784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7785. EXPECT_EQ(StatusCode::OK_200, res->status);
  7786. EXPECT_EQ("close", res->get_header_value("Connection"));
  7787. }
  7788. TEST_F(ServerTest, TooManyRedirect) {
  7789. cli_.set_follow_location(true);
  7790. auto res = cli_.Get("/redirect/0");
  7791. ASSERT_TRUE(!res);
  7792. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7793. }
  7794. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7795. Request req;
  7796. req.method = "FOOBAR";
  7797. req.path = "/hi";
  7798. cli_.set_keep_alive(true);
  7799. auto res = cli_.send(req);
  7800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7801. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7802. EXPECT_EQ("close", res->get_header_value("Connection"));
  7803. EXPECT_FALSE(cli_.is_socket_open());
  7804. }
  7805. TEST_F(ServerTest, CustomRouteReadsBody) {
  7806. const std::string xml =
  7807. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7808. Request req;
  7809. req.method = "PROPFIND";
  7810. req.path = "/dav/dir";
  7811. req.set_header("Depth", "1");
  7812. req.body = xml;
  7813. auto res = cli_.send(req);
  7814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7815. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7816. EXPECT_EQ(xml, res->body);
  7817. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7818. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7819. }
  7820. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7821. Request req;
  7822. req.method = "PROPFIND";
  7823. req.path = "/dav/42";
  7824. auto res = cli_.send(req);
  7825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7826. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7827. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7828. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7829. }
  7830. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7831. Request req;
  7832. req.method = "PROPFIND";
  7833. req.path = "/dav-re/123";
  7834. auto res = cli_.send(req);
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7837. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7838. }
  7839. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7840. Request req;
  7841. req.method = "MKCOL";
  7842. req.path = "/dav-mkcol";
  7843. auto res = cli_.send(req);
  7844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7845. EXPECT_EQ(StatusCode::Created_201, res->status);
  7846. }
  7847. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7848. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7849. Request req;
  7850. req.method = "REPORT";
  7851. req.path = "/dav-report";
  7852. req.body = xml;
  7853. auto res = cli_.send(req);
  7854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7855. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7856. EXPECT_EQ(xml, res->body);
  7857. }
  7858. // A content reader route must fire even when the request carries no body,
  7859. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7860. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7861. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7862. Request req;
  7863. req.method = "REPORT";
  7864. req.path = "/dav-report";
  7865. auto res = cli_.send(req);
  7866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7867. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7868. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7869. }
  7870. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7871. Request req;
  7872. req.method = "PROPFIND";
  7873. req.path = "/not-dav";
  7874. auto res = cli_.send(req);
  7875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7876. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7877. }
  7878. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7879. Request req;
  7880. req.method = "UNLOCK";
  7881. req.path = "/dav/dir";
  7882. cli_.set_keep_alive(true);
  7883. auto res = cli_.send(req);
  7884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7885. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7886. EXPECT_EQ("close", res->get_header_value("Connection"));
  7887. EXPECT_FALSE(cli_.is_socket_open());
  7888. }
  7889. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7890. // The mount point serves this path, but only for GET and HEAD.
  7891. auto get_res = cli_.Get("/dir/index.html");
  7892. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7893. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7894. Request req;
  7895. req.method = "PROPFIND";
  7896. req.path = "/dir/index.html";
  7897. auto res = cli_.send(req);
  7898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7899. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7900. }
  7901. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7902. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7903. cli_.set_keep_alive(true);
  7904. for (auto i = 0; i < 2; i++) {
  7905. Request req;
  7906. req.method = "PROPFIND";
  7907. req.path = "/dav/dir";
  7908. req.body = xml;
  7909. auto res = cli_.send(req);
  7910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7911. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7912. EXPECT_EQ(xml, res->body);
  7913. EXPECT_TRUE(cli_.is_socket_open());
  7914. }
  7915. // A built-in method must still be served on the same connection.
  7916. cli_.set_keep_alive(false);
  7917. auto res = cli_.Get("/hi");
  7918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7919. EXPECT_EQ(StatusCode::OK_200, res->status);
  7920. EXPECT_EQ("close", res->get_header_value("Connection"));
  7921. }
  7922. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7923. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7924. Request req;
  7925. req.method = "PROPFIND";
  7926. req.path = "/dav/dir";
  7927. req.set_header("Expect", "100-continue");
  7928. req.body = xml;
  7929. auto res = cli_.send(req);
  7930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7931. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7932. EXPECT_EQ(xml, res->body);
  7933. }
  7934. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7935. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7936. TEST_F(ServerTest, Gzip) {
  7937. Headers headers;
  7938. headers.emplace("Accept-Encoding", "gzip, deflate");
  7939. auto res = cli_.Get("/compress", headers);
  7940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7941. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7942. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7943. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7944. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7945. "7890123456789012345678901234567890",
  7946. res->body);
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. }
  7949. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7950. Headers headers;
  7951. headers.emplace("Accept-Encoding", "gzip, deflate");
  7952. auto res = cli_.Get("/compress-with-charset", headers);
  7953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7954. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7955. EXPECT_EQ("application/json; charset=utf-8",
  7956. res->get_header_value("Content-Type"));
  7957. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7958. "7890123456789012345678901234567890",
  7959. res->body);
  7960. EXPECT_EQ(StatusCode::OK_200, res->status);
  7961. }
  7962. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7963. Headers headers;
  7964. headers.emplace("Accept-Encoding", "");
  7965. auto res = cli_.Get("/compress", headers);
  7966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7967. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7968. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7969. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7970. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7971. "7890123456789012345678901234567890",
  7972. res->body);
  7973. EXPECT_EQ(StatusCode::OK_200, res->status);
  7974. }
  7975. TEST_F(ServerTest, GzipWithContentReceiver) {
  7976. Headers headers;
  7977. headers.emplace("Accept-Encoding", "gzip, deflate");
  7978. std::string body;
  7979. auto res = cli_.Get("/compress", headers,
  7980. [&](const char *data, uint64_t data_length) {
  7981. EXPECT_EQ(100U, data_length);
  7982. body.append(data, data_length);
  7983. return true;
  7984. });
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7987. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7988. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7989. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7990. "7890123456789012345678901234567890",
  7991. body);
  7992. EXPECT_EQ(StatusCode::OK_200, res->status);
  7993. }
  7994. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7995. Headers headers;
  7996. headers.emplace("Accept-Encoding", "gzip, deflate");
  7997. cli_.set_decompress(false);
  7998. auto res = cli_.Get("/compress", headers);
  7999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8000. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8001. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8002. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8003. EXPECT_EQ(33U, res->body.size());
  8004. EXPECT_EQ(StatusCode::OK_200, res->status);
  8005. }
  8006. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8007. Headers headers;
  8008. headers.emplace("Accept-Encoding", "");
  8009. std::string body;
  8010. auto res = cli_.Get("/compress", headers,
  8011. [&](const char *data, uint64_t data_length) {
  8012. EXPECT_EQ(100U, data_length);
  8013. body.append(data, data_length);
  8014. return true;
  8015. });
  8016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8017. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8018. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8019. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8020. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8021. "7890123456789012345678901234567890",
  8022. body);
  8023. EXPECT_EQ(StatusCode::OK_200, res->status);
  8024. }
  8025. TEST_F(ServerTest, NoGzip) {
  8026. Headers headers;
  8027. headers.emplace("Accept-Encoding", "gzip, deflate");
  8028. auto res = cli_.Get("/nocompress", headers);
  8029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8030. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8031. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8032. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8033. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8034. "7890123456789012345678901234567890",
  8035. res->body);
  8036. EXPECT_EQ(StatusCode::OK_200, res->status);
  8037. }
  8038. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8039. Headers headers;
  8040. headers.emplace("Accept-Encoding", "gzip, deflate");
  8041. std::string body;
  8042. auto res = cli_.Get("/nocompress", headers,
  8043. [&](const char *data, uint64_t data_length) {
  8044. EXPECT_EQ(100U, data_length);
  8045. body.append(data, data_length);
  8046. return true;
  8047. });
  8048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8049. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8050. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8051. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8052. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8053. "7890123456789012345678901234567890",
  8054. body);
  8055. EXPECT_EQ(StatusCode::OK_200, res->status);
  8056. }
  8057. TEST_F(ServerTest, MultipartFormDataGzip) {
  8058. UploadFormDataItems items = {
  8059. {"key1", "test", "", ""},
  8060. {"key2", "--abcdefg123", "", ""},
  8061. };
  8062. cli_.set_compress(true);
  8063. auto res = cli_.Post("/compress-multipart", items);
  8064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8065. EXPECT_EQ(StatusCode::OK_200, res->status);
  8066. }
  8067. #endif
  8068. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8069. // Static file compression is opt-in, so these run their own server rather than
  8070. // flipping it on for the shared ServerTest fixture, which would silently
  8071. // rewrite what every other static file test is asserting.
  8072. class StaticFileCompressionTest : public ::testing::Test {
  8073. protected:
  8074. void TearDown() override {
  8075. if (t_.joinable()) {
  8076. svr_.stop();
  8077. t_.join();
  8078. }
  8079. }
  8080. int start(const std::function<void(Server &)> &configure = nullptr) {
  8081. // Serves the same tree as a directory of build-time compressed assets
  8082. // would be served: the mount point names the coding the files are already
  8083. // stored in. Registered before "/" so it is the one that matches.
  8084. svr_.set_mount_point("/pre-encoded", "./www",
  8085. {{"Content-Encoding", "gzip"}});
  8086. svr_.set_mount_point("/", "./www");
  8087. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8088. res.set_file_content("./www/dir/index.html", "text/html");
  8089. });
  8090. svr_.Get("/pre-encoded-file-content",
  8091. [](const Request & /*req*/, Response &res) {
  8092. res.set_header("Content-Encoding", "gzip");
  8093. res.set_file_content("./www/dir/index.html", "text/html");
  8094. });
  8095. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8096. res.set_content_provider(
  8097. 6, "text/plain",
  8098. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8099. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8100. return true;
  8101. });
  8102. });
  8103. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8104. res.set_content_provider(
  8105. 1000, "text/plain",
  8106. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8107. if (offset < 100) {
  8108. std::string data(100, 'A');
  8109. sink.write(data.data(), data.size());
  8110. return true;
  8111. }
  8112. std::this_thread::sleep_for(std::chrono::seconds(2));
  8113. std::string data(900, 'B');
  8114. sink.write(data.data(), data.size());
  8115. return true;
  8116. });
  8117. });
  8118. if (configure) { configure(svr_); }
  8119. auto port = svr_.bind_to_any_port(HOST);
  8120. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8121. svr_.wait_until_ready();
  8122. return port;
  8123. }
  8124. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8125. // Every file under ./www except 1MB.txt is smaller than the default
  8126. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8127. // it out of the way.
  8128. static void enable_without_floor(Server &svr) {
  8129. svr.set_static_file_compression(true);
  8130. svr.set_static_file_compression_min_length(0);
  8131. }
  8132. Server svr_;
  8133. std::thread t_;
  8134. };
  8135. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8136. auto port = start();
  8137. Client cli(HOST, port);
  8138. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8140. EXPECT_EQ(StatusCode::OK_200, res->status);
  8141. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8142. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8143. EXPECT_EQ(1048576U, res->body.size());
  8144. }
  8145. TEST_F(StaticFileCompressionTest, MountPoint) {
  8146. auto port = start(enable);
  8147. Client cli(HOST, port);
  8148. cli.set_decompress(false);
  8149. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8151. EXPECT_EQ(StatusCode::OK_200, res->status);
  8152. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8153. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8154. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8155. // The response stays self-delimiting: a length, not a chunked body.
  8156. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8157. EXPECT_EQ(std::to_string(res->body.size()),
  8158. res->get_header_value("Content-Length"));
  8159. EXPECT_LT(res->body.size(), 1048576U);
  8160. EXPECT_FALSE(res->body.empty());
  8161. }
  8162. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8163. auto port = start(enable);
  8164. Client cli(HOST, port);
  8165. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. EXPECT_EQ(StatusCode::OK_200, res->status);
  8168. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8169. EXPECT_EQ(1048576U, res->body.size());
  8170. }
  8171. TEST_F(StaticFileCompressionTest, FileContent) {
  8172. auto port = start(enable_without_floor);
  8173. Client cli(HOST, port);
  8174. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8176. EXPECT_EQ(StatusCode::OK_200, res->status);
  8177. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8178. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8179. EXPECT_EQ(104U, res->body.size());
  8180. }
  8181. // A handler that serves an already-encoded file names the coding itself. The
  8182. // file-backed path decided its coding from Accept-Encoding and the content
  8183. // type alone, so it compressed the stored bytes a second time and appended a
  8184. // second Content-Encoding field line.
  8185. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8186. auto port = start(enable_without_floor);
  8187. Client cli(HOST, port);
  8188. cli.set_decompress(false);
  8189. auto res = cli.Get("/pre-encoded-file-content",
  8190. Headers{{"Accept-Encoding", "gzip"}});
  8191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8192. EXPECT_EQ(StatusCode::OK_200, res->status);
  8193. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8194. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8195. // Vary belongs to a coding the server chose, and it chose none here.
  8196. EXPECT_FALSE(res->has_header("Vary"));
  8197. // The file travels exactly as it is stored on disk.
  8198. EXPECT_EQ(104U, res->body.size());
  8199. }
  8200. // The 1MB file clears the default floor, so this one runs the configuration a
  8201. // deployment would actually have.
  8202. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8203. auto port = start(enable);
  8204. Client cli(HOST, port);
  8205. cli.set_decompress(false);
  8206. auto res =
  8207. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. EXPECT_EQ(StatusCode::OK_200, res->status);
  8210. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8211. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8212. EXPECT_FALSE(res->has_header("Vary"));
  8213. EXPECT_EQ(1048576U, res->body.size());
  8214. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8215. }
  8216. TEST_F(StaticFileCompressionTest, Head) {
  8217. auto port = start(enable);
  8218. Client cli(HOST, port);
  8219. cli.set_decompress(false);
  8220. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8221. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8222. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8224. EXPECT_EQ(StatusCode::OK_200, res->status);
  8225. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8226. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8227. // HEAD still reports the size a GET would return.
  8228. EXPECT_EQ(get->get_header_value("Content-Length"),
  8229. res->get_header_value("Content-Length"));
  8230. EXPECT_TRUE(res->body.empty());
  8231. }
  8232. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8233. auto port = start(enable);
  8234. Client cli(HOST, port);
  8235. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8236. {"Accept-Encoding", "gzip"}});
  8237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8238. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8239. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8240. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8241. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8242. EXPECT_EQ("cd", res->body);
  8243. }
  8244. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8245. auto port = start(enable);
  8246. Client cli(HOST, port);
  8247. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8249. EXPECT_EQ(StatusCode::OK_200, res->status);
  8250. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8251. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8252. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8253. }
  8254. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8255. auto port = start(enable);
  8256. Client cli(HOST, port);
  8257. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8259. EXPECT_EQ(StatusCode::OK_200, res->status);
  8260. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8261. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8262. EXPECT_TRUE(res->body.empty());
  8263. }
  8264. TEST_F(StaticFileCompressionTest, MinLength) {
  8265. auto port = start(enable);
  8266. Client cli(HOST, port);
  8267. // 104 bytes, well under the default floor. Compressing it would add the
  8268. // gzip header and trailer to a body that already fits in one packet.
  8269. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8271. EXPECT_EQ(StatusCode::OK_200, res->status);
  8272. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8273. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8274. }
  8275. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8276. auto port = start([](Server &svr) {
  8277. svr.set_static_file_compression(true);
  8278. svr.set_static_file_compression_min_length(1);
  8279. });
  8280. Client cli(HOST, port);
  8281. cli.set_decompress(false);
  8282. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8284. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8285. // A 9-byte file comes back larger than it went in, because gzip's header and
  8286. // trailer outweigh anything deflate can save. That is the end of the range
  8287. // the floor exists to keep out.
  8288. EXPECT_GT(res->body.size(), 9U);
  8289. }
  8290. TEST_F(StaticFileCompressionTest, MaxLength) {
  8291. auto port = start([](Server &svr) {
  8292. svr.set_static_file_compression(true);
  8293. svr.set_static_file_compression_min_length(0);
  8294. svr.set_static_file_compression_max_length(1024);
  8295. });
  8296. Client cli(HOST, port);
  8297. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8298. // defines `small` as a macro on Windows.
  8299. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8300. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8301. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8302. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8303. // Under it: compressed.
  8304. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8305. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8306. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8307. }
  8308. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8309. auto port = start(enable_without_floor);
  8310. Client cli(HOST, port);
  8311. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8312. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8313. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8314. auto identity_etag = identity->get_header_value("ETag");
  8315. ASSERT_FALSE(identity_etag.empty());
  8316. auto gzipped =
  8317. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8318. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8319. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8320. auto gzip_etag = gzipped->get_header_value("ETag");
  8321. ASSERT_FALSE(gzip_etag.empty());
  8322. // Two representations, two validators.
  8323. EXPECT_NE(identity_etag, gzip_etag);
  8324. // Each one revalidates against the request that would produce it...
  8325. auto fresh =
  8326. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8327. {"If-None-Match", gzip_etag}});
  8328. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8329. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8330. auto fresh_identity =
  8331. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8332. {"If-None-Match", identity_etag}});
  8333. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8334. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8335. // ...and not against the other representation.
  8336. auto crossed =
  8337. cli.Get("/dir/index.html",
  8338. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8339. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8340. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8341. }
  8342. // The opt-in covers responses the server reads off disk itself. A caller's own
  8343. // known-length provider keeps its Content-Length and, more importantly, keeps
  8344. // delivering incrementally: routing it through a compressor would hold every
  8345. // write back until zlib's window filled.
  8346. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8347. auto port = start(enable);
  8348. Client cli(HOST, port);
  8349. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8351. EXPECT_EQ(StatusCode::OK_200, res->status);
  8352. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8353. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8354. EXPECT_EQ("aaabbb", res->body);
  8355. }
  8356. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8357. auto port = start(enable);
  8358. Client cli(HOST, port);
  8359. cli.set_read_timeout(1, 0);
  8360. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8361. Headers{{"Accept-Encoding", "gzip"}});
  8362. ASSERT_TRUE(handle.is_valid());
  8363. // The provider writes 100 bytes and then stalls for longer than the read
  8364. // timeout. Those first bytes have to arrive anyway: run the response through
  8365. // a compressor and zlib holds them until its window fills, so the read would
  8366. // come back empty instead.
  8367. char buf[256];
  8368. auto n = handle.read(buf, sizeof(buf));
  8369. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8370. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8371. }
  8372. #endif
  8373. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8374. TEST_F(ServerTest, Brotli) {
  8375. Headers headers;
  8376. headers.emplace("Accept-Encoding", "br");
  8377. auto res = cli_.Get("/compress", headers);
  8378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8379. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8380. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8381. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8382. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8383. "7890123456789012345678901234567890",
  8384. res->body);
  8385. EXPECT_EQ(StatusCode::OK_200, res->status);
  8386. }
  8387. #endif
  8388. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8389. TEST_F(ServerTest, Zstd) {
  8390. Headers headers;
  8391. headers.emplace("Accept-Encoding", "zstd");
  8392. auto res = cli_.Get("/compress", headers);
  8393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8394. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8395. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8396. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8397. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8398. "7890123456789012345678901234567890",
  8399. res->body);
  8400. EXPECT_EQ(StatusCode::OK_200, res->status);
  8401. }
  8402. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8403. Headers headers;
  8404. headers.emplace("Accept-Encoding", "");
  8405. auto res = cli_.Get("/compress", headers);
  8406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8407. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8408. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8409. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8410. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8411. "7890123456789012345678901234567890",
  8412. res->body);
  8413. EXPECT_EQ(StatusCode::OK_200, res->status);
  8414. }
  8415. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8416. Headers headers;
  8417. headers.emplace("Accept-Encoding", "zstd");
  8418. std::string body;
  8419. auto res = cli_.Get("/compress", headers,
  8420. [&](const char *data, uint64_t data_length) {
  8421. EXPECT_EQ(100U, data_length);
  8422. body.append(data, data_length);
  8423. return true;
  8424. });
  8425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8426. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8427. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8428. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8429. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8430. "7890123456789012345678901234567890",
  8431. body);
  8432. EXPECT_EQ(StatusCode::OK_200, res->status);
  8433. }
  8434. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8435. Headers headers;
  8436. headers.emplace("Accept-Encoding", "zstd");
  8437. cli_.set_decompress(false);
  8438. auto res = cli_.Get("/compress", headers);
  8439. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8440. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8441. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8442. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8444. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8445. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8446. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8447. EXPECT_EQ(StatusCode::OK_200, res->status);
  8448. ASSERT_EQ(26U, res->body.size());
  8449. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8450. 0);
  8451. }
  8452. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8453. Headers headers;
  8454. headers.emplace("Accept-Encoding", "");
  8455. std::string body;
  8456. auto res = cli_.Get("/compress", headers,
  8457. [&](const char *data, uint64_t data_length) {
  8458. EXPECT_EQ(100U, data_length);
  8459. body.append(data, data_length);
  8460. return true;
  8461. });
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8464. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8465. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8466. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8467. "7890123456789012345678901234567890",
  8468. body);
  8469. EXPECT_EQ(StatusCode::OK_200, res->status);
  8470. }
  8471. TEST_F(ServerTest, NoZstd) {
  8472. Headers headers;
  8473. headers.emplace("Accept-Encoding", "zstd");
  8474. auto res = cli_.Get("/nocompress", headers);
  8475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8476. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8477. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8478. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8479. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8480. "7890123456789012345678901234567890",
  8481. res->body);
  8482. EXPECT_EQ(StatusCode::OK_200, res->status);
  8483. }
  8484. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8485. Headers headers;
  8486. headers.emplace("Accept-Encoding", "zstd");
  8487. std::string body;
  8488. auto res = cli_.Get("/nocompress", headers,
  8489. [&](const char *data, uint64_t data_length) {
  8490. EXPECT_EQ(100U, data_length);
  8491. body.append(data, data_length);
  8492. return true;
  8493. });
  8494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8495. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8496. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8497. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8498. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8499. "7890123456789012345678901234567890",
  8500. body);
  8501. EXPECT_EQ(StatusCode::OK_200, res->status);
  8502. }
  8503. // TODO: How to enable zstd ??
  8504. TEST_F(ServerTest, MultipartFormDataZstd) {
  8505. UploadFormDataItems items = {
  8506. {"key1", "test", "", ""},
  8507. {"key2", "--abcdefg123", "", ""},
  8508. };
  8509. Headers headers;
  8510. headers.emplace("Accept-Encoding", "zstd");
  8511. cli_.set_compress(true);
  8512. auto res = cli_.Post("/compress-multipart", headers, items);
  8513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8514. EXPECT_EQ(StatusCode::OK_200, res->status);
  8515. }
  8516. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8517. Headers headers;
  8518. headers.emplace("Accept-Encoding", "zstd");
  8519. cli_.set_compress(true);
  8520. auto res = cli_.Put(
  8521. "/put", headers, 3,
  8522. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8523. sink.os << "PUT";
  8524. return true;
  8525. },
  8526. "text/plain");
  8527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8528. EXPECT_EQ(StatusCode::OK_200, res->status);
  8529. EXPECT_EQ("PUT", res->body);
  8530. }
  8531. // Pre-compression logging tests
  8532. TEST_F(ServerTest, PreCompressionLogging) {
  8533. // Test data for compression (matches the actual /compress endpoint content)
  8534. const std::string test_content =
  8535. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8536. "3456789012345678901234567890";
  8537. // Variables to capture logging data
  8538. std::string pre_compression_body;
  8539. std::string pre_compression_content_type;
  8540. std::string pre_compression_content_encoding;
  8541. std::string post_compression_body;
  8542. std::string post_compression_content_type;
  8543. std::string post_compression_content_encoding;
  8544. // Set up pre-compression logger
  8545. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8546. const Response &res) {
  8547. pre_compression_body = res.body;
  8548. pre_compression_content_type = res.get_header_value("Content-Type");
  8549. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8550. });
  8551. // Set up post-compression logger
  8552. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8553. post_compression_body = res.body;
  8554. post_compression_content_type = res.get_header_value("Content-Type");
  8555. post_compression_content_encoding =
  8556. res.get_header_value("Content-Encoding");
  8557. });
  8558. // Test with gzip compression
  8559. Headers headers;
  8560. headers.emplace("Accept-Encoding", "gzip");
  8561. auto res = cli_.Get("/compress", headers);
  8562. // Verify response was compressed
  8563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8564. EXPECT_EQ(StatusCode::OK_200, res->status);
  8565. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8566. // Verify pre-compression logger captured uncompressed content
  8567. EXPECT_EQ(test_content, pre_compression_body);
  8568. EXPECT_EQ("text/plain", pre_compression_content_type);
  8569. EXPECT_TRUE(pre_compression_content_encoding
  8570. .empty()); // No encoding header before compression
  8571. // Verify post-compression logger captured compressed content
  8572. EXPECT_NE(test_content,
  8573. post_compression_body); // Should be different after compression
  8574. EXPECT_EQ("text/plain", post_compression_content_type);
  8575. EXPECT_EQ("gzip", post_compression_content_encoding);
  8576. // Verify compressed content is smaller
  8577. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8578. }
  8579. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8580. const std::string test_content =
  8581. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8582. "3456789012345678901234567890";
  8583. std::string pre_compression_body;
  8584. std::string post_compression_body;
  8585. svr_.set_pre_compression_logger(
  8586. [&](const Request & /*req*/, const Response &res) {
  8587. pre_compression_body = res.body;
  8588. });
  8589. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8590. post_compression_body = res.body;
  8591. });
  8592. Headers headers;
  8593. headers.emplace("Accept-Encoding", "br");
  8594. auto res = cli_.Get("/compress", headers);
  8595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8596. EXPECT_EQ(StatusCode::OK_200, res->status);
  8597. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8598. // Verify pre-compression content is uncompressed
  8599. EXPECT_EQ(test_content, pre_compression_body);
  8600. // Verify post-compression content is compressed
  8601. EXPECT_NE(test_content, post_compression_body);
  8602. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8603. }
  8604. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8605. const std::string test_content =
  8606. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8607. "3456789012345678901234567890";
  8608. std::string pre_compression_body;
  8609. std::string post_compression_body;
  8610. svr_.set_pre_compression_logger(
  8611. [&](const Request & /*req*/, const Response &res) {
  8612. pre_compression_body = res.body;
  8613. });
  8614. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8615. post_compression_body = res.body;
  8616. });
  8617. // Request without compression (use /nocompress endpoint)
  8618. Headers headers;
  8619. auto res = cli_.Get("/nocompress", headers);
  8620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8621. EXPECT_EQ(StatusCode::OK_200, res->status);
  8622. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8623. // Pre-compression logger should not be called when no compression is applied
  8624. EXPECT_TRUE(
  8625. pre_compression_body.empty()); // Pre-compression logger not called
  8626. EXPECT_EQ(
  8627. test_content,
  8628. post_compression_body); // Post-compression logger captures final content
  8629. }
  8630. TEST_F(ServerTest, LoggerSeesContentLength) {
  8631. size_t logged_content_length = 0;
  8632. std::string logged_content_length_header;
  8633. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8634. logged_content_length = res.content_length_;
  8635. logged_content_length_header = res.get_header_value("Content-Length");
  8636. });
  8637. auto res = cli_.Get("/nocompress");
  8638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8639. EXPECT_EQ(StatusCode::OK_200, res->status);
  8640. EXPECT_EQ(res->body.size(), logged_content_length);
  8641. EXPECT_EQ(std::to_string(logged_content_length),
  8642. logged_content_length_header);
  8643. }
  8644. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8645. const std::string test_content =
  8646. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8647. "3456789012345678901234567890";
  8648. std::string pre_compression_body;
  8649. bool pre_logger_called = false;
  8650. // Set only pre-compression logger
  8651. svr_.set_pre_compression_logger(
  8652. [&](const Request & /*req*/, const Response &res) {
  8653. pre_compression_body = res.body;
  8654. pre_logger_called = true;
  8655. });
  8656. Headers headers;
  8657. headers.emplace("Accept-Encoding", "gzip");
  8658. auto res = cli_.Get("/compress", headers);
  8659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8660. EXPECT_EQ(StatusCode::OK_200, res->status);
  8661. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8662. // Verify pre-compression logger was called
  8663. EXPECT_TRUE(pre_logger_called);
  8664. EXPECT_EQ(test_content, pre_compression_body);
  8665. }
  8666. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8667. {
  8668. // Test with Expect: 100-continue header - success case
  8669. // Server returns 100 Continue, client sends body, server returns 200 OK
  8670. Request req;
  8671. req.method = "POST";
  8672. req.path = "/post-large";
  8673. req.set_header("Expect", "100-continue");
  8674. req.body = LARGE_DATA;
  8675. Response res;
  8676. auto error = Error::Success;
  8677. cli_.set_keep_alive(true);
  8678. auto ret = cli_.send(req, res, error);
  8679. EXPECT_TRUE(ret);
  8680. EXPECT_EQ(StatusCode::OK_200, res.status);
  8681. EXPECT_EQ(LARGE_DATA, res.body);
  8682. }
  8683. {
  8684. // Test with Expect: 100-continue header - error case
  8685. // Client should not send the body when server returns an error
  8686. Request req;
  8687. req.method = "POST";
  8688. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8689. req.set_header("Expect", "100-continue");
  8690. req.body = LARGE_DATA;
  8691. Response res;
  8692. auto error = Error::Success;
  8693. auto start = std::chrono::high_resolution_clock::now();
  8694. cli_.set_keep_alive(true);
  8695. auto ret = cli_.send(req, res, error);
  8696. auto end = std::chrono::high_resolution_clock::now();
  8697. auto elapsed =
  8698. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8699. .count();
  8700. // With Expect: 100-continue, request completes successfully but with error
  8701. EXPECT_TRUE(ret);
  8702. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8703. EXPECT_EQ("close", res.get_header_value("Connection"));
  8704. EXPECT_FALSE(cli_.is_socket_open());
  8705. EXPECT_LE(elapsed, 2000);
  8706. }
  8707. {
  8708. // Send an extra GET request to ensure error recovery without hanging
  8709. Request req;
  8710. req.method = "GET";
  8711. req.path = "/hi";
  8712. auto start = std::chrono::high_resolution_clock::now();
  8713. auto res = cli_.send(req);
  8714. auto end = std::chrono::high_resolution_clock::now();
  8715. auto elapsed =
  8716. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8717. .count();
  8718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8719. EXPECT_EQ(StatusCode::OK_200, res->status);
  8720. EXPECT_EQ("Hello World!", res->body);
  8721. EXPECT_LE(elapsed, 500);
  8722. }
  8723. }
  8724. TEST(ZstdDecompressor, ChunkedDecompression) {
  8725. std::string data;
  8726. for (size_t i = 0; i < 32 * 1024; ++i) {
  8727. data.push_back(static_cast<char>('a' + i % 26));
  8728. }
  8729. std::string compressed_data;
  8730. {
  8731. httplib::detail::zstd_compressor compressor;
  8732. bool result = compressor.compress(
  8733. data.data(), data.size(),
  8734. /*last=*/true,
  8735. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8736. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8737. compressed_data_size);
  8738. return true;
  8739. });
  8740. ASSERT_TRUE(result);
  8741. }
  8742. std::string decompressed_data;
  8743. {
  8744. httplib::detail::zstd_decompressor decompressor;
  8745. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8746. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8747. size_t chunk_size = 130;
  8748. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8749. chunk_begin += chunk_size) {
  8750. size_t current_chunk_size =
  8751. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8752. bool result = decompressor.decompress(
  8753. compressed_data.data() + chunk_begin, current_chunk_size,
  8754. [&](const char *decompressed_data_chunk,
  8755. size_t decompressed_data_chunk_size) {
  8756. decompressed_data.insert(decompressed_data.size(),
  8757. decompressed_data_chunk,
  8758. decompressed_data_chunk_size);
  8759. return true;
  8760. });
  8761. ASSERT_TRUE(result);
  8762. }
  8763. }
  8764. ASSERT_EQ(data, decompressed_data);
  8765. }
  8766. TEST(ZstdDecompressor, Decompress) {
  8767. std::string original_text = "Compressed with ZSTD";
  8768. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8769. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8770. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8771. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8772. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8773. std::string decompressed_data;
  8774. {
  8775. httplib::detail::zstd_decompressor decompressor;
  8776. bool result = decompressor.decompress(
  8777. compressed_data.data(), compressed_data.size(),
  8778. [&](const char *decompressed_data_chunk,
  8779. size_t decompressed_data_chunk_size) {
  8780. decompressed_data.insert(decompressed_data.size(),
  8781. decompressed_data_chunk,
  8782. decompressed_data_chunk_size);
  8783. return true;
  8784. });
  8785. ASSERT_TRUE(result);
  8786. }
  8787. ASSERT_EQ(original_text, decompressed_data);
  8788. }
  8789. #endif
  8790. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8791. // separate chunks so that the server sees each part in its own read(). Used to
  8792. // place a read boundary at a specific offset of a request body.
  8793. static bool send_request_in_parts(time_t read_timeout_sec,
  8794. const std::vector<std::string> &parts,
  8795. std::string *resp = nullptr,
  8796. int port = PORT) {
  8797. auto error = Error::Success;
  8798. auto client_sock = detail::create_client_socket(
  8799. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8800. /*connection_timeout_sec=*/5, 0,
  8801. /*read_timeout_sec=*/5, 0,
  8802. /*write_timeout_sec=*/5, 0, std::string(), error);
  8803. if (client_sock == INVALID_SOCKET) { return false; }
  8804. auto ret = detail::process_client_socket(
  8805. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8806. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8807. for (size_t i = 0; i < parts.size(); i++) {
  8808. const auto &part = parts[i];
  8809. if (part.size() !=
  8810. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8811. return false;
  8812. }
  8813. if (i + 1 < parts.size()) {
  8814. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8815. }
  8816. }
  8817. char buf[512];
  8818. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8819. while (line_reader.getline()) {
  8820. if (resp) { *resp += line_reader.ptr(); }
  8821. }
  8822. return true;
  8823. });
  8824. detail::close_socket(client_sock);
  8825. return ret;
  8826. }
  8827. // Sends a raw request to a server listening at HOST:PORT.
  8828. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8829. std::string *resp = nullptr, int port = PORT) {
  8830. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8831. }
  8832. #ifdef CPPHTTPLIB_SSL_ENABLED
  8833. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8834. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8835. ASSERT_TRUE(svr.is_valid());
  8836. svr.set_read_timeout(1, 0);
  8837. thread t = thread([&]() { ASSERT_TRUE(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. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8845. // keeps each wait well within the read timeout. The server gives up a
  8846. // second in, so the bytes sent after that fail.
  8847. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8848. parts.resize(26, std::string(1, '\0'));
  8849. EXPECT_FALSE(send_request_in_parts(5, parts));
  8850. }
  8851. #endif
  8852. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8853. Server svr;
  8854. std::string header_value;
  8855. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8856. header_value = req.get_header_value("foo");
  8857. res.set_content("ok", "text/plain");
  8858. });
  8859. thread t = thread([&] { svr.listen(HOST, PORT); });
  8860. auto se = detail::scope_exit([&] {
  8861. svr.stop();
  8862. t.join();
  8863. ASSERT_FALSE(svr.is_running());
  8864. });
  8865. svr.wait_until_ready();
  8866. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8867. // like characters are not treated the same - use vertical tab and escape.
  8868. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8869. "foo: \t \v bar \x1B\t \r\n"
  8870. "Connection: close\r\n"
  8871. "\r\n";
  8872. std::string res;
  8873. ASSERT_TRUE(send_request(5, req, &res));
  8874. EXPECT_EQ(header_value, "");
  8875. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8876. }
  8877. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8878. Server svr;
  8879. std::string received;
  8880. svr.Get("/order", [&](const Request &req, Response &res) {
  8881. received = entries_to_string(req.headers);
  8882. res.set_content("ok", "text/plain");
  8883. });
  8884. auto port = svr.bind_to_any_port(HOST);
  8885. thread t = thread([&] { svr.listen_after_bind(); });
  8886. auto se = detail::scope_exit([&] {
  8887. svr.stop();
  8888. t.join();
  8889. ASSERT_FALSE(svr.is_running());
  8890. });
  8891. svr.wait_until_ready();
  8892. const std::string req = "GET /order HTTP/1.1\r\n"
  8893. "Host: localhost\r\n"
  8894. "X-First: 1\r\n"
  8895. "X-Dup: a\r\n"
  8896. "X-Second: 2\r\n"
  8897. "X-Dup: b\r\n"
  8898. "Connection: close\r\n"
  8899. "\r\n";
  8900. std::string res;
  8901. ASSERT_TRUE(send_request(5, req, &res, port));
  8902. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8903. EXPECT_EQ(
  8904. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  8905. received);
  8906. }
  8907. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8908. Server svr;
  8909. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8910. res.set_header("Set-Cookie", "first=1");
  8911. res.set_header("X-Between", "y");
  8912. res.set_header("Set-Cookie", "second=2");
  8913. res.set_content("ok", "text/plain");
  8914. });
  8915. auto port = svr.bind_to_any_port(HOST);
  8916. thread t = thread([&] { svr.listen_after_bind(); });
  8917. auto se = detail::scope_exit([&] {
  8918. svr.stop();
  8919. t.join();
  8920. ASSERT_FALSE(svr.is_running());
  8921. });
  8922. svr.wait_until_ready();
  8923. Client cli(HOST, port);
  8924. auto res = cli.Get("/cookies");
  8925. ASSERT_TRUE(res);
  8926. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8927. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8928. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8929. }
  8930. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8931. Server svr;
  8932. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8933. auto i = new int(0);
  8934. res.set_header("Trailer", "X-Safe, X-Reflected");
  8935. res.set_chunked_content_provider(
  8936. "text/plain",
  8937. [i](size_t /*offset*/, DataSink &sink) {
  8938. if (*i == 0) {
  8939. sink.os << "body";
  8940. } else {
  8941. Headers trailer;
  8942. // A valid trailer that must survive.
  8943. trailer.emplace("X-Safe", "safe");
  8944. // Attacker-controlled value carrying CR/LF (response splitting).
  8945. trailer.emplace("X-Reflected",
  8946. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8947. // Attacker-controlled name carrying CR/LF.
  8948. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8949. sink.done_with_trailer(trailer);
  8950. }
  8951. (*i)++;
  8952. return true;
  8953. },
  8954. [i](bool /*success*/) { delete i; });
  8955. });
  8956. thread t = thread([&] { svr.listen(HOST, PORT); });
  8957. auto se = detail::scope_exit([&] {
  8958. svr.stop();
  8959. t.join();
  8960. ASSERT_FALSE(svr.is_running());
  8961. });
  8962. svr.wait_until_ready();
  8963. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8964. "Host: " + HOST +
  8965. "\r\n"
  8966. "Connection: close\r\n"
  8967. "\r\n";
  8968. std::string res;
  8969. ASSERT_TRUE(send_request(5, req, &res));
  8970. // The injected fields must not appear anywhere in the raw response.
  8971. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8972. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8973. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8974. // Invalid trailers are dropped entirely, matching set_header().
  8975. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8976. // The valid trailer still passes through.
  8977. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8978. }
  8979. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8980. Server svr;
  8981. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8982. // res.headers is a public field an application can populate directly,
  8983. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8984. // A valid header that must survive.
  8985. res.headers.emplace("X-Safe", "safe");
  8986. // Attacker-controlled value carrying CR/LF (response splitting).
  8987. res.headers.emplace("X-Reflected",
  8988. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8989. // Attacker-controlled name carrying CR/LF.
  8990. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8991. res.set_content("body", "text/plain");
  8992. });
  8993. thread t = thread([&] { svr.listen(HOST, PORT); });
  8994. auto se = detail::scope_exit([&] {
  8995. svr.stop();
  8996. t.join();
  8997. ASSERT_FALSE(svr.is_running());
  8998. });
  8999. svr.wait_until_ready();
  9000. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9001. "Host: " + HOST +
  9002. "\r\n"
  9003. "Connection: close\r\n"
  9004. "\r\n";
  9005. std::string res;
  9006. ASSERT_TRUE(send_request(5, req, &res));
  9007. // The injected fields must not appear anywhere in the raw response.
  9008. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9009. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9010. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9011. // Invalid headers are dropped entirely, matching set_header().
  9012. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9013. // The valid header still passes through.
  9014. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9015. }
  9016. // Forward declaration: in split builds split.py strips `inline` and moves the
  9017. // definition into httplib.cc, so detail::write_request_line is not visible from
  9018. // the public httplib.h. Re-declaring it here lets the tests link against the
  9019. // symbol in both header-only and split builds.
  9020. namespace httplib {
  9021. namespace detail {
  9022. ssize_t write_request_line(Stream &strm, const std::string &method,
  9023. const std::string &path);
  9024. } // namespace detail
  9025. } // namespace httplib
  9026. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9027. // A well-formed target is written verbatim.
  9028. {
  9029. detail::BufferStream strm;
  9030. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9031. EXPECT_GT(n, 0);
  9032. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9033. }
  9034. // A target carrying CR/LF, SP or other control octets must be rejected
  9035. // before anything reaches the wire, otherwise it splits the request line and
  9036. // injects a header or a whole request.
  9037. const std::string evil_targets[] = {
  9038. "/a\r\nInjected: pwned",
  9039. "/a\rInjected",
  9040. "/a\nInjected",
  9041. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9042. "/a b",
  9043. "/a\tb",
  9044. "/a\x7f",
  9045. };
  9046. for (const auto &evil : evil_targets) {
  9047. detail::BufferStream strm;
  9048. auto n = detail::write_request_line(strm, "GET", evil);
  9049. EXPECT_LT(n, 0);
  9050. EXPECT_TRUE(strm.get_buffer().empty());
  9051. }
  9052. }
  9053. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9054. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9055. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9056. // target reaches write_request. The client must fail cleanly with
  9057. // Error::Write instead of putting a request-line-less, header-injecting
  9058. // request on the wire.
  9059. Server svr;
  9060. svr.Get("/a", [](const Request &, Response &res) {
  9061. res.set_content("ok", "text/plain");
  9062. });
  9063. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9064. auto se = detail::scope_exit([&] {
  9065. svr.stop();
  9066. thread.join();
  9067. ASSERT_FALSE(svr.is_running());
  9068. });
  9069. svr.wait_until_ready();
  9070. {
  9071. Client cli(HOST, PORT);
  9072. cli.set_path_encode(false);
  9073. // The request is rejected before anything is written, so the connection
  9074. // stays silent and the subsequent response read would otherwise block for
  9075. // the full default read timeout. Shorten it -- the assertion is on the
  9076. // error, not the timeout.
  9077. cli.set_read_timeout(1, 0);
  9078. auto res = cli.Get("/a\r\nInjected: pwned");
  9079. EXPECT_FALSE(res);
  9080. EXPECT_EQ(Error::Write, res.error());
  9081. }
  9082. }
  9083. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9084. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9085. // including extension methods.
  9086. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9087. for (const auto &method : good_methods) {
  9088. detail::BufferStream strm;
  9089. auto n = detail::write_request_line(strm, method, "/");
  9090. EXPECT_GT(n, 0);
  9091. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9092. }
  9093. // A method carrying CR/LF would split the request line and smuggle a whole
  9094. // request ahead of the real one. A space or an empty method corrupts the
  9095. // request line. All must be rejected before anything reaches the wire.
  9096. const std::string evil_methods[] = {
  9097. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9098. "GET\r\nInjected: pwned",
  9099. "GET\r",
  9100. "GET\n",
  9101. "GE T",
  9102. "",
  9103. };
  9104. for (const auto &evil : evil_methods) {
  9105. detail::BufferStream strm;
  9106. auto n = detail::write_request_line(strm, evil, "/");
  9107. EXPECT_LT(n, 0);
  9108. EXPECT_TRUE(strm.get_buffer().empty());
  9109. }
  9110. }
  9111. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9112. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9113. // through Client::send must fail with Error::Write and no request, neither
  9114. // the smuggled one nor the real one, may reach the server.
  9115. Server svr;
  9116. std::atomic<int> request_count(0);
  9117. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9118. request_count++;
  9119. res.status = StatusCode::OK_200;
  9120. return Server::HandlerResponse::Handled;
  9121. });
  9122. auto port = svr.bind_to_any_port(HOST);
  9123. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9124. auto se = detail::scope_exit([&] {
  9125. svr.stop();
  9126. thread.join();
  9127. ASSERT_FALSE(svr.is_running());
  9128. });
  9129. svr.wait_until_ready();
  9130. {
  9131. Client cli(HOST, port);
  9132. const std::string evil_methods[] = {
  9133. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9134. "GE T",
  9135. "",
  9136. };
  9137. for (const auto &evil : evil_methods) {
  9138. Request req;
  9139. req.method = evil;
  9140. req.path = "/";
  9141. auto res = cli.send(req);
  9142. EXPECT_FALSE(res);
  9143. EXPECT_EQ(Error::Write, res.error());
  9144. }
  9145. auto handle =
  9146. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9147. EXPECT_FALSE(handle.is_valid());
  9148. EXPECT_EQ(Error::Write, handle.error);
  9149. // A valid request on the same client still goes through.
  9150. auto res = cli.Get("/");
  9151. ASSERT_TRUE(res);
  9152. EXPECT_EQ(StatusCode::OK_200, res->status);
  9153. }
  9154. EXPECT_EQ(1, request_count.load());
  9155. }
  9156. // Sends a raw request and verifies that there isn't a crash or exception.
  9157. static void test_raw_request(const std::string &req,
  9158. std::string *out = nullptr) {
  9159. Server svr;
  9160. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9161. res.set_content("ok", "text/plain");
  9162. });
  9163. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9164. res.set_content("ok", "text/plain");
  9165. });
  9166. svr.Get("/header_field_value_check",
  9167. [&](const Request & /*req*/, Response &res) {
  9168. res.set_content("ok", "text/plain");
  9169. });
  9170. svr.CustomRoute("PROPFIND", "/dav",
  9171. [&](const Request & /*req*/, Response &res) {
  9172. res.status = StatusCode::MultiStatus_207;
  9173. });
  9174. // Server read timeout must be longer than the client read timeout for the
  9175. // bug to reproduce, probably to force the server to process a request
  9176. // without a trailing blank line.
  9177. const time_t client_read_timeout_sec = 1;
  9178. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9179. bool listen_thread_ok = false;
  9180. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9181. auto se = detail::scope_exit([&] {
  9182. svr.stop();
  9183. t.join();
  9184. ASSERT_FALSE(svr.is_running());
  9185. EXPECT_TRUE(listen_thread_ok);
  9186. });
  9187. svr.wait_until_ready();
  9188. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9189. }
  9190. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9191. // A certain header line causes an exception if the header property is parsed
  9192. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9193. test_raw_request(
  9194. "GET /hi HTTP/1.1\r\n"
  9195. " : "
  9196. " "
  9197. " ");
  9198. }
  9199. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9200. // A certain header line causes an exception if the header property *name* is
  9201. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9202. // greedy matcher and requires backtracking when there are a lot of ":"
  9203. // characters.
  9204. // This occurs with libc++ but not libstdc++.
  9205. test_raw_request(
  9206. "GET /hi HTTP/1.1\r\n"
  9207. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9208. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9209. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9210. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9211. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9212. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9213. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9214. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9215. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9216. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9217. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9218. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9219. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9220. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9221. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9222. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9223. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9224. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9225. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9226. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9227. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9228. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9229. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9230. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9231. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9232. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9233. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9234. "&&&%%%");
  9235. }
  9236. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9237. // Make sure this doesn't crash the server.
  9238. // In a previous version of the header line regex, the "\r" rendered the line
  9239. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9240. // a new position where the leading white space ended and the field value
  9241. // began.
  9242. // The crash occurs with libc++ but not libstdc++.
  9243. test_raw_request("GET /hi HTTP/1.1\r\n"
  9244. "a:" +
  9245. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9246. "\r\n"
  9247. "\r\n");
  9248. }
  9249. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9250. const char *rejected[] = {
  9251. // RFC 9112 §3: one SP between the parts, and nothing else
  9252. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9253. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9254. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9255. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9256. // A request-target has no fragment
  9257. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9258. // An HTTP/1.1 request needs a Host
  9259. "GET /hi HTTP/1.1\r\n\r\n",
  9260. };
  9261. for (auto request : rejected) {
  9262. std::string out;
  9263. test_raw_request(request, &out);
  9264. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9265. }
  9266. std::string out;
  9267. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9268. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9269. }
  9270. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9271. // RFC 9112 §6.1
  9272. const char *requests[] = {
  9273. "PUT /put_hi HTTP/1.1\r\n"
  9274. "Host: localhost\r\n"
  9275. "Content-Length: 0\r\n"
  9276. "Transfer-Encoding: chunked\r\n"
  9277. "\r\n"
  9278. "0\r\n\r\n",
  9279. "PUT /put_hi HTTP/1.0\r\n"
  9280. "Connection: keep-alive\r\n"
  9281. "Transfer-Encoding: chunked\r\n"
  9282. "\r\n"
  9283. "0\r\n\r\n",
  9284. };
  9285. for (auto request : requests) {
  9286. std::string out;
  9287. test_raw_request(request, &out);
  9288. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9289. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9290. }
  9291. }
  9292. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9293. std::string out;
  9294. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9295. "Content-Type: text/plain\r\n"
  9296. "Transfer-Encoding: chunked\r\n"
  9297. "\r\n"
  9298. "nothex\r\n",
  9299. &out);
  9300. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9301. }
  9302. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9303. std::string out;
  9304. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9305. "Content-Type: text/plain\r\n"
  9306. "Transfer-Encoding: chunked\r\n"
  9307. "\r\n"
  9308. "3\r\n"
  9309. "xyz\r\n"
  9310. "NaN\r\n",
  9311. &out);
  9312. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9313. }
  9314. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9315. std::string out;
  9316. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9317. "Content-Type: text/plain\r\n"
  9318. "Transfer-Encoding: chunked\r\n"
  9319. "\r\n"
  9320. // Length is too large for 64 bits.
  9321. "1ffffffffffffffff\r\n"
  9322. "xyz\r\n",
  9323. &out);
  9324. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9325. }
  9326. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9327. test_raw_request("GET /hi HTTP/1.1\r\n"
  9328. "Content-Type: text/plain\r\n\r");
  9329. }
  9330. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9331. std::string out;
  9332. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9333. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9334. }
  9335. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9336. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9337. std::string out;
  9338. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9339. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9340. }
  9341. }
  9342. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9343. std::string out;
  9344. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9345. "Host: localhost\r\n"
  9346. "Connection: close\r\n\r\n",
  9347. &out);
  9348. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9349. }
  9350. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9351. Server svr;
  9352. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9353. EXPECT_TRUE(!req.remote_addr.empty());
  9354. });
  9355. thread t = thread([&] { svr.listen(HOST, PORT); });
  9356. auto se = detail::scope_exit([&] {
  9357. svr.stop();
  9358. t.join();
  9359. ASSERT_FALSE(svr.is_running());
  9360. });
  9361. svr.wait_until_ready();
  9362. // Send an invalid request line to trigger Bad Request
  9363. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9364. std::string out;
  9365. ASSERT_TRUE(send_request(5, bad_req, &out));
  9366. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9367. }
  9368. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9369. // answered right away rather than blocking on a read that waits for EOF.
  9370. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9371. std::string out;
  9372. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9373. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9374. }
  9375. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9376. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9377. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9378. for (const auto *method : methods) {
  9379. Server svr;
  9380. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9381. EXPECT_FALSE(svr.is_valid()) << method;
  9382. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9383. }
  9384. }
  9385. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9386. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9387. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9388. for (const auto *method : methods) {
  9389. Server svr;
  9390. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9391. EXPECT_FALSE(svr.is_valid()) << method;
  9392. }
  9393. }
  9394. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9395. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9396. "COPY", "MOVE", "LOCK",
  9397. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9398. Server svr;
  9399. for (const auto *method : methods) {
  9400. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9401. }
  9402. EXPECT_TRUE(svr.is_valid());
  9403. }
  9404. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9405. Server svr;
  9406. svr.CustomRoute("POST", "/x",
  9407. [](const Request &, Response &, const ContentReader &) {});
  9408. EXPECT_FALSE(svr.is_valid());
  9409. }
  9410. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9411. Server svr;
  9412. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9413. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9414. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9415. EXPECT_FALSE(svr.is_valid());
  9416. }
  9417. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9418. Server svr;
  9419. auto captured = Error::Success;
  9420. svr.set_error_logger(
  9421. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9422. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9423. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9424. }
  9425. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9426. std::string out;
  9427. std::string request(
  9428. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9429. test_raw_request(request, &out);
  9430. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9431. }
  9432. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9433. std::string out;
  9434. std::string request(
  9435. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9436. test_raw_request(request, &out);
  9437. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9438. }
  9439. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9440. std::string out;
  9441. std::string request(
  9442. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9443. test_raw_request(request, &out);
  9444. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9445. }
  9446. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9447. std::string out;
  9448. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9449. "Host: localhost\r\n"
  9450. "Test: \r\n\r\n",
  9451. &out);
  9452. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9453. }
  9454. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9455. Server svr;
  9456. std::string x_custom;
  9457. std::string cookie;
  9458. std::string xff;
  9459. std::string x_unicode;
  9460. std::string x_iis;
  9461. svr.Get("/check", [&](const Request &req, Response &res) {
  9462. x_custom = req.get_header_value("X-Custom");
  9463. cookie = req.get_header_value("Cookie");
  9464. xff = req.get_header_value("X-Forwarded-For");
  9465. x_unicode = req.get_header_value("X-Unicode");
  9466. x_iis = req.get_header_value("X-IIS");
  9467. res.set_content("ok", "text/plain");
  9468. });
  9469. thread t = thread([&] { svr.listen(HOST, PORT); });
  9470. auto se = detail::scope_exit([&] {
  9471. svr.stop();
  9472. t.join();
  9473. ASSERT_FALSE(svr.is_running());
  9474. });
  9475. svr.wait_until_ready();
  9476. const std::string req = "GET /check HTTP/1.1\r\n"
  9477. "Host: localhost\r\n"
  9478. "X-Custom: a%0D%0AInjected: b\r\n"
  9479. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9480. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9481. "X-Unicode: %E3%81%82\r\n"
  9482. "X-IIS: %u00E9\r\n"
  9483. "Connection: close\r\n"
  9484. "\r\n";
  9485. std::string res;
  9486. ASSERT_TRUE(send_request(5, req, &res));
  9487. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9488. // Every value must be returned verbatim (wire form), with no decoding.
  9489. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9490. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9491. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9492. EXPECT_EQ("%E3%81%82", x_unicode);
  9493. EXPECT_EQ("%u00E9", x_iis);
  9494. }
  9495. // Applications that previously relied on automatic percent-decoding can
  9496. // reproduce the old behavior by explicitly calling decode_path_component()
  9497. // or, for RFC 3986 conformance, decode_uri_component().
  9498. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9499. Server svr;
  9500. std::string decoded;
  9501. svr.Get("/check", [&](const Request &req, Response &res) {
  9502. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9503. res.set_content("ok", "text/plain");
  9504. });
  9505. thread t = thread([&] { svr.listen(HOST, PORT); });
  9506. auto se = detail::scope_exit([&] {
  9507. svr.stop();
  9508. t.join();
  9509. ASSERT_FALSE(svr.is_running());
  9510. });
  9511. svr.wait_until_ready();
  9512. const std::string req = "GET /check HTTP/1.1\r\n"
  9513. "Host: localhost\r\n"
  9514. "X-Custom: hello%20world\r\n"
  9515. "Connection: close\r\n"
  9516. "\r\n";
  9517. std::string res;
  9518. ASSERT_TRUE(send_request(5, req, &res));
  9519. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9520. EXPECT_EQ("hello world", decoded);
  9521. }
  9522. // Regression test for #2033. Browsers send Referer values that include
  9523. // percent-encoded characters such as %0A inside the URL. Decoding the
  9524. // header value would either trip the post-decode CR/LF/NUL guard (the
  9525. // original bug, returning 400) or, after that guard was relaxed, silently
  9526. // store a literal LF — both unacceptable. The wire form must round-trip.
  9527. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9528. Server svr;
  9529. std::string referer;
  9530. svr.Get("/check", [&](const Request &req, Response &res) {
  9531. referer = req.get_header_value("Referer");
  9532. res.set_content("ok", "text/plain");
  9533. });
  9534. thread t = thread([&] { svr.listen(HOST, PORT); });
  9535. auto se = detail::scope_exit([&] {
  9536. svr.stop();
  9537. t.join();
  9538. ASSERT_FALSE(svr.is_running());
  9539. });
  9540. svr.wait_until_ready();
  9541. const std::string req = "GET /check HTTP/1.1\r\n"
  9542. "Host: localhost\r\n"
  9543. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9544. "Connection: close\r\n"
  9545. "\r\n";
  9546. std::string res;
  9547. ASSERT_TRUE(send_request(5, req, &res));
  9548. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9549. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9550. }
  9551. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9552. Server svr;
  9553. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9554. res.set_header("Cache-Control", "no-cache");
  9555. res.set_chunked_content_provider(
  9556. "text/event-stream", [](size_t offset, DataSink &sink) {
  9557. std::string s = "data:";
  9558. s += std::to_string(offset);
  9559. s += "\n\n";
  9560. auto ret = sink.write(s.data(), s.size());
  9561. EXPECT_TRUE(ret);
  9562. std::this_thread::sleep_for(std::chrono::seconds(1));
  9563. return true;
  9564. });
  9565. });
  9566. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9567. svr.wait_until_ready();
  9568. Client client(HOST, PORT);
  9569. const Headers headers = {{"Accept", "text/event-stream"}};
  9570. auto get_thread = std::thread([&client, &headers]() {
  9571. auto res = client.Get(
  9572. "/events", headers,
  9573. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9574. });
  9575. auto se = detail::scope_exit([&] {
  9576. svr.stop();
  9577. get_thread.join();
  9578. listen_thread.join();
  9579. ASSERT_FALSE(svr.is_running());
  9580. });
  9581. // Give GET time to get a few messages.
  9582. std::this_thread::sleep_for(std::chrono::seconds(2));
  9583. }
  9584. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9585. httplib::Server svr;
  9586. svr.Post("/hi",
  9587. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9588. res.status = StatusCode::OK_200;
  9589. });
  9590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9591. svr.wait_until_ready();
  9592. Client cli(HOST, PORT);
  9593. auto res = cli.Post("/hi", "data", "text/plain");
  9594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9595. EXPECT_EQ(StatusCode::OK_200, res->status);
  9596. svr.stop();
  9597. thread.join();
  9598. ASSERT_FALSE(svr.is_running());
  9599. res = cli.Post("/hi", "data", "text/plain");
  9600. ASSERT_FALSE(res);
  9601. }
  9602. TEST(ServerStopTest, ListenFailure) {
  9603. Server svr;
  9604. auto t = thread([&]() {
  9605. auto ret = svr.listen("????", PORT);
  9606. EXPECT_FALSE(ret);
  9607. });
  9608. svr.wait_until_ready();
  9609. svr.stop();
  9610. t.join();
  9611. }
  9612. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9613. TEST(ServerStopTest, Decommision) {
  9614. Server svr;
  9615. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9616. for (int i = 0; i < 4; i++) {
  9617. auto is_even = !(i % 2);
  9618. std::thread t{[&] {
  9619. try {
  9620. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9621. if (is_even) {
  9622. throw std::runtime_error("Some thing that happens to go wrong.");
  9623. }
  9624. svr.listen(HOST, PORT);
  9625. } catch (...) { svr.decommission(); }
  9626. }};
  9627. svr.wait_until_ready();
  9628. // Server is up
  9629. {
  9630. Client cli(HOST, PORT);
  9631. auto res = cli.Get("/hi");
  9632. if (is_even) {
  9633. EXPECT_FALSE(res);
  9634. } else {
  9635. EXPECT_TRUE(res);
  9636. EXPECT_EQ("hi...", res->body);
  9637. }
  9638. }
  9639. svr.stop();
  9640. t.join();
  9641. // Server is down...
  9642. {
  9643. Client cli(HOST, PORT);
  9644. auto res = cli.Get("/hi");
  9645. EXPECT_FALSE(res);
  9646. }
  9647. }
  9648. }
  9649. #endif
  9650. // Helper function for string body upload progress tests
  9651. template <typename SetupHandler, typename ClientCall>
  9652. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9653. ClientCall &&client_call,
  9654. const string &body) {
  9655. Server svr;
  9656. setup_handler(svr);
  9657. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9658. auto se = detail::scope_exit([&] {
  9659. svr.stop();
  9660. t.join();
  9661. });
  9662. svr.wait_until_ready();
  9663. Client cli(HOST, PORT);
  9664. vector<uint64_t> progress_values;
  9665. bool progress_called = false;
  9666. auto res =
  9667. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9668. progress_values.push_back(current);
  9669. progress_called = true;
  9670. return true;
  9671. });
  9672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9673. EXPECT_EQ(200, res->status);
  9674. EXPECT_TRUE(progress_called);
  9675. }
  9676. TEST(UploadProgressTest, PostStringBodyBasic) {
  9677. TestStringBodyUploadProgress(
  9678. [](Server &svr) {
  9679. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9680. res.set_content("received", "text/plain");
  9681. });
  9682. },
  9683. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9684. return cli.Post("/test", body, "text/plain", progress_callback);
  9685. },
  9686. "test data for upload progress");
  9687. }
  9688. TEST(UploadProgressTest, PutStringBodyBasic) {
  9689. TestStringBodyUploadProgress(
  9690. [](Server &svr) {
  9691. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9692. res.set_content("put received", "text/plain");
  9693. });
  9694. },
  9695. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9696. return cli.Put("/test", body, "text/plain", progress_callback);
  9697. },
  9698. "put test data for upload progress");
  9699. }
  9700. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9701. TestStringBodyUploadProgress(
  9702. [](Server &svr) {
  9703. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9704. res.set_content("patch received", "text/plain");
  9705. });
  9706. },
  9707. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9708. return cli.Patch("/test", body, "text/plain", progress_callback);
  9709. },
  9710. "patch test data for upload progress");
  9711. }
  9712. // Helper function for content provider upload progress tests
  9713. template <typename SetupHandler, typename ClientCall>
  9714. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9715. ClientCall &&client_call) {
  9716. Server svr;
  9717. setup_handler(svr);
  9718. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9719. auto se = detail::scope_exit([&] {
  9720. svr.stop();
  9721. t.join();
  9722. });
  9723. svr.wait_until_ready();
  9724. Client cli(HOST, PORT);
  9725. vector<uint64_t> progress_values;
  9726. auto res =
  9727. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9728. progress_values.push_back(current);
  9729. return true;
  9730. });
  9731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9732. EXPECT_EQ(200, res->status);
  9733. EXPECT_FALSE(progress_values.empty());
  9734. }
  9735. TEST(UploadProgressTest, PostContentProviderProgress) {
  9736. TestContentProviderUploadProgress(
  9737. [](Server &svr) {
  9738. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9739. res.set_content("provider received", "text/plain");
  9740. });
  9741. },
  9742. [](Client &cli, UploadProgress progress_callback) {
  9743. return cli.Post(
  9744. "/test", 10,
  9745. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9746. sink.os << "test data";
  9747. return true;
  9748. },
  9749. "text/plain", progress_callback);
  9750. });
  9751. }
  9752. // Helper function for multipart upload progress tests
  9753. template <typename SetupHandler, typename ClientCall>
  9754. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9755. ClientCall &&client_call,
  9756. const string &endpoint) {
  9757. Server svr;
  9758. setup_handler(svr);
  9759. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9760. auto se = detail::scope_exit([&] {
  9761. svr.stop();
  9762. t.join();
  9763. });
  9764. svr.wait_until_ready();
  9765. Client cli(HOST, PORT);
  9766. vector<uint64_t> progress_values;
  9767. UploadFormDataItems items = {
  9768. {"field1", "value1", "", ""},
  9769. {"field2", "longer value for progress tracking test", "", ""},
  9770. {"file1", "file content data for upload progress", "test.txt",
  9771. "text/plain"}};
  9772. auto res = client_call(cli, endpoint, items,
  9773. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9774. progress_values.push_back(current);
  9775. return true;
  9776. });
  9777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9778. EXPECT_EQ(200, res->status);
  9779. EXPECT_FALSE(progress_values.empty());
  9780. }
  9781. TEST(UploadProgressTest, PostMultipartProgress) {
  9782. TestMultipartUploadProgress(
  9783. [](Server &svr) {
  9784. svr.Post("/multipart", [](const Request &req, Response &res) {
  9785. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9786. res.set_content("multipart received", "text/plain");
  9787. });
  9788. },
  9789. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9790. UploadProgress progress_callback) {
  9791. return cli.Post(endpoint, items, progress_callback);
  9792. },
  9793. "/multipart");
  9794. }
  9795. // Helper function for basic download progress tests
  9796. template <typename SetupHandler, typename ClientCall>
  9797. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9798. ClientCall &&client_call, const string &endpoint,
  9799. size_t expected_content_size) {
  9800. Server svr;
  9801. setup_handler(svr);
  9802. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9803. auto se = detail::scope_exit([&] {
  9804. svr.stop();
  9805. t.join();
  9806. });
  9807. svr.wait_until_ready();
  9808. Client cli(HOST, PORT);
  9809. vector<uint64_t> progress_values;
  9810. auto res = client_call(cli, endpoint,
  9811. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9812. progress_values.push_back(current);
  9813. return true;
  9814. });
  9815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9816. EXPECT_EQ(200, res->status);
  9817. EXPECT_FALSE(progress_values.empty());
  9818. EXPECT_EQ(expected_content_size, res->body.size());
  9819. }
  9820. TEST(DownloadProgressTest, GetBasic) {
  9821. TestBasicDownloadProgress(
  9822. [](Server &svr) {
  9823. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9824. string content(1000, 'D');
  9825. res.set_content(content, "text/plain");
  9826. });
  9827. },
  9828. [](Client &cli, const string &endpoint,
  9829. DownloadProgress progress_callback) {
  9830. return cli.Get(endpoint, progress_callback);
  9831. },
  9832. "/download", 1000u);
  9833. }
  9834. // Helper function for content receiver download progress tests
  9835. template <typename SetupHandler, typename ClientCall>
  9836. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9837. ClientCall &&client_call,
  9838. const string &endpoint,
  9839. size_t expected_content_size) {
  9840. Server svr;
  9841. setup_handler(svr);
  9842. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9843. auto se = detail::scope_exit([&] {
  9844. svr.stop();
  9845. t.join();
  9846. });
  9847. svr.wait_until_ready();
  9848. Client cli(HOST, PORT);
  9849. vector<uint64_t> progress_values;
  9850. string received_body;
  9851. auto res = client_call(
  9852. cli, endpoint,
  9853. [&](const char *data, size_t data_length) -> bool {
  9854. received_body.append(data, data_length);
  9855. return true;
  9856. },
  9857. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9858. progress_values.push_back(current);
  9859. return true;
  9860. });
  9861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9862. EXPECT_EQ(200, res->status);
  9863. EXPECT_FALSE(progress_values.empty());
  9864. EXPECT_EQ(expected_content_size, received_body.size());
  9865. EXPECT_TRUE(res->body.empty());
  9866. }
  9867. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9868. TestContentReceiverDownloadProgress(
  9869. [](Server &svr) {
  9870. svr.Get("/download-receiver",
  9871. [](const Request & /*req*/, Response &res) {
  9872. string content(2000, 'R');
  9873. res.set_content(content, "text/plain");
  9874. });
  9875. },
  9876. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9877. DownloadProgress progress_callback) {
  9878. return cli.Get(endpoint, content_receiver, progress_callback);
  9879. },
  9880. "/download-receiver", 2000u);
  9881. }
  9882. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9883. // A provider reaching a pass with nothing to hand over - an empty buffer
  9884. // popped off a queue, say - must not be taken to mean the body is finished.
  9885. // It used to end the loop with the terminating chunk unwritten while the
  9886. // server still considered the response complete, so the peer waited for an
  9887. // end that never arrived.
  9888. Server svr;
  9889. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9890. auto step = std::make_shared<int>(0);
  9891. res.set_chunked_content_provider("text/plain",
  9892. [step](size_t /*offset*/, DataSink &sink) {
  9893. switch ((*step)++) {
  9894. case 0: sink.write("", 0); break;
  9895. case 1: sink.write("hello", 5); break;
  9896. default: sink.done(); break;
  9897. }
  9898. return true;
  9899. });
  9900. });
  9901. auto port = svr.bind_to_any_port(HOST);
  9902. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9903. auto listen_se = detail::scope_exit([&] {
  9904. svr.stop();
  9905. listen_thread.join();
  9906. ASSERT_FALSE(svr.is_running());
  9907. });
  9908. svr.wait_until_ready();
  9909. Client cli(HOST, port);
  9910. // Without the fix the body is never terminated, so bound the wait rather
  9911. // than letting the test hang on the default read timeout.
  9912. cli.set_read_timeout(5, 0);
  9913. auto res = cli.Get("/stream");
  9914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9915. EXPECT_EQ(StatusCode::OK_200, res->status);
  9916. EXPECT_EQ("hello", res->body);
  9917. }
  9918. TEST(StreamingTest, NoContentLengthStreaming) {
  9919. Server svr;
  9920. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9921. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9922. if (offset < 6) {
  9923. sink.os << (offset < 3 ? "a" : "b");
  9924. } else {
  9925. sink.done();
  9926. }
  9927. return true;
  9928. });
  9929. });
  9930. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9931. auto listen_se = detail::scope_exit([&] {
  9932. svr.stop();
  9933. listen_thread.join();
  9934. ASSERT_FALSE(svr.is_running());
  9935. });
  9936. svr.wait_until_ready();
  9937. Client client(HOST, PORT);
  9938. auto get_thread = std::thread([&client]() {
  9939. std::string s;
  9940. auto res =
  9941. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9942. s += std::string(data, len);
  9943. return true;
  9944. });
  9945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9946. EXPECT_EQ(StatusCode::OK_200, res->status);
  9947. EXPECT_EQ("aaabbb", s);
  9948. });
  9949. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9950. // Give GET time to get a few messages.
  9951. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9952. }
  9953. TEST(MountTest, Unmount) {
  9954. Server svr;
  9955. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9956. auto se = detail::scope_exit([&] {
  9957. svr.stop();
  9958. listen_thread.join();
  9959. ASSERT_FALSE(svr.is_running());
  9960. });
  9961. svr.wait_until_ready();
  9962. Client cli("localhost", PORT);
  9963. svr.set_mount_point("/mount2", "./www2");
  9964. auto res = cli.Get("/");
  9965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9966. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9967. res = cli.Get("/mount2/dir/test.html");
  9968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9969. EXPECT_EQ(StatusCode::OK_200, res->status);
  9970. svr.set_mount_point("/", "./www");
  9971. res = cli.Get("/dir/");
  9972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9973. EXPECT_EQ(StatusCode::OK_200, res->status);
  9974. svr.remove_mount_point("/");
  9975. res = cli.Get("/dir/");
  9976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9978. svr.remove_mount_point("/mount2");
  9979. res = cli.Get("/mount2/dir/test.html");
  9980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9981. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9982. }
  9983. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  9984. Server svr;
  9985. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  9986. svr.Get("/api/hello", [](const Request &, Response &res) {
  9987. res.set_content("api", "text/plain");
  9988. });
  9989. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9990. auto se = detail::scope_exit([&] {
  9991. svr.stop();
  9992. listen_thread.join();
  9993. ASSERT_FALSE(svr.is_running());
  9994. });
  9995. svr.wait_until_ready();
  9996. Client cli(HOST, PORT);
  9997. auto res = cli.Get("/dir/test.html");
  9998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9999. EXPECT_EQ(StatusCode::OK_200, res->status);
  10000. res = cli.Get("/api/hello");
  10001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10002. EXPECT_EQ(StatusCode::OK_200, res->status);
  10003. EXPECT_EQ("api", res->body);
  10004. }
  10005. TEST(MountTest, PathSegmentBoundary) {
  10006. Server svr;
  10007. svr.set_mount_point("/mount2", "./www2");
  10008. svr.set_mount_point("/", "./www");
  10009. auto port = svr.bind_to_any_port(HOST);
  10010. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10011. auto se = detail::scope_exit([&] {
  10012. svr.stop();
  10013. listen_thread.join();
  10014. ASSERT_FALSE(svr.is_running());
  10015. });
  10016. svr.wait_until_ready();
  10017. Client cli(HOST, port);
  10018. auto res = cli.Get("/mount2/dir/test.html");
  10019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10020. EXPECT_EQ(StatusCode::OK_200, res->status);
  10021. // "/mount2" must not match part-way through a path segment.
  10022. res = cli.Get("/mount2dir/test.html");
  10023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10024. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10025. // A mount point ending in '/' keeps matching every path below it.
  10026. res = cli.Get("/dir/test.html");
  10027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10028. EXPECT_EQ(StatusCode::OK_200, res->status);
  10029. }
  10030. TEST(MountTest, Redicect) {
  10031. Server svr;
  10032. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10033. auto se = detail::scope_exit([&] {
  10034. svr.stop();
  10035. listen_thread.join();
  10036. ASSERT_FALSE(svr.is_running());
  10037. });
  10038. svr.set_mount_point("/", "./www");
  10039. svr.wait_until_ready();
  10040. Client cli("localhost", PORT);
  10041. auto res = cli.Get("/dir/");
  10042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10043. EXPECT_EQ(StatusCode::OK_200, res->status);
  10044. res = cli.Get("/dir");
  10045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10046. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10047. res = cli.Get("/file");
  10048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10049. EXPECT_EQ(StatusCode::OK_200, res->status);
  10050. res = cli.Get("/file/");
  10051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10052. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10053. cli.set_follow_location(true);
  10054. res = cli.Get("/dir");
  10055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10056. EXPECT_EQ(StatusCode::OK_200, res->status);
  10057. }
  10058. TEST(MountTest, MultibytesPathName) {
  10059. Server svr;
  10060. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10061. auto se = detail::scope_exit([&] {
  10062. svr.stop();
  10063. listen_thread.join();
  10064. ASSERT_FALSE(svr.is_running());
  10065. });
  10066. svr.set_mount_point("/", "./www");
  10067. svr.wait_until_ready();
  10068. Client cli("localhost", PORT);
  10069. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10071. EXPECT_EQ(StatusCode::OK_200, res->status);
  10072. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10073. }
  10074. #ifdef _WIN32
  10075. // Issue #2435: mmap::open() must succeed even when another handle holds
  10076. // the file open for writing (e.g. an active log file).
  10077. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10078. const char *path = "mmap_concurrent_writer_test.txt";
  10079. const char *content = "hello";
  10080. {
  10081. std::ofstream f(path, std::ios::binary);
  10082. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10083. }
  10084. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10085. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10086. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10087. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10088. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10089. detail::mmap m(path);
  10090. ASSERT_TRUE(m.is_open());
  10091. EXPECT_EQ(strlen(content), m.size());
  10092. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  10093. }
  10094. #endif
  10095. #ifndef _WIN32
  10096. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  10097. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  10098. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  10099. TEST(MmapTest, FailedMappingIsNotOpen) {
  10100. const char *path = "./mmap_failed_mapping_test_dir";
  10101. ASSERT_EQ(0, ::mkdir(path, 0755));
  10102. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10103. detail::mmap m(path);
  10104. EXPECT_FALSE(m.is_open());
  10105. EXPECT_EQ(0U, m.size());
  10106. EXPECT_NE(static_cast<const void *>(m.data()),
  10107. static_cast<const void *>(MAP_FAILED));
  10108. }
  10109. #endif
  10110. TEST(KeepAliveTest, ReadTimeout) {
  10111. Server svr;
  10112. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10113. std::this_thread::sleep_for(std::chrono::seconds(2));
  10114. res.set_content("a", "text/plain");
  10115. });
  10116. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10117. res.set_content("b", "text/plain");
  10118. });
  10119. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10120. auto se = detail::scope_exit([&] {
  10121. svr.stop();
  10122. listen_thread.join();
  10123. ASSERT_FALSE(svr.is_running());
  10124. });
  10125. svr.wait_until_ready();
  10126. Client cli("localhost", PORT);
  10127. cli.set_keep_alive(true);
  10128. cli.set_read_timeout(std::chrono::seconds(1));
  10129. auto resa = cli.Get("/a");
  10130. ASSERT_FALSE(resa);
  10131. EXPECT_EQ(Error::Read, resa.error());
  10132. auto resb = cli.Get("/b");
  10133. ASSERT_TRUE(resb);
  10134. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10135. EXPECT_EQ("b", resb->body);
  10136. }
  10137. TEST(KeepAliveTest, MaxCount) {
  10138. size_t keep_alive_max_count = 3;
  10139. Server svr;
  10140. svr.set_keep_alive_max_count(keep_alive_max_count);
  10141. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10142. res.set_content("Hello World!", "text/plain");
  10143. });
  10144. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10145. auto se = detail::scope_exit([&] {
  10146. svr.stop();
  10147. listen_thread.join();
  10148. ASSERT_FALSE(svr.is_running());
  10149. });
  10150. svr.wait_until_ready();
  10151. Client cli(HOST, PORT);
  10152. cli.set_keep_alive(true);
  10153. for (size_t i = 0; i < 5; i++) {
  10154. auto result = cli.Get("/hi");
  10155. ASSERT_TRUE(result);
  10156. EXPECT_EQ(StatusCode::OK_200, result->status);
  10157. if (i == keep_alive_max_count - 1) {
  10158. EXPECT_EQ("close", result->get_header_value("Connection"));
  10159. } else {
  10160. EXPECT_FALSE(result->has_header("Connection"));
  10161. }
  10162. }
  10163. }
  10164. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10165. // can pull the next one into the server's buffer. The server must serve it
  10166. // without waiting for the socket to become readable again. The keep-alive
  10167. // timeout outlasts the client's read timeout, so a request left waiting for it
  10168. // shows up as a missing response.
  10169. static void serve_pipelining_routes(Server &svr,
  10170. const std::function<void(int)> &client) {
  10171. svr.set_keep_alive_timeout(5);
  10172. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10173. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10174. });
  10175. svr.Post("/echo", [](const Request &req, Response &res) {
  10176. res.set_content("echo " + req.body, "text/plain");
  10177. });
  10178. auto port = svr.bind_to_any_port(HOST);
  10179. thread t = thread([&] { svr.listen_after_bind(); });
  10180. auto se = detail::scope_exit([&] {
  10181. svr.stop();
  10182. t.join();
  10183. });
  10184. svr.wait_until_ready();
  10185. client(port);
  10186. }
  10187. static std::string
  10188. send_pipelined_requests(const std::vector<std::string> &parts) {
  10189. Server svr;
  10190. std::string res;
  10191. serve_pipelining_routes(svr, [&](int port) {
  10192. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10193. });
  10194. return res;
  10195. }
  10196. static void expect_in_order(const std::string &res,
  10197. const std::vector<std::string> &bodies) {
  10198. size_t pos = 0;
  10199. for (const auto &body : bodies) {
  10200. pos = res.find(body, pos);
  10201. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10202. pos += body.size();
  10203. }
  10204. }
  10205. TEST(KeepAliveTest, PipelinedRequests) {
  10206. auto res = send_pipelined_requests(
  10207. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10208. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10209. "Content-Length: 4\r\n\r\nbody"
  10210. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10211. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10212. }
  10213. // The second request starts in the server's buffer and ends on the socket.
  10214. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10215. auto res =
  10216. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10217. "GET /hi/2 HTTP/1.1\r\nHo",
  10218. "st: localhost\r\nConnection: close\r\n\r\n"});
  10219. expect_in_order(res, {"hi 1", "hi 2"});
  10220. }
  10221. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10222. // CRLF after a body does not turn into a 400 for the next request.
  10223. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10224. auto res = send_pipelined_requests(
  10225. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10226. "Content-Length: 4\r\n\r\nbody\r\n"
  10227. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10228. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10229. expect_in_order(res, {"echo body", "hi 2"});
  10230. }
  10231. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10232. // must not be served as the next request.
  10233. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10234. auto res = send_pipelined_requests(
  10235. {"INVALID REQUEST LINE\r\n\r\n"
  10236. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10237. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10238. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10239. }
  10240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10241. // Over TLS, the next request is held by the TLS library as already decrypted
  10242. // data rather than on the socket.
  10243. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10244. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10245. std::string res;
  10246. serve_pipelining_routes(svr, [&](int port) {
  10247. auto error = Error::Success;
  10248. auto sock = detail::create_client_socket(
  10249. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10250. /*connection_timeout_sec=*/5, 0,
  10251. /*read_timeout_sec=*/2, 0,
  10252. /*write_timeout_sec=*/5, 0, std::string(), error);
  10253. ASSERT_NE(INVALID_SOCKET, sock);
  10254. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10255. auto ctx = SSL_CTX_new(TLS_client_method());
  10256. auto ssl = SSL_new(ctx);
  10257. auto ssl_se = detail::scope_exit([&] {
  10258. SSL_free(ssl);
  10259. SSL_CTX_free(ctx);
  10260. });
  10261. SSL_set_fd(ssl, static_cast<int>(sock));
  10262. ASSERT_EQ(1, SSL_connect(ssl));
  10263. // One write, so all three requests arrive in one TLS record
  10264. const std::string req =
  10265. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10266. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10267. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10268. ASSERT_EQ(static_cast<int>(req.size()),
  10269. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10270. char buf[512];
  10271. int n;
  10272. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10273. res.append(buf, static_cast<size_t>(n));
  10274. }
  10275. });
  10276. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10277. }
  10278. #endif
  10279. TEST(KeepAliveTest, Issue1041) {
  10280. Server svr;
  10281. svr.set_keep_alive_timeout(3);
  10282. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10283. res.set_content("Hello World!", "text/plain");
  10284. });
  10285. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10286. auto se = detail::scope_exit([&] {
  10287. svr.stop();
  10288. listen_thread.join();
  10289. ASSERT_FALSE(svr.is_running());
  10290. });
  10291. svr.wait_until_ready();
  10292. Client cli(HOST, PORT);
  10293. cli.set_keep_alive(true);
  10294. auto result = cli.Get("/hi");
  10295. ASSERT_TRUE(result);
  10296. EXPECT_EQ(StatusCode::OK_200, result->status);
  10297. std::this_thread::sleep_for(std::chrono::seconds(5));
  10298. result = cli.Get("/hi");
  10299. ASSERT_TRUE(result);
  10300. EXPECT_EQ(StatusCode::OK_200, result->status);
  10301. }
  10302. TEST(KeepAliveTest, Issue1959) {
  10303. Server svr;
  10304. svr.set_keep_alive_timeout(5);
  10305. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10306. res.set_content("a", "text/plain");
  10307. });
  10308. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10309. auto se = detail::scope_exit([&] {
  10310. if (!svr.is_running()) return;
  10311. svr.stop();
  10312. listen_thread.join();
  10313. ASSERT_FALSE(svr.is_running());
  10314. });
  10315. svr.wait_until_ready();
  10316. Client cli("localhost", PORT);
  10317. cli.set_keep_alive(true);
  10318. using namespace std::chrono;
  10319. auto start = steady_clock::now();
  10320. cli.Get("/a");
  10321. svr.stop();
  10322. listen_thread.join();
  10323. auto end = steady_clock::now();
  10324. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10325. EXPECT_LT(elapsed, 5000);
  10326. }
  10327. #ifdef CPPHTTPLIB_SSL_ENABLED
  10328. TEST(KeepAliveTest, SSLClientReconnection) {
  10329. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10330. ASSERT_TRUE(svr.is_valid());
  10331. svr.set_keep_alive_timeout(1);
  10332. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10333. res.set_content("Hello World!", "text/plain");
  10334. });
  10335. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10336. auto se = detail::scope_exit([&] {
  10337. svr.stop();
  10338. listen_thread.join();
  10339. ASSERT_FALSE(svr.is_running());
  10340. });
  10341. svr.wait_until_ready();
  10342. SSLClient cli(HOST, PORT);
  10343. cli.enable_server_certificate_verification(false);
  10344. cli.set_keep_alive(true);
  10345. auto result = cli.Get("/hi");
  10346. ASSERT_TRUE(result);
  10347. EXPECT_EQ(StatusCode::OK_200, result->status);
  10348. result = cli.Get("/hi");
  10349. ASSERT_TRUE(result);
  10350. EXPECT_EQ(StatusCode::OK_200, result->status);
  10351. std::this_thread::sleep_for(std::chrono::seconds(2));
  10352. // Recoonect
  10353. result = cli.Get("/hi");
  10354. ASSERT_TRUE(result);
  10355. EXPECT_EQ(StatusCode::OK_200, result->status);
  10356. result = cli.Get("/hi");
  10357. ASSERT_TRUE(result);
  10358. EXPECT_EQ(StatusCode::OK_200, result->status);
  10359. }
  10360. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10362. ASSERT_TRUE(svr.is_valid());
  10363. svr.set_keep_alive_timeout(1);
  10364. std::string content = "reconnect";
  10365. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10366. res.set_content("Hello World!", "text/plain");
  10367. });
  10368. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10369. auto se = detail::scope_exit([&] {
  10370. svr.stop();
  10371. listen_thread.join();
  10372. ASSERT_FALSE(svr.is_running());
  10373. });
  10374. svr.wait_until_ready();
  10375. SSLClient cli(HOST, PORT);
  10376. cli.enable_server_certificate_verification(false);
  10377. cli.set_keep_alive(true);
  10378. auto result = cli.Post(
  10379. "/hi", content.size(),
  10380. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10381. sink.write(content.c_str(), content.size());
  10382. return true;
  10383. },
  10384. "text/plain");
  10385. ASSERT_TRUE(result);
  10386. EXPECT_EQ(200, result->status);
  10387. std::this_thread::sleep_for(std::chrono::seconds(2));
  10388. // Recoonect
  10389. result = cli.Post(
  10390. "/hi", content.size(),
  10391. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10392. sink.write(content.c_str(), content.size());
  10393. return true;
  10394. },
  10395. "text/plain");
  10396. ASSERT_TRUE(result);
  10397. EXPECT_EQ(200, result->status);
  10398. result = cli.Post(
  10399. "/hi", content.size(),
  10400. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10401. sink.write(content.c_str(), content.size());
  10402. return true;
  10403. },
  10404. "text/plain");
  10405. ASSERT_TRUE(result);
  10406. EXPECT_EQ(200, result->status);
  10407. }
  10408. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10409. using namespace httplib::tls;
  10410. {
  10411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10412. ASSERT_TRUE(svr.is_valid());
  10413. svr.Get("/sni", [&](const Request &req, Response &res) {
  10414. std::string expected = req.sni();
  10415. EXPECT_EQ(expected, req.get_param_value("expected"));
  10416. res.set_content("ok", "text/plain");
  10417. });
  10418. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10419. auto se = detail::scope_exit([&] {
  10420. svr.stop();
  10421. listen_thread.join();
  10422. ASSERT_FALSE(svr.is_running());
  10423. });
  10424. svr.wait_until_ready();
  10425. {
  10426. SSLClient cli("localhost", PORT);
  10427. cli.enable_server_certificate_verification(false);
  10428. auto res = cli.Get("/sni?expected=localhost");
  10429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10430. }
  10431. {
  10432. SSLClient cli("::1", PORT);
  10433. cli.enable_server_certificate_verification(false);
  10434. auto res = cli.Get("/sni?expected=");
  10435. // NOTE: This may fail if the server is listening on IPv4 only
  10436. // (e.g., when localhost resolves to 127.0.0.1 only)
  10437. if (res) {
  10438. EXPECT_EQ(StatusCode::OK_200, res->status);
  10439. } else {
  10440. EXPECT_EQ(Error::Connection, res.error());
  10441. }
  10442. }
  10443. }
  10444. }
  10445. #endif
  10446. TEST(ClientProblemDetectionTest, ContentProvider) {
  10447. Server svr;
  10448. size_t content_length = 1024 * 1024;
  10449. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10450. res.set_content_provider(
  10451. content_length, "text/plain",
  10452. [&](size_t offset, size_t length, DataSink &sink) {
  10453. auto out_len = std::min(length, static_cast<size_t>(1024));
  10454. std::string out(out_len, '@');
  10455. sink.write(out.data(), out_len);
  10456. return offset < 4096;
  10457. },
  10458. [](bool success) { ASSERT_FALSE(success); });
  10459. });
  10460. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10461. res.set_content_provider(
  10462. 0, "text/plain",
  10463. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10464. EXPECT_TRUE(false);
  10465. return true;
  10466. },
  10467. [](bool success) { ASSERT_FALSE(success); });
  10468. });
  10469. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10470. auto se = detail::scope_exit([&] {
  10471. svr.stop();
  10472. listen_thread.join();
  10473. ASSERT_FALSE(svr.is_running());
  10474. });
  10475. svr.wait_until_ready();
  10476. Client cli("localhost", PORT);
  10477. {
  10478. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10479. size_t /*data_length*/) { return false; });
  10480. ASSERT_FALSE(res);
  10481. }
  10482. {
  10483. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10484. size_t /*data_length*/) { return false; });
  10485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10486. }
  10487. }
  10488. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10489. // A provider that reports success without writing anything and without
  10490. // calling done() used to be handed the same offset and length again on every
  10491. // pass, so it spun for as long as the peer stayed connected.
  10492. Server svr;
  10493. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10494. res.set_content("ok", "text/plain");
  10495. });
  10496. auto port = svr.bind_to_any_port(HOST);
  10497. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10498. auto se = detail::scope_exit([&] {
  10499. svr.stop();
  10500. listen_thread.join();
  10501. ASSERT_FALSE(svr.is_running());
  10502. });
  10503. svr.wait_until_ready();
  10504. std::atomic<int> call_count{0};
  10505. Client cli(HOST, port);
  10506. auto res = cli.Post(
  10507. "/", 1024,
  10508. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10509. // Give up after enough passes to show the spin, so that losing the
  10510. // check below fails this test instead of hanging it.
  10511. return ++call_count < 100;
  10512. },
  10513. "text/plain");
  10514. ASSERT_FALSE(res);
  10515. EXPECT_EQ(Error::Write, res.error());
  10516. EXPECT_EQ(1, call_count.load());
  10517. }
  10518. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10519. // A writer only has to assign `write`. The other three used to be left as
  10520. // empty std::functions, so a provider calling one threw
  10521. // std::bad_function_call out of the thread running it and took the whole
  10522. // process down.
  10523. DataSink sink;
  10524. std::string written;
  10525. sink.write = [&](const char *data, size_t data_len) {
  10526. written.append(data, data_len);
  10527. return true;
  10528. };
  10529. EXPECT_TRUE(sink.is_writable());
  10530. sink.done();
  10531. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10532. EXPECT_TRUE(written.empty());
  10533. }
  10534. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10535. // A sink that cannot carry trailers still has to finish.
  10536. DataSink sink;
  10537. auto done_count = 0;
  10538. sink.done = [&]() { done_count++; };
  10539. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10540. EXPECT_EQ(1, done_count);
  10541. }
  10542. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10543. Server svr;
  10544. const std::string body(4096, 'x');
  10545. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10546. res.set_content_provider(body.size(), "text/plain",
  10547. [&](size_t offset, size_t length, DataSink &sink) {
  10548. sink.write(body.data() + offset, length);
  10549. sink.done();
  10550. return true;
  10551. });
  10552. });
  10553. auto port = svr.bind_to_any_port(HOST);
  10554. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10555. auto se = detail::scope_exit([&] {
  10556. svr.stop();
  10557. listen_thread.join();
  10558. ASSERT_FALSE(svr.is_running());
  10559. });
  10560. svr.wait_until_ready();
  10561. Client cli(HOST, port);
  10562. auto res = cli.Get("/");
  10563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10564. EXPECT_EQ(StatusCode::OK_200, res->status);
  10565. EXPECT_EQ(body, res->body);
  10566. }
  10567. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10568. Server svr;
  10569. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10570. res.set_content_provider(
  10571. 1024, "text/plain",
  10572. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10573. sink.write("hello", 5);
  10574. sink.done(); // short of the 1024 bytes the response promised
  10575. return true;
  10576. });
  10577. });
  10578. auto port = svr.bind_to_any_port(HOST);
  10579. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10580. auto se = detail::scope_exit([&] {
  10581. svr.stop();
  10582. listen_thread.join();
  10583. ASSERT_FALSE(svr.is_running());
  10584. });
  10585. svr.wait_until_ready();
  10586. Client cli(HOST, port);
  10587. cli.set_read_timeout(5, 0);
  10588. // The response is short of its Content-Length, so the client cannot read a
  10589. // complete body. What matters is that this returns at all: a no-op done()
  10590. // would leave the writer looping over a provider that never makes progress.
  10591. auto res = cli.Get("/");
  10592. EXPECT_FALSE(res);
  10593. }
  10594. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10595. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10596. // The compressed path builds the whole body before connecting, so this
  10597. // fails client-side and never reaches a server.
  10598. Client cli(HOST, PORT);
  10599. cli.set_compress(true);
  10600. auto res = cli.Post(
  10601. "/", 1024,
  10602. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10603. sink.write("hello", 5);
  10604. sink.done(); // short of the 1024 bytes the request announced
  10605. return true;
  10606. },
  10607. "text/plain");
  10608. ASSERT_FALSE(res);
  10609. EXPECT_EQ(Error::Write, res.error());
  10610. }
  10611. #endif
  10612. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10613. Server svr;
  10614. svr.set_error_handler([](Request const &, Response &res) -> void {
  10615. res.set_chunked_content_provider(
  10616. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10617. sink.os << "hello";
  10618. sink.os << "world";
  10619. sink.done();
  10620. return true;
  10621. });
  10622. });
  10623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10624. auto se = detail::scope_exit([&] {
  10625. svr.stop();
  10626. listen_thread.join();
  10627. ASSERT_FALSE(svr.is_running());
  10628. });
  10629. svr.wait_until_ready();
  10630. Client cli("localhost", PORT);
  10631. auto res = cli.Get("/");
  10632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10634. EXPECT_EQ("helloworld", res->body);
  10635. }
  10636. // A body set after a content provider must replace it, not be sent through it.
  10637. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10638. Server svr;
  10639. svr.set_mount_point("/", "./www");
  10640. svr.set_file_request_handler([](const Request &req, Response &res) {
  10641. if (req.path == "/dir/test.html") {
  10642. res.status = StatusCode::Forbidden_403;
  10643. res.set_content(std::string(5000, 'D'), "text/plain");
  10644. } else if (req.path == "/file") {
  10645. res.status = StatusCode::Forbidden_403;
  10646. res.body = "Denied";
  10647. }
  10648. });
  10649. auto port = svr.bind_to_any_port(HOST);
  10650. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10651. auto se = detail::scope_exit([&] {
  10652. svr.stop();
  10653. t.join();
  10654. ASSERT_FALSE(svr.is_running());
  10655. });
  10656. svr.wait_until_ready();
  10657. Client cli(HOST, port);
  10658. {
  10659. auto res = cli.Get("/dir/test.html");
  10660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10661. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10662. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10663. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10664. }
  10665. {
  10666. auto res = cli.Get("/file");
  10667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10668. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10669. EXPECT_EQ("Denied", res->body);
  10670. }
  10671. {
  10672. auto res = cli.Get("/dir/index.html");
  10673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10674. EXPECT_EQ(StatusCode::OK_200, res->status);
  10675. EXPECT_EQ(0U, res->body.find("<html>"));
  10676. }
  10677. }
  10678. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10679. Server svr;
  10680. std::vector<bool> released;
  10681. std::mutex released_mutex;
  10682. auto releaser = [&](bool success) {
  10683. std::lock_guard<std::mutex> guard(released_mutex);
  10684. released.push_back(success);
  10685. };
  10686. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10687. return sink.write(&"hello"[offset], length);
  10688. };
  10689. svr.Get("/sized", [&](const Request &, Response &res) {
  10690. res.status = StatusCode::NotFound_404;
  10691. res.set_content_provider(5, "text/plain", provider, releaser);
  10692. });
  10693. svr.Get("/chunked", [&](const Request &, Response &res) {
  10694. res.status = StatusCode::ServiceUnavailable_503;
  10695. res.set_chunked_content_provider(
  10696. "text/plain",
  10697. [](size_t, DataSink &sink) {
  10698. sink.os << "chunk";
  10699. sink.done();
  10700. return true;
  10701. },
  10702. releaser);
  10703. });
  10704. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10705. res.set_content_provider(5, "text/plain", provider, releaser);
  10706. throw std::runtime_error("after the provider");
  10707. });
  10708. svr.set_error_handler([](const Request &req, Response &res) {
  10709. // Leave the exception handler's content to it.
  10710. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10711. res.set_content(std::string(1000, 'E'), "text/html");
  10712. return Server::HandlerResponse::Handled;
  10713. });
  10714. svr.set_exception_handler(
  10715. [](const Request &, Response &res, std::exception_ptr) {
  10716. res.status = StatusCode::InternalServerError_500;
  10717. res.set_content(std::string(1000, 'X'), "text/html");
  10718. });
  10719. auto port = svr.bind_to_any_port(HOST);
  10720. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10721. auto se = detail::scope_exit([&] {
  10722. svr.stop();
  10723. t.join();
  10724. ASSERT_FALSE(svr.is_running());
  10725. });
  10726. svr.wait_until_ready();
  10727. Client cli(HOST, port);
  10728. {
  10729. auto res = cli.Get("/sized");
  10730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10731. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10732. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10733. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10734. }
  10735. {
  10736. auto res = cli.Get("/chunked");
  10737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10738. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10739. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10740. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10741. }
  10742. {
  10743. auto res = cli.Get("/throw");
  10744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10745. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10746. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10747. }
  10748. std::lock_guard<std::mutex> guard(released_mutex);
  10749. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10750. }
  10751. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10752. Server svr;
  10753. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10754. return sink.write(&"abc"[offset], length);
  10755. };
  10756. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10757. res.set_file_content("./www/dir/test.html");
  10758. res.set_content("body", "text/plain");
  10759. });
  10760. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10761. res.set_content(std::string(100, 'B'), "text/plain");
  10762. res.set_file_content("./www/dir/test.html");
  10763. });
  10764. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10765. res.set_content(std::string(100, 'B'), "text/plain");
  10766. res.set_content_provider(3, "text/plain", abc);
  10767. });
  10768. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10769. res.set_content_provider(3, "text/plain", abc);
  10770. res.set_content(std::string(100, 'B'), "text/plain");
  10771. });
  10772. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10773. res.set_content_provider(3, "text/plain", abc);
  10774. res.body = "direct";
  10775. });
  10776. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10777. res.set_file_content("./www/dir/test.html");
  10778. res.body = "direct";
  10779. });
  10780. auto port = svr.bind_to_any_port(HOST);
  10781. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10782. auto se = detail::scope_exit([&] {
  10783. svr.stop();
  10784. t.join();
  10785. ASSERT_FALSE(svr.is_running());
  10786. });
  10787. svr.wait_until_ready();
  10788. Client cli(HOST, port);
  10789. auto expect_body = [&](const char *path, const std::string &body) {
  10790. // Uncompressed, so Content-Length can be compared with the body.
  10791. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10792. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10793. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10794. EXPECT_EQ(body, res->body) << path;
  10795. EXPECT_EQ(std::to_string(body.size()),
  10796. res->get_header_value("Content-Length"))
  10797. << path;
  10798. };
  10799. expect_body("/file-then-body", "body");
  10800. expect_body("/body-then-file", "test.html");
  10801. expect_body("/body-then-provider", "abc");
  10802. expect_body("/provider-then-body", std::string(100, 'B'));
  10803. expect_body("/provider-then-direct-body", "direct");
  10804. expect_body("/file-then-direct-body", "direct");
  10805. // Ranges are checked against the body, not the dropped provider.
  10806. {
  10807. auto res = cli.Get("/provider-then-direct-body",
  10808. Headers{{make_range_header({{1, 2}})}});
  10809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10810. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10811. EXPECT_EQ("ir", res->body);
  10812. }
  10813. {
  10814. auto res = cli.Get("/file-then-direct-body",
  10815. Headers{{make_range_header({{7, 8}})}});
  10816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10817. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10818. }
  10819. }
  10820. // Forward declaration (see the base64_encode note).
  10821. namespace httplib {
  10822. namespace detail {
  10823. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10824. const std::string &content_type,
  10825. EncodingType encoding);
  10826. } // namespace detail
  10827. } // namespace httplib
  10828. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10829. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10830. ASSERT_TRUE(mm->is_open());
  10831. Response res;
  10832. detail::set_file_content_provider(res, mm, "text/html",
  10833. detail::EncodingType::None);
  10834. std::string out;
  10835. DataSink sink;
  10836. sink.write = [&](const char *d, size_t l) {
  10837. out.append(d, l);
  10838. return true;
  10839. };
  10840. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10841. EXPECT_EQ("test.html", out);
  10842. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10843. EXPECT_EQ("test.html", out);
  10844. }
  10845. TEST(LongPollingTest, ClientCloseDetection) {
  10846. Server svr;
  10847. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10848. res.set_chunked_content_provider(
  10849. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10850. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10851. sink.os << "hello";
  10852. auto count = 10;
  10853. while (count > 0 && sink.is_writable()) {
  10854. this_thread::sleep_for(chrono::milliseconds(10));
  10855. count--;
  10856. }
  10857. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10858. return true;
  10859. });
  10860. });
  10861. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10862. auto se = detail::scope_exit([&] {
  10863. svr.stop();
  10864. listen_thread.join();
  10865. ASSERT_FALSE(svr.is_running());
  10866. });
  10867. svr.wait_until_ready();
  10868. Client cli("localhost", PORT);
  10869. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10870. EXPECT_EQ("hello", string(data, data_length));
  10871. return false; // close the socket immediately.
  10872. });
  10873. ASSERT_FALSE(res);
  10874. }
  10875. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10876. Server svr;
  10877. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10878. res.set_chunked_content_provider(
  10879. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10880. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10881. sink.os << "hello";
  10882. EXPECT_TRUE(sink.os.good());
  10883. // Wait for the client to close the connection
  10884. auto count = 10;
  10885. while (count > 0 && sink.is_writable()) {
  10886. this_thread::sleep_for(chrono::milliseconds(10));
  10887. count--;
  10888. }
  10889. // After client disconnect, write repeatedly until the socket
  10890. // write actually fails (small writes may be absorbed by the
  10891. // kernel buffer)
  10892. std::string chunk(1024, 'x');
  10893. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10894. sink.os << chunk;
  10895. }
  10896. EXPECT_TRUE(sink.os.fail());
  10897. return true;
  10898. });
  10899. });
  10900. auto port = svr.bind_to_any_port("localhost");
  10901. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10902. auto se = detail::scope_exit([&] {
  10903. svr.stop();
  10904. listen_thread.join();
  10905. ASSERT_FALSE(svr.is_running());
  10906. });
  10907. svr.wait_until_ready();
  10908. Client cli("localhost", port);
  10909. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10910. EXPECT_EQ("hello", string(data, data_length));
  10911. return false; // close the socket immediately.
  10912. });
  10913. ASSERT_FALSE(res);
  10914. }
  10915. TEST(GetWithParametersTest, GetWithParameters) {
  10916. Server svr;
  10917. svr.Get("/", [&](const Request &req, Response &) {
  10918. EXPECT_EQ("world", req.get_param_value("hello"));
  10919. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10920. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10921. });
  10922. svr.Get("/params", [&](const Request &req, Response &) {
  10923. EXPECT_EQ("world", req.get_param_value("hello"));
  10924. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10925. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10926. });
  10927. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10928. EXPECT_EQ("resource-id", req.matches[1]);
  10929. EXPECT_EQ("foo", req.get_param_value("param1"));
  10930. EXPECT_EQ("bar", req.get_param_value("param2"));
  10931. });
  10932. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10933. EXPECT_EQ("user-id", req.path_params.at("id"));
  10934. EXPECT_EQ("foo", req.get_param_value("param1"));
  10935. EXPECT_EQ("bar", req.get_param_value("param2"));
  10936. });
  10937. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10938. auto se = detail::scope_exit([&] {
  10939. svr.stop();
  10940. listen_thread.join();
  10941. ASSERT_FALSE(svr.is_running());
  10942. });
  10943. svr.wait_until_ready();
  10944. {
  10945. Client cli(HOST, PORT);
  10946. Params params;
  10947. params.emplace("hello", "world");
  10948. params.emplace("hello2", "world2");
  10949. params.emplace("hello3", "world3");
  10950. auto res = cli.Get("/", params, Headers{});
  10951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10952. EXPECT_EQ(StatusCode::OK_200, res->status);
  10953. }
  10954. {
  10955. Client cli(HOST, PORT);
  10956. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10958. EXPECT_EQ(StatusCode::OK_200, res->status);
  10959. }
  10960. {
  10961. Client cli(HOST, PORT);
  10962. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10964. EXPECT_EQ(StatusCode::OK_200, res->status);
  10965. }
  10966. {
  10967. Client cli(HOST, PORT);
  10968. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10970. EXPECT_EQ(StatusCode::OK_200, res->status);
  10971. }
  10972. }
  10973. TEST(GetWithParametersTest, GetWithParameters2) {
  10974. Server svr;
  10975. svr.Get("/", [&](const Request &req, Response &res) {
  10976. auto text = req.get_param_value("hello");
  10977. res.set_content(text, "text/plain");
  10978. });
  10979. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10980. auto se = detail::scope_exit([&] {
  10981. svr.stop();
  10982. listen_thread.join();
  10983. ASSERT_FALSE(svr.is_running());
  10984. });
  10985. svr.wait_until_ready();
  10986. Client cli("localhost", PORT);
  10987. Params params;
  10988. params.emplace("hello", "world");
  10989. std::string body;
  10990. auto res = cli.Get("/", params, Headers{},
  10991. [&](const char *data, size_t data_length) {
  10992. body.append(data, data_length);
  10993. return true;
  10994. });
  10995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10996. EXPECT_EQ(StatusCode::OK_200, res->status);
  10997. EXPECT_EQ("world", body);
  10998. }
  10999. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11000. Server svr;
  11001. svr.Get("/search", [&](const Request &req, Response &res) {
  11002. auto q = req.get_param_value("q");
  11003. res.set_content(q, "text/plain");
  11004. });
  11005. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11006. auto se = detail::scope_exit([&] {
  11007. svr.stop();
  11008. listen_thread.join();
  11009. ASSERT_FALSE(svr.is_running());
  11010. });
  11011. svr.wait_until_ready();
  11012. Client cli("localhost", PORT);
  11013. // Verify that Get(path, params) works without requiring Headers argument
  11014. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11016. EXPECT_EQ(StatusCode::OK_200, res->status);
  11017. EXPECT_EQ("cpp-httplib", res->body);
  11018. }
  11019. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11020. auto host = "httpbingo.org";
  11021. auto path = std::string{"/range/32"};
  11022. #ifdef CPPHTTPLIB_SSL_ENABLED
  11023. SSLClient cli(host);
  11024. #else
  11025. Client cli(host);
  11026. #endif
  11027. cli.set_default_headers({make_range_header({{1, 10}})});
  11028. cli.set_connection_timeout(5);
  11029. {
  11030. auto res = cli.Get(path);
  11031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11032. EXPECT_EQ("bcdefghijk", res->body);
  11033. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11034. }
  11035. {
  11036. auto res = cli.Get(path);
  11037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11038. EXPECT_EQ("bcdefghijk", res->body);
  11039. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11040. }
  11041. }
  11042. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11043. Server svr;
  11044. svr.set_default_headers({{"Hello", "World"}});
  11045. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11046. res.set_content("ok", "text/plain");
  11047. });
  11048. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11049. auto se = detail::scope_exit([&] {
  11050. svr.stop();
  11051. listen_thread.join();
  11052. ASSERT_FALSE(svr.is_running());
  11053. });
  11054. svr.wait_until_ready();
  11055. Client cli("localhost", PORT);
  11056. auto res = cli.Get("/");
  11057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11058. EXPECT_EQ(StatusCode::OK_200, res->status);
  11059. EXPECT_EQ("ok", res->body);
  11060. EXPECT_EQ("World", res->get_header_value("Hello"));
  11061. }
  11062. #ifdef CPPHTTPLIB_SSL_ENABLED
  11063. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11064. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11065. ASSERT_TRUE(svr.is_valid());
  11066. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11067. std::this_thread::sleep_for(std::chrono::seconds(2));
  11068. res.set_content("a", "text/plain");
  11069. });
  11070. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11071. res.set_content("b", "text/plain");
  11072. });
  11073. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11074. auto se = detail::scope_exit([&] {
  11075. svr.stop();
  11076. listen_thread.join();
  11077. ASSERT_FALSE(svr.is_running());
  11078. });
  11079. svr.wait_until_ready();
  11080. SSLClient cli("localhost", PORT);
  11081. cli.enable_server_certificate_verification(false);
  11082. cli.set_keep_alive(true);
  11083. cli.set_read_timeout(std::chrono::seconds(1));
  11084. auto resa = cli.Get("/a");
  11085. ASSERT_TRUE(!resa);
  11086. EXPECT_EQ(Error::Read, resa.error());
  11087. auto resb = cli.Get("/b");
  11088. ASSERT_TRUE(resb);
  11089. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11090. EXPECT_EQ("b", resb->body);
  11091. }
  11092. // Closing an idle keep-alive connection sends close_notify and returns. The
  11093. // server must not wait for the client's close_notify: an idle client never
  11094. // sends one, so the worker would be held until the read timeout expires, and
  11095. // stop() would wait for it.
  11096. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11098. ASSERT_TRUE(svr.is_valid());
  11099. svr.set_keep_alive_timeout(1);
  11100. svr.set_read_timeout(10, 0);
  11101. svr.Get("/", [](const Request &, Response &res) {
  11102. res.set_content("ok", "text/plain");
  11103. });
  11104. auto port = svr.bind_to_any_port(HOST);
  11105. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11106. auto se = detail::scope_exit([&] {
  11107. if (listen_thread.joinable()) {
  11108. svr.stop();
  11109. listen_thread.join();
  11110. }
  11111. });
  11112. svr.wait_until_ready();
  11113. SSLClient cli(HOST, port);
  11114. cli.enable_server_certificate_verification(false);
  11115. cli.set_keep_alive(true);
  11116. auto res = cli.Get("/");
  11117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11118. EXPECT_EQ(StatusCode::OK_200, res->status);
  11119. // Stay idle past the keep-alive timeout so the server closes the connection.
  11120. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11121. auto start = std::chrono::steady_clock::now();
  11122. svr.stop();
  11123. listen_thread.join();
  11124. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11125. std::chrono::steady_clock::now() - start)
  11126. .count();
  11127. EXPECT_LT(elapsed, 3000);
  11128. }
  11129. #endif
  11130. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11131. protected:
  11132. ServerTestWithAI_PASSIVE()
  11133. : cli_(HOST, PORT)
  11134. #ifdef CPPHTTPLIB_SSL_ENABLED
  11135. ,
  11136. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11137. #endif
  11138. {
  11139. #ifdef CPPHTTPLIB_SSL_ENABLED
  11140. cli_.enable_server_certificate_verification(false);
  11141. #endif
  11142. }
  11143. virtual void SetUp() {
  11144. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11145. res.set_content("Hello World!", "text/plain");
  11146. });
  11147. t_ = thread(
  11148. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11149. svr_.wait_until_ready();
  11150. }
  11151. virtual void TearDown() {
  11152. svr_.stop();
  11153. t_.join();
  11154. }
  11155. #ifdef CPPHTTPLIB_SSL_ENABLED
  11156. SSLClient cli_;
  11157. SSLServer svr_;
  11158. #else
  11159. Client cli_;
  11160. Server svr_;
  11161. #endif
  11162. thread t_;
  11163. };
  11164. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11165. auto res = cli_.Get("/hi");
  11166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11167. EXPECT_EQ(StatusCode::OK_200, res->status);
  11168. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11169. EXPECT_EQ("Hello World!", res->body);
  11170. }
  11171. class ServerUpDownTest : public ::testing::Test {
  11172. protected:
  11173. ServerUpDownTest() : cli_(HOST, PORT) {}
  11174. virtual void SetUp() {
  11175. t_ = thread([&]() {
  11176. svr_.bind_to_any_port(HOST);
  11177. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11178. ASSERT_TRUE(svr_.listen_after_bind());
  11179. });
  11180. svr_.wait_until_ready();
  11181. }
  11182. virtual void TearDown() {
  11183. svr_.stop();
  11184. t_.join();
  11185. }
  11186. Client cli_;
  11187. Server svr_;
  11188. thread t_;
  11189. };
  11190. TEST_F(ServerUpDownTest, QuickStartStop) {
  11191. // Should not crash, especially when run with
  11192. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11193. }
  11194. class PayloadMaxLengthTest : public ::testing::Test {
  11195. protected:
  11196. PayloadMaxLengthTest()
  11197. : cli_(HOST, PORT)
  11198. #ifdef CPPHTTPLIB_SSL_ENABLED
  11199. ,
  11200. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11201. #endif
  11202. {
  11203. #ifdef CPPHTTPLIB_SSL_ENABLED
  11204. cli_.enable_server_certificate_verification(false);
  11205. #endif
  11206. }
  11207. virtual void SetUp() {
  11208. svr_.set_payload_max_length(8);
  11209. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11210. res.set_content("test", "text/plain");
  11211. });
  11212. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11213. svr_.wait_until_ready();
  11214. }
  11215. virtual void TearDown() {
  11216. svr_.stop();
  11217. t_.join();
  11218. }
  11219. #ifdef CPPHTTPLIB_SSL_ENABLED
  11220. SSLClient cli_;
  11221. SSLServer svr_;
  11222. #else
  11223. Client cli_;
  11224. Server svr_;
  11225. #endif
  11226. thread t_;
  11227. };
  11228. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11229. auto res = cli_.Post("/test", "123456789", "text/plain");
  11230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11231. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11232. res = cli_.Post("/test", "12345678", "text/plain");
  11233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11234. EXPECT_EQ(StatusCode::OK_200, res->status);
  11235. }
  11236. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11237. // Test chunked encoding with payload exceeding the 8-byte limit
  11238. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11239. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11241. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11242. }
  11243. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11244. // Test chunked encoding with payload within the 8-byte limit
  11245. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11246. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11248. EXPECT_EQ(StatusCode::OK_200, res->status);
  11249. }
  11250. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11251. // Test using send_request to send chunked data exceeding payload limit
  11252. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11253. "Host: " +
  11254. std::string(HOST) + ":" + std::to_string(PORT) +
  11255. "\r\n"
  11256. "Transfer-Encoding: chunked\r\n"
  11257. "Connection: close\r\n"
  11258. "\r\n"
  11259. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11260. "0123456789\r\n"
  11261. "0\r\n" // End chunk
  11262. "\r\n";
  11263. std::string response;
  11264. bool result = send_request(1, chunked_request, &response);
  11265. if (!result) {
  11266. // If send_request fails, it might be because the server closed the
  11267. // connection due to payload limit enforcement, which is acceptable
  11268. SUCCEED()
  11269. << "Server rejected oversized chunked request (connection closed)";
  11270. } else {
  11271. // If we got a response, check if it's an error response or connection was
  11272. // closed early Short response length indicates connection was closed due to
  11273. // payload limit
  11274. if (response.length() <= 10) {
  11275. SUCCEED() << "Server closed connection for oversized chunked request";
  11276. } else {
  11277. // Check for error status codes
  11278. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11279. response.find("Payload Too Large") != std::string::npos ||
  11280. response.find("400") != std::string::npos);
  11281. }
  11282. }
  11283. }
  11284. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11285. // Test request without Content-Length header exceeding payload limit
  11286. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11287. "Host: " +
  11288. std::string(HOST) + ":" +
  11289. std::to_string(PORT) +
  11290. "\r\n"
  11291. "Connection: close\r\n"
  11292. "\r\n";
  11293. // Add payload exceeding the 8-byte limit
  11294. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11295. request_without_content_length += large_payload;
  11296. std::string response;
  11297. bool result = send_request(1, request_without_content_length, &response);
  11298. if (!result) {
  11299. // If send_request fails, server likely closed connection due to payload
  11300. // limit
  11301. SUCCEED() << "Server rejected oversized request without Content-Length "
  11302. "(connection closed)";
  11303. } else {
  11304. // Check if server responded with error or closed connection early
  11305. if (response.length() <= 10) {
  11306. SUCCEED() << "Server closed connection for oversized request without "
  11307. "Content-Length";
  11308. } else {
  11309. // Check for error status codes
  11310. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11311. response.find("Payload Too Large") != std::string::npos ||
  11312. response.find("400") != std::string::npos);
  11313. }
  11314. }
  11315. }
  11316. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11317. // Test request without Content-Length header within payload limit
  11318. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11319. "Host: " +
  11320. std::string(HOST) + ":" +
  11321. std::to_string(PORT) +
  11322. "\r\n"
  11323. "Connection: close\r\n"
  11324. "\r\n";
  11325. // Add payload within the 8-byte limit
  11326. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11327. request_without_content_length += small_payload;
  11328. std::string response;
  11329. bool result = send_request(1, request_without_content_length, &response);
  11330. // For requests without Content-Length, the server may have different behavior
  11331. // The key is that it should not reject due to payload limit for small
  11332. // payloads
  11333. if (result) {
  11334. // Check for any HTTP response (success or error, but not connection closed)
  11335. if (response.length() > 10) {
  11336. SUCCEED()
  11337. << "Server processed request without Content-Length within limit";
  11338. } else {
  11339. // Short response might indicate connection closed, which is acceptable
  11340. SUCCEED() << "Server closed connection for request without "
  11341. "Content-Length (acceptable behavior)";
  11342. }
  11343. } else {
  11344. // Connection failure might be due to protocol requirements
  11345. SUCCEED() << "Connection issue with request without Content-Length "
  11346. "(environment-specific)";
  11347. }
  11348. }
  11349. class LargePayloadMaxLengthTest : public ::testing::Test {
  11350. protected:
  11351. LargePayloadMaxLengthTest()
  11352. : cli_(HOST, PORT)
  11353. #ifdef CPPHTTPLIB_SSL_ENABLED
  11354. ,
  11355. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11356. #endif
  11357. {
  11358. #ifdef CPPHTTPLIB_SSL_ENABLED
  11359. cli_.enable_server_certificate_verification(false);
  11360. #endif
  11361. }
  11362. virtual void SetUp() {
  11363. // Set 10MB payload limit
  11364. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11365. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11366. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11367. res.set_content("Large payload test", "text/plain");
  11368. });
  11369. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11370. svr_.wait_until_ready();
  11371. }
  11372. virtual void TearDown() {
  11373. svr_.stop();
  11374. t_.join();
  11375. }
  11376. #ifdef CPPHTTPLIB_SSL_ENABLED
  11377. SSLClient cli_;
  11378. SSLServer svr_;
  11379. #else
  11380. Client cli_;
  11381. Server svr_;
  11382. #endif
  11383. thread t_;
  11384. };
  11385. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11386. // Test chunked encoding with payload within 10MB limit
  11387. std::string medium_payload(5 * 1024 * 1024,
  11388. 'A'); // 5MB payload, within 10MB limit
  11389. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11391. EXPECT_EQ(StatusCode::OK_200, res->status);
  11392. }
  11393. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11394. // Test chunked encoding with payload exceeding 10MB limit
  11395. std::string large_payload(12 * 1024 * 1024,
  11396. 'B'); // 12MB payload, exceeds 10MB limit
  11397. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11398. // Server may either return 413 or close the connection
  11399. if (res) {
  11400. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11401. } else {
  11402. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11403. }
  11404. }
  11405. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11406. // Test request without Content-Length header within 10MB limit
  11407. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11408. "Host: " +
  11409. std::string(HOST) + ":" +
  11410. std::to_string(PORT) +
  11411. "\r\n"
  11412. "Connection: close\r\n"
  11413. "\r\n";
  11414. // Add 1MB payload (within 10MB limit)
  11415. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11416. request_without_content_length += medium_payload;
  11417. std::string response;
  11418. bool result = send_request(5, request_without_content_length, &response);
  11419. if (result) {
  11420. // Should get a proper HTTP response for payloads within limit
  11421. if (response.length() > 10) {
  11422. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11423. "10MB limit";
  11424. } else {
  11425. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11426. "Content-Length)";
  11427. }
  11428. } else {
  11429. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11430. }
  11431. }
  11432. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11433. // Test request without Content-Length header exceeding 10MB limit
  11434. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11435. "Host: " +
  11436. std::string(HOST) + ":" +
  11437. std::to_string(PORT) +
  11438. "\r\n"
  11439. "Connection: close\r\n"
  11440. "\r\n";
  11441. // Add 12MB payload (exceeds 10MB limit)
  11442. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11443. request_without_content_length += large_payload;
  11444. std::string response;
  11445. bool result = send_request(10, request_without_content_length, &response);
  11446. if (!result) {
  11447. // Server should close connection due to payload limit
  11448. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11449. "(connection closed)";
  11450. } else {
  11451. // Check for error response
  11452. if (response.length() <= 10) {
  11453. SUCCEED()
  11454. << "Server closed connection for 12MB request exceeding 10MB limit";
  11455. } else {
  11456. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11457. response.find("Payload Too Large") != std::string::npos ||
  11458. response.find("400") != std::string::npos);
  11459. }
  11460. }
  11461. }
  11462. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11463. Server svr;
  11464. svr.Get("/", [](const Request &, Response &res) {
  11465. // Claims far more than it sends, then drops the connection.
  11466. res.set_content_provider(size_t(1) << 41, "text/plain",
  11467. [](size_t, size_t, DataSink &sink) {
  11468. sink.write("abc", 3);
  11469. return false;
  11470. });
  11471. });
  11472. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11473. auto se = detail::scope_exit([&] {
  11474. svr.stop();
  11475. thread.join();
  11476. ASSERT_FALSE(svr.is_running());
  11477. });
  11478. svr.wait_until_ready();
  11479. Client cli(HOST, PORT);
  11480. cli.set_payload_max_length(0);
  11481. EXPECT_FALSE(cli.Get("/"));
  11482. }
  11483. // Accepts one connection on 127.0.0.1:port, reads the request head and sends
  11484. // back the given bytes, which httplib::Server could not be made to send.
  11485. static void serve_raw_once(int port, const std::string &response) {
  11486. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11487. default_socket_options(srv);
  11488. sockaddr_in addr{};
  11489. addr.sin_family = AF_INET;
  11490. addr.sin_port = htons(static_cast<uint16_t>(port));
  11491. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11492. int opt = 1;
  11493. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11494. #ifdef _WIN32
  11495. reinterpret_cast<const char *>(&opt),
  11496. #else
  11497. &opt,
  11498. #endif
  11499. sizeof(opt));
  11500. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11501. ::listen(srv, 1);
  11502. auto cli = ::accept(srv, nullptr, nullptr);
  11503. if (cli != INVALID_SOCKET) {
  11504. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11505. std::string head;
  11506. char c;
  11507. while (head.find("\r\n\r\n") == std::string::npos &&
  11508. ::recv(cli, &c, 1, 0) == 1) {
  11509. head += c;
  11510. }
  11511. ::send(cli, response.data(), static_cast<int>(response.size()), 0);
  11512. detail::close_socket(cli);
  11513. }
  11514. detail::close_socket(srv);
  11515. }
  11516. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  11517. const char *responses[] = {
  11518. "HTTP/1.1 103 Early Hints\r\n"
  11519. "Link: </style.css>; rel=preload\r\n"
  11520. "\r\n"
  11521. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11522. "HTTP/1.1 100 Continue\r\n"
  11523. "X-Note: interim\r\n"
  11524. "\r\n"
  11525. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11526. };
  11527. for (auto response : responses) {
  11528. std::thread t([&]() { serve_raw_once(PORT, response); });
  11529. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11530. Client cli("127.0.0.1", PORT);
  11531. auto res = cli.Get("/");
  11532. t.join();
  11533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11534. EXPECT_EQ(StatusCode::OK_200, res->status);
  11535. EXPECT_EQ("ok", res->body);
  11536. }
  11537. }
  11538. #ifdef CPPHTTPLIB_SSL_ENABLED
  11539. TEST(ProxyConnectTest, OnlyARefusalIsPassedOn) {
  11540. // Anything but 200 or a refusal would read as the origin's own response.
  11541. {
  11542. std::thread t([] {
  11543. serve_raw_once(PORT, "HTTP/1.1 201 Created\r\n"
  11544. "Set-Cookie: session=from-proxy\r\n"
  11545. "Content-Length: 0\r\n\r\n");
  11546. });
  11547. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11548. SSLClient cli("example.com", 443);
  11549. cli.set_proxy("127.0.0.1", PORT);
  11550. auto res = cli.Get("/");
  11551. t.join();
  11552. EXPECT_FALSE(res);
  11553. EXPECT_EQ(Error::ProxyConnection, res.error());
  11554. }
  11555. {
  11556. std::thread t([] {
  11557. serve_raw_once(PORT, "HTTP/1.1 407 Proxy Authentication Required\r\n"
  11558. "Content-Length: 0\r\n\r\n");
  11559. });
  11560. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11561. SSLClient cli("example.com", 443);
  11562. cli.set_proxy("127.0.0.1", PORT);
  11563. auto res = cli.Get("/");
  11564. t.join();
  11565. ASSERT_TRUE(res);
  11566. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  11567. }
  11568. }
  11569. #endif
  11570. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  11571. std::atomic<bool> closed_by_client{false};
  11572. auto server_thread = std::thread([&] {
  11573. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11574. default_socket_options(srv);
  11575. sockaddr_in addr{};
  11576. addr.sin_family = AF_INET;
  11577. addr.sin_port = htons(static_cast<uint16_t>(PORT));
  11578. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11579. int opt = 1;
  11580. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11581. #ifdef _WIN32
  11582. reinterpret_cast<const char *>(&opt),
  11583. #else
  11584. &opt,
  11585. #endif
  11586. sizeof(opt));
  11587. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11588. ::listen(srv, 1);
  11589. auto cli = ::accept(srv, nullptr, nullptr);
  11590. if (cli != INVALID_SOCKET) {
  11591. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11592. // Answer the head without asking for the body, and keep the connection.
  11593. std::string head;
  11594. char c;
  11595. while (head.find("\r\n\r\n") == std::string::npos &&
  11596. ::recv(cli, &c, 1, 0) == 1) {
  11597. head += c;
  11598. }
  11599. std::string res =
  11600. "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n";
  11601. ::send(cli, res.data(), static_cast<int>(res.size()), 0);
  11602. // Bytes here would be read as the body the first request declared.
  11603. char buf[256];
  11604. closed_by_client = ::recv(cli, buf, sizeof(buf), 0) == 0;
  11605. detail::close_socket(cli);
  11606. }
  11607. detail::close_socket(srv);
  11608. });
  11609. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11610. Client cli("127.0.0.1", PORT);
  11611. cli.set_keep_alive(true);
  11612. cli.set_read_timeout(1, 0);
  11613. // Long enough for the client to send Expect: 100-continue.
  11614. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  11615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11616. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  11617. cli.Get("/second");
  11618. server_thread.join();
  11619. EXPECT_TRUE(closed_by_client);
  11620. }
  11621. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11622. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11623. // path.
  11624. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11625. Server svr;
  11626. const size_t LIMIT = 64 * 1024; // 64KB
  11627. svr.set_payload_max_length(LIMIT);
  11628. size_t total = 0;
  11629. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11630. const ContentReader &content_reader) {
  11631. content_reader([&](const char * /*data*/, size_t len) {
  11632. total += len;
  11633. return true;
  11634. });
  11635. res.status = 200;
  11636. res.set_content("stream_ok", "text/plain");
  11637. });
  11638. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11639. auto se = detail::scope_exit([&] {
  11640. svr.stop();
  11641. thread.join();
  11642. ASSERT_FALSE(svr.is_running());
  11643. });
  11644. svr.wait_until_ready();
  11645. // Prepare 256KB raw data and gzip-compress it
  11646. std::string raw(256 * 1024, 'A');
  11647. std::string gz;
  11648. {
  11649. z_stream zs{};
  11650. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11651. Z_DEFAULT_STRATEGY);
  11652. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11653. zs.avail_in = static_cast<uInt>(raw.size());
  11654. char outbuf[4096];
  11655. int ret;
  11656. do {
  11657. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11658. zs.avail_out = sizeof(outbuf);
  11659. ret = deflate(&zs, Z_FINISH);
  11660. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11661. } while (ret != Z_STREAM_END);
  11662. deflateEnd(&zs);
  11663. }
  11664. Client cli(HOST, PORT);
  11665. cli.set_connection_timeout(std::chrono::seconds(5));
  11666. Headers headers = {{"Content-Encoding", "gzip"}};
  11667. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11668. "application/octet-stream");
  11669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11670. // Server must reject oversized decompressed payloads with 413.
  11671. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11672. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11673. EXPECT_LE(total, LIMIT);
  11674. }
  11675. #ifndef CPPHTTPLIB_SSL_ENABLED
  11676. // For a request with neither Content-Length nor Transfer-Encoding, the
  11677. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11678. // compressed wire bytes straight to the ContentReader without ever routing
  11679. // them through the decompressor, so payload_max_length_ only bounded the
  11680. // compressed size on the wire, not the decompressed size.
  11681. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11682. Server svr;
  11683. const size_t LIMIT = 64 * 1024; // 64KB
  11684. svr.set_payload_max_length(LIMIT);
  11685. size_t total = 0;
  11686. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11687. const ContentReader &content_reader) {
  11688. content_reader([&](const char * /*data*/, size_t len) {
  11689. total += len;
  11690. return true;
  11691. });
  11692. res.status = 200;
  11693. res.set_content("stream_ok", "text/plain");
  11694. });
  11695. auto port = svr.bind_to_any_port(HOST);
  11696. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11697. auto se = detail::scope_exit([&] {
  11698. svr.stop();
  11699. thread.join();
  11700. ASSERT_FALSE(svr.is_running());
  11701. });
  11702. svr.wait_until_ready();
  11703. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11704. // StreamingGzipDecompression test above.
  11705. std::string raw(256 * 1024, 'A');
  11706. std::string gz;
  11707. {
  11708. httplib::detail::gzip_compressor compressor;
  11709. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11710. [&](const char *chunk, size_t len) {
  11711. gz.append(chunk, len);
  11712. return true;
  11713. });
  11714. ASSERT_TRUE(result);
  11715. }
  11716. // Send the gzip body over raw TCP with neither Content-Length nor
  11717. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11718. // kicks in.
  11719. std::string req = "POST /stream HTTP/1.1\r\n"
  11720. "Host: " +
  11721. std::string(HOST) + ":" + std::to_string(port) +
  11722. "\r\n"
  11723. "Content-Encoding: gzip\r\n"
  11724. "Connection: close\r\n"
  11725. "\r\n" +
  11726. gz;
  11727. std::string response;
  11728. ASSERT_TRUE(send_request(5, req, &response, port));
  11729. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11730. EXPECT_LE(total, LIMIT);
  11731. }
  11732. #endif
  11733. #endif
  11734. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11735. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11736. // the payload must be passed through untouched instead of being rejected.
  11737. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11738. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11739. Server svr;
  11740. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11741. res.set_content(body, "image/jpeg");
  11742. res.set_header("Content-Encoding", "UTF-8");
  11743. });
  11744. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11745. res.set_content(body, "image/jpeg");
  11746. res.set_header("Content-Encoding", "identity");
  11747. });
  11748. svr.Post("/echo", [](const Request &req, Response &res) {
  11749. res.set_content(req.body, "image/jpeg");
  11750. });
  11751. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11752. auto se = detail::scope_exit([&] {
  11753. svr.stop();
  11754. t.join();
  11755. ASSERT_FALSE(svr.is_running());
  11756. });
  11757. svr.wait_until_ready();
  11758. Client cli(HOST, PORT);
  11759. {
  11760. auto res = cli.Get("/image");
  11761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11762. EXPECT_EQ(StatusCode::OK_200, res->status);
  11763. EXPECT_EQ(body, res->body);
  11764. }
  11765. {
  11766. auto res = cli.Get("/identity");
  11767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11768. EXPECT_EQ(StatusCode::OK_200, res->status);
  11769. EXPECT_EQ(body, res->body);
  11770. }
  11771. {
  11772. // The same applies to a request body reaching the server.
  11773. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11774. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11776. EXPECT_EQ(StatusCode::OK_200, res->status);
  11777. EXPECT_EQ(body, res->body);
  11778. }
  11779. }
  11780. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11781. // gzip-encoded response even when the build has no zlib support.
  11782. static const char GZIPPED_HELLO_WORLD[] = {
  11783. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11784. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11785. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11786. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11787. // A content coding is a whole token, not something the field value merely
  11788. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11789. // as "fibre" look like Brotli, and turned a multi-coding value like
  11790. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11791. // it was never meant to see.
  11792. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11793. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11794. Server svr;
  11795. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11796. res.set_content(body, "image/jpeg");
  11797. res.set_header("Content-Encoding", "fibre");
  11798. });
  11799. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11800. res.set_content(body, "image/jpeg");
  11801. res.set_header("Content-Encoding", "gzip, br");
  11802. });
  11803. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11804. res.set_content(body, "image/jpeg");
  11805. res.set_header("Content-Encoding", "x-zstd-ish");
  11806. });
  11807. auto port = svr.bind_to_any_port(HOST);
  11808. thread t = thread([&]() { svr.listen_after_bind(); });
  11809. auto se = detail::scope_exit([&] {
  11810. svr.stop();
  11811. t.join();
  11812. ASSERT_FALSE(svr.is_running());
  11813. });
  11814. svr.wait_until_ready();
  11815. Client cli(HOST, port);
  11816. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11817. auto res = cli.Get(path);
  11818. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11819. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11820. // Not a coding we recognize, so the payload comes back untouched
  11821. EXPECT_EQ(body, res->body) << path;
  11822. }
  11823. }
  11824. // A content coding cpp-httplib recognizes but was not built with must be
  11825. // reported as such. Handing the still-compressed payload back to the caller
  11826. // would silently corrupt it.
  11827. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11828. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11829. Server svr;
  11830. // "image/jpeg" keeps the server from applying a content coding of its own,
  11831. // so the hand-crafted Content-Encoding below survives.
  11832. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11833. res.set_content(gzipped, "image/jpeg");
  11834. res.set_header("Content-Encoding", "gzip");
  11835. });
  11836. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11837. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11838. res.set_content(gzipped, "image/jpeg");
  11839. res.set_header("Content-Encoding", "GZIP");
  11840. });
  11841. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11842. auto se = detail::scope_exit([&] {
  11843. svr.stop();
  11844. t.join();
  11845. ASSERT_FALSE(svr.is_running());
  11846. });
  11847. svr.wait_until_ready();
  11848. Client cli(HOST, PORT);
  11849. {
  11850. auto res = cli.Get("/gzipped");
  11851. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11853. EXPECT_EQ("Hello World!", res->body);
  11854. #else
  11855. ASSERT_FALSE(res);
  11856. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11857. #endif
  11858. }
  11859. {
  11860. // open_stream() must behave the same way.
  11861. auto handle = cli.open_stream("GET", "/gzipped");
  11862. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11863. ASSERT_TRUE(handle.is_valid());
  11864. std::string received;
  11865. char buf[256];
  11866. ssize_t n;
  11867. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11868. received.append(buf, static_cast<size_t>(n));
  11869. }
  11870. EXPECT_EQ("Hello World!", received);
  11871. #else
  11872. EXPECT_FALSE(handle.is_valid());
  11873. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11874. #endif
  11875. }
  11876. {
  11877. // A differently-cased coding must not be mistaken for an unknown one, or
  11878. // the body would be handed back still compressed.
  11879. auto res = cli.Get("/gzipped-uppercase");
  11880. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11882. EXPECT_EQ("Hello World!", res->body);
  11883. #else
  11884. ASSERT_FALSE(res);
  11885. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11886. #endif
  11887. }
  11888. }
  11889. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11890. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11891. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11892. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11893. // body a second time and appending a second Content-Encoding field line, so
  11894. // clients that decode one coding per listed value handed back raw gzip bytes.
  11895. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11896. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11897. Server svr;
  11898. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11899. // keeps the server from applying a coding of its own.
  11900. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11901. res.set_content(gzipped, "text/plain");
  11902. res.set_header("Content-Encoding", "gzip");
  11903. });
  11904. auto port = svr.bind_to_any_port(HOST);
  11905. thread t = thread([&]() { svr.listen_after_bind(); });
  11906. auto se = detail::scope_exit([&] {
  11907. svr.stop();
  11908. t.join();
  11909. ASSERT_FALSE(svr.is_running());
  11910. });
  11911. svr.wait_until_ready();
  11912. Client cli(HOST, port);
  11913. Headers headers = {{"Accept-Encoding", "gzip"}};
  11914. auto res = cli.Get("/pre-gzipped", headers);
  11915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11916. EXPECT_EQ(StatusCode::OK_200, res->status);
  11917. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11918. EXPECT_EQ("Hello World!", res->body);
  11919. }
  11920. // A chunked provider settles its coding where the headers are written and
  11921. // reuses it at write time. Both ends of that have to hold: a handler's own
  11922. // Content-Encoding suppresses the coding, and a response without one is still
  11923. // compressed as it always was.
  11924. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11925. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11926. const std::string plain = "Hello World! Hello World! Hello World!";
  11927. Server svr;
  11928. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11929. res.set_header("Content-Encoding", "gzip");
  11930. res.set_chunked_content_provider(
  11931. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11932. sink.write(gzipped.data(), gzipped.size());
  11933. sink.done();
  11934. return true;
  11935. });
  11936. });
  11937. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11938. res.set_chunked_content_provider(
  11939. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11940. sink.write(plain.data(), plain.size());
  11941. sink.done();
  11942. return true;
  11943. });
  11944. });
  11945. auto port = svr.bind_to_any_port(HOST);
  11946. thread t = thread([&]() { svr.listen_after_bind(); });
  11947. auto se = detail::scope_exit([&] {
  11948. svr.stop();
  11949. t.join();
  11950. ASSERT_FALSE(svr.is_running());
  11951. });
  11952. svr.wait_until_ready();
  11953. Client cli(HOST, port);
  11954. Headers headers = {{"Accept-Encoding", "gzip"}};
  11955. {
  11956. auto res = cli.Get("/pre-gzipped", headers);
  11957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11958. EXPECT_EQ(StatusCode::OK_200, res->status);
  11959. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11960. EXPECT_EQ("Hello World!", res->body);
  11961. }
  11962. {
  11963. auto res = cli.Get("/negotiated", headers);
  11964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11965. EXPECT_EQ(StatusCode::OK_200, res->status);
  11966. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11967. EXPECT_EQ(plain, res->body);
  11968. }
  11969. }
  11970. #endif
  11971. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11972. // the same message as the comma-joined one, so both have to be read the same
  11973. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11974. // single gzip coding, and a body the sender says was encoded twice was handed
  11975. // back after one pass, still compressed but presented as decoded.
  11976. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11977. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11978. Server svr;
  11979. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11980. res.set_content(body, "image/jpeg");
  11981. res.headers.emplace("Content-Encoding", "gzip");
  11982. res.headers.emplace("Content-Encoding", "gzip");
  11983. });
  11984. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11985. res.set_content(body, "image/jpeg");
  11986. res.set_header("Content-Encoding", "gzip, gzip");
  11987. });
  11988. auto port = svr.bind_to_any_port(HOST);
  11989. thread t = thread([&]() { svr.listen_after_bind(); });
  11990. auto se = detail::scope_exit([&] {
  11991. svr.stop();
  11992. t.join();
  11993. ASSERT_FALSE(svr.is_running());
  11994. });
  11995. svr.wait_until_ready();
  11996. Client cli(HOST, port);
  11997. // Two codings is not something cpp-httplib decodes, so both representations
  11998. // take the pass-through path rather than one of them being gunzipped once.
  11999. for (const char *path : {"/split", "/joined"}) {
  12000. auto res = cli.Get(path);
  12001. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12002. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12003. EXPECT_EQ(body, res->body) << path;
  12004. }
  12005. }
  12006. // Regression test for DoS vulnerability: a malicious server sending a response
  12007. // without Content-Length header must not cause unbounded memory consumption on
  12008. // the client side. The client should stop reading after a reasonable limit,
  12009. // similar to the server-side set_payload_max_length protection.
  12010. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12011. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12012. #ifndef _WIN32
  12013. signal(SIGPIPE, SIG_IGN);
  12014. #endif
  12015. auto server_thread = std::thread([] {
  12016. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12017. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12018. default_socket_options(srv);
  12019. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12020. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12021. sockaddr_in addr{};
  12022. addr.sin_family = AF_INET;
  12023. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12024. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12025. int opt = 1;
  12026. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12027. #ifdef _WIN32
  12028. reinterpret_cast<const char *>(&opt),
  12029. #else
  12030. &opt,
  12031. #endif
  12032. sizeof(opt));
  12033. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12034. ::listen(srv, 1);
  12035. sockaddr_in cli_addr{};
  12036. socklen_t cli_len = sizeof(cli_addr);
  12037. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12038. if (cli != INVALID_SOCKET) {
  12039. char buf[4096];
  12040. ::recv(cli, buf, sizeof(buf), 0);
  12041. // Malicious response: no Content-Length, no chunked encoding
  12042. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12043. "Connection: close\r\n"
  12044. "\r\n";
  12045. ::send(cli,
  12046. #ifdef _WIN32
  12047. static_cast<const char *>(response_header.c_str()),
  12048. static_cast<int>(response_header.size()),
  12049. #else
  12050. response_header.c_str(), response_header.size(),
  12051. #endif
  12052. 0);
  12053. // Send 10MB of data
  12054. std::string chunk(64 * 1024, 'A');
  12055. size_t total_sent = 0;
  12056. while (total_sent < MALICIOUS_DATA_SIZE) {
  12057. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12058. auto sent = ::send(cli,
  12059. #ifdef _WIN32
  12060. static_cast<const char *>(chunk.c_str()),
  12061. static_cast<int>(to_send),
  12062. #else
  12063. chunk.c_str(), to_send,
  12064. #endif
  12065. 0);
  12066. if (sent <= 0) break;
  12067. total_sent += static_cast<size_t>(sent);
  12068. }
  12069. detail::close_socket(cli);
  12070. }
  12071. detail::close_socket(srv);
  12072. });
  12073. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12074. size_t total_read = 0;
  12075. {
  12076. Client cli("127.0.0.1", PORT + 2);
  12077. cli.set_read_timeout(5, 0);
  12078. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12079. auto stream = cli.open_stream("GET", "/malicious");
  12080. ASSERT_TRUE(stream.is_valid());
  12081. char buffer[64 * 1024];
  12082. ssize_t n;
  12083. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12084. total_read += static_cast<size_t>(n);
  12085. }
  12086. } // StreamHandle and Client destroyed here, closing the socket
  12087. server_thread.join();
  12088. // With set_payload_max_length, the client must stop reading before consuming
  12089. // all 10MB. The read loop should be cut off at or near the configured limit.
  12090. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12091. << "Client read " << total_read << " bytes, exceeding the configured "
  12092. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12093. }
  12094. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12095. // the entire response body without truncation.
  12096. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12097. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12098. #ifndef _WIN32
  12099. signal(SIGPIPE, SIG_IGN);
  12100. #endif
  12101. auto server_thread = std::thread([] {
  12102. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12103. default_socket_options(srv);
  12104. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12105. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12106. sockaddr_in addr{};
  12107. addr.sin_family = AF_INET;
  12108. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12109. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12110. int opt = 1;
  12111. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12112. #ifdef _WIN32
  12113. reinterpret_cast<const char *>(&opt),
  12114. #else
  12115. &opt,
  12116. #endif
  12117. sizeof(opt));
  12118. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12119. ::listen(srv, 1);
  12120. sockaddr_in cli_addr{};
  12121. socklen_t cli_len = sizeof(cli_addr);
  12122. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12123. if (cli != INVALID_SOCKET) {
  12124. char buf[4096];
  12125. ::recv(cli, buf, sizeof(buf), 0);
  12126. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12127. "Connection: close\r\n"
  12128. "\r\n";
  12129. ::send(cli,
  12130. #ifdef _WIN32
  12131. static_cast<const char *>(response_header.c_str()),
  12132. static_cast<int>(response_header.size()),
  12133. #else
  12134. response_header.c_str(), response_header.size(),
  12135. #endif
  12136. 0);
  12137. std::string chunk(64 * 1024, 'A');
  12138. size_t total_sent = 0;
  12139. while (total_sent < DATA_SIZE) {
  12140. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12141. auto sent = ::send(cli,
  12142. #ifdef _WIN32
  12143. static_cast<const char *>(chunk.c_str()),
  12144. static_cast<int>(to_send),
  12145. #else
  12146. chunk.c_str(), to_send,
  12147. #endif
  12148. 0);
  12149. if (sent <= 0) break;
  12150. total_sent += static_cast<size_t>(sent);
  12151. }
  12152. #ifdef _WIN32
  12153. ::shutdown(cli, SD_SEND);
  12154. #else
  12155. ::shutdown(cli, SHUT_WR);
  12156. #endif
  12157. // Drain until the client closes its end, ensuring all data is delivered
  12158. char drain[1024];
  12159. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12160. detail::close_socket(cli);
  12161. }
  12162. detail::close_socket(srv);
  12163. });
  12164. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12165. size_t total_read = 0;
  12166. {
  12167. Client cli("127.0.0.1", PORT + 2);
  12168. cli.set_read_timeout(5, 0);
  12169. cli.set_payload_max_length(0); // 0 means no limit
  12170. auto stream = cli.open_stream("GET", "/data");
  12171. ASSERT_TRUE(stream.is_valid());
  12172. char buffer[64 * 1024];
  12173. ssize_t n;
  12174. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12175. total_read += static_cast<size_t>(n);
  12176. }
  12177. }
  12178. server_thread.join();
  12179. EXPECT_EQ(total_read, DATA_SIZE)
  12180. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12181. << " bytes without truncation, but only read " << total_read << " bytes.";
  12182. }
  12183. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12184. // enormous Content-Length must not cause the client to pre-allocate a huge
  12185. // response body buffer. The reservation is capped at payload_max_length_, and
  12186. // the read itself fails when the body exceeds the limit.
  12187. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12188. #ifndef _WIN32
  12189. signal(SIGPIPE, SIG_IGN);
  12190. #endif
  12191. auto server_thread = std::thread([] {
  12192. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12193. default_socket_options(srv);
  12194. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12195. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12196. sockaddr_in addr{};
  12197. addr.sin_family = AF_INET;
  12198. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12199. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12200. int opt = 1;
  12201. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12202. #ifdef _WIN32
  12203. reinterpret_cast<const char *>(&opt),
  12204. #else
  12205. &opt,
  12206. #endif
  12207. sizeof(opt));
  12208. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12209. ::listen(srv, 1);
  12210. sockaddr_in cli_addr{};
  12211. socklen_t cli_len = sizeof(cli_addr);
  12212. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12213. if (cli != INVALID_SOCKET) {
  12214. char buf[4096];
  12215. ::recv(cli, buf, sizeof(buf), 0);
  12216. // Malicious response: claim a 20GB body but send only a tiny payload.
  12217. std::string response = "HTTP/1.1 200 OK\r\n"
  12218. "Content-Length: 20000000000\r\n"
  12219. "\r\n"
  12220. "abc";
  12221. ::send(cli,
  12222. #ifdef _WIN32
  12223. static_cast<const char *>(response.c_str()),
  12224. static_cast<int>(response.size()),
  12225. #else
  12226. response.c_str(), response.size(),
  12227. #endif
  12228. 0);
  12229. detail::close_socket(cli);
  12230. }
  12231. detail::close_socket(srv);
  12232. });
  12233. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12234. {
  12235. Client cli("127.0.0.1", PORT + 2);
  12236. cli.set_read_timeout(5, 0);
  12237. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12238. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12239. // (server claims more bytes than payload_max_length permits), but it must
  12240. // not exhaust memory before getting there.
  12241. auto res = cli.Get("/malicious");
  12242. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12243. }
  12244. server_thread.join();
  12245. }
  12246. // Verify that content_receiver bypasses the default payload_max_length,
  12247. // allowing streaming downloads larger than 100MB without requiring an explicit
  12248. // set_payload_max_length call.
  12249. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12250. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12251. #ifndef _WIN32
  12252. signal(SIGPIPE, SIG_IGN);
  12253. #endif
  12254. auto server_thread = std::thread([] {
  12255. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12256. default_socket_options(srv);
  12257. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12258. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12259. sockaddr_in addr{};
  12260. addr.sin_family = AF_INET;
  12261. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12262. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12263. int opt = 1;
  12264. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12265. #ifdef _WIN32
  12266. reinterpret_cast<const char *>(&opt),
  12267. #else
  12268. &opt,
  12269. #endif
  12270. sizeof(opt));
  12271. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12272. ::listen(srv, 1);
  12273. sockaddr_in cli_addr{};
  12274. socklen_t cli_len = sizeof(cli_addr);
  12275. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12276. if (cli != INVALID_SOCKET) {
  12277. char buf[4096];
  12278. ::recv(cli, buf, sizeof(buf), 0);
  12279. // Response with Content-Length larger than default 100MB limit
  12280. auto content_length = std::to_string(DATA_SIZE);
  12281. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12282. "Content-Length: " +
  12283. content_length +
  12284. "\r\n"
  12285. "Connection: close\r\n"
  12286. "\r\n";
  12287. ::send(cli,
  12288. #ifdef _WIN32
  12289. static_cast<const char *>(response_header.c_str()),
  12290. static_cast<int>(response_header.size()),
  12291. #else
  12292. response_header.c_str(), response_header.size(),
  12293. #endif
  12294. 0);
  12295. std::string chunk(64 * 1024, 'A');
  12296. size_t total_sent = 0;
  12297. while (total_sent < DATA_SIZE) {
  12298. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12299. auto sent = ::send(cli,
  12300. #ifdef _WIN32
  12301. static_cast<const char *>(chunk.c_str()),
  12302. static_cast<int>(to_send),
  12303. #else
  12304. chunk.c_str(), to_send,
  12305. #endif
  12306. 0);
  12307. if (sent <= 0) break;
  12308. total_sent += static_cast<size_t>(sent);
  12309. }
  12310. detail::close_socket(cli);
  12311. }
  12312. detail::close_socket(srv);
  12313. });
  12314. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12315. size_t total_received = 0;
  12316. {
  12317. Client cli("127.0.0.1", PORT + 2);
  12318. cli.set_read_timeout(10, 0);
  12319. // Do NOT call set_payload_max_length — use the default 100MB limit
  12320. auto res =
  12321. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12322. total_received += data_length;
  12323. return true;
  12324. });
  12325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12326. EXPECT_EQ(StatusCode::OK_200, res->status);
  12327. }
  12328. server_thread.join();
  12329. EXPECT_EQ(total_received, DATA_SIZE)
  12330. << "With content_receiver, the client should read all " << DATA_SIZE
  12331. << " bytes despite the default 100MB payload_max_length, but only read "
  12332. << total_received << " bytes.";
  12333. }
  12334. // Verify that an explicit set_payload_max_length smaller than the response is
  12335. // enforced even when a content_receiver is used.
  12336. TEST(ClientVulnerabilityTest,
  12337. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12338. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12339. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12340. #ifndef _WIN32
  12341. signal(SIGPIPE, SIG_IGN);
  12342. #endif
  12343. auto server_thread = std::thread([] {
  12344. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12345. default_socket_options(srv);
  12346. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12347. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12348. sockaddr_in addr{};
  12349. addr.sin_family = AF_INET;
  12350. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12351. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12352. int opt = 1;
  12353. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12354. #ifdef _WIN32
  12355. reinterpret_cast<const char *>(&opt),
  12356. #else
  12357. &opt,
  12358. #endif
  12359. sizeof(opt));
  12360. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12361. ::listen(srv, 1);
  12362. sockaddr_in cli_addr{};
  12363. socklen_t cli_len = sizeof(cli_addr);
  12364. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12365. if (cli != INVALID_SOCKET) {
  12366. char buf[4096];
  12367. ::recv(cli, buf, sizeof(buf), 0);
  12368. auto content_length = std::to_string(DATA_SIZE);
  12369. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12370. "Content-Length: " +
  12371. content_length +
  12372. "\r\n"
  12373. "Connection: close\r\n"
  12374. "\r\n";
  12375. ::send(cli,
  12376. #ifdef _WIN32
  12377. static_cast<const char *>(response_header.c_str()),
  12378. static_cast<int>(response_header.size()),
  12379. #else
  12380. response_header.c_str(), response_header.size(),
  12381. #endif
  12382. 0);
  12383. std::string chunk(64 * 1024, 'A');
  12384. size_t total_sent = 0;
  12385. while (total_sent < DATA_SIZE) {
  12386. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12387. auto sent = ::send(cli,
  12388. #ifdef _WIN32
  12389. static_cast<const char *>(chunk.c_str()),
  12390. static_cast<int>(to_send),
  12391. #else
  12392. chunk.c_str(), to_send,
  12393. #endif
  12394. 0);
  12395. if (sent <= 0) break;
  12396. total_sent += static_cast<size_t>(sent);
  12397. }
  12398. detail::close_socket(cli);
  12399. }
  12400. detail::close_socket(srv);
  12401. });
  12402. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12403. size_t total_received = 0;
  12404. {
  12405. Client cli("127.0.0.1", PORT + 2);
  12406. cli.set_read_timeout(10, 0);
  12407. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12408. auto res =
  12409. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12410. total_received += data_length;
  12411. return true;
  12412. });
  12413. // Should fail because 200MB exceeds the explicit 150MB limit
  12414. EXPECT_FALSE(res);
  12415. }
  12416. server_thread.join();
  12417. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12418. << "Client with content_receiver should respect the explicit "
  12419. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12420. << total_received << " bytes.";
  12421. }
  12422. // Verify that an explicit set_payload_max_length larger than the response
  12423. // allows the content_receiver to read all data successfully.
  12424. TEST(ClientVulnerabilityTest,
  12425. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12426. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12427. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12428. #ifndef _WIN32
  12429. signal(SIGPIPE, SIG_IGN);
  12430. #endif
  12431. auto server_thread = std::thread([] {
  12432. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12433. default_socket_options(srv);
  12434. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12435. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12436. sockaddr_in addr{};
  12437. addr.sin_family = AF_INET;
  12438. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12439. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12440. int opt = 1;
  12441. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12442. #ifdef _WIN32
  12443. reinterpret_cast<const char *>(&opt),
  12444. #else
  12445. &opt,
  12446. #endif
  12447. sizeof(opt));
  12448. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12449. ::listen(srv, 1);
  12450. sockaddr_in cli_addr{};
  12451. socklen_t cli_len = sizeof(cli_addr);
  12452. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12453. if (cli != INVALID_SOCKET) {
  12454. char buf[4096];
  12455. ::recv(cli, buf, sizeof(buf), 0);
  12456. auto content_length = std::to_string(DATA_SIZE);
  12457. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12458. "Content-Length: " +
  12459. content_length +
  12460. "\r\n"
  12461. "Connection: close\r\n"
  12462. "\r\n";
  12463. ::send(cli,
  12464. #ifdef _WIN32
  12465. static_cast<const char *>(response_header.c_str()),
  12466. static_cast<int>(response_header.size()),
  12467. #else
  12468. response_header.c_str(), response_header.size(),
  12469. #endif
  12470. 0);
  12471. std::string chunk(64 * 1024, 'A');
  12472. size_t total_sent = 0;
  12473. while (total_sent < DATA_SIZE) {
  12474. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12475. auto sent = ::send(cli,
  12476. #ifdef _WIN32
  12477. static_cast<const char *>(chunk.c_str()),
  12478. static_cast<int>(to_send),
  12479. #else
  12480. chunk.c_str(), to_send,
  12481. #endif
  12482. 0);
  12483. if (sent <= 0) break;
  12484. total_sent += static_cast<size_t>(sent);
  12485. }
  12486. #ifdef _WIN32
  12487. ::shutdown(cli, SD_SEND);
  12488. #else
  12489. ::shutdown(cli, SHUT_WR);
  12490. #endif
  12491. char drain[1024];
  12492. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12493. detail::close_socket(cli);
  12494. }
  12495. detail::close_socket(srv);
  12496. });
  12497. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12498. size_t total_received = 0;
  12499. {
  12500. Client cli("127.0.0.1", PORT + 2);
  12501. cli.set_read_timeout(10, 0);
  12502. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12503. auto res =
  12504. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12505. total_received += data_length;
  12506. return true;
  12507. });
  12508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12509. EXPECT_EQ(StatusCode::OK_200, res->status);
  12510. }
  12511. server_thread.join();
  12512. EXPECT_EQ(total_received, DATA_SIZE)
  12513. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12514. << " bytes (larger than " << DATA_SIZE
  12515. << " bytes response), content_receiver should read all data, but only "
  12516. "read "
  12517. << total_received << " bytes.";
  12518. }
  12519. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12520. // Regression test for "zip bomb" attack on the client side: a malicious server
  12521. // sends a small gzip-compressed response that decompresses to a huge payload.
  12522. // The client must enforce payload_max_length on the decompressed size.
  12523. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12524. constexpr size_t DECOMPRESSED_SIZE =
  12525. 10 * 1024 * 1024; // 10MB after decompression
  12526. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12527. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12528. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12529. std::string compressed;
  12530. {
  12531. httplib::detail::gzip_compressor compressor;
  12532. bool ok =
  12533. compressor.compress(uncompressed.data(), uncompressed.size(),
  12534. /*last=*/true, [&](const char *buf, size_t len) {
  12535. compressed.append(buf, len);
  12536. return true;
  12537. });
  12538. ASSERT_TRUE(ok);
  12539. }
  12540. // Sanity: compressed data should be much smaller than the decompressed size
  12541. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12542. #ifndef _WIN32
  12543. signal(SIGPIPE, SIG_IGN);
  12544. #endif
  12545. // Set up the listening socket in the main thread so the server is guaranteed
  12546. // to be ready before the client connects (eliminates race condition).
  12547. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12548. default_socket_options(srv);
  12549. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12550. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12551. sockaddr_in addr{};
  12552. addr.sin_family = AF_INET;
  12553. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12554. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12555. int opt = 1;
  12556. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12557. #ifdef _WIN32
  12558. reinterpret_cast<const char *>(&opt),
  12559. #else
  12560. &opt,
  12561. #endif
  12562. sizeof(opt));
  12563. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12564. ASSERT_EQ(0, ::listen(srv, 1));
  12565. auto server_thread = std::thread([&compressed, srv] {
  12566. sockaddr_in cli_addr{};
  12567. socklen_t cli_len = sizeof(cli_addr);
  12568. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12569. if (cli != INVALID_SOCKET) {
  12570. // Read the full HTTP request (until \r\n\r\n)
  12571. char buf[4096];
  12572. size_t total = 0;
  12573. while (total < sizeof(buf)) {
  12574. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12575. if (n <= 0) break;
  12576. total += static_cast<size_t>(n);
  12577. // Check for end of headers
  12578. if (total >= 4) {
  12579. std::string req(buf, total);
  12580. if (req.find("\r\n\r\n") != std::string::npos) break;
  12581. }
  12582. }
  12583. // Malicious response: gzip-compressed body, no Content-Length
  12584. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12585. "Content-Encoding: gzip\r\n"
  12586. "Connection: close\r\n"
  12587. "\r\n";
  12588. ::send(cli,
  12589. #ifdef _WIN32
  12590. static_cast<const char *>(response_header.c_str()),
  12591. static_cast<int>(response_header.size()),
  12592. #else
  12593. response_header.c_str(), response_header.size(),
  12594. #endif
  12595. 0);
  12596. // Send the compressed payload (small on the wire, huge when decompressed)
  12597. size_t total_sent = 0;
  12598. while (total_sent < compressed.size()) {
  12599. auto to_send = std::min(compressed.size() - total_sent,
  12600. static_cast<size_t>(64 * 1024));
  12601. auto sent =
  12602. ::send(cli,
  12603. #ifdef _WIN32
  12604. static_cast<const char *>(compressed.c_str() + total_sent),
  12605. static_cast<int>(to_send),
  12606. #else
  12607. compressed.c_str() + total_sent, to_send,
  12608. #endif
  12609. 0);
  12610. if (sent <= 0) break;
  12611. total_sent += static_cast<size_t>(sent);
  12612. }
  12613. detail::close_socket(cli);
  12614. }
  12615. });
  12616. auto se = detail::scope_exit([&] {
  12617. detail::close_socket(srv);
  12618. server_thread.join();
  12619. });
  12620. size_t total_decompressed = 0;
  12621. {
  12622. Client cli("127.0.0.1", PORT + 3);
  12623. cli.set_read_timeout(5, 0);
  12624. cli.set_decompress(true);
  12625. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12626. auto stream = cli.open_stream("GET", "/zipbomb");
  12627. ASSERT_TRUE(stream.is_valid());
  12628. char buffer[64 * 1024];
  12629. ssize_t n;
  12630. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12631. total_decompressed += static_cast<size_t>(n);
  12632. }
  12633. }
  12634. // The decompressed size must be capped by payload_max_length. Without
  12635. // protection, the client would decompress the full 10MB from a tiny
  12636. // compressed payload, enabling a zip bomb DoS attack.
  12637. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12638. << "Client decompressed " << total_decompressed
  12639. << " bytes from a gzip response. The decompressed size should be "
  12640. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12641. }
  12642. #endif
  12643. TEST(HostAndPortPropertiesTest, NoSSL) {
  12644. httplib::Client cli("www.google.com", 1234);
  12645. ASSERT_EQ("www.google.com", cli.host());
  12646. ASSERT_EQ(1234, cli.port());
  12647. }
  12648. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12649. httplib::Client cli("www.google.com:1234");
  12650. ASSERT_EQ("www.google.com", cli.host());
  12651. ASSERT_EQ(1234, cli.port());
  12652. }
  12653. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12654. // Port number that overflows int — should not crash, client becomes invalid
  12655. httplib::Client cli("http://www.google.com:99999999999999999999");
  12656. ASSERT_FALSE(cli.is_valid());
  12657. }
  12658. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12659. // Port 99999 exceeds valid range (1-65535) — should not crash
  12660. httplib::Client cli("http://www.google.com:99999");
  12661. ASSERT_FALSE(cli.is_valid());
  12662. auto res = cli.Get("/");
  12663. EXPECT_FALSE(res);
  12664. EXPECT_EQ(Error::Connection, res.error());
  12665. }
  12666. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12667. httplib::Client cli("http://www.google.com:80abc");
  12668. ASSERT_FALSE(cli.is_valid());
  12669. }
  12670. #ifdef CPPHTTPLIB_SSL_ENABLED
  12671. TEST(HostAndPortPropertiesTest, SSL) {
  12672. httplib::SSLClient cli("www.google.com");
  12673. ASSERT_EQ("www.google.com", cli.host());
  12674. ASSERT_EQ(443, cli.port());
  12675. }
  12676. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12677. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12678. std::string cert;
  12679. read_file(CA_CERT_FILE, cert);
  12680. httplib::SSLClient httplib_client("www.google.com");
  12681. // Load CA store first time
  12682. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12683. // Load CA store second time (update)
  12684. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12685. // Verify client is still valid and can make connections
  12686. httplib_client.enable_server_certificate_verification(true);
  12687. auto res = httplib_client.Get("/");
  12688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12689. // Google may return 200 or 301 depending on various factors
  12690. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12691. res->status == StatusCode::MovedPermanently_301);
  12692. }
  12693. TEST(SSLClientTest, ServerNameIndication_Online) {
  12694. auto host = "httpbingo.org";
  12695. auto path = std::string{"/get"};
  12696. SSLClient cli(host, 443);
  12697. auto res = cli.Get(path);
  12698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12699. ASSERT_EQ(StatusCode::OK_200, res->status);
  12700. }
  12701. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12702. // Use a site that will cause SSL verification failure due to self-signed cert
  12703. SSLClient cli("self-signed.badssl.com", 443);
  12704. cli.enable_server_certificate_verification(true);
  12705. auto res = cli.Get("/");
  12706. ASSERT_TRUE(!res);
  12707. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12708. // Verify backend error is captured for SSLServerVerification
  12709. // This occurs when certificate verification fails
  12710. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12711. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12712. EXPECT_NE(0UL, res.ssl_backend_error());
  12713. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12714. // For OpenSSL, ssl_error is 0 for verification errors
  12715. EXPECT_EQ(0, res.ssl_error());
  12716. #if !defined(_WIN32) || \
  12717. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12718. // On non-Windows or when Windows Schannel is disabled, the error comes
  12719. // from OpenSSL's verification
  12720. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12721. res.ssl_backend_error());
  12722. #endif
  12723. #endif
  12724. }
  12725. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12726. // Use a site where hostname doesn't match the certificate
  12727. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12728. SSLClient cli("wrong.host.badssl.com", 443);
  12729. cli.enable_server_certificate_verification(true);
  12730. cli.enable_server_hostname_verification(true);
  12731. auto res = cli.Get("/");
  12732. ASSERT_TRUE(!res);
  12733. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12734. // Verify backend error is captured for hostname verification failure
  12735. EXPECT_NE(0UL, res.ssl_backend_error());
  12736. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12737. // For OpenSSL, ssl_error is 0 for verification errors
  12738. EXPECT_EQ(0, res.ssl_error());
  12739. #if !defined(_WIN32) || \
  12740. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12741. // On non-Windows or when Windows Schannel is disabled, the error comes
  12742. // from OpenSSL's hostname verification
  12743. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12744. res.ssl_backend_error());
  12745. #endif
  12746. #endif
  12747. }
  12748. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12749. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12750. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12751. SSLClient cli("www.google.com", 443);
  12752. cli.enable_server_certificate_verification(true);
  12753. auto res = cli.Get("/");
  12754. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12755. }
  12756. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12757. SSLClient cli("www.google.com", 443);
  12758. cli.enable_server_certificate_verification(true);
  12759. cli.enable_windows_certificate_verification(false);
  12760. auto res = cli.Get("/");
  12761. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12762. }
  12763. // The server sends an intermediate cross-signed by a root Windows trusts,
  12764. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12765. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12766. SSLClient cli("accounts.spotify.com", 443);
  12767. auto res = cli.Get("/");
  12768. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12769. << " ssl_backend_error=" << res.ssl_backend_error();
  12770. }
  12771. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12772. // policy status, which no backend reports for a self-signed certificate.
  12773. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12774. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12775. ASSERT_TRUE(svr.is_valid());
  12776. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12777. auto se = detail::scope_exit([&] {
  12778. svr.stop();
  12779. t.join();
  12780. ASSERT_FALSE(svr.is_running());
  12781. });
  12782. svr.wait_until_ready();
  12783. SSLClient cli("127.0.0.1", PORT);
  12784. cli.set_connection_timeout(30);
  12785. auto res = cli.Get("/");
  12786. ASSERT_FALSE(res);
  12787. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12788. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12789. }
  12790. #endif
  12791. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12792. Client cli("https://google.com");
  12793. auto res = cli.Get("/");
  12794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12795. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12796. }
  12797. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12798. SSLClient cli("google.com");
  12799. cli.set_ca_cert_path(CA_CERT_FILE);
  12800. auto res = cli.Get("/");
  12801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12802. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12803. }
  12804. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12805. SSLClient cli("google.com");
  12806. cli.enable_server_certificate_verification(true);
  12807. cli.set_ca_cert_path("hello");
  12808. auto res = cli.Get("/");
  12809. ASSERT_TRUE(!res);
  12810. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12811. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12812. // should be set
  12813. EXPECT_EQ(0, res.ssl_error());
  12814. // Verify backend error is captured for SSLLoadingCerts
  12815. // This error occurs when loading CA certificates fails
  12816. EXPECT_NE(0UL, res.ssl_backend_error());
  12817. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12818. // OpenSSL specific error codes:
  12819. // > openssl errstr 0x80000002
  12820. // error:80000002:system library::No such file or directory
  12821. // > openssl errstr 0xA000126
  12822. // error:0A000126:SSL routines::unexpected eof while reading
  12823. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12824. res.ssl_backend_error() == 0xA000126);
  12825. #endif
  12826. }
  12827. TEST(SSLClientTest, ServerCertificateVerification4) {
  12828. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12829. ASSERT_TRUE(svr.is_valid());
  12830. svr.Get("/test", [&](const Request &, Response &res) {
  12831. res.set_content("test", "text/plain");
  12832. svr.stop();
  12833. ASSERT_TRUE(true);
  12834. });
  12835. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12836. auto se = detail::scope_exit([&] {
  12837. t.join();
  12838. ASSERT_FALSE(svr.is_running());
  12839. });
  12840. svr.wait_until_ready();
  12841. SSLClient cli("127.0.0.1", PORT);
  12842. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12843. cli.enable_server_certificate_verification(true);
  12844. cli.set_connection_timeout(30);
  12845. auto res = cli.Get("/test");
  12846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12847. ASSERT_EQ(StatusCode::OK_200, res->status);
  12848. }
  12849. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12850. std::string cert;
  12851. read_file(CA_CERT_FILE, cert);
  12852. SSLClient cli("google.com");
  12853. cli.load_ca_cert_store(cert.data(), cert.size());
  12854. const auto res = cli.Get("/");
  12855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12856. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12857. }
  12858. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12859. // clang-format off
  12860. static constexpr char cert[] =
  12861. "GlobalSign Root CA\n"
  12862. "==================\n"
  12863. "-----BEGIN CERTIFICATE-----\n"
  12864. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12865. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12866. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12867. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12868. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12869. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12870. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12871. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12872. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12873. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12874. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12875. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12876. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12877. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12878. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12879. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12880. "-----END CERTIFICATE-----\n";
  12881. // clang-format on
  12882. SSLClient cli("google.com");
  12883. cli.load_ca_cert_store(cert, sizeof(cert));
  12884. const auto res = cli.Get("/");
  12885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12886. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12887. }
  12888. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12889. SSLClient cli("www.youtube.com");
  12890. cli.set_ca_cert_path(CA_CERT_FILE);
  12891. cli.enable_server_certificate_verification(true);
  12892. cli.set_follow_location(true);
  12893. auto res = cli.Get("/");
  12894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12895. ASSERT_EQ(StatusCode::OK_200, res->status);
  12896. }
  12897. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12898. SSLClient cli("wWw.YouTube.Com");
  12899. cli.set_ca_cert_path(CA_CERT_FILE);
  12900. cli.enable_server_certificate_verification(true);
  12901. cli.enable_server_hostname_verification(true);
  12902. cli.set_follow_location(true);
  12903. auto res = cli.Get("/");
  12904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12905. ASSERT_EQ(StatusCode::OK_200, res->status);
  12906. }
  12907. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12908. SSLClient cli("gOoGlE.COm");
  12909. cli.enable_server_certificate_verification(true);
  12910. cli.enable_server_hostname_verification(true);
  12911. cli.set_follow_location(true);
  12912. auto res = cli.Get("/");
  12913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12914. ASSERT_EQ(StatusCode::OK_200, res->status);
  12915. }
  12916. TEST(SSLClientTest, Issue2004_Online) {
  12917. Client client("https://google.com");
  12918. client.set_follow_location(true);
  12919. auto res = client.Get("/");
  12920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12921. ASSERT_EQ(StatusCode::OK_200, res->status);
  12922. auto body = res->body;
  12923. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12924. }
  12925. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12926. // Create SSLClient with invalid cert/key to make is_valid() return false
  12927. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12928. "nonexistent_key.pem");
  12929. // is_valid() should be false due to cert loading failure
  12930. ASSERT_FALSE(cli.is_valid());
  12931. auto res = cli.Get("/");
  12932. ASSERT_FALSE(res);
  12933. EXPECT_EQ(Error::SSLConnection, res.error());
  12934. }
  12935. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12936. // Test for Issue #2251: SSL error not properly reported when client cert
  12937. // and key paths are swapped or mismatched
  12938. // This simulates the scenario where user accidentally swaps the cert and key
  12939. // files
  12940. // Using client cert file as private key and vice versa (completely wrong)
  12941. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12942. // Should fail validation due to cert/key mismatch
  12943. ASSERT_FALSE(cli.is_valid());
  12944. // Attempt to make a request should fail with proper error
  12945. auto res = cli.Get("/");
  12946. ASSERT_FALSE(res);
  12947. EXPECT_EQ(Error::SSLConnection, res.error());
  12948. // SSL error should be recorded in the Result object (this is the key fix for
  12949. // Issue #2251)
  12950. auto backend_error = res.ssl_backend_error();
  12951. EXPECT_NE(0u, backend_error);
  12952. }
  12953. // Tests cert/key mismatch detection at the TLS context level
  12954. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12955. // Test that using mismatched cert/key causes connection failure.
  12956. // We verify this at the SSLClient level rather than through internal
  12957. // TLS API functions.
  12958. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12959. cli.enable_server_certificate_verification(false);
  12960. cli.set_connection_timeout(2);
  12961. // The mismatch should cause a connection or handshake error
  12962. auto res = cli.Get("/test");
  12963. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12964. // Either way, the request should fail
  12965. EXPECT_FALSE(res);
  12966. }
  12967. #endif
  12968. #if 0
  12969. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12970. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12971. ASSERT_TRUE(cli != nullptr);
  12972. cli->set_address_family(AF_INET6);
  12973. cli->set_interface("en0");
  12974. auto res = cli->Get("/get");
  12975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12976. ASSERT_EQ(StatusCode::OK_200, res->status);
  12977. }
  12978. #endif
  12979. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12980. #ifdef CPPHTTPLIB_SSL_ENABLED
  12981. void ClientCertPresent(
  12982. const std::string &client_cert_file,
  12983. const std::string &client_private_key_file,
  12984. const std::string &client_encrypted_private_key_pass = std::string()) {
  12985. using namespace httplib::tls;
  12986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12987. CLIENT_CA_CERT_DIR);
  12988. ASSERT_TRUE(svr.is_valid());
  12989. svr.Get("/test", [&](const Request &req, Response &res) {
  12990. res.set_content("test", "text/plain");
  12991. auto cert = req.peer_cert();
  12992. ASSERT_TRUE(static_cast<bool>(cert));
  12993. std::string common_name = cert.subject_cn();
  12994. EXPECT_EQ("Common Name", common_name);
  12995. });
  12996. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12997. auto se = detail::scope_exit([&] {
  12998. svr.stop();
  12999. t.join();
  13000. ASSERT_FALSE(svr.is_running());
  13001. });
  13002. svr.wait_until_ready();
  13003. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13004. client_encrypted_private_key_pass);
  13005. cli.enable_server_certificate_verification(false);
  13006. cli.set_connection_timeout(30);
  13007. auto res = cli.Get("/test");
  13008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13009. ASSERT_EQ(StatusCode::OK_200, res->status);
  13010. }
  13011. TEST(SSLClientServerTest, ClientCertPresent) {
  13012. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13013. }
  13014. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13015. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13016. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13017. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13018. }
  13019. // PEM memory-based constructor tests (works with all TLS backends)
  13020. void PemMemoryClientCertPresent(
  13021. const std::string &client_cert_file,
  13022. const std::string &client_private_key_file,
  13023. const std::string &client_encrypted_private_key_pass = std::string()) {
  13024. // Read PEM files into memory
  13025. std::string server_cert_pem, server_key_pem;
  13026. std::string client_ca_pem;
  13027. std::string client_cert_pem, client_key_pem;
  13028. read_file(SERVER_CERT_FILE, server_cert_pem);
  13029. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13030. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13031. read_file(client_cert_file, client_cert_pem);
  13032. read_file(client_private_key_file, client_key_pem);
  13033. // Create server with PEM memory
  13034. SSLServer::PemMemory server_pem = {
  13035. server_cert_pem.c_str(),
  13036. server_cert_pem.size(),
  13037. server_key_pem.c_str(),
  13038. server_key_pem.size(),
  13039. client_ca_pem.c_str(),
  13040. client_ca_pem.size(),
  13041. nullptr // no password for server key
  13042. };
  13043. SSLServer svr(server_pem);
  13044. ASSERT_TRUE(svr.is_valid());
  13045. svr.Get("/test", [&](const Request &, Response &res) {
  13046. res.set_content("test", "text/plain");
  13047. });
  13048. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13049. auto se = detail::scope_exit([&] {
  13050. svr.stop();
  13051. t.join();
  13052. ASSERT_FALSE(svr.is_running());
  13053. });
  13054. svr.wait_until_ready();
  13055. // Create client with PEM memory
  13056. const char *password = client_encrypted_private_key_pass.empty()
  13057. ? nullptr
  13058. : client_encrypted_private_key_pass.c_str();
  13059. SSLClient::PemMemory client_pem = {
  13060. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13061. client_key_pem.size(), password};
  13062. SSLClient cli(HOST, PORT, client_pem);
  13063. cli.enable_server_certificate_verification(false);
  13064. cli.set_connection_timeout(30);
  13065. auto res = cli.Get("/test");
  13066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13067. ASSERT_EQ(StatusCode::OK_200, res->status);
  13068. }
  13069. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13070. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13071. }
  13072. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13073. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13074. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13075. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13076. }
  13077. TEST(SSLClientServerTest, ClientCertMissing) {
  13078. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13079. CLIENT_CA_CERT_DIR);
  13080. ASSERT_TRUE(svr.is_valid());
  13081. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13082. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, 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(HOST, PORT);
  13090. cli.set_connection_timeout(30);
  13091. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13092. // the chain check on Windows, so the result does not depend on the order.
  13093. cli.enable_server_hostname_verification(false);
  13094. auto res = cli.Get("/test");
  13095. ASSERT_TRUE(!res);
  13096. // When client cert is missing and server requires it, connection fails
  13097. // Error type depends on backend implementation
  13098. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13099. res.error() == Error::SSLConnection);
  13100. // Verify backend error is captured
  13101. // Note: This test may have different error codes depending on the exact
  13102. // verification failure
  13103. EXPECT_NE(0UL, res.ssl_backend_error());
  13104. }
  13105. TEST(SSLClientServerTest, TrustDirOptional) {
  13106. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13107. ASSERT_TRUE(svr.is_valid());
  13108. svr.Get("/test", [&](const Request &, Response &res) {
  13109. res.set_content("test", "text/plain");
  13110. });
  13111. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13112. auto se = detail::scope_exit([&] {
  13113. svr.stop();
  13114. t.join();
  13115. ASSERT_FALSE(svr.is_running());
  13116. });
  13117. svr.wait_until_ready();
  13118. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13119. cli.enable_server_certificate_verification(false);
  13120. cli.set_connection_timeout(30);
  13121. auto res = cli.Get("/test");
  13122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13123. ASSERT_EQ(StatusCode::OK_200, res->status);
  13124. }
  13125. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13126. class NoListenSSLServer : public SSLServer {
  13127. public:
  13128. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13129. const char *client_ca_cert_file_path,
  13130. const char *client_ca_cert_dir_path = nullptr)
  13131. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13132. client_ca_cert_dir_path),
  13133. stop_(false) {}
  13134. std::atomic_bool stop_;
  13135. private:
  13136. bool process_and_close_socket(socket_t /*sock*/) override {
  13137. // Don't create SSL context
  13138. while (!stop_.load()) {
  13139. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13140. }
  13141. return true;
  13142. }
  13143. };
  13144. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13145. CLIENT_CA_CERT_FILE);
  13146. ASSERT_TRUE(svr.is_valid());
  13147. svr.Get("/test", [&](const Request &, Response &res) {
  13148. res.set_content("test", "text/plain");
  13149. });
  13150. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13151. auto se = detail::scope_exit([&] {
  13152. svr.stop_ = true;
  13153. svr.stop();
  13154. t.join();
  13155. ASSERT_FALSE(svr.is_running());
  13156. });
  13157. svr.wait_until_ready();
  13158. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13159. cli.enable_server_certificate_verification(false);
  13160. cli.set_connection_timeout(1);
  13161. auto res = cli.Get("/test");
  13162. ASSERT_TRUE(!res);
  13163. EXPECT_EQ(Error::SSLConnection, res.error());
  13164. // Timeout results in WantRead error code (maps to backend-specific value)
  13165. EXPECT_NE(0, res.ssl_error());
  13166. }
  13167. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13168. // Test SSLServer with client certificate verification using the standard
  13169. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13170. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13171. CLIENT_CA_CERT_DIR);
  13172. ASSERT_TRUE(svr.is_valid());
  13173. svr.Get("/test", [&](const Request &req, Response &res) {
  13174. res.set_content("test", "text/plain");
  13175. auto cert = req.peer_cert();
  13176. ASSERT_TRUE(static_cast<bool>(cert));
  13177. auto common_name = cert.subject_cn();
  13178. EXPECT_EQ("Common Name", common_name);
  13179. });
  13180. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13181. auto se = detail::scope_exit([&] {
  13182. svr.stop();
  13183. t.join();
  13184. ASSERT_FALSE(svr.is_running());
  13185. });
  13186. svr.wait_until_ready();
  13187. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13188. cli.enable_server_certificate_verification(false);
  13189. cli.set_connection_timeout(30);
  13190. auto res = cli.Get("/test");
  13191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13192. ASSERT_EQ(StatusCode::OK_200, res->status);
  13193. }
  13194. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13195. // Verifies that wildcard matching and exact matching work consistently
  13196. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13197. using namespace httplib::tls;
  13198. // We need a running server to test against
  13199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13200. ASSERT_TRUE(svr.is_valid());
  13201. svr.Get("/test", [](const Request &, Response &res) {
  13202. res.set_content("ok", "text/plain");
  13203. });
  13204. thread t([&]() { svr.listen(HOST, PORT); });
  13205. auto se = detail::scope_exit([&] {
  13206. svr.stop();
  13207. t.join();
  13208. });
  13209. svr.wait_until_ready();
  13210. bool verify_callback_called = false;
  13211. bool verify_result_wrong = false;
  13212. SSLClient cli(HOST, PORT);
  13213. cli.enable_server_certificate_verification(true);
  13214. cli.set_ca_cert_path(CA_CERT_FILE);
  13215. cli.set_connection_timeout(5);
  13216. // Note: Test certificate has CN="Common Name", not "localhost"
  13217. bool verify_result_cn = false;
  13218. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13219. verify_callback_called = true;
  13220. if (!ctx.cert) return false;
  13221. // Test 1: "Common Name" should match (our test server cert CN)
  13222. verify_result_cn = ctx.check_hostname("Common Name");
  13223. // Test 2: wrong hostname should not match
  13224. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13225. return true; // Accept for the purpose of this test
  13226. });
  13227. auto res = cli.Get("/test");
  13228. // The request may succeed or fail depending on cert configuration
  13229. // but the callback should have been called
  13230. ASSERT_TRUE(verify_callback_called)
  13231. << "Verify callback should have been called";
  13232. // CN="Common Name" should match our test certificate
  13233. //
  13234. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13235. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13236. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13237. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13238. // <openssl/base.h>, which is included transitively when
  13239. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13240. #if defined(OPENSSL_IS_BORINGSSL)
  13241. EXPECT_FALSE(verify_result_cn)
  13242. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13243. #else
  13244. EXPECT_TRUE(verify_result_cn)
  13245. << "verify_hostname should match 'Common Name' (certificate CN)";
  13246. #endif
  13247. // Wrong hostname should not match
  13248. EXPECT_FALSE(verify_result_wrong)
  13249. << "verify_hostname should not match 'wronghost.example.com'";
  13250. }
  13251. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13252. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13253. // X509_check_ip behavior and must hold for every backend.
  13254. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13255. using namespace httplib::tls;
  13256. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13257. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13258. ASSERT_TRUE(svr.is_valid());
  13259. svr.Get("/test", [](const Request &, Response &res) {
  13260. res.set_content("ok", "text/plain");
  13261. });
  13262. thread t([&]() { svr.listen(HOST, PORT); });
  13263. auto se = detail::scope_exit([&] {
  13264. svr.stop();
  13265. t.join();
  13266. });
  13267. svr.wait_until_ready();
  13268. bool verify_callback_called = false;
  13269. bool ip_matched_via_cn = true;
  13270. SSLClient cli(HOST, PORT);
  13271. cli.enable_server_certificate_verification(true);
  13272. cli.set_ca_cert_path(CA_CERT_FILE);
  13273. cli.set_connection_timeout(5);
  13274. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13275. verify_callback_called = true;
  13276. if (!ctx.cert) return false;
  13277. // The IP appears only in the CN, so it must NOT be accepted.
  13278. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13279. return true; // Accept for the purpose of this test
  13280. });
  13281. cli.Get("/test");
  13282. ASSERT_TRUE(verify_callback_called)
  13283. << "Verify callback should have been called";
  13284. EXPECT_FALSE(ip_matched_via_cn)
  13285. << "An IP host must not be authenticated via the certificate CN";
  13286. }
  13287. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13288. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13289. using namespace httplib::tls;
  13290. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13291. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13292. ASSERT_TRUE(svr.is_valid());
  13293. svr.Get("/test", [](const Request &, Response &res) {
  13294. res.set_content("ok", "text/plain");
  13295. });
  13296. thread t([&]() { svr.listen(HOST, PORT); });
  13297. auto se = detail::scope_exit([&] {
  13298. svr.stop();
  13299. t.join();
  13300. });
  13301. svr.wait_until_ready();
  13302. bool verify_callback_called = false;
  13303. bool san_matched = false;
  13304. bool wrong_ipv6_matched = true;
  13305. bool cn_ipv6_matched = true;
  13306. SSLClient cli(HOST, PORT);
  13307. cli.enable_server_certificate_verification(true);
  13308. cli.set_ca_cert_path(CA_CERT_FILE);
  13309. cli.set_connection_timeout(5);
  13310. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13311. verify_callback_called = true;
  13312. if (!ctx.cert) return false;
  13313. // Matches the IPv6 iPAddress SAN.
  13314. san_matched = ctx.check_hostname("2001:db8::1");
  13315. // A different IPv6 address must not match.
  13316. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13317. // "::1" lives only in the CN, so it must not be accepted.
  13318. cn_ipv6_matched = ctx.check_hostname("::1");
  13319. return true; // Accept for the purpose of this test
  13320. });
  13321. cli.Get("/test");
  13322. ASSERT_TRUE(verify_callback_called)
  13323. << "Verify callback should have been called";
  13324. EXPECT_TRUE(san_matched)
  13325. << "verify_hostname should match an IPv6 iPAddress SAN";
  13326. EXPECT_FALSE(wrong_ipv6_matched)
  13327. << "verify_hostname should not match a non-matching IPv6 address";
  13328. EXPECT_FALSE(cn_ipv6_matched)
  13329. << "An IPv6 host must not be authenticated via the certificate CN";
  13330. }
  13331. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13332. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13333. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13334. using namespace httplib::tls;
  13335. // SANs: DNS:a.zz, IP:42.46.122.122
  13336. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13337. ASSERT_TRUE(svr.is_valid());
  13338. svr.Get("/test", [](const Request &, Response &res) {
  13339. res.set_content("ok", "text/plain");
  13340. });
  13341. auto port = svr.bind_to_any_port(HOST);
  13342. thread t([&]() { svr.listen_after_bind(); });
  13343. auto se = detail::scope_exit([&] {
  13344. svr.stop();
  13345. t.join();
  13346. });
  13347. svr.wait_until_ready();
  13348. bool verify_callback_called = false;
  13349. bool dns_san_matched = false;
  13350. bool ip_san_matched = false;
  13351. bool ip_matched_via_dns_san = true;
  13352. bool dns_matched_via_ip_san = true;
  13353. SSLClient cli(HOST, port);
  13354. cli.enable_server_certificate_verification(true);
  13355. cli.set_ca_cert_path(CA_CERT_FILE);
  13356. cli.set_connection_timeout(5);
  13357. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13358. verify_callback_called = true;
  13359. if (!ctx.cert) return false;
  13360. dns_san_matched = ctx.check_hostname("a.zz");
  13361. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13362. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13363. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13364. return true; // Accept for the purpose of this test
  13365. });
  13366. cli.Get("/test");
  13367. ASSERT_TRUE(verify_callback_called)
  13368. << "Verify callback should have been called";
  13369. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13370. EXPECT_TRUE(ip_san_matched)
  13371. << "verify_hostname should match an iPAddress SAN";
  13372. EXPECT_FALSE(ip_matched_via_dns_san)
  13373. << "An IP host must not be authenticated via a dNSName SAN";
  13374. EXPECT_FALSE(dns_matched_via_ip_san)
  13375. << "A DNS host must not be authenticated via an iPAddress SAN";
  13376. }
  13377. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13378. // "www.*.example.test" names one host and not every host under example.test.
  13379. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13380. using namespace httplib::tls;
  13381. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13382. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13383. ASSERT_TRUE(svr.is_valid());
  13384. svr.Get("/test", [](const Request &, Response &res) {
  13385. res.set_content("ok", "text/plain");
  13386. });
  13387. auto port = svr.bind_to_any_port(HOST);
  13388. thread t([&]() { svr.listen_after_bind(); });
  13389. auto se = detail::scope_exit([&] {
  13390. svr.stop();
  13391. t.join();
  13392. });
  13393. svr.wait_until_ready();
  13394. bool verify_callback_called = false;
  13395. bool leftmost_wildcard_matched = false;
  13396. bool wildcard_spanned_labels = true;
  13397. bool inner_wildcard_matched = true;
  13398. SSLClient cli(HOST, port);
  13399. cli.enable_server_certificate_verification(true);
  13400. cli.set_ca_cert_path(CA_CERT_FILE);
  13401. cli.set_connection_timeout(5);
  13402. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13403. verify_callback_called = true;
  13404. if (!ctx.cert) return false;
  13405. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13406. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13407. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13408. return true; // Accept for the purpose of this test
  13409. });
  13410. cli.Get("/test");
  13411. ASSERT_TRUE(verify_callback_called)
  13412. << "Verify callback should have been called";
  13413. EXPECT_TRUE(leftmost_wildcard_matched)
  13414. << "A leftmost wildcard should match a single label";
  13415. EXPECT_FALSE(wildcard_spanned_labels)
  13416. << "A wildcard label must not match more than one label";
  13417. EXPECT_FALSE(inner_wildcard_matched)
  13418. << "A wildcard outside the leftmost label must not be honoured";
  13419. }
  13420. // sans() must report each SAN entry under its own type.
  13421. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13422. using namespace httplib::tls;
  13423. // SANs: DNS:a.zz, IP:42.46.122.122
  13424. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13425. ASSERT_TRUE(svr.is_valid());
  13426. svr.Get("/test", [](const Request &, Response &res) {
  13427. res.set_content("ok", "text/plain");
  13428. });
  13429. auto port = svr.bind_to_any_port(HOST);
  13430. thread t([&]() { svr.listen_after_bind(); });
  13431. auto se = detail::scope_exit([&] {
  13432. svr.stop();
  13433. t.join();
  13434. });
  13435. svr.wait_until_ready();
  13436. bool verify_callback_called = false;
  13437. std::vector<SanEntry> sans;
  13438. SSLClient cli(HOST, port);
  13439. cli.enable_server_certificate_verification(true);
  13440. cli.set_ca_cert_path(CA_CERT_FILE);
  13441. cli.set_connection_timeout(5);
  13442. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13443. verify_callback_called = true;
  13444. if (!ctx.cert) return false;
  13445. sans = ctx.sans();
  13446. return true; // Accept for the purpose of this test
  13447. });
  13448. cli.Get("/test");
  13449. ASSERT_TRUE(verify_callback_called)
  13450. << "Verify callback should have been called";
  13451. auto has_san = [&](SanType type, const std::string &value) {
  13452. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13453. return san.type == type && san.value == value;
  13454. });
  13455. };
  13456. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13457. << "sans() should report the dNSName SAN";
  13458. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13459. << "sans() should report the iPAddress SAN";
  13460. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13461. << "sans() must not report the dNSName SAN as an address";
  13462. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13463. << "sans() must not report the iPAddress SAN as a DNS name";
  13464. }
  13465. #endif
  13466. // mbedTLS-specific callback constructor test
  13467. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13468. #ifdef CPPHTTPLIB_SSL_ENABLED
  13469. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13470. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13471. ASSERT_TRUE(svr.is_valid());
  13472. // Set up a handler to verify client certificate is present
  13473. bool client_cert_verified = false;
  13474. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13475. // Verify that client certificate was provided
  13476. client_cert_verified = true;
  13477. res.set_content("success", "text/plain");
  13478. });
  13479. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13480. auto se = detail::scope_exit([&] {
  13481. svr.stop();
  13482. t.join();
  13483. ASSERT_FALSE(svr.is_running());
  13484. });
  13485. svr.wait_until_ready();
  13486. // Client with certificate
  13487. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13488. cli.enable_server_certificate_verification(false);
  13489. cli.set_connection_timeout(30);
  13490. auto res = cli.Get("/test");
  13491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13492. ASSERT_EQ(StatusCode::OK_200, res->status);
  13493. ASSERT_TRUE(client_cert_verified);
  13494. EXPECT_EQ("success", res->body);
  13495. }
  13496. #endif
  13497. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13498. // backends
  13499. #ifdef CPPHTTPLIB_SSL_ENABLED
  13500. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13501. using namespace httplib::tls;
  13502. // Test that when client CA cert file is provided,
  13503. // the server properly requests and validates client certificates
  13504. // Create a server with client authentication
  13505. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13506. ASSERT_TRUE(svr.is_valid());
  13507. bool handler_called = false;
  13508. svr.Get("/test", [&](const Request &req, Response &res) {
  13509. handler_called = true;
  13510. // Verify that a client certificate was provided
  13511. auto cert = req.peer_cert();
  13512. ASSERT_TRUE(static_cast<bool>(cert));
  13513. // Get the issuer name
  13514. std::string issuer_str = cert.issuer_name();
  13515. ASSERT_FALSE(issuer_str.empty());
  13516. // The client certificate should be issued by our test CA
  13517. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13518. res.set_content("authenticated", "text/plain");
  13519. });
  13520. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13521. auto se = detail::scope_exit([&] {
  13522. svr.stop();
  13523. t.join();
  13524. ASSERT_FALSE(svr.is_running());
  13525. });
  13526. svr.wait_until_ready();
  13527. // Connect with a client certificate issued by the CA
  13528. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13529. cli.enable_server_certificate_verification(false);
  13530. cli.set_connection_timeout(30);
  13531. auto res = cli.Get("/test");
  13532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13533. ASSERT_EQ(StatusCode::OK_200, res->status);
  13534. ASSERT_TRUE(handler_called);
  13535. EXPECT_EQ("authenticated", res->body);
  13536. }
  13537. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13538. using namespace httplib::tls;
  13539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13540. ASSERT_TRUE(svr.is_valid());
  13541. svr.Get("/test", [](const Request &, Response &res) {
  13542. res.set_content("ok", "text/plain");
  13543. });
  13544. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13545. auto se = detail::scope_exit([&] {
  13546. svr.stop();
  13547. t.join();
  13548. });
  13549. svr.wait_until_ready();
  13550. SSLClient cli(HOST, PORT);
  13551. cli.enable_server_certificate_verification(false);
  13552. cli.set_connection_timeout(30);
  13553. bool cert_checked = false;
  13554. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13555. if (ctx.cert) {
  13556. auto sans = ctx.sans();
  13557. // Test certificate may or may not have SANs - just verify the API
  13558. // works If SANs exist, verify the types are valid
  13559. for (const auto &san : sans) {
  13560. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13561. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13562. san.type == SanType::OTHER);
  13563. EXPECT_FALSE(san.value.empty());
  13564. }
  13565. cert_checked = true;
  13566. }
  13567. return true;
  13568. });
  13569. auto res = cli.Get("/test");
  13570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13571. EXPECT_TRUE(cert_checked);
  13572. }
  13573. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13574. using namespace httplib::tls;
  13575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13576. ASSERT_TRUE(svr.is_valid());
  13577. svr.Get("/test", [](const Request &, Response &res) {
  13578. res.set_content("ok", "text/plain");
  13579. });
  13580. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13581. auto se = detail::scope_exit([&] {
  13582. svr.stop();
  13583. t.join();
  13584. });
  13585. svr.wait_until_ready();
  13586. SSLClient cli(HOST, PORT);
  13587. cli.enable_server_certificate_verification(false);
  13588. cli.set_connection_timeout(30);
  13589. bool validity_checked = false;
  13590. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13591. if (ctx.cert) {
  13592. time_t not_before = 0, not_after = 0;
  13593. bool result = ctx.validity(not_before, not_after);
  13594. EXPECT_TRUE(result);
  13595. // Verify that not_before < now < not_after for a valid cert
  13596. time_t now = time(nullptr);
  13597. EXPECT_LT(not_before, now);
  13598. EXPECT_GT(not_after, now);
  13599. validity_checked = true;
  13600. }
  13601. return true;
  13602. });
  13603. auto res = cli.Get("/test");
  13604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13605. EXPECT_TRUE(validity_checked);
  13606. }
  13607. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13608. using namespace httplib::tls;
  13609. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13610. ASSERT_TRUE(svr.is_valid());
  13611. svr.Get("/test", [](const Request &, Response &res) {
  13612. res.set_content("ok", "text/plain");
  13613. });
  13614. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13615. auto se = detail::scope_exit([&] {
  13616. svr.stop();
  13617. t.join();
  13618. });
  13619. svr.wait_until_ready();
  13620. SSLClient cli(HOST, PORT);
  13621. cli.enable_server_certificate_verification(false);
  13622. cli.set_connection_timeout(30);
  13623. bool serial_checked = false;
  13624. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13625. if (ctx.cert) {
  13626. std::string serial = ctx.serial();
  13627. EXPECT_FALSE(serial.empty());
  13628. // Serial should be a hex string
  13629. for (char c : serial) {
  13630. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13631. (c >= 'a' && c <= 'f'));
  13632. }
  13633. serial_checked = true;
  13634. }
  13635. return true;
  13636. });
  13637. auto res = cli.Get("/test");
  13638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13639. EXPECT_TRUE(serial_checked);
  13640. }
  13641. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13642. // Test 1: Valid CA file - no error should be recorded
  13643. {
  13644. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13645. CLIENT_CA_CERT_FILE);
  13646. ASSERT_TRUE(svr.is_valid());
  13647. // With valid setup, last_ssl_error should be 0
  13648. EXPECT_EQ(0, svr.ssl_last_error());
  13649. }
  13650. // Test 2: Invalid CA file content
  13651. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13652. {
  13653. // Create a temporary file with completely invalid content
  13654. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13655. {
  13656. std::ofstream ofs(temp_invalid_ca);
  13657. ofs << "This is not a certificate file at all\n";
  13658. ofs << "Just plain text content\n";
  13659. }
  13660. // Create server with invalid CA file
  13661. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13662. // Clean up temporary file
  13663. std::remove(temp_invalid_ca);
  13664. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13665. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13666. // Note: SSL_CTX_load_verify_locations typically fails first,
  13667. // but our error handling code path is still exercised
  13668. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13669. }
  13670. }
  13671. TEST(VerifyCallbackTest, VerifyContextFields) {
  13672. using namespace httplib::tls;
  13673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13674. ASSERT_TRUE(svr.is_valid());
  13675. svr.Get("/test", [](const Request &, Response &res) {
  13676. res.set_content("ok", "text/plain");
  13677. });
  13678. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13679. auto se = detail::scope_exit([&] {
  13680. svr.stop();
  13681. t.join();
  13682. });
  13683. svr.wait_until_ready();
  13684. SSLClient cli(HOST, PORT);
  13685. cli.enable_server_certificate_verification(false);
  13686. cli.set_connection_timeout(30);
  13687. int callback_count = 0;
  13688. bool saw_leaf_cert = false;
  13689. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13690. if (ctx.cert) {
  13691. callback_count++;
  13692. // We should see at least one certificate (the leaf)
  13693. std::string cn = ctx.subject_cn();
  13694. if (!cn.empty()) { saw_leaf_cert = true; }
  13695. // Verify context fields are populated
  13696. EXPECT_NE(ctx.session, nullptr);
  13697. EXPECT_GE(ctx.depth, 0);
  13698. }
  13699. return true;
  13700. });
  13701. auto res = cli.Get("/test");
  13702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13703. EXPECT_GT(callback_count, 0);
  13704. EXPECT_TRUE(saw_leaf_cert);
  13705. }
  13706. // A verifier belongs to the client that set it, not to the thread that set it.
  13707. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13708. using namespace httplib::tls;
  13709. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13710. ASSERT_TRUE(svr.is_valid());
  13711. svr.Get("/test", [](const Request &, Response &res) {
  13712. res.set_content("ok", "text/plain");
  13713. });
  13714. auto port = svr.bind_to_any_port(HOST);
  13715. thread t([&]() { svr.listen_after_bind(); });
  13716. auto se = detail::scope_exit([&] {
  13717. svr.stop();
  13718. t.join();
  13719. });
  13720. svr.wait_until_ready();
  13721. auto rejecting_calls = 0;
  13722. SSLClient rejecting(HOST, port);
  13723. rejecting.enable_server_certificate_verification(false);
  13724. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13725. rejecting_calls++;
  13726. return false;
  13727. });
  13728. auto accepting_calls = 0;
  13729. SSLClient accepting(HOST, port);
  13730. accepting.enable_server_certificate_verification(false);
  13731. // Set on another thread than the requests below.
  13732. thread([&]() {
  13733. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13734. accepting_calls++;
  13735. return true;
  13736. });
  13737. }).join();
  13738. // Requested on another thread than the verifier was set on.
  13739. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13740. EXPECT_GT(rejecting_calls, 0);
  13741. auto res = accepting.Get("/test");
  13742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13743. EXPECT_GT(accepting_calls, 0);
  13744. }
  13745. // VerifyContext::session is the same handle the other tls:: functions take.
  13746. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13747. using namespace httplib::tls;
  13748. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13749. ASSERT_TRUE(svr.is_valid());
  13750. svr.Get("/test", [](const Request &, Response &res) {
  13751. res.set_content("ok", "text/plain");
  13752. });
  13753. auto port = svr.bind_to_any_port(HOST);
  13754. thread t([&]() { svr.listen_after_bind(); });
  13755. auto se = detail::scope_exit([&] {
  13756. svr.stop();
  13757. t.join();
  13758. });
  13759. svr.wait_until_ready();
  13760. SSLClient cli(HOST, port);
  13761. cli.enable_server_certificate_verification(false);
  13762. session_t verifier_session = nullptr;
  13763. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13764. verifier_session = ctx.session;
  13765. return true;
  13766. });
  13767. session_t session_verifier_session = nullptr;
  13768. cli.set_session_verifier([&](session_t session) {
  13769. session_verifier_session = session;
  13770. return SSLVerifierResponse::NoDecisionMade;
  13771. });
  13772. auto res = cli.Get("/test");
  13773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13774. EXPECT_NE(nullptr, verifier_session);
  13775. EXPECT_EQ(session_verifier_session, verifier_session);
  13776. }
  13777. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13778. using httplib::tls::TlsError;
  13779. // Test that verify_error_to_string returns empty for success
  13780. std::string success_str = TlsError::verify_error_to_string(0);
  13781. EXPECT_TRUE(success_str.empty());
  13782. // Test that verify_error_to_string returns non-empty for error codes
  13783. // Using a common error code (certificate expired)
  13784. std::string error_str =
  13785. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13786. EXPECT_FALSE(error_str.empty());
  13787. }
  13788. TEST(SessionVerifierTest, CertificateAccepted) {
  13789. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13790. ASSERT_TRUE(svr.is_valid());
  13791. svr.Get("/test", [](const Request &, Response &res) {
  13792. res.set_content("ok", "text/plain");
  13793. });
  13794. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13795. auto se = detail::scope_exit([&] {
  13796. svr.stop();
  13797. t.join();
  13798. });
  13799. svr.wait_until_ready();
  13800. SSLClient cli(HOST, PORT);
  13801. cli.enable_server_certificate_verification(false);
  13802. cli.set_connection_timeout(30);
  13803. bool callback_called = false;
  13804. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13805. EXPECT_NE(session, nullptr);
  13806. callback_called = true;
  13807. return SSLVerifierResponse::CertificateAccepted;
  13808. });
  13809. auto res = cli.Get("/test");
  13810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13811. EXPECT_EQ(200, res->status);
  13812. EXPECT_TRUE(callback_called);
  13813. }
  13814. TEST(SessionVerifierTest, CertificateRejected) {
  13815. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13816. ASSERT_TRUE(svr.is_valid());
  13817. svr.Get("/test", [](const Request &, Response &res) {
  13818. res.set_content("ok", "text/plain");
  13819. });
  13820. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13821. auto se = detail::scope_exit([&] {
  13822. svr.stop();
  13823. t.join();
  13824. });
  13825. svr.wait_until_ready();
  13826. SSLClient cli(HOST, PORT);
  13827. cli.enable_server_certificate_verification(false);
  13828. cli.set_connection_timeout(30);
  13829. bool callback_called = false;
  13830. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13831. EXPECT_NE(session, nullptr);
  13832. callback_called = true;
  13833. return SSLVerifierResponse::CertificateRejected;
  13834. });
  13835. auto res = cli.Get("/test");
  13836. EXPECT_FALSE(res);
  13837. EXPECT_TRUE(callback_called);
  13838. }
  13839. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13840. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13841. ASSERT_TRUE(svr.is_valid());
  13842. svr.Get("/test", [](const Request &, Response &res) {
  13843. res.set_content("ok", "text/plain");
  13844. });
  13845. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13846. auto se = detail::scope_exit([&] {
  13847. svr.stop();
  13848. t.join();
  13849. });
  13850. svr.wait_until_ready();
  13851. // NoDecisionMade with verification disabled should succeed (no default check)
  13852. SSLClient cli(HOST, PORT);
  13853. cli.enable_server_certificate_verification(false);
  13854. cli.set_connection_timeout(30);
  13855. bool callback_called = false;
  13856. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13857. EXPECT_NE(session, nullptr);
  13858. callback_called = true;
  13859. return SSLVerifierResponse::NoDecisionMade;
  13860. });
  13861. auto res = cli.Get("/test");
  13862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13863. EXPECT_EQ(200, res->status);
  13864. EXPECT_TRUE(callback_called);
  13865. }
  13866. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13868. ASSERT_TRUE(svr.is_valid());
  13869. svr.Get("/test", [](const Request &, Response &res) {
  13870. res.set_content("ok", "text/plain");
  13871. });
  13872. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13873. auto se = detail::scope_exit([&] {
  13874. svr.stop();
  13875. t.join();
  13876. });
  13877. svr.wait_until_ready();
  13878. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13879. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13880. // so we only check that the request fails, not whether the callback was
  13881. // called.
  13882. SSLClient cli(HOST, PORT);
  13883. cli.enable_server_certificate_verification(true);
  13884. cli.set_connection_timeout(30);
  13885. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13886. EXPECT_NE(session, nullptr);
  13887. return SSLVerifierResponse::NoDecisionMade;
  13888. });
  13889. auto res = cli.Get("/test");
  13890. EXPECT_FALSE(res);
  13891. }
  13892. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13893. // Test SSL server using PemMemory constructor with client CA certificates
  13894. // Read PEM files
  13895. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13896. read_file(SERVER_CERT_FILE, server_cert_pem);
  13897. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13898. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13899. // Create SSLServer with PemMemory constructor including client CA
  13900. SSLServer::PemMemory server_pem = {
  13901. server_cert_pem.c_str(),
  13902. server_cert_pem.size(),
  13903. server_key_pem.c_str(),
  13904. server_key_pem.size(),
  13905. client_ca_pem.c_str(),
  13906. client_ca_pem.size(),
  13907. nullptr // no password for server key
  13908. };
  13909. SSLServer svr(server_pem);
  13910. ASSERT_TRUE(svr.is_valid());
  13911. // No SSL error should be recorded for valid setup
  13912. EXPECT_EQ(0, svr.ssl_last_error());
  13913. // Set up server endpoints
  13914. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13915. res.set_content("ok", "text/plain");
  13916. });
  13917. // Start server in a thread
  13918. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13919. svr.wait_until_ready();
  13920. // Connect with client certificate (using constructor with paths)
  13921. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13922. cli.enable_server_certificate_verification(false);
  13923. auto res = cli.Get("/test-pem-ca");
  13924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13925. EXPECT_EQ(200, res->status);
  13926. EXPECT_EQ("ok", res->body);
  13927. svr.stop();
  13928. server_thread.join();
  13929. }
  13930. #endif
  13931. #ifdef _WIN32
  13932. TEST(CleanupTest, WSACleanup) {
  13933. int ret = WSACleanup();
  13934. ASSERT_EQ(0, ret);
  13935. }
  13936. #endif
  13937. #ifndef CPPHTTPLIB_SSL_ENABLED
  13938. TEST(NoSSLSupport, SimpleInterface) {
  13939. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13940. }
  13941. #endif
  13942. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13943. TEST(InvalidScheme, SimpleInterface) {
  13944. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13945. }
  13946. #endif
  13947. TEST(NoScheme, SimpleInterface) {
  13948. Client cli("yahoo.com:80");
  13949. ASSERT_TRUE(cli.is_valid());
  13950. }
  13951. TEST(SendAPI, SimpleInterface_Online) {
  13952. Client cli("http://yahoo.com");
  13953. Request req;
  13954. req.method = "GET";
  13955. req.path = "/";
  13956. auto res = cli.send(req);
  13957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13958. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13959. }
  13960. TEST(SendAPI, WithParamsInRequest) {
  13961. Server svr;
  13962. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13963. EXPECT_TRUE(req.has_param("test"));
  13964. EXPECT_EQ("test_value", req.get_param_value("test"));
  13965. });
  13966. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13967. auto se = detail::scope_exit([&] {
  13968. svr.stop();
  13969. t.join();
  13970. ASSERT_FALSE(svr.is_running());
  13971. });
  13972. svr.wait_until_ready();
  13973. Client cli(HOST, PORT);
  13974. {
  13975. Request req;
  13976. req.method = "GET";
  13977. req.path = "/";
  13978. req.params.emplace("test", "test_value");
  13979. auto res = cli.send(req);
  13980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13981. }
  13982. {
  13983. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13985. }
  13986. }
  13987. TEST(ClientImplMethods, GetSocketTest) {
  13988. httplib::Server svr;
  13989. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13990. res.status = StatusCode::OK_200;
  13991. });
  13992. auto port = svr.bind_to_any_port("127.0.0.1");
  13993. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13994. auto se = detail::scope_exit([&] {
  13995. svr.stop();
  13996. thread.join();
  13997. ASSERT_FALSE(svr.is_running());
  13998. });
  13999. svr.wait_until_ready();
  14000. {
  14001. httplib::Client cli("127.0.0.1", port);
  14002. cli.set_keep_alive(true);
  14003. // Use the behavior of cpp-httplib of opening the connection
  14004. // only when the first request happens. If that changes,
  14005. // this test would be obsolete.
  14006. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14007. // This also implicitly tests the server. But other tests would fail much
  14008. // earlier than this one to be considered.
  14009. auto res = cli.Get("/");
  14010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14011. EXPECT_EQ(StatusCode::OK_200, res->status);
  14012. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14013. }
  14014. }
  14015. #ifdef CPPHTTPLIB_SSL_ENABLED
  14016. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14017. Client cli("http://yahoo.com");
  14018. auto res = cli.Get("/");
  14019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14020. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14021. cli.set_follow_location(true);
  14022. res = cli.Get("/");
  14023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14024. EXPECT_EQ(StatusCode::OK_200, res->status);
  14025. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14026. }
  14027. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14028. Client cli("https://yahoo.com");
  14029. auto res = cli.Get("/");
  14030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14031. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14032. cli.set_follow_location(true);
  14033. res = cli.Get("/");
  14034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14035. EXPECT_EQ(StatusCode::OK_200, res->status);
  14036. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14037. }
  14038. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14039. Client cli("https://yahoo.com");
  14040. auto res = cli.Get("/");
  14041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14042. ASSERT_FALSE(!res);
  14043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14044. ASSERT_FALSE(res == nullptr);
  14045. ASSERT_TRUE(res != nullptr);
  14046. EXPECT_EQ(Error::Success, res.error());
  14047. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14048. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14049. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14050. cli.set_follow_location(true);
  14051. res = cli.Get("/");
  14052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14053. EXPECT_EQ(Error::Success, res.error());
  14054. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14055. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14056. EXPECT_EQ(StatusCode::OK_200, res->status);
  14057. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14058. }
  14059. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14060. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14061. Client cli("https://cdnjs.cloudflare.com");
  14062. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14063. Headers{{"Accept-Encoding", "br"}});
  14064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14065. EXPECT_EQ(StatusCode::OK_200, res->status);
  14066. EXPECT_EQ(287630U, res->body.size());
  14067. EXPECT_EQ("application/javascript; charset=utf-8",
  14068. res->get_header_value("Content-Type"));
  14069. }
  14070. #endif
  14071. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14072. #undef REDIR_HOST // Silence compiler warning
  14073. #define REDIR_HOST "https://httpbingo.org"
  14074. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14075. Client cli(REDIR_HOST);
  14076. cli.set_follow_location(true);
  14077. auto res =
  14078. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14080. EXPECT_EQ(StatusCode::OK_200, res->status);
  14081. }
  14082. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14083. Client cli(REDIR_HOST);
  14084. cli.set_follow_location(true);
  14085. Params params;
  14086. params.emplace("url", "http://example.com");
  14087. params.emplace("status_code", "302");
  14088. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14090. EXPECT_EQ(StatusCode::OK_200, res->status);
  14091. }
  14092. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14093. Client cli(REDIR_HOST);
  14094. cli.set_follow_location(true);
  14095. Params params;
  14096. params.emplace("url", "http://example.com");
  14097. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14099. EXPECT_EQ(StatusCode::OK_200, res->status);
  14100. }
  14101. TEST(HttpToHttpsRedirectTest, CertFile) {
  14102. auto ssl_port = PORT + 1;
  14103. Server svr;
  14104. ASSERT_TRUE(svr.is_valid());
  14105. svr.Get("/index", [&](const Request &, Response &res) {
  14106. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14107. "/index");
  14108. svr.stop();
  14109. });
  14110. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14111. ASSERT_TRUE(ssl_svr.is_valid());
  14112. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14113. res.set_content("test", "text/plain");
  14114. ssl_svr.stop();
  14115. });
  14116. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14117. thread t2 =
  14118. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14119. auto se = detail::scope_exit([&] {
  14120. t2.join();
  14121. t.join();
  14122. ASSERT_FALSE(svr.is_running());
  14123. });
  14124. svr.wait_until_ready();
  14125. ssl_svr.wait_until_ready();
  14126. Client cli("127.0.0.1", PORT);
  14127. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14128. cli.enable_server_certificate_verification(true);
  14129. cli.set_follow_location(true);
  14130. cli.set_connection_timeout(30);
  14131. auto res = cli.Get("/index");
  14132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14133. ASSERT_EQ(StatusCode::OK_200, res->status);
  14134. }
  14135. TEST(SSLClientRedirectTest, CertFile) {
  14136. auto ssl_port = PORT + 1;
  14137. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14138. ASSERT_TRUE(ssl_svr1.is_valid());
  14139. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14140. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14141. "/index");
  14142. ssl_svr1.stop();
  14143. });
  14144. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14145. ASSERT_TRUE(ssl_svr2.is_valid());
  14146. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14147. res.set_content("test", "text/plain");
  14148. ssl_svr2.stop();
  14149. });
  14150. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14151. thread t2 =
  14152. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14153. auto se = detail::scope_exit([&] {
  14154. t2.join();
  14155. t.join();
  14156. ASSERT_FALSE(ssl_svr1.is_running());
  14157. });
  14158. ssl_svr1.wait_until_ready();
  14159. ssl_svr2.wait_until_ready();
  14160. SSLClient cli("127.0.0.1", PORT);
  14161. std::string cert;
  14162. read_file(SERVER_CERT2_FILE, cert);
  14163. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14164. cli.enable_server_certificate_verification(true);
  14165. cli.set_follow_location(true);
  14166. cli.set_connection_timeout(30);
  14167. auto res = cli.Get("/index");
  14168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14169. ASSERT_EQ(StatusCode::OK_200, res->status);
  14170. }
  14171. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14172. // another port, so the client follows it with a new client.
  14173. static Result GetThroughTlsRedirectToDifferentPort(
  14174. const std::function<void(SSLClient &)> &setup,
  14175. const char *target_cert = SERVER_CERT2_FILE) {
  14176. auto ssl_port = PORT + 1;
  14177. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14178. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14179. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14180. "/index");
  14181. });
  14182. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14183. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14184. res.set_content("test", "text/plain");
  14185. });
  14186. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14187. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14188. auto se = detail::scope_exit([&] {
  14189. ssl_svr2.stop();
  14190. ssl_svr1.stop();
  14191. t2.join();
  14192. t.join();
  14193. });
  14194. ssl_svr1.wait_until_ready();
  14195. ssl_svr2.wait_until_ready();
  14196. SSLClient cli("127.0.0.1", PORT);
  14197. cli.set_follow_location(true);
  14198. cli.set_connection_timeout(30);
  14199. setup(cli);
  14200. return cli.Get("/index");
  14201. }
  14202. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14203. auto calls = 0;
  14204. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14205. cli.enable_server_certificate_verification(false);
  14206. // Accept the first server only.
  14207. cli.set_session_verifier([&](tls::session_t) {
  14208. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14209. : SSLVerifierResponse::CertificateRejected;
  14210. });
  14211. });
  14212. EXPECT_FALSE(res);
  14213. EXPECT_EQ(2, calls);
  14214. }
  14215. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14216. std::string pinned;
  14217. auto res = GetThroughTlsRedirectToDifferentPort(
  14218. [&](SSLClient &cli) {
  14219. cli.enable_server_certificate_verification(false);
  14220. // Pin the first certificate seen.
  14221. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14222. if (pinned.empty()) { pinned = ctx.serial(); }
  14223. return ctx.serial() == pinned;
  14224. });
  14225. },
  14226. // A certificate other than the first server's.
  14227. SERVER_CERT_FILE);
  14228. EXPECT_FALSE(res);
  14229. EXPECT_FALSE(pinned.empty());
  14230. }
  14231. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14232. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14233. std::string cert;
  14234. read_file(SERVER_CERT2_FILE, cert);
  14235. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14236. });
  14237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14238. EXPECT_EQ(StatusCode::OK_200, res->status);
  14239. }
  14240. #endif
  14241. #ifdef CPPHTTPLIB_SSL_ENABLED
  14242. // Test that set_ca_cert_store() skips system certs (consistent with
  14243. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14244. // should be trusted - system certs should NOT be loaded.
  14245. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14246. // Load a specific cert that is NOT a system CA cert
  14247. std::string cert;
  14248. read_file(SERVER_CERT2_FILE, cert);
  14249. SSLClient cli("google.com");
  14250. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14251. cli.enable_server_certificate_verification(true);
  14252. // This should FAIL because:
  14253. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14254. // 2. System certs should NOT be loaded when custom store is set
  14255. // If system certs WERE loaded, this would succeed
  14256. auto res = cli.Get("/");
  14257. ASSERT_FALSE(res);
  14258. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14259. }
  14260. // Same as above, but through the native store handle path. Regression test:
  14261. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14262. // merged system certs into the user-provided store.
  14263. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14264. std::string cert;
  14265. read_file(SERVER_CERT2_FILE, cert);
  14266. SSLClient cli("google.com");
  14267. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14268. cli.enable_server_certificate_verification(true);
  14269. auto res = cli.Get("/");
  14270. ASSERT_FALSE(res);
  14271. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14272. }
  14273. // A custom store set via the native handle must still verify a server whose
  14274. // cert it does contain.
  14275. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14276. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14277. ASSERT_TRUE(svr.is_valid());
  14278. svr.Get("/test", [&](const Request &, Response &res) {
  14279. res.set_content("test", "text/plain");
  14280. });
  14281. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14282. auto se = detail::scope_exit([&] {
  14283. svr.stop();
  14284. t.join();
  14285. ASSERT_FALSE(svr.is_running());
  14286. });
  14287. svr.wait_until_ready();
  14288. SSLClient cli("127.0.0.1", PORT);
  14289. std::string cert;
  14290. read_file(SERVER_CERT2_FILE, cert);
  14291. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14292. cli.enable_server_certificate_verification(true);
  14293. cli.set_connection_timeout(30);
  14294. auto res = cli.Get("/test");
  14295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14296. ASSERT_EQ(StatusCode::OK_200, res->status);
  14297. }
  14298. // CA certs loaded through the universal Client must be transferred to the
  14299. // client created internally for following an HTTPS redirect. Regression test:
  14300. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14301. // the CA data for redirect transfer.
  14302. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14303. auto ssl_port = PORT + 1;
  14304. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14305. ASSERT_TRUE(ssl_svr1.is_valid());
  14306. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14307. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14308. "/index");
  14309. });
  14310. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14311. ASSERT_TRUE(ssl_svr2.is_valid());
  14312. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14313. res.set_content("test", "text/plain");
  14314. });
  14315. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14316. thread t2 =
  14317. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14318. auto se = detail::scope_exit([&] {
  14319. ssl_svr2.stop();
  14320. ssl_svr1.stop();
  14321. t2.join();
  14322. t.join();
  14323. ASSERT_FALSE(ssl_svr1.is_running());
  14324. });
  14325. ssl_svr1.wait_until_ready();
  14326. ssl_svr2.wait_until_ready();
  14327. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14328. std::string cert;
  14329. read_file(SERVER_CERT2_FILE, cert);
  14330. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14331. cli.enable_server_certificate_verification(true);
  14332. cli.set_follow_location(true);
  14333. cli.set_connection_timeout(30);
  14334. auto res = cli.Get("/index");
  14335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14336. ASSERT_EQ(StatusCode::OK_200, res->status);
  14337. }
  14338. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14339. // so a host signed by a system CA verifies even though a custom CA is set
  14340. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14341. std::string cert;
  14342. read_file(SERVER_CERT2_FILE, cert);
  14343. SSLClient cli("google.com");
  14344. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14345. cli.enable_system_ca(true);
  14346. cli.enable_server_certificate_verification(true);
  14347. auto res = cli.Get("/");
  14348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14349. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14350. }
  14351. // The custom CA remains effective when combined with the system CA
  14352. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14353. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14354. ASSERT_TRUE(svr.is_valid());
  14355. svr.Get("/test", [&](const Request &, Response &res) {
  14356. res.set_content("test", "text/plain");
  14357. });
  14358. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14359. auto se = detail::scope_exit([&] {
  14360. svr.stop();
  14361. t.join();
  14362. ASSERT_FALSE(svr.is_running());
  14363. });
  14364. svr.wait_until_ready();
  14365. SSLClient cli("127.0.0.1", PORT);
  14366. std::string cert;
  14367. read_file(SERVER_CERT2_FILE, cert);
  14368. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14369. cli.enable_system_ca(true);
  14370. cli.enable_server_certificate_verification(true);
  14371. cli.set_connection_timeout(30);
  14372. auto res = cli.Get("/test");
  14373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14374. ASSERT_EQ(StatusCode::OK_200, res->status);
  14375. }
  14376. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14377. // skip chain verification entirely (only the certificate identity was
  14378. // checked), so a server presenting an untrusted certificate with a matching
  14379. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14380. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14381. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14382. ASSERT_TRUE(svr.is_valid());
  14383. svr.Get("/test", [&](const Request &, Response &res) {
  14384. res.set_content("test", "text/plain");
  14385. });
  14386. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14387. auto se = detail::scope_exit([&] {
  14388. svr.stop();
  14389. t.join();
  14390. ASSERT_FALSE(svr.is_running());
  14391. });
  14392. svr.wait_until_ready();
  14393. SSLClient cli("127.0.0.1", PORT);
  14394. std::string cert;
  14395. // A trusted CA that did not sign the server certificate. The server cert
  14396. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14397. // this connection.
  14398. read_file(CLIENT_CA_CERT_FILE, cert);
  14399. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14400. cli.enable_server_certificate_verification(true);
  14401. cli.set_connection_timeout(30);
  14402. auto res = cli.Get("/test");
  14403. ASSERT_FALSE(res);
  14404. }
  14405. // enable_system_ca(false) prevents system CA loading entirely
  14406. TEST(SSLClientTest, DisableSystemCa_Online) {
  14407. SSLClient cli("google.com");
  14408. cli.enable_system_ca(false);
  14409. cli.enable_server_certificate_verification(true);
  14410. auto res = cli.Get("/");
  14411. ASSERT_FALSE(res);
  14412. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14413. // itself when the CA chain is empty
  14414. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14415. res.error() == Error::SSLConnection);
  14416. }
  14417. // The universal Client forwards enable_system_ca()
  14418. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14419. std::string cert;
  14420. read_file(SERVER_CERT2_FILE, cert);
  14421. Client cli("https://google.com");
  14422. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14423. cli.enable_system_ca(true);
  14424. cli.enable_server_certificate_verification(true);
  14425. auto res = cli.Get("/");
  14426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14427. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14428. }
  14429. // The system CA policy must carry over to the client created internally for
  14430. // following a cross-host HTTPS redirect
  14431. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14432. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14433. ASSERT_TRUE(svr.is_valid());
  14434. svr.Get("/index", [&](const Request &, Response &res) {
  14435. res.set_redirect("https://www.google.com/");
  14436. });
  14437. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14438. auto se = detail::scope_exit([&] {
  14439. svr.stop();
  14440. t.join();
  14441. ASSERT_FALSE(svr.is_running());
  14442. });
  14443. svr.wait_until_ready();
  14444. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14445. std::string cert;
  14446. read_file(SERVER_CERT2_FILE, cert);
  14447. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14448. cli.enable_system_ca(true);
  14449. cli.enable_server_certificate_verification(true);
  14450. cli.set_follow_location(true);
  14451. cli.set_connection_timeout(30);
  14452. // Receiving any response proves the redirect client completed the TLS
  14453. // handshake with a system-CA-signed host
  14454. auto res = cli.Get("/index");
  14455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14456. }
  14457. TEST(MultipartFormDataTest, LargeData) {
  14458. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14459. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14460. const ContentReader &content_reader) {
  14461. if (req.is_multipart_form_data()) {
  14462. std::vector<FormData> items;
  14463. content_reader(
  14464. [&](const FormData &file) {
  14465. items.push_back(file);
  14466. return true;
  14467. },
  14468. [&](const char *data, size_t data_length) {
  14469. items.back().content.append(data, data_length);
  14470. return true;
  14471. });
  14472. EXPECT_TRUE(std::string(items[0].name) == "document");
  14473. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14474. EXPECT_TRUE(items[0].filename == "2MB_data");
  14475. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14476. EXPECT_TRUE(items[1].name == "hello");
  14477. EXPECT_TRUE(items[1].content == "world");
  14478. EXPECT_TRUE(items[1].filename == "");
  14479. EXPECT_TRUE(items[1].content_type == "");
  14480. } else {
  14481. std::string body;
  14482. content_reader([&](const char *data, size_t data_length) {
  14483. body.append(data, data_length);
  14484. return true;
  14485. });
  14486. }
  14487. });
  14488. auto port = svr.bind_to_any_port(HOST);
  14489. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14490. auto se = detail::scope_exit([&] {
  14491. svr.stop();
  14492. t.join();
  14493. ASSERT_FALSE(svr.is_running());
  14494. });
  14495. svr.wait_until_ready();
  14496. {
  14497. std::string data(1024 * 1024 * 2, '.');
  14498. std::stringstream buffer;
  14499. buffer << data;
  14500. SSLClient cli(HOST, port);
  14501. cli.enable_server_certificate_verification(false);
  14502. UploadFormDataItems items{
  14503. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14504. {"hello", "world", "", ""},
  14505. };
  14506. auto res = cli.Post("/post", items);
  14507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14508. ASSERT_EQ(StatusCode::OK_200, res->status);
  14509. }
  14510. }
  14511. TEST(MultipartFormDataTest, DataProviderItems) {
  14512. std::random_device seed_gen;
  14513. std::mt19937 random(seed_gen());
  14514. std::string rand1;
  14515. rand1.resize(1000);
  14516. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14517. std::string rand2;
  14518. rand2.resize(3000);
  14519. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14520. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14521. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14522. const ContentReader &content_reader) {
  14523. ASSERT_FALSE(req.is_multipart_form_data());
  14524. std::string body;
  14525. content_reader([&](const char *data, size_t data_length) {
  14526. body.append(data, data_length);
  14527. return true;
  14528. });
  14529. EXPECT_EQ(body, "");
  14530. });
  14531. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14532. const ContentReader &content_reader) {
  14533. ASSERT_TRUE(req.is_multipart_form_data());
  14534. std::vector<FormData> items;
  14535. content_reader(
  14536. [&](const FormData &file) {
  14537. items.push_back(file);
  14538. return true;
  14539. },
  14540. [&](const char *data, size_t data_length) {
  14541. items.back().content.append(data, data_length);
  14542. return true;
  14543. });
  14544. ASSERT_TRUE(items.size() == 2);
  14545. EXPECT_EQ(std::string(items[0].name), "name1");
  14546. EXPECT_EQ(items[0].content, "Testing123");
  14547. EXPECT_EQ(items[0].filename, "filename1");
  14548. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14549. EXPECT_EQ(items[1].name, "name2");
  14550. EXPECT_EQ(items[1].content, "Testing456");
  14551. EXPECT_EQ(items[1].filename, "");
  14552. EXPECT_EQ(items[1].content_type, "");
  14553. });
  14554. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14555. const ContentReader &content_reader) {
  14556. ASSERT_TRUE(req.is_multipart_form_data());
  14557. std::vector<FormData> items;
  14558. content_reader(
  14559. [&](const FormData &file) {
  14560. items.push_back(file);
  14561. return true;
  14562. },
  14563. [&](const char *data, size_t data_length) {
  14564. items.back().content.append(data, data_length);
  14565. return true;
  14566. });
  14567. ASSERT_TRUE(items.size() == 2);
  14568. EXPECT_EQ(items[0].name, "name3");
  14569. EXPECT_EQ(items[0].content, rand1);
  14570. EXPECT_EQ(items[0].filename, "filename3");
  14571. EXPECT_EQ(items[0].content_type, "");
  14572. EXPECT_EQ(items[1].name, "name4");
  14573. EXPECT_EQ(items[1].content, rand2);
  14574. EXPECT_EQ(items[1].filename, "filename4");
  14575. EXPECT_EQ(items[1].content_type, "");
  14576. });
  14577. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14578. const ContentReader &content_reader) {
  14579. ASSERT_TRUE(req.is_multipart_form_data());
  14580. std::vector<FormData> items;
  14581. content_reader(
  14582. [&](const FormData &file) {
  14583. items.push_back(file);
  14584. return true;
  14585. },
  14586. [&](const char *data, size_t data_length) {
  14587. items.back().content.append(data, data_length);
  14588. return true;
  14589. });
  14590. ASSERT_TRUE(items.size() == 4);
  14591. EXPECT_EQ(std::string(items[0].name), "name1");
  14592. EXPECT_EQ(items[0].content, "Testing123");
  14593. EXPECT_EQ(items[0].filename, "filename1");
  14594. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14595. EXPECT_EQ(items[1].name, "name2");
  14596. EXPECT_EQ(items[1].content, "Testing456");
  14597. EXPECT_EQ(items[1].filename, "");
  14598. EXPECT_EQ(items[1].content_type, "");
  14599. EXPECT_EQ(items[2].name, "name3");
  14600. EXPECT_EQ(items[2].content, rand1);
  14601. EXPECT_EQ(items[2].filename, "filename3");
  14602. EXPECT_EQ(items[2].content_type, "");
  14603. EXPECT_EQ(items[3].name, "name4");
  14604. EXPECT_EQ(items[3].content, rand2);
  14605. EXPECT_EQ(items[3].filename, "filename4");
  14606. EXPECT_EQ(items[3].content_type, "");
  14607. });
  14608. auto port = svr.bind_to_any_port("localhost");
  14609. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14610. auto se = detail::scope_exit([&] {
  14611. svr.stop();
  14612. t.join();
  14613. ASSERT_FALSE(svr.is_running());
  14614. });
  14615. svr.wait_until_ready();
  14616. {
  14617. SSLClient cli("localhost", port);
  14618. cli.enable_server_certificate_verification(false);
  14619. UploadFormDataItems items{
  14620. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14621. {"name2", "Testing456", "", ""}, // not a file
  14622. };
  14623. {
  14624. auto res = cli.Post("/post-none", {}, {}, {});
  14625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14626. ASSERT_EQ(StatusCode::OK_200, res->status);
  14627. }
  14628. FormDataProviderItems providers;
  14629. {
  14630. auto res =
  14631. cli.Post("/post-items", {}, items, providers); // empty providers
  14632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14633. ASSERT_EQ(StatusCode::OK_200, res->status);
  14634. }
  14635. providers.push_back({"name3",
  14636. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14637. // test the offset is given correctly at each step
  14638. if (!offset)
  14639. sink.os.write(rand1.data(), 30);
  14640. else if (offset == 30)
  14641. sink.os.write(rand1.data() + 30, 300);
  14642. else if (offset == 330)
  14643. sink.os.write(rand1.data() + 330, 670);
  14644. else if (offset == rand1.size())
  14645. sink.done();
  14646. return true;
  14647. },
  14648. "filename3",
  14649. {}});
  14650. providers.push_back({"name4",
  14651. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14652. // test the offset is given correctly at each step
  14653. if (!offset)
  14654. sink.os.write(rand2.data(), 2000);
  14655. else if (offset == 2000)
  14656. sink.os.write(rand2.data() + 2000, 1);
  14657. else if (offset == 2001)
  14658. sink.os.write(rand2.data() + 2001, 999);
  14659. else if (offset == rand2.size())
  14660. sink.done();
  14661. return true;
  14662. },
  14663. "filename4",
  14664. {}});
  14665. {
  14666. auto res = cli.Post("/post-providers", {}, {}, providers);
  14667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14668. ASSERT_EQ(StatusCode::OK_200, res->status);
  14669. }
  14670. {
  14671. auto res = cli.Post("/post-both", {}, items, providers);
  14672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14673. ASSERT_EQ(StatusCode::OK_200, res->status);
  14674. }
  14675. }
  14676. }
  14677. TEST(MultipartFormDataTest, BadHeader) {
  14678. Server svr;
  14679. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14680. res.set_content("ok", "text/plain");
  14681. });
  14682. thread t = thread([&] { svr.listen(HOST, PORT); });
  14683. auto se = detail::scope_exit([&] {
  14684. svr.stop();
  14685. t.join();
  14686. ASSERT_FALSE(svr.is_running());
  14687. });
  14688. svr.wait_until_ready();
  14689. const std::string body =
  14690. "This is the preamble. It is to be ignored, though it\r\n"
  14691. "is a handy place for composition agents to include an\r\n"
  14692. "explanatory note to non-MIME conformant readers.\r\n"
  14693. "\r\n"
  14694. "\r\n"
  14695. "--simple boundary\r\n"
  14696. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14697. ": BAD...\r\n"
  14698. "\r\n"
  14699. "value1\r\n"
  14700. "--simple boundary\r\n"
  14701. "Content-Disposition: form-data; name=\"field2\"; "
  14702. "filename=\"example.txt\"\r\n"
  14703. "\r\n"
  14704. "value2\r\n"
  14705. "--simple boundary--\r\n"
  14706. "This is the epilogue. It is also to be ignored.\r\n";
  14707. std::string content_type =
  14708. R"(multipart/form-data; boundary="simple boundary")";
  14709. Client cli(HOST, PORT);
  14710. auto res = cli.Post("/post", body, content_type.c_str());
  14711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14712. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14713. }
  14714. TEST(MultipartFormDataTest, WithPreamble) {
  14715. Server svr;
  14716. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14717. res.set_content("ok", "text/plain");
  14718. });
  14719. thread t = thread([&] { svr.listen(HOST, PORT); });
  14720. auto se = detail::scope_exit([&] {
  14721. svr.stop();
  14722. t.join();
  14723. ASSERT_FALSE(svr.is_running());
  14724. });
  14725. svr.wait_until_ready();
  14726. const std::string body =
  14727. "This is the preamble. It is to be ignored, though it\r\n"
  14728. "is a handy place for composition agents to include an\r\n"
  14729. "explanatory note to non-MIME conformant readers.\r\n"
  14730. "\r\n"
  14731. "\r\n"
  14732. "--simple boundary\r\n"
  14733. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14734. "\r\n"
  14735. "value1\r\n"
  14736. "--simple boundary\r\n"
  14737. "Content-Disposition: form-data; name=\"field2\"; "
  14738. "filename=\"example.txt\"\r\n"
  14739. "\r\n"
  14740. "value2\r\n"
  14741. "--simple boundary--\r\n"
  14742. "This is the epilogue. It is also to be ignored.\r\n";
  14743. std::string content_type =
  14744. R"(multipart/form-data; boundary="simple boundary")";
  14745. Client cli(HOST, PORT);
  14746. auto res = cli.Post("/post", body, content_type.c_str());
  14747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14748. EXPECT_EQ(StatusCode::OK_200, res->status);
  14749. }
  14750. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14751. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14752. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14753. const ContentReader &content_reader) {
  14754. if (req.is_multipart_form_data()) {
  14755. std::vector<FormData> items;
  14756. content_reader(
  14757. [&](const FormData &file) {
  14758. items.push_back(file);
  14759. return true;
  14760. },
  14761. [&](const char *data, size_t data_length) {
  14762. items.back().content.append(data, data_length);
  14763. return true;
  14764. });
  14765. EXPECT_TRUE(std::string(items[0].name) == "document");
  14766. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14767. EXPECT_TRUE(items[0].filename == "2MB_data");
  14768. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14769. EXPECT_TRUE(items[1].name == "hello");
  14770. EXPECT_TRUE(items[1].content == "world");
  14771. EXPECT_TRUE(items[1].filename == "");
  14772. EXPECT_TRUE(items[1].content_type == "");
  14773. } else {
  14774. std::string body;
  14775. content_reader([&](const char *data, size_t data_length) {
  14776. body.append(data, data_length);
  14777. return true;
  14778. });
  14779. }
  14780. });
  14781. auto port = svr.bind_to_any_port("localhost");
  14782. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14783. auto se = detail::scope_exit([&] {
  14784. svr.stop();
  14785. t.join();
  14786. ASSERT_FALSE(svr.is_running());
  14787. });
  14788. svr.wait_until_ready();
  14789. {
  14790. std::string data(1024 * 1024 * 2, '.');
  14791. std::stringstream buffer;
  14792. buffer << data;
  14793. SSLClient cli("localhost", port);
  14794. cli.enable_server_certificate_verification(false);
  14795. UploadFormDataItems items{
  14796. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14797. {"hello", "world", "", ""},
  14798. };
  14799. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14801. ASSERT_EQ(StatusCode::OK_200, res->status);
  14802. }
  14803. }
  14804. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14805. std::string data(1024 * 1024 * 2, '&');
  14806. std::stringstream buffer;
  14807. buffer << data;
  14808. Client cli("https://localhost:8080");
  14809. UploadFormDataItems items{
  14810. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14811. {"hello", "world", "", ""},
  14812. };
  14813. for (const char &c : " \t\r\n") {
  14814. auto res =
  14815. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14816. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14817. ASSERT_FALSE(res);
  14818. }
  14819. }
  14820. TEST(MultipartFormDataTest, PutFormData) {
  14821. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14822. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14823. const ContentReader &content_reader) {
  14824. if (req.is_multipart_form_data()) {
  14825. std::vector<FormData> items;
  14826. content_reader(
  14827. [&](const FormData &file) {
  14828. items.push_back(file);
  14829. return true;
  14830. },
  14831. [&](const char *data, size_t data_length) {
  14832. items.back().content.append(data, data_length);
  14833. return true;
  14834. });
  14835. EXPECT_TRUE(std::string(items[0].name) == "document");
  14836. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14837. EXPECT_TRUE(items[0].filename == "2MB_data");
  14838. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14839. EXPECT_TRUE(items[1].name == "hello");
  14840. EXPECT_TRUE(items[1].content == "world");
  14841. EXPECT_TRUE(items[1].filename == "");
  14842. EXPECT_TRUE(items[1].content_type == "");
  14843. } else {
  14844. std::string body;
  14845. content_reader([&](const char *data, size_t data_length) {
  14846. body.append(data, data_length);
  14847. return true;
  14848. });
  14849. }
  14850. });
  14851. auto port = svr.bind_to_any_port("localhost");
  14852. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14853. auto se = detail::scope_exit([&] {
  14854. svr.stop();
  14855. t.join();
  14856. ASSERT_FALSE(svr.is_running());
  14857. });
  14858. svr.wait_until_ready();
  14859. {
  14860. std::string data(1024 * 1024 * 2, '&');
  14861. std::stringstream buffer;
  14862. buffer << data;
  14863. SSLClient cli("localhost", port);
  14864. cli.enable_server_certificate_verification(false);
  14865. UploadFormDataItems items{
  14866. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14867. {"hello", "world", "", ""},
  14868. };
  14869. auto res = cli.Put("/put", items);
  14870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14871. ASSERT_EQ(StatusCode::OK_200, res->status);
  14872. }
  14873. }
  14874. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14875. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14876. svr.Put("/put_customboundary",
  14877. [&](const Request &req, const Response & /*res*/,
  14878. const ContentReader &content_reader) {
  14879. if (req.is_multipart_form_data()) {
  14880. std::vector<FormData> items;
  14881. content_reader(
  14882. [&](const FormData &file) {
  14883. items.push_back(file);
  14884. return true;
  14885. },
  14886. [&](const char *data, size_t data_length) {
  14887. items.back().content.append(data, data_length);
  14888. return true;
  14889. });
  14890. EXPECT_TRUE(std::string(items[0].name) == "document");
  14891. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14892. EXPECT_TRUE(items[0].filename == "2MB_data");
  14893. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14894. EXPECT_TRUE(items[1].name == "hello");
  14895. EXPECT_TRUE(items[1].content == "world");
  14896. EXPECT_TRUE(items[1].filename == "");
  14897. EXPECT_TRUE(items[1].content_type == "");
  14898. } else {
  14899. std::string body;
  14900. content_reader([&](const char *data, size_t data_length) {
  14901. body.append(data, data_length);
  14902. return true;
  14903. });
  14904. }
  14905. });
  14906. auto port = svr.bind_to_any_port("localhost");
  14907. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14908. auto se = detail::scope_exit([&] {
  14909. svr.stop();
  14910. t.join();
  14911. ASSERT_FALSE(svr.is_running());
  14912. });
  14913. svr.wait_until_ready();
  14914. {
  14915. std::string data(1024 * 1024 * 2, '&');
  14916. std::stringstream buffer;
  14917. buffer << data;
  14918. SSLClient cli("localhost", port);
  14919. cli.enable_server_certificate_verification(false);
  14920. UploadFormDataItems items{
  14921. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14922. {"hello", "world", "", ""},
  14923. };
  14924. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14926. ASSERT_EQ(StatusCode::OK_200, res->status);
  14927. }
  14928. }
  14929. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14930. std::string data(1024 * 1024 * 2, '&');
  14931. std::stringstream buffer;
  14932. buffer << data;
  14933. Client cli("https://localhost:8080");
  14934. cli.enable_server_certificate_verification(false);
  14935. UploadFormDataItems items{
  14936. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14937. {"hello", "world", "", ""},
  14938. };
  14939. for (const char &c : " \t\r\n") {
  14940. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14941. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14942. ASSERT_FALSE(res);
  14943. }
  14944. }
  14945. TEST(MultipartFormDataTest, AlternateFilename) {
  14946. auto handled = false;
  14947. Server svr;
  14948. svr.Post("/test", [&](const Request &req, Response &res) {
  14949. ASSERT_EQ(2u, req.form.files.size());
  14950. ASSERT_EQ(1u, req.form.fields.size());
  14951. // Test files
  14952. const auto &file1 = req.form.get_file("file1");
  14953. ASSERT_EQ("file1", file1.name);
  14954. ASSERT_EQ("A.txt", file1.filename);
  14955. ASSERT_EQ("text/plain", file1.content_type);
  14956. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14957. const auto &file2 = req.form.get_file("file2");
  14958. ASSERT_EQ("file2", file2.name);
  14959. ASSERT_EQ("a.html", file2.filename);
  14960. ASSERT_EQ("text/html", file2.content_type);
  14961. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14962. file2.content);
  14963. // Test text field
  14964. const auto &text = req.form.get_field("text");
  14965. ASSERT_EQ("text default", text);
  14966. res.set_content("ok", "text/plain");
  14967. handled = true;
  14968. });
  14969. thread t = thread([&] { svr.listen(HOST, PORT); });
  14970. auto se = detail::scope_exit([&] {
  14971. svr.stop();
  14972. t.join();
  14973. ASSERT_FALSE(svr.is_running());
  14974. ASSERT_TRUE(handled);
  14975. });
  14976. svr.wait_until_ready();
  14977. auto req = "POST /test HTTP/1.1\r\n"
  14978. "Host: localhost\r\n"
  14979. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14980. "Content-Length: 399\r\n"
  14981. "\r\n"
  14982. "----------\r\n"
  14983. "Content-Disposition: form-data; name=\"text\"\r\n"
  14984. "\r\n"
  14985. "text default\r\n"
  14986. "----------\r\n"
  14987. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14988. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14989. "Content-Type: text/plain\r\n"
  14990. "\r\n"
  14991. "Content of a.txt.\r\n"
  14992. "\r\n"
  14993. "----------\r\n"
  14994. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14995. "\"a.html\"\r\n"
  14996. "Content-Type: text/html\r\n"
  14997. "\r\n"
  14998. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14999. "\r\n"
  15000. "------------\r\n";
  15001. ASSERT_TRUE(send_request(1, req));
  15002. }
  15003. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15004. auto handled = false;
  15005. Server svr;
  15006. svr.Post("/test", [&](const Request &req, Response &res) {
  15007. // Case-insensitive "utf-8''" prefix with a long value
  15008. const auto &file = req.form.get_file("file1");
  15009. ASSERT_EQ("file1", file.name);
  15010. // 8000 chars exercises both the Content-Disposition parser and the
  15011. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15012. // Prior to the fix, std::regex_match on this header would cause O(N)
  15013. // stack recursion in libstdc++, leading to SIGSEGV.
  15014. std::string expected_filename(8000, 'A');
  15015. ASSERT_EQ(expected_filename, file.filename);
  15016. res.set_content("ok", "text/plain");
  15017. handled = true;
  15018. });
  15019. thread t = thread([&] { svr.listen(HOST, PORT); });
  15020. auto se = detail::scope_exit([&] {
  15021. svr.stop();
  15022. t.join();
  15023. ASSERT_FALSE(svr.is_running());
  15024. ASSERT_TRUE(handled);
  15025. });
  15026. svr.wait_until_ready();
  15027. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15028. // Regression test for GHSA-qq6v-r583-3h69
  15029. std::string long_filename(8000, 'A');
  15030. std::string body = "----------\r\n"
  15031. "Content-Disposition: form-data; name=\"file1\"; "
  15032. "filename*=\"Utf-8''" +
  15033. long_filename +
  15034. "\"\r\n"
  15035. "\r\n"
  15036. "hello\r\n"
  15037. "------------\r\n";
  15038. auto req = "POST /test HTTP/1.1\r\n"
  15039. "Host: localhost\r\n"
  15040. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15041. "Content-Length: " +
  15042. std::to_string(body.size()) + "\r\n\r\n" + body;
  15043. ASSERT_TRUE(send_request(1, req));
  15044. }
  15045. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15046. auto handled = false;
  15047. Server svr;
  15048. svr.Post("/test", [&](const Request &req, Response &) {
  15049. ASSERT_EQ(2u, req.form.fields.size());
  15050. const auto &text1 = req.form.get_field("text1");
  15051. ASSERT_EQ("text1", text1);
  15052. const auto &text2 = req.form.get_field("text2");
  15053. ASSERT_EQ("text2", text2);
  15054. handled = true;
  15055. });
  15056. thread t = thread([&] { svr.listen(HOST, PORT); });
  15057. auto se = detail::scope_exit([&] {
  15058. svr.stop();
  15059. t.join();
  15060. ASSERT_FALSE(svr.is_running());
  15061. ASSERT_TRUE(handled);
  15062. });
  15063. svr.wait_until_ready();
  15064. auto req = "POST /test HTTP/1.1\r\n"
  15065. "Host: localhost\r\n"
  15066. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15067. "Content-Length: 146\r\n"
  15068. "\r\n----------\r\n"
  15069. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15070. "\r\n"
  15071. "text1"
  15072. "\r\n----------\r\n"
  15073. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15074. "\r\n"
  15075. "text2"
  15076. "\r\n------------";
  15077. std::string response;
  15078. ASSERT_TRUE(send_request(1, req, &response));
  15079. ASSERT_EQ("200", response.substr(9, 3));
  15080. }
  15081. TEST(MultipartFormDataTest, ContentLength) {
  15082. auto handled = false;
  15083. Server svr;
  15084. svr.Post("/test", [&](const Request &req, Response &) {
  15085. ASSERT_EQ(2u, req.form.fields.size());
  15086. const auto &text1 = req.form.get_field("text1");
  15087. ASSERT_EQ("text1", text1);
  15088. const auto &text2 = req.form.get_field("text2");
  15089. ASSERT_EQ("text2", text2);
  15090. handled = true;
  15091. });
  15092. thread t = thread([&] { svr.listen(HOST, PORT); });
  15093. auto se = detail::scope_exit([&] {
  15094. svr.stop();
  15095. t.join();
  15096. ASSERT_FALSE(svr.is_running());
  15097. ASSERT_TRUE(handled);
  15098. });
  15099. svr.wait_until_ready();
  15100. auto req = "POST /test HTTP/1.1\r\n"
  15101. "Host: localhost\r\n"
  15102. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15103. "Content-Length: 167\r\n"
  15104. "\r\n----------\r\n"
  15105. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15106. "Content-Length: 5\r\n"
  15107. "\r\n"
  15108. "text1"
  15109. "\r\n----------\r\n"
  15110. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15111. "\r\n"
  15112. "text2"
  15113. "\r\n------------\r\n";
  15114. std::string response;
  15115. ASSERT_TRUE(send_request(1, req, &response));
  15116. ASSERT_EQ("200", response.substr(9, 3));
  15117. }
  15118. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15119. auto handled = false;
  15120. Server svr;
  15121. svr.Post("/test", [&](const Request &req, Response &) {
  15122. ASSERT_EQ(2u, req.form.fields.size());
  15123. const auto &text1 = req.form.get_field("text1");
  15124. ASSERT_EQ("text1", text1);
  15125. // TODO: Add header access for text fields if needed
  15126. const auto &text2 = req.form.get_field("text2");
  15127. ASSERT_EQ("text2", text2);
  15128. // TODO: Header access for text fields needs to be implemented
  15129. // auto &headers = it->second.headers;
  15130. // ASSERT_EQ(3U, headers.size());
  15131. // auto custom_header = headers.find("x-whatever");
  15132. // ASSERT_TRUE(custom_header != headers.end());
  15133. // ASSERT_NE("customvalue", custom_header->second);
  15134. // ASSERT_EQ("CustomValue", custom_header->second);
  15135. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15136. handled = true;
  15137. });
  15138. thread t = thread([&] { svr.listen(HOST, PORT); });
  15139. auto se = detail::scope_exit([&] {
  15140. svr.stop();
  15141. t.join();
  15142. ASSERT_FALSE(svr.is_running());
  15143. ASSERT_TRUE(handled);
  15144. });
  15145. svr.wait_until_ready();
  15146. auto req = "POST /test HTTP/1.1\r\n"
  15147. "Host: localhost\r\n"
  15148. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15149. "Content-Length: 232\r\n"
  15150. "\r\n----------\r\n"
  15151. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15152. "Content-Length: 5\r\n"
  15153. "X-Test: 1\r\n"
  15154. "\r\n"
  15155. "text1"
  15156. "\r\n----------\r\n"
  15157. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15158. "Content-Type: text/plain\r\n"
  15159. "X-Whatever: CustomValue\r\n"
  15160. "\r\n"
  15161. "text2"
  15162. "\r\n------------\r\n"
  15163. "That should be disregarded. Not even read";
  15164. std::string response;
  15165. ASSERT_TRUE(send_request(1, req, &response));
  15166. ASSERT_EQ("200", response.substr(9, 3));
  15167. }
  15168. TEST(MultipartFormDataTest, LargeHeader) {
  15169. auto handled = false;
  15170. Server svr;
  15171. svr.Post("/test", [&](const Request &req, Response &) {
  15172. ASSERT_EQ(1u, req.form.fields.size());
  15173. const auto &text = req.form.get_field("name1");
  15174. ASSERT_EQ("text1", text);
  15175. handled = true;
  15176. });
  15177. thread t = thread([&] { svr.listen(HOST, PORT); });
  15178. auto se = detail::scope_exit([&] {
  15179. svr.stop();
  15180. t.join();
  15181. ASSERT_FALSE(svr.is_running());
  15182. ASSERT_TRUE(handled);
  15183. });
  15184. svr.wait_until_ready();
  15185. auto boundary = std::string("cpp-httplib-multipart-data");
  15186. std::string content = "--" + boundary +
  15187. "\r\n"
  15188. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15189. "\r\n"
  15190. "text1\r\n"
  15191. "--" +
  15192. boundary + "--\r\n";
  15193. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15194. "Host: localhost\r\n"
  15195. "Content-Type: multipart/form-data;boundary=" +
  15196. boundary +
  15197. "\r\n"
  15198. "Content-Length: " +
  15199. std::to_string(content.size()) +
  15200. "\r\n"
  15201. "Dummy-Header: ";
  15202. std::string header_suffix = "\r\n"
  15203. "\r\n";
  15204. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15205. size_t header_dummy_size =
  15206. read_buff_size -
  15207. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15208. auto header_dummy = std::string(header_dummy_size, '@');
  15209. auto req = header_prefix + header_dummy + header_suffix + content;
  15210. std::string response;
  15211. ASSERT_TRUE(send_request(1, req, &response));
  15212. ASSERT_EQ("200", response.substr(9, 3));
  15213. }
  15214. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15215. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15216. // (not chunked Transfer-Encoding) after the streaming refactor.
  15217. auto handled = false;
  15218. Server svr;
  15219. svr.Post("/upload", [&](const Request &req, Response &res) {
  15220. auto cl_it = req.headers.find("Content-Length");
  15221. EXPECT_TRUE(cl_it != req.headers.end());
  15222. auto te_it = req.headers.find("Transfer-Encoding");
  15223. EXPECT_TRUE(te_it == req.headers.end());
  15224. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15225. res.set_content("ok", "text/plain");
  15226. handled = true;
  15227. });
  15228. auto port = svr.bind_to_any_port(HOST);
  15229. auto t = thread([&] { svr.listen_after_bind(); });
  15230. auto se = detail::scope_exit([&] {
  15231. svr.stop();
  15232. t.join();
  15233. ASSERT_FALSE(svr.is_running());
  15234. ASSERT_TRUE(handled);
  15235. });
  15236. svr.wait_until_ready();
  15237. UploadFormDataItems items = {
  15238. {"field1", "hello", "", "text/plain"},
  15239. {"file1", "world", "test.txt", "application/octet-stream"},
  15240. };
  15241. Client cli(HOST, port);
  15242. auto res = cli.Post("/upload", {}, items);
  15243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15244. EXPECT_EQ(StatusCode::OK_200, res->status);
  15245. }
  15246. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15247. // Verify that make_multipart_content_provider coalesces many small segments
  15248. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15249. constexpr size_t kItemCount = 1000;
  15250. UploadFormDataItems items;
  15251. items.reserve(kItemCount);
  15252. for (size_t i = 0; i < kItemCount; i++) {
  15253. items.push_back(
  15254. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15255. }
  15256. const std::string boundary = "----test-boundary";
  15257. auto content_length = detail::get_multipart_content_length(items, boundary);
  15258. auto provider = detail::make_multipart_content_provider(items, boundary);
  15259. // Drive the provider the same way write_content_with_progress does
  15260. size_t write_count = 0;
  15261. size_t total_bytes = 0;
  15262. DataSink sink;
  15263. size_t offset = 0;
  15264. sink.write = [&](const char *d, size_t l) -> bool {
  15265. (void)d;
  15266. write_count++;
  15267. total_bytes += l;
  15268. offset += l;
  15269. return true;
  15270. };
  15271. sink.is_writable = []() -> bool { return true; };
  15272. while (offset < content_length) {
  15273. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15274. }
  15275. EXPECT_EQ(content_length, total_bytes);
  15276. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15277. // With buffering into 64KB blocks, write_count should be much smaller.
  15278. auto segment_count = 3 * kItemCount + 1;
  15279. EXPECT_LT(write_count, segment_count / 10);
  15280. }
  15281. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15282. // Integration test: send many UploadFormDataItems and verify the server
  15283. // receives all of them correctly (#2410).
  15284. constexpr size_t kItemCount = 500;
  15285. auto handled = false;
  15286. Server svr;
  15287. svr.Post("/upload", [&](const Request &req, Response &res) {
  15288. EXPECT_EQ(kItemCount, req.form.fields.size());
  15289. for (size_t i = 0; i < kItemCount; i++) {
  15290. auto key = "field" + std::to_string(i);
  15291. auto val = "value" + std::to_string(i);
  15292. auto it = req.form.fields.find(key);
  15293. if (it != req.form.fields.end()) {
  15294. EXPECT_EQ(val, it->second.content);
  15295. } else {
  15296. ADD_FAILURE() << "Missing field: " << key;
  15297. }
  15298. }
  15299. res.set_content("ok", "text/plain");
  15300. handled = true;
  15301. });
  15302. auto port = svr.bind_to_any_port(HOST);
  15303. auto t = thread([&] { svr.listen_after_bind(); });
  15304. auto se = detail::scope_exit([&] {
  15305. svr.stop();
  15306. t.join();
  15307. ASSERT_FALSE(svr.is_running());
  15308. ASSERT_TRUE(handled);
  15309. });
  15310. svr.wait_until_ready();
  15311. UploadFormDataItems items;
  15312. items.reserve(kItemCount);
  15313. for (size_t i = 0; i < kItemCount; i++) {
  15314. items.push_back(
  15315. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15316. }
  15317. Client cli(HOST, port);
  15318. auto res = cli.Post("/upload", items);
  15319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15320. EXPECT_EQ(StatusCode::OK_200, res->status);
  15321. }
  15322. TEST(MultipartFormDataTest, MakeFileProvider) {
  15323. // Verify make_file_provider sends a file's contents correctly.
  15324. const std::string file_content(4096, 'Z');
  15325. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15326. {
  15327. std::ofstream ofs(tmp_path, std::ios::binary);
  15328. ofs.write(file_content.data(),
  15329. static_cast<std::streamsize>(file_content.size()));
  15330. }
  15331. auto handled = false;
  15332. Server svr;
  15333. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15334. const ContentReader &content_reader) {
  15335. ASSERT_TRUE(req.is_multipart_form_data());
  15336. std::vector<FormData> items;
  15337. content_reader(
  15338. [&](const FormData &file) {
  15339. items.push_back(file);
  15340. return true;
  15341. },
  15342. [&](const char *data, size_t data_length) {
  15343. items.back().content.append(data, data_length);
  15344. return true;
  15345. });
  15346. ASSERT_EQ(1u, items.size());
  15347. EXPECT_EQ("myfile", items[0].name);
  15348. EXPECT_EQ("data.bin", items[0].filename);
  15349. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15350. EXPECT_EQ(file_content, items[0].content);
  15351. handled = true;
  15352. });
  15353. auto port = svr.bind_to_any_port(HOST);
  15354. auto t = thread([&] { svr.listen_after_bind(); });
  15355. auto se = detail::scope_exit([&] {
  15356. svr.stop();
  15357. t.join();
  15358. ASSERT_FALSE(svr.is_running());
  15359. ASSERT_TRUE(handled);
  15360. std::remove(tmp_path.c_str());
  15361. });
  15362. svr.wait_until_ready();
  15363. FormDataProviderItems providers;
  15364. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15365. "application/octet-stream"));
  15366. Client cli(HOST, port);
  15367. auto res = cli.Post("/upload", {}, {}, providers);
  15368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15369. EXPECT_EQ(StatusCode::OK_200, res->status);
  15370. }
  15371. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15372. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15373. // (100) headers is rejected with a 400 Bad Request response.
  15374. Server svr;
  15375. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15376. res.set_content("ok", "text/plain");
  15377. });
  15378. thread t = thread([&] { svr.listen(HOST, PORT); });
  15379. auto se = detail::scope_exit([&] {
  15380. svr.stop();
  15381. t.join();
  15382. ASSERT_FALSE(svr.is_running());
  15383. });
  15384. svr.wait_until_ready();
  15385. // Build a multipart part with 101 custom headers (exceeding
  15386. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15387. std::stringstream body;
  15388. body << "--simpleboundary\r\n"
  15389. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15390. for (int i = 0; i < 101; i++) {
  15391. body << "X-Custom-Header-" << i << ": value\r\n";
  15392. }
  15393. body << "\r\n"
  15394. << "value1\r\n"
  15395. << "--simpleboundary--\r\n";
  15396. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15397. Client cli(HOST, PORT);
  15398. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15400. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15401. }
  15402. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15403. // A body that never contains the declared boundary must not be accumulated
  15404. // while the parser waits for it. Buffering it would also make every read
  15405. // rescan everything seen so far, which is quadratic in the body size.
  15406. Server svr;
  15407. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15408. res.set_content("ok", "text/plain");
  15409. });
  15410. auto port = svr.bind_to_any_port(HOST);
  15411. thread t = thread([&] { svr.listen_after_bind(); });
  15412. auto se = detail::scope_exit([&] {
  15413. svr.stop();
  15414. t.join();
  15415. ASSERT_FALSE(svr.is_running());
  15416. });
  15417. svr.wait_until_ready();
  15418. Client cli(HOST, port);
  15419. cli.set_read_timeout(60, 0);
  15420. cli.set_write_timeout(60, 0);
  15421. // '-' is the worst case: it matches the first character of the boundary, so
  15422. // every position has to be checked against it.
  15423. auto post_dashes = [&](size_t size) {
  15424. const std::string body(size, '-');
  15425. auto start = std::chrono::steady_clock::now();
  15426. auto res =
  15427. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15428. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15429. std::chrono::steady_clock::now() - start)
  15430. .count();
  15431. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15432. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15433. return ms;
  15434. };
  15435. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15436. // Windows.
  15437. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15438. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15439. // Comparing the two sizes rather than checking an absolute duration keeps
  15440. // this meaningful across build types and CI load, both of which move the
  15441. // absolute numbers by more than an order of magnitude. Four times the bytes
  15442. // costs about four times the time when parsing is linear, and about sixteen
  15443. // times when the body is buffered and rescanned.
  15444. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15445. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15446. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15447. << "ms, which suggests the body is being buffered and rescanned";
  15448. }
  15449. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15450. // A boundary can only be followed by CRLF or by "--", so anything else is
  15451. // malformed no matter what comes next. The parser must say so right away
  15452. // instead of buffering the rest of the declared body.
  15453. Server svr;
  15454. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15455. res.set_content("ok", "text/plain");
  15456. });
  15457. auto port = svr.bind_to_any_port(HOST);
  15458. thread t = thread([&] { svr.listen_after_bind(); });
  15459. auto se = detail::scope_exit([&] {
  15460. svr.stop();
  15461. t.join();
  15462. ASSERT_FALSE(svr.is_running());
  15463. });
  15464. svr.wait_until_ready();
  15465. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15466. // buffers instead of failing would still be waiting for the remaining bytes.
  15467. const std::string body = "--zzzz\r\n"
  15468. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15469. "\r\n"
  15470. "text1"
  15471. "\r\n--zzzzXX";
  15472. const std::string req = "POST /post HTTP/1.1\r\n"
  15473. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15474. "Content-Length: 1048576\r\n"
  15475. "\r\n" +
  15476. body;
  15477. std::string response;
  15478. ASSERT_TRUE(send_request(3, req, &response, port));
  15479. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15480. EXPECT_EQ("400", response.substr(9, 3));
  15481. }
  15482. // Posts a multipart body split into two writes, so that the server sees the
  15483. // split at whatever offset the caller chose, and expects the single "text1"
  15484. // field to come through.
  15485. static void expect_split_multipart_ok(const std::string &body1,
  15486. const std::string &body2) {
  15487. auto handled = false;
  15488. Server svr;
  15489. svr.Post("/post", [&](const Request &req, Response &) {
  15490. EXPECT_EQ(1u, req.form.fields.size());
  15491. EXPECT_EQ("text1", req.form.get_field("text1"));
  15492. handled = true;
  15493. });
  15494. auto port = svr.bind_to_any_port(HOST);
  15495. thread t = thread([&] { svr.listen_after_bind(); });
  15496. auto se = detail::scope_exit([&] {
  15497. svr.stop();
  15498. t.join();
  15499. ASSERT_FALSE(svr.is_running());
  15500. ASSERT_TRUE(handled);
  15501. });
  15502. svr.wait_until_ready();
  15503. // "Connection: close" makes the server close once it has answered, so the
  15504. // response drain ends immediately instead of idling until the read timeout.
  15505. const std::string head =
  15506. "POST /post HTTP/1.1\r\n"
  15507. "Host: localhost\r\n"
  15508. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15509. "Connection: close\r\n"
  15510. "Content-Length: " +
  15511. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15512. std::string response;
  15513. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15514. ASSERT_GE(response.size(), 12u) << "no response";
  15515. EXPECT_EQ("200", response.substr(9, 3));
  15516. }
  15517. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15518. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15519. // ignored, including when it does not arrive in the same read as the
  15520. // close-delimiter itself.
  15521. expect_split_multipart_ok("--zzzz\r\n"
  15522. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15523. "\r\n"
  15524. "text1"
  15525. "\r\n--zzzz--",
  15526. "\r\nthis epilogue must be ignored\r\n");
  15527. }
  15528. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15529. // The initial boundary may be preceded by a preamble of any length and may
  15530. // straddle a read boundary. Discarding data while waiting for it must not
  15531. // throw away a partial boundary sitting at the end of the buffer.
  15532. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15533. "zz\r\n"
  15534. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15535. "\r\n"
  15536. "text1"
  15537. "\r\n--zzzz--\r\n");
  15538. }
  15539. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15540. // The received boundary was only checked for being non-empty, so it could be
  15541. // as long as a header is allowed to be. The parser scans the body for
  15542. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15543. // costs a nearly full comparison at nearly every position, making the
  15544. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15545. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15546. Server svr;
  15547. svr.Post("/post", [](const Request &req, Response &res) {
  15548. EXPECT_EQ(1u, req.form.fields.size());
  15549. EXPECT_EQ("text1", req.form.get_field("text1"));
  15550. res.set_content("ok", "text/plain");
  15551. });
  15552. auto port = svr.bind_to_any_port(HOST);
  15553. thread t = thread([&] { svr.listen_after_bind(); });
  15554. auto se = detail::scope_exit([&] {
  15555. svr.stop();
  15556. t.join();
  15557. ASSERT_FALSE(svr.is_running());
  15558. });
  15559. svr.wait_until_ready();
  15560. Client cli(HOST, port);
  15561. auto post_with_boundary_of_length = [&](size_t len) {
  15562. const std::string boundary(len, 'a');
  15563. const std::string body =
  15564. "--" + boundary +
  15565. "\r\n"
  15566. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15567. "\r\n"
  15568. "text1"
  15569. "\r\n--" +
  15570. boundary + "--\r\n";
  15571. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15572. };
  15573. auto res = post_with_boundary_of_length(70);
  15574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15575. EXPECT_EQ(StatusCode::OK_200, res->status);
  15576. res = post_with_boundary_of_length(71);
  15577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15578. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15579. }
  15580. TEST(MakeFileBodyTest, Basic) {
  15581. const std::string file_content(4096, 'Z');
  15582. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15583. {
  15584. std::ofstream ofs(tmp_path, std::ios::binary);
  15585. ofs.write(file_content.data(),
  15586. static_cast<std::streamsize>(file_content.size()));
  15587. }
  15588. auto handled = false;
  15589. Server svr;
  15590. svr.Post("/upload", [&](const Request &req, Response &res) {
  15591. EXPECT_EQ(file_content, req.body);
  15592. handled = true;
  15593. res.status = StatusCode::OK_200;
  15594. });
  15595. auto port = svr.bind_to_any_port(HOST);
  15596. auto t = thread([&] { svr.listen_after_bind(); });
  15597. auto se = detail::scope_exit([&] {
  15598. svr.stop();
  15599. t.join();
  15600. ASSERT_FALSE(svr.is_running());
  15601. ASSERT_TRUE(handled);
  15602. std::remove(tmp_path.c_str());
  15603. });
  15604. svr.wait_until_ready();
  15605. auto fb = make_file_body(tmp_path);
  15606. ASSERT_GT(fb.first, 0u);
  15607. Client cli(HOST, port);
  15608. auto res =
  15609. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15611. EXPECT_EQ(StatusCode::OK_200, res->status);
  15612. }
  15613. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15614. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15615. {
  15616. std::ofstream ofs(path, std::ios::binary);
  15617. const std::string content(100, 'A');
  15618. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15619. }
  15620. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15621. auto body = make_file_body(path);
  15622. ASSERT_EQ(100u, body.first);
  15623. ASSERT_TRUE(static_cast<bool>(body.second));
  15624. // Rewritten shorter after its length was measured - and, on a server, after
  15625. // that length has already gone out as Content-Length.
  15626. {
  15627. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15628. const std::string content(10, 'A');
  15629. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15630. }
  15631. std::string written;
  15632. DataSink sink;
  15633. sink.write = [&](const char *d, size_t l) {
  15634. written.append(d, l);
  15635. return true;
  15636. };
  15637. // The provider has to report failure. write_content_with_progress() advances
  15638. // its offset only by what was written, so a provider that returns true
  15639. // without completing the length it promised is called again straight away,
  15640. // and again.
  15641. EXPECT_FALSE(body.second(0, body.first, sink));
  15642. EXPECT_EQ(std::string(10, 'A'), written);
  15643. }
  15644. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15645. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15646. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15647. {
  15648. std::ofstream ofs(path, std::ios::binary);
  15649. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15650. }
  15651. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15652. auto body = make_file_body(path);
  15653. ASSERT_EQ(content.size(), body.first);
  15654. ASSERT_TRUE(static_cast<bool>(body.second));
  15655. std::string written;
  15656. DataSink sink;
  15657. sink.write = [&](const char *d, size_t l) {
  15658. written.append(d, l);
  15659. return true;
  15660. };
  15661. EXPECT_TRUE(body.second(0, body.first, sink));
  15662. EXPECT_EQ(content, written);
  15663. }
  15664. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15665. static constexpr unsigned int number_of_tasks{1000000};
  15666. std::atomic_uint count{0};
  15667. std::unique_ptr<TaskQueue> task_queue{
  15668. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15669. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15670. auto queued = task_queue->enqueue(
  15671. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15672. EXPECT_TRUE(queued);
  15673. }
  15674. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15675. task_queue->shutdown();
  15676. #else
  15677. EXPECT_NO_THROW(task_queue->shutdown());
  15678. #endif
  15679. EXPECT_EQ(number_of_tasks, count.load());
  15680. }
  15681. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15682. static constexpr unsigned int number_of_tasks{1000000};
  15683. static constexpr unsigned int qlimit{2};
  15684. unsigned int queued_count{0};
  15685. std::atomic_uint count{0};
  15686. std::unique_ptr<TaskQueue> task_queue{
  15687. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15688. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15689. if (task_queue->enqueue(
  15690. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15691. queued_count++;
  15692. }
  15693. }
  15694. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15695. task_queue->shutdown();
  15696. #else
  15697. EXPECT_NO_THROW(task_queue->shutdown());
  15698. #endif
  15699. EXPECT_EQ(queued_count, count.load());
  15700. EXPECT_TRUE(queued_count <= number_of_tasks);
  15701. EXPECT_TRUE(queued_count >= qlimit);
  15702. }
  15703. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15704. // Use a short idle timeout so a dynamic thread spawns, times out and
  15705. // exits during the test, and the pool keeps working afterwards.
  15706. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15707. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15708. /*idle_timeout_sec=*/1}};
  15709. std::atomic_uint count{0};
  15710. std::condition_variable cv;
  15711. std::mutex mtx;
  15712. bool release = false;
  15713. // Block the base thread so the second task spawns a dynamic thread.
  15714. EXPECT_TRUE(task_queue->enqueue([&] {
  15715. std::unique_lock<std::mutex> lock(mtx);
  15716. while (!release) {
  15717. cv.wait(lock);
  15718. }
  15719. count++;
  15720. }));
  15721. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15722. // Let the dynamic thread finish its task and exceed the idle timeout.
  15723. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15724. {
  15725. std::unique_lock<std::mutex> lock(mtx);
  15726. release = true;
  15727. }
  15728. cv.notify_all();
  15729. // The pool must still accept and run tasks after the dynamic thread exited.
  15730. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15731. task_queue->shutdown();
  15732. EXPECT_EQ(3u, count.load());
  15733. }
  15734. TEST(TaskQueueTest, MaxQueuedRequests) {
  15735. static constexpr unsigned int qlimit{3};
  15736. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15737. std::condition_variable sem_cv;
  15738. std::mutex sem_mtx;
  15739. int credits = 0;
  15740. bool queued;
  15741. /* Fill up the queue with tasks that will block until we give them credits to
  15742. * complete. */
  15743. for (unsigned int n = 0; n <= qlimit;) {
  15744. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15745. std::unique_lock<std::mutex> lock(sem_mtx);
  15746. while (credits <= 0) {
  15747. sem_cv.wait(lock);
  15748. }
  15749. /* Consume the credit and signal the test code if they are all gone. */
  15750. if (--credits == 0) { sem_cv.notify_one(); }
  15751. });
  15752. if (n < qlimit) {
  15753. /* The first qlimit enqueues must succeed. */
  15754. EXPECT_TRUE(queued);
  15755. } else {
  15756. /* The last one will succeed only when the worker thread
  15757. * starts and dequeues the first blocking task. Although
  15758. * not necessary for the correctness of this test, we sleep for
  15759. * a short while to avoid busy waiting. */
  15760. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15761. }
  15762. if (queued) { n++; }
  15763. }
  15764. /* Further enqueues must fail since the queue is full. */
  15765. for (auto i = 0; i < 4; i++) {
  15766. queued = task_queue->enqueue([] {});
  15767. EXPECT_FALSE(queued);
  15768. }
  15769. /* Give the credits to allow the previous tasks to complete. */
  15770. {
  15771. std::unique_lock<std::mutex> lock(sem_mtx);
  15772. credits += qlimit + 1;
  15773. }
  15774. sem_cv.notify_all();
  15775. /* Wait for all the credits to be consumed. */
  15776. {
  15777. std::unique_lock<std::mutex> lock(sem_mtx);
  15778. while (credits > 0) {
  15779. sem_cv.wait(lock);
  15780. }
  15781. }
  15782. /* Check that we are able again to enqueue at least qlimit tasks. */
  15783. for (unsigned int i = 0; i < qlimit; i++) {
  15784. queued = task_queue->enqueue([] {});
  15785. EXPECT_TRUE(queued);
  15786. }
  15787. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15788. task_queue->shutdown();
  15789. #else
  15790. EXPECT_NO_THROW(task_queue->shutdown());
  15791. #endif
  15792. }
  15793. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15794. Server svr;
  15795. std::string method;
  15796. std::string body;
  15797. auto has_content_length = false;
  15798. auto has_transfer_encoding = false;
  15799. std::atomic<int> bad_requests{0};
  15800. // Leftover body bytes get parsed as a malformed request and answered with
  15801. // 400
  15802. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15803. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15804. });
  15805. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15806. res.set_redirect("/down", StatusCode::SeeOther_303);
  15807. });
  15808. svr.Get("/down", [&](const Request &req, Response &res) {
  15809. method = req.method;
  15810. body = req.body;
  15811. has_content_length = req.has_header("Content-Length");
  15812. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15813. res.set_content("ok", "text/plain");
  15814. });
  15815. auto port = svr.bind_to_any_port(HOST);
  15816. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15817. auto se = detail::scope_exit([&] {
  15818. svr.stop();
  15819. thread.join();
  15820. ASSERT_FALSE(svr.is_running());
  15821. });
  15822. svr.wait_until_ready();
  15823. const std::string payload = "SECRET-BODY";
  15824. auto check = [&](Client &cli, const Result &res) {
  15825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15826. EXPECT_EQ(StatusCode::OK_200, res->status);
  15827. EXPECT_EQ("ok", res->body);
  15828. EXPECT_EQ("GET", method);
  15829. EXPECT_TRUE(body.empty());
  15830. EXPECT_FALSE(has_content_length);
  15831. EXPECT_FALSE(has_transfer_encoding);
  15832. // Nothing of the original body may be left on the connection
  15833. auto res2 = cli.Get("/down");
  15834. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15835. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15836. EXPECT_EQ("ok", res2->body);
  15837. EXPECT_EQ(0, bad_requests);
  15838. };
  15839. // With content length
  15840. {
  15841. Client cli(HOST, port);
  15842. cli.set_keep_alive(true);
  15843. cli.set_follow_location(true);
  15844. auto res = cli.Post(
  15845. "/up", payload.size(),
  15846. [&](size_t offset, size_t length, DataSink &sink) {
  15847. return sink.write(payload.data() + offset, length);
  15848. },
  15849. "text/plain");
  15850. check(cli, res);
  15851. }
  15852. // Without content length (chunked)
  15853. {
  15854. Client cli(HOST, port);
  15855. cli.set_keep_alive(true);
  15856. cli.set_follow_location(true);
  15857. auto res = cli.Post(
  15858. "/up",
  15859. [&](size_t /*offset*/, DataSink &sink) {
  15860. sink.write(payload.data(), payload.size());
  15861. sink.done();
  15862. return true;
  15863. },
  15864. "text/plain");
  15865. check(cli, res);
  15866. }
  15867. }
  15868. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15869. Server svr;
  15870. std::string target;
  15871. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15872. // Echo the still-encoded name back in the Location
  15873. const std::string prefix = "/start/";
  15874. res.status = StatusCode::Found_302;
  15875. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15876. });
  15877. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15878. target = req.target;
  15879. res.set_content("ok", "text/plain");
  15880. });
  15881. auto port = svr.bind_to_any_port(HOST);
  15882. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15883. auto se = detail::scope_exit([&] {
  15884. svr.stop();
  15885. thread.join();
  15886. ASSERT_FALSE(svr.is_running());
  15887. });
  15888. svr.wait_until_ready();
  15889. // Decoding the Location path would turn the first four into a path
  15890. // separator, a query delimiter, a fragment delimiter and a different
  15891. // percent-encoded octet. The rest must keep reaching the server as they are.
  15892. const std::vector<std::string> names = {
  15893. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15894. };
  15895. for (auto path_encode : {true, false}) {
  15896. Client cli(HOST, port);
  15897. cli.set_follow_location(true);
  15898. cli.set_path_encode(path_encode);
  15899. for (const auto &name : names) {
  15900. target.clear();
  15901. auto res = cli.Get("/start/" + name);
  15902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15903. EXPECT_EQ(StatusCode::OK_200, res->status);
  15904. EXPECT_EQ("/dest/" + name, target);
  15905. }
  15906. }
  15907. }
  15908. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15909. Server svr;
  15910. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15911. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15912. });
  15913. svr.Get("/hello", [](const Request &req, Response &res) {
  15914. res.set_content(req.get_param_value("key"), "text/plain");
  15915. });
  15916. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15917. auto se = detail::scope_exit([&] {
  15918. svr.stop();
  15919. thread.join();
  15920. ASSERT_FALSE(svr.is_running());
  15921. });
  15922. svr.wait_until_ready();
  15923. {
  15924. Client cli(HOST, PORT);
  15925. cli.set_follow_location(true);
  15926. auto res = cli.Get("/");
  15927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15928. EXPECT_EQ(StatusCode::OK_200, res->status);
  15929. EXPECT_EQ("val&key2=val2", res->body);
  15930. }
  15931. }
  15932. #endif
  15933. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15934. Server svr;
  15935. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15936. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15937. });
  15938. svr.Get("/hello", [](const Request &req, Response &res) {
  15939. res.set_content(req.get_param_value("key"), "text/plain");
  15940. });
  15941. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15942. auto se = detail::scope_exit([&] {
  15943. svr.stop();
  15944. thread.join();
  15945. ASSERT_FALSE(svr.is_running());
  15946. });
  15947. svr.wait_until_ready();
  15948. {
  15949. Client cli(HOST, PORT);
  15950. cli.set_follow_location(true);
  15951. auto res = cli.Get("/");
  15952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15953. EXPECT_EQ(StatusCode::OK_200, res->status);
  15954. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15955. }
  15956. }
  15957. TEST(RedirectTest, RedirectWithPlusInPath) {
  15958. Server svr;
  15959. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15960. res.set_redirect("/a+b");
  15961. });
  15962. // Route pattern uses regex; escape + as \\+
  15963. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15964. res.set_content(req.path, "text/plain");
  15965. });
  15966. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15967. auto se = detail::scope_exit([&] {
  15968. svr.stop();
  15969. thread.join();
  15970. ASSERT_FALSE(svr.is_running());
  15971. });
  15972. svr.wait_until_ready();
  15973. {
  15974. Client cli(HOST, PORT);
  15975. cli.set_follow_location(true);
  15976. auto res = cli.Get("/");
  15977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15978. EXPECT_EQ(StatusCode::OK_200, res->status);
  15979. EXPECT_EQ("/a+b", res->body);
  15980. }
  15981. }
  15982. TEST(RedirectTest, ResolveRelativeLocation) {
  15983. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15984. const std::vector<std::pair<std::string, std::string>> cases = {
  15985. {"g", "/b/c/g"},
  15986. {"./g", "/b/c/g"},
  15987. {"g/", "/b/c/g/"},
  15988. {"?y", "/b/c/d;p?y"},
  15989. {"g?y", "/b/c/g?y"},
  15990. {"#s", "/b/c/d;p?q#s"},
  15991. {"g#s", "/b/c/g#s"},
  15992. {"g?y#s", "/b/c/g?y#s"},
  15993. {";x", "/b/c/;x"},
  15994. {"g;x", "/b/c/g;x"},
  15995. {".", "/b/c/"},
  15996. {"./", "/b/c/"},
  15997. {"..", "/b/"},
  15998. {"../", "/b/"},
  15999. {"../g", "/b/g"},
  16000. {"../..", "/"},
  16001. {"../../", "/"},
  16002. {"../../g", "/g"},
  16003. {"../../../g", "/g"},
  16004. {"g.", "/b/c/g."},
  16005. {".g", "/b/c/.g"},
  16006. {"g..", "/b/c/g.."},
  16007. {"..g", "/b/c/..g"},
  16008. {"./../g", "/b/g"},
  16009. {"./g/.", "/b/c/g/"},
  16010. {"g/./h", "/b/c/g/h"},
  16011. {"g/../h", "/b/c/h"},
  16012. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16013. {"g;x=1/../y", "/b/c/y"},
  16014. {"g?y/./x", "/b/c/g?y/./x"},
  16015. {"g#s/../x", "/b/c/g#s/../x"},
  16016. // Not relative-path references, so left for parse_url.
  16017. {"/g", "/g"},
  16018. {"//g", "//g"},
  16019. {"http://g/x", "http://g/x"},
  16020. {"g:h", "g:h"},
  16021. };
  16022. for (const auto &c : cases) {
  16023. EXPECT_EQ(c.second,
  16024. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16025. << c.first;
  16026. }
  16027. }
  16028. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16029. Server svr;
  16030. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16031. res.set_redirect(req.get_param_value("to"));
  16032. });
  16033. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16034. res.set_content(req.target, "text/plain");
  16035. });
  16036. svr.Get("/other", [](const Request &req, Response &res) {
  16037. res.set_content(req.target, "text/plain");
  16038. });
  16039. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16040. auto se = detail::scope_exit([&] {
  16041. svr.stop();
  16042. thread.join();
  16043. ASSERT_FALSE(svr.is_running());
  16044. });
  16045. svr.wait_until_ready();
  16046. const std::vector<std::pair<std::string, std::string>> cases = {
  16047. {"next", "/dir/next"},
  16048. {"./next?x=1", "/dir/next?x=1"},
  16049. {"../other", "/other"},
  16050. };
  16051. for (const auto &c : cases) {
  16052. Client cli(HOST, PORT);
  16053. cli.set_follow_location(true);
  16054. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16055. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16056. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16057. EXPECT_EQ(c.second, res->body) << c.first;
  16058. }
  16059. }
  16060. #ifdef CPPHTTPLIB_SSL_ENABLED
  16061. TEST(RedirectTest, Issue2185_Online) {
  16062. SSLClient client("github.com");
  16063. client.set_follow_location(true);
  16064. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16065. "Coollab-Windows.zip");
  16066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16067. EXPECT_EQ(StatusCode::OK_200, res->status);
  16068. EXPECT_EQ(9920427U, res->body.size());
  16069. }
  16070. #endif
  16071. TEST(VulnerabilityTest, CRLFInjection) {
  16072. Server svr;
  16073. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16074. res.set_content("Hello 1", "text/plain");
  16075. });
  16076. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16077. res.set_content("Hello 2", "text/plain");
  16078. });
  16079. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16080. res.set_content("Hello 3", "text/plain");
  16081. });
  16082. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16083. res.set_content("Hello 4", "text/plain");
  16084. });
  16085. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16086. for (const auto &x : req.headers) {
  16087. auto key = x.first;
  16088. EXPECT_STRNE("evil", key.c_str());
  16089. }
  16090. });
  16091. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16092. auto se = detail::scope_exit([&] {
  16093. svr.stop();
  16094. thread.join();
  16095. ASSERT_FALSE(svr.is_running());
  16096. });
  16097. svr.wait_until_ready();
  16098. {
  16099. Client cli(HOST, PORT);
  16100. cli.Post("/test1", "A=B",
  16101. "application/x-www-form-urlencoded\r\nevil: hello1");
  16102. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16103. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16104. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16105. }
  16106. }
  16107. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16108. auto server_thread = std::thread([] {
  16109. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16110. default_socket_options(srv);
  16111. sockaddr_in addr{};
  16112. addr.sin_family = AF_INET;
  16113. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16114. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16115. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16116. ::listen(srv, 1);
  16117. sockaddr_in cli_addr{};
  16118. socklen_t cli_len = sizeof(cli_addr);
  16119. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16120. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16121. std::string buf_all;
  16122. char buf[2048];
  16123. ssize_t n;
  16124. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16125. buf_all.append(buf, static_cast<size_t>(n));
  16126. size_t pos;
  16127. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16128. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16129. auto e = request_block.find("\r\n");
  16130. if (e != std::string::npos) {
  16131. auto request_line = request_block.substr(0, e);
  16132. std::string msg =
  16133. "CRLF injection detected in request line: '" + request_line + "'";
  16134. EXPECT_FALSE(true) << msg;
  16135. }
  16136. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16137. ::send(cli,
  16138. #ifdef _WIN32
  16139. static_cast<const char *>(resp.c_str()),
  16140. static_cast<int>(resp.size()),
  16141. #else
  16142. resp.c_str(), resp.size(),
  16143. #endif
  16144. 0);
  16145. buf_all.erase(0, pos + 4);
  16146. }
  16147. }
  16148. detail::close_socket(cli);
  16149. detail::close_socket(srv);
  16150. });
  16151. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16152. auto cli = Client("127.0.0.1", PORT + 1);
  16153. auto headers = Headers{
  16154. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16155. {"Connection", "keep-alive"}};
  16156. auto res = cli.Get("/hi", headers);
  16157. EXPECT_FALSE(res);
  16158. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16159. server_thread.join();
  16160. }
  16161. // A request rejected before any byte reaches the socket must fail right away
  16162. // instead of waiting for a response the server will never send.
  16163. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16164. // The kernel completes the TCP handshake from the listen backlog, so the
  16165. // client connects, but nothing ever reads, responds or closes.
  16166. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16167. default_socket_options(srv);
  16168. sockaddr_in addr{};
  16169. addr.sin_family = AF_INET;
  16170. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16171. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16172. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16173. ASSERT_EQ(0, ::listen(srv, 8));
  16174. auto cli = Client("127.0.0.1", PORT + 1);
  16175. cli.set_read_timeout(10, 0);
  16176. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16177. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16178. std::chrono::steady_clock::now() - start)
  16179. .count();
  16180. };
  16181. {
  16182. Request req;
  16183. req.method = "GE T";
  16184. req.path = "/";
  16185. auto start = std::chrono::steady_clock::now();
  16186. auto res = cli.send(req);
  16187. EXPECT_FALSE(res);
  16188. EXPECT_EQ(Error::Write, res.error());
  16189. EXPECT_LT(elapsed_ms(start), 1000);
  16190. }
  16191. {
  16192. auto start = std::chrono::steady_clock::now();
  16193. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16194. EXPECT_FALSE(res);
  16195. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16196. EXPECT_LT(elapsed_ms(start), 1000);
  16197. }
  16198. EXPECT_FALSE(cli.is_socket_open());
  16199. detail::close_socket(srv);
  16200. }
  16201. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16202. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16203. default_socket_options(srv);
  16204. sockaddr_in addr{};
  16205. addr.sin_family = AF_INET;
  16206. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16207. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16208. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16209. ASSERT_EQ(0, ::listen(srv, 1));
  16210. std::string received;
  16211. auto server_thread = std::thread([&] {
  16212. auto sock = ::accept(srv, nullptr, nullptr);
  16213. if (sock == INVALID_SOCKET) { return; }
  16214. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16215. char buf[2048];
  16216. ssize_t n;
  16217. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16218. received.append(buf, static_cast<size_t>(n));
  16219. }
  16220. detail::close_socket(sock);
  16221. });
  16222. {
  16223. auto cli = Client("127.0.0.1", PORT + 1);
  16224. // "Z" sorts after the default headers, so writing straight to the socket
  16225. // would have sent the request line and those headers before the rejection.
  16226. auto handle =
  16227. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16228. EXPECT_FALSE(handle.is_valid());
  16229. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16230. }
  16231. server_thread.join();
  16232. detail::close_socket(srv);
  16233. EXPECT_TRUE(received.empty()) << received;
  16234. }
  16235. TEST(PathParamsTest, StaticMatch) {
  16236. const auto pattern = "/users/all";
  16237. detail::PathParamsMatcher matcher(pattern);
  16238. Request request;
  16239. request.path = "/users/all";
  16240. ASSERT_TRUE(matcher.match(request));
  16241. std::unordered_map<std::string, std::string> expected_params = {};
  16242. EXPECT_EQ(request.path_params, expected_params);
  16243. }
  16244. TEST(PathParamsTest, StaticMismatch) {
  16245. const auto pattern = "/users/all";
  16246. detail::PathParamsMatcher matcher(pattern);
  16247. Request request;
  16248. request.path = "/users/1";
  16249. ASSERT_FALSE(matcher.match(request));
  16250. }
  16251. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16252. const auto pattern = "/users/:id/subscriptions";
  16253. detail::PathParamsMatcher matcher(pattern);
  16254. Request request;
  16255. request.path = "/users/42/subscriptions";
  16256. ASSERT_TRUE(matcher.match(request));
  16257. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16258. EXPECT_EQ(request.path_params, expected_params);
  16259. }
  16260. TEST(PathParamsTest, SingleParamInTheEnd) {
  16261. const auto pattern = "/users/:id";
  16262. detail::PathParamsMatcher matcher(pattern);
  16263. Request request;
  16264. request.path = "/users/24";
  16265. ASSERT_TRUE(matcher.match(request));
  16266. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16267. EXPECT_EQ(request.path_params, expected_params);
  16268. }
  16269. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16270. const auto pattern = "/users/:id/";
  16271. detail::PathParamsMatcher matcher(pattern);
  16272. Request request;
  16273. request.path = "/users/42/";
  16274. ASSERT_TRUE(matcher.match(request));
  16275. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16276. EXPECT_EQ(request.path_params, expected_params);
  16277. }
  16278. TEST(PathParamsTest, EmptyParam) {
  16279. const auto pattern = "/users/:id/";
  16280. detail::PathParamsMatcher matcher(pattern);
  16281. Request request;
  16282. request.path = "/users//";
  16283. ASSERT_TRUE(matcher.match(request));
  16284. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16285. EXPECT_EQ(request.path_params, expected_params);
  16286. }
  16287. TEST(PathParamsTest, FragmentMismatch) {
  16288. const auto pattern = "/users/:id/";
  16289. detail::PathParamsMatcher matcher(pattern);
  16290. Request request;
  16291. request.path = "/admins/24/";
  16292. ASSERT_FALSE(matcher.match(request));
  16293. }
  16294. TEST(PathParamsTest, ExtraFragments) {
  16295. const auto pattern = "/users/:id";
  16296. detail::PathParamsMatcher matcher(pattern);
  16297. Request request;
  16298. request.path = "/users/42/subscriptions";
  16299. ASSERT_FALSE(matcher.match(request));
  16300. }
  16301. TEST(PathParamsTest, MissingTrailingParam) {
  16302. const auto pattern = "/users/:id";
  16303. detail::PathParamsMatcher matcher(pattern);
  16304. Request request;
  16305. request.path = "/users";
  16306. ASSERT_FALSE(matcher.match(request));
  16307. }
  16308. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16309. const auto pattern = "/users/:id/subscriptions";
  16310. detail::PathParamsMatcher matcher(pattern);
  16311. Request request;
  16312. request.path = "/users/subscriptions";
  16313. ASSERT_FALSE(matcher.match(request));
  16314. }
  16315. TEST(PathParamsTest, MultipleParams) {
  16316. const auto pattern = "/users/:userid/subscriptions/:subid";
  16317. detail::PathParamsMatcher matcher(pattern);
  16318. Request request;
  16319. request.path = "/users/42/subscriptions/2";
  16320. ASSERT_TRUE(matcher.match(request));
  16321. std::unordered_map<std::string, std::string> expected_params = {
  16322. {"userid", "42"}, {"subid", "2"}};
  16323. EXPECT_EQ(request.path_params, expected_params);
  16324. }
  16325. TEST(PathParamsTest, SequenceOfParams) {
  16326. const auto pattern = "/values/:x/:y/:z";
  16327. detail::PathParamsMatcher matcher(pattern);
  16328. Request request;
  16329. request.path = "/values/1/2/3";
  16330. ASSERT_TRUE(matcher.match(request));
  16331. std::unordered_map<std::string, std::string> expected_params = {
  16332. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16333. EXPECT_EQ(request.path_params, expected_params);
  16334. }
  16335. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16336. const auto pattern = "/prefix:suffix";
  16337. detail::PathParamsMatcher matcher(pattern);
  16338. Request request;
  16339. request.path = "/prefix:suffix";
  16340. ASSERT_TRUE(matcher.match(request));
  16341. const std::unordered_map<std::string, std::string> expected_params = {};
  16342. EXPECT_EQ(request.path_params, expected_params);
  16343. }
  16344. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16345. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16346. // calling thread's stack on a long enough path for a quantified pattern;
  16347. // RegexMatcher must refuse to run regex matching on paths beyond
  16348. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16349. detail::RegexMatcher matcher("/files/(.*)");
  16350. Request within_limit;
  16351. within_limit.path = "/files/" + std::string(10, 'A');
  16352. EXPECT_TRUE(matcher.match(within_limit));
  16353. Request over_limit;
  16354. over_limit.path =
  16355. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16356. EXPECT_FALSE(matcher.match(over_limit));
  16357. }
  16358. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16359. Server svr;
  16360. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16361. res.set_content("ok", "text/plain");
  16362. });
  16363. auto port = svr.bind_to_any_port(HOST);
  16364. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16365. auto se = detail::scope_exit([&] {
  16366. svr.stop();
  16367. thread.join();
  16368. ASSERT_FALSE(svr.is_running());
  16369. });
  16370. svr.wait_until_ready();
  16371. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16372. // request URI limit; this used to be able to crash the process.
  16373. std::string path =
  16374. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16375. std::string req = "GET " + path +
  16376. " HTTP/1.1\r\n"
  16377. "Host: " +
  16378. std::string(HOST) + ":" + std::to_string(port) +
  16379. "\r\n"
  16380. "Connection: close\r\n"
  16381. "\r\n";
  16382. std::string response;
  16383. ASSERT_TRUE(send_request(5, req, &response, port));
  16384. EXPECT_NE(std::string::npos, response.find("404"));
  16385. }
  16386. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16387. Server svr;
  16388. auto handler = [](const Request & /*req*/, Response &res) {
  16389. res.set_content("hit", "text/plain");
  16390. };
  16391. // No regex metacharacter, so this one is compared literally
  16392. svr.Get("/literal/route", handler);
  16393. // '.' is a regex metacharacter, so this one must keep regex semantics
  16394. svr.Get("/a.c", handler);
  16395. auto port = svr.bind_to_any_port(HOST);
  16396. std::thread t([&]() { svr.listen_after_bind(); });
  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. struct {
  16405. const char *path;
  16406. int status;
  16407. } cases[] = {
  16408. {"/literal/route", StatusCode::OK_200},
  16409. {"/literal/routes", StatusCode::NotFound_404},
  16410. {"/literal/rout", StatusCode::NotFound_404},
  16411. {"/abc", StatusCode::OK_200},
  16412. {"/a.c", StatusCode::OK_200},
  16413. };
  16414. for (const auto &x : cases) {
  16415. auto res = cli.Get(x.path);
  16416. ASSERT_TRUE(res) << x.path;
  16417. EXPECT_EQ(x.status, res->status) << x.path;
  16418. }
  16419. }
  16420. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16421. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16422. // from exhausting the stack, so it must only constrain routes that actually
  16423. // run a regular expression. A literal route is matched by comparison and
  16424. // stays usable at any length.
  16425. Server svr;
  16426. const std::string pattern =
  16427. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16428. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16429. res.set_content("hit", "text/plain");
  16430. });
  16431. auto port = svr.bind_to_any_port(HOST);
  16432. std::thread t([&]() { svr.listen_after_bind(); });
  16433. auto se = detail::scope_exit([&] {
  16434. svr.stop();
  16435. t.join();
  16436. ASSERT_FALSE(svr.is_running());
  16437. });
  16438. svr.wait_until_ready();
  16439. Client cli(HOST, port);
  16440. auto res = cli.Get(pattern);
  16441. ASSERT_TRUE(res);
  16442. EXPECT_EQ(StatusCode::OK_200, res->status);
  16443. }
  16444. TEST(ParseUrlTest, VariousPatterns) {
  16445. {
  16446. detail::UrlComponents uc;
  16447. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16448. EXPECT_EQ("http", uc.scheme);
  16449. EXPECT_EQ("example.com", uc.host);
  16450. EXPECT_EQ("8080", uc.port);
  16451. EXPECT_EQ("/path", uc.path);
  16452. EXPECT_EQ("?q=1", uc.query);
  16453. }
  16454. {
  16455. detail::UrlComponents uc;
  16456. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16457. EXPECT_EQ("https", uc.scheme);
  16458. EXPECT_EQ("example.com", uc.host);
  16459. EXPECT_TRUE(uc.port.empty());
  16460. EXPECT_EQ("/path", uc.path);
  16461. }
  16462. {
  16463. detail::UrlComponents uc;
  16464. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16465. EXPECT_EQ("::1", uc.host);
  16466. EXPECT_EQ("8080", uc.port);
  16467. EXPECT_EQ("/path", uc.path);
  16468. }
  16469. {
  16470. detail::UrlComponents uc;
  16471. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16472. }
  16473. {
  16474. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16475. // the path while the connection still targets the bracketed host.
  16476. detail::UrlComponents uc;
  16477. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16478. }
  16479. {
  16480. detail::UrlComponents uc;
  16481. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16482. }
  16483. {
  16484. detail::UrlComponents uc;
  16485. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16486. EXPECT_EQ("::1", uc.host);
  16487. EXPECT_TRUE(uc.port.empty());
  16488. EXPECT_EQ("/path", uc.path);
  16489. }
  16490. {
  16491. detail::UrlComponents uc;
  16492. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16493. EXPECT_TRUE(uc.scheme.empty());
  16494. EXPECT_EQ("example.com", uc.host);
  16495. EXPECT_EQ("/path", uc.path);
  16496. EXPECT_EQ("?q=1", uc.query);
  16497. }
  16498. {
  16499. detail::UrlComponents uc;
  16500. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16501. EXPECT_TRUE(uc.host.empty());
  16502. EXPECT_EQ("/path", uc.path);
  16503. EXPECT_EQ("?q=1", uc.query);
  16504. }
  16505. {
  16506. detail::UrlComponents uc;
  16507. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16508. EXPECT_EQ("example.com", uc.host);
  16509. EXPECT_EQ("8080", uc.port);
  16510. }
  16511. {
  16512. // Unix socket path — must not be parsed as host
  16513. detail::UrlComponents uc;
  16514. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16515. EXPECT_TRUE(uc.host.empty());
  16516. }
  16517. {
  16518. detail::UrlComponents uc;
  16519. ASSERT_TRUE(detail::parse_url("", uc));
  16520. EXPECT_TRUE(uc.host.empty());
  16521. EXPECT_TRUE(uc.path.empty());
  16522. }
  16523. {
  16524. detail::UrlComponents uc;
  16525. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16526. }
  16527. {
  16528. detail::UrlComponents uc;
  16529. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16530. }
  16531. {
  16532. // Accepted by parse_url; callers restrict to http/https
  16533. detail::UrlComponents uc;
  16534. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16535. EXPECT_EQ("ftp", uc.scheme);
  16536. }
  16537. {
  16538. detail::UrlComponents uc;
  16539. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16540. }
  16541. {
  16542. detail::UrlComponents uc;
  16543. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16544. }
  16545. }
  16546. TEST(ParseUrlTest, FragmentHandling) {
  16547. {
  16548. detail::UrlComponents uc;
  16549. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16550. EXPECT_EQ("/path", uc.path);
  16551. EXPECT_TRUE(uc.query.empty());
  16552. }
  16553. {
  16554. detail::UrlComponents uc;
  16555. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16556. EXPECT_TRUE(uc.path.empty());
  16557. EXPECT_TRUE(uc.query.empty());
  16558. }
  16559. }
  16560. TEST(ParseUrlTest, UserinfoHandling) {
  16561. // userinfo is not supported. Parsers that honour it, or take a backslash for
  16562. // '/', would see evil.com where the host used to be the whole authority.
  16563. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16564. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16565. for (auto url : urls) {
  16566. detail::UrlComponents uc;
  16567. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16568. }
  16569. }
  16570. TEST(ParseUrlTest, IPv6EdgeCases) {
  16571. {
  16572. detail::UrlComponents uc;
  16573. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16574. EXPECT_TRUE(uc.scheme.empty());
  16575. EXPECT_EQ("::1", uc.host);
  16576. EXPECT_EQ("8080", uc.port);
  16577. }
  16578. {
  16579. // Zone ID '%25' is not in [a-fA-F0-9:]
  16580. detail::UrlComponents uc;
  16581. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16582. }
  16583. }
  16584. TEST(ParseUrlTest, SchemeEdgeCases) {
  16585. {
  16586. detail::UrlComponents uc;
  16587. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16588. }
  16589. {
  16590. detail::UrlComponents uc;
  16591. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16592. }
  16593. {
  16594. detail::UrlComponents uc;
  16595. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16596. }
  16597. }
  16598. TEST(ParseUrlTest, PortEdgeCases) {
  16599. {
  16600. detail::UrlComponents uc;
  16601. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16602. EXPECT_TRUE(uc.port.empty());
  16603. EXPECT_EQ("/path", uc.path);
  16604. }
  16605. {
  16606. // parse_url accepts any port string; validation is done by parse_port
  16607. detail::UrlComponents uc;
  16608. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16609. EXPECT_EQ("abc", uc.port);
  16610. }
  16611. }
  16612. TEST(ParseUrlTest, WebSocketPatterns) {
  16613. {
  16614. detail::UrlComponents uc;
  16615. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16616. EXPECT_EQ("ws", uc.scheme);
  16617. EXPECT_EQ("echo.example.com", uc.host);
  16618. EXPECT_EQ("8080", uc.port);
  16619. EXPECT_EQ("/ws", uc.path);
  16620. }
  16621. {
  16622. detail::UrlComponents uc;
  16623. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16624. EXPECT_EQ("wss", uc.scheme);
  16625. EXPECT_EQ("echo.example.com", uc.host);
  16626. EXPECT_TRUE(uc.port.empty());
  16627. EXPECT_EQ("/ws", uc.path);
  16628. }
  16629. }
  16630. TEST(ParseUrlTest, QueryOnly) {
  16631. detail::UrlComponents uc;
  16632. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16633. EXPECT_TRUE(uc.host.empty());
  16634. EXPECT_TRUE(uc.path.empty());
  16635. EXPECT_EQ("?q=1&r=2", uc.query);
  16636. }
  16637. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16638. detail::UrlComponents uc;
  16639. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16640. EXPECT_TRUE(uc.scheme.empty());
  16641. EXPECT_EQ("example.com", uc.host);
  16642. EXPECT_EQ("443", uc.port);
  16643. EXPECT_EQ("/path", uc.path);
  16644. }
  16645. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16646. // If ipv6 regex working, regex match codepath is taken.
  16647. // else port will default to 80 in Client impl
  16648. int clientImplMagicPort = 80;
  16649. int port = 4321;
  16650. // above ports must be different to avoid false negative
  16651. EXPECT_NE(clientImplMagicPort, port);
  16652. std::string ipV6TestURL = "http://[ff06::c3]";
  16653. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16654. CLIENT_PRIVATE_KEY_FILE);
  16655. EXPECT_EQ(cli.port(), port);
  16656. }
  16657. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16658. auto file_path = "./www/dir/index.html";
  16659. auto dir_path = "./www/dir";
  16660. detail::FileStat stat_file(file_path);
  16661. EXPECT_TRUE(stat_file.is_file());
  16662. EXPECT_FALSE(stat_file.is_dir());
  16663. detail::FileStat stat_dir(dir_path);
  16664. EXPECT_FALSE(stat_dir.is_file());
  16665. EXPECT_TRUE(stat_dir.is_dir());
  16666. }
  16667. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16668. // IPv4 with default HTTP port (80)
  16669. EXPECT_EQ("example.com",
  16670. detail::make_host_and_port_string("example.com", 80, false));
  16671. // IPv4 with default HTTPS port (443)
  16672. EXPECT_EQ("example.com",
  16673. detail::make_host_and_port_string("example.com", 443, true));
  16674. // IPv4 with non-default HTTP port
  16675. EXPECT_EQ("example.com:8080",
  16676. detail::make_host_and_port_string("example.com", 8080, false));
  16677. // IPv4 with non-default HTTPS port
  16678. EXPECT_EQ("example.com:8443",
  16679. detail::make_host_and_port_string("example.com", 8443, true));
  16680. // IPv6 with default HTTP port (80)
  16681. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16682. // IPv6 with default HTTPS port (443)
  16683. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16684. // IPv6 with non-default HTTP port
  16685. EXPECT_EQ("[::1]:8080",
  16686. detail::make_host_and_port_string("::1", 8080, false));
  16687. // IPv6 with non-default HTTPS port
  16688. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16689. // IPv6 full address with default port
  16690. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16691. detail::make_host_and_port_string(
  16692. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16693. // IPv6 full address with non-default port
  16694. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16695. detail::make_host_and_port_string(
  16696. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16697. // IPv6 localhost with non-default port
  16698. EXPECT_EQ("[::1]:3000",
  16699. detail::make_host_and_port_string("::1", 3000, false));
  16700. // IPv6 with zone ID (link-local address) with default port
  16701. EXPECT_EQ("[fe80::1%eth0]",
  16702. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16703. // IPv6 with zone ID (link-local address) with non-default port
  16704. EXPECT_EQ("[fe80::1%eth0]:8080",
  16705. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16706. // Edge case: Port 443 with is_ssl=false (should add port)
  16707. EXPECT_EQ("example.com:443",
  16708. detail::make_host_and_port_string("example.com", 443, false));
  16709. // Edge case: Port 80 with is_ssl=true (should add port)
  16710. EXPECT_EQ("example.com:80",
  16711. detail::make_host_and_port_string("example.com", 80, true));
  16712. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16713. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16714. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16715. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16716. // Security fix: Already bracketed IPv6 should not get double brackets
  16717. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16718. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16719. EXPECT_EQ("[::1]:8080",
  16720. detail::make_host_and_port_string("[::1]", 8080, false));
  16721. EXPECT_EQ("[2001:db8::1]:8080",
  16722. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16723. EXPECT_EQ("[fe80::1%eth0]",
  16724. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16725. EXPECT_EQ("[fe80::1%eth0]:8080",
  16726. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16727. // Edge case: Empty host (should return as-is)
  16728. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16729. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16730. // This is a known limitation but shouldn't crash
  16731. EXPECT_EQ("[host:name]",
  16732. detail::make_host_and_port_string("host:name", 80, false));
  16733. // Port number edge cases (no validation, but should not crash)
  16734. EXPECT_EQ("example.com:0",
  16735. detail::make_host_and_port_string("example.com", 0, false));
  16736. EXPECT_EQ("example.com:-1",
  16737. detail::make_host_and_port_string("example.com", -1, false));
  16738. EXPECT_EQ("example.com:65535",
  16739. detail::make_host_and_port_string("example.com", 65535, false));
  16740. EXPECT_EQ("example.com:65536",
  16741. detail::make_host_and_port_string("example.com", 65536, false));
  16742. }
  16743. #ifdef CPPHTTPLIB_SSL_ENABLED
  16744. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16745. httplib::SSLClient cli("roblox.com", 443);
  16746. cli.set_follow_location(true);
  16747. auto res = cli.Get("/");
  16748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16749. EXPECT_EQ(StatusCode::OK_200, res->status);
  16750. }
  16751. #endif
  16752. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16753. Server svr;
  16754. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16755. EXPECT_EQ(res.status, 400);
  16756. });
  16757. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16758. auto se = detail::scope_exit([&] {
  16759. svr.stop();
  16760. thread.join();
  16761. ASSERT_FALSE(svr.is_running());
  16762. });
  16763. svr.wait_until_ready();
  16764. Client cli(HOST, PORT);
  16765. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16766. }
  16767. TEST(InvalidHeaderCharsTest, is_field_name) {
  16768. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16769. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16770. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16771. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16772. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16773. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16774. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16775. EXPECT_FALSE(detail::fields::is_field_name(""));
  16776. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16777. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16778. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16779. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16780. }
  16781. TEST(InvalidHeaderCharsTest, is_field_value) {
  16782. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16783. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16784. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16785. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16786. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16787. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16788. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16789. EXPECT_TRUE(detail::fields::is_field_value(""));
  16790. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16791. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16792. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16793. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16794. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16795. }
  16796. TEST(InvalidHeaderCharsTest, OnServer) {
  16797. Server svr;
  16798. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16799. std::string header = "Not Set";
  16800. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16801. res.set_header(header, "value");
  16802. res.set_content("Page Content Page Content", "text/plain");
  16803. });
  16804. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16805. std::string header = "Not Set";
  16806. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16807. res.set_header("X-Test", header);
  16808. res.set_content("Page Content Page Content", "text/plain");
  16809. });
  16810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16811. auto se = detail::scope_exit([&] {
  16812. svr.stop();
  16813. thread.join();
  16814. ASSERT_FALSE(svr.is_running());
  16815. });
  16816. svr.wait_until_ready();
  16817. Client cli(HOST, PORT);
  16818. {
  16819. auto res = cli.Get(
  16820. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16822. EXPECT_EQ("Page Content Page Content", res->body);
  16823. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16824. }
  16825. {
  16826. auto res = cli.Get(
  16827. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16829. EXPECT_EQ("Page Content Page Content", res->body);
  16830. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16831. }
  16832. }
  16833. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16834. auto handled = false;
  16835. Server svr;
  16836. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16837. thread t = thread([&] { svr.listen(HOST, PORT); });
  16838. auto se = detail::scope_exit([&] {
  16839. svr.stop();
  16840. t.join();
  16841. ASSERT_FALSE(svr.is_running());
  16842. ASSERT_FALSE(handled);
  16843. });
  16844. svr.wait_until_ready();
  16845. auto req = "POST /test HTTP/1.1\r\n"
  16846. "Content-Length: x\r\n"
  16847. "\r\n";
  16848. std::string response;
  16849. ASSERT_TRUE(send_request(1, req, &response));
  16850. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16851. response.substr(0, response.find("\r\n")));
  16852. }
  16853. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16854. // case-insensitive, and a server that receives a 100-continue expectation in
  16855. // an HTTP/1.0 request MUST ignore it.
  16856. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16857. std::string response;
  16858. ASSERT_TRUE(send_request(1, req, &response, port));
  16859. *got_100 = response.find("100 Continue") != std::string::npos;
  16860. }
  16861. class ExpectTokenTest : public ::testing::Test {
  16862. protected:
  16863. void SetUp() override {
  16864. svr_.Post("/p", [](const Request &, Response &res) {
  16865. res.set_content("ok", "text/plain");
  16866. });
  16867. port_ = svr_.bind_to_any_port(HOST);
  16868. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16869. svr_.wait_until_ready();
  16870. }
  16871. void TearDown() override {
  16872. svr_.stop();
  16873. if (thread_.joinable()) { thread_.join(); }
  16874. }
  16875. std::string request(const char *version, const char *expect_value) const {
  16876. return std::string("POST /p ") + version +
  16877. "\r\n"
  16878. "Host: localhost\r\n"
  16879. "Content-Length: 2\r\n"
  16880. "Connection: close\r\n"
  16881. "Expect: " +
  16882. expect_value +
  16883. "\r\n"
  16884. "\r\n"
  16885. "hi";
  16886. }
  16887. Server svr_;
  16888. int port_ = 0;
  16889. thread thread_;
  16890. };
  16891. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16892. bool got_100 = false;
  16893. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16894. EXPECT_TRUE(got_100);
  16895. }
  16896. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16897. bool got_100 = true;
  16898. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16899. EXPECT_FALSE(got_100);
  16900. }
  16901. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16902. bool got_100 = false;
  16903. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16904. EXPECT_TRUE(got_100);
  16905. }
  16906. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16907. bool got_100 = false;
  16908. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16909. EXPECT_TRUE(got_100);
  16910. }
  16911. // `100 Continue` is sent only when the server starts reading the body, so a
  16912. // request rejected before that never invites the client to send it. The
  16913. // requests below carry the expectation but withhold the body, as a client
  16914. // waiting for `100 Continue` would.
  16915. // A POST that expects `100 Continue` and withholds its two-byte body.
  16916. static std::string expect_headers_only(const std::string &path) {
  16917. return "POST " + path +
  16918. " HTTP/1.1\r\n"
  16919. "Host: localhost\r\n"
  16920. "Content-Length: 2\r\n"
  16921. "Expect: 100-continue\r\n"
  16922. "\r\n";
  16923. }
  16924. class ExpectLazyContinueTest : public ::testing::Test {
  16925. protected:
  16926. void SetUp() override {
  16927. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16928. if (req.path == "/pre-routing") {
  16929. res.status = StatusCode::Unauthorized_401;
  16930. return Server::HandlerResponse::Handled;
  16931. }
  16932. return Server::HandlerResponse::Unhandled;
  16933. });
  16934. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16935. if (req.matched_route == "/pre-request") {
  16936. res.status = StatusCode::Forbidden_403;
  16937. return Server::HandlerResponse::Handled;
  16938. }
  16939. return Server::HandlerResponse::Unhandled;
  16940. });
  16941. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16942. res.set_content("ok", "text/plain");
  16943. });
  16944. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16945. res.set_content("ok", "text/plain");
  16946. });
  16947. svr_.Post("/reader-used", [](const Request &, Response &res,
  16948. const ContentReader &content_reader) {
  16949. std::string body;
  16950. content_reader([&](const char *data, size_t len) {
  16951. body.append(data, len);
  16952. return true;
  16953. });
  16954. res.set_content(body, "text/plain");
  16955. });
  16956. svr_.Post("/reader-unused",
  16957. [](const Request &, Response &res, const ContentReader &) {
  16958. res.set_content("ignored", "text/plain");
  16959. });
  16960. port_ = svr_.bind_to_any_port(HOST);
  16961. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16962. svr_.wait_until_ready();
  16963. }
  16964. void TearDown() override {
  16965. svr_.stop();
  16966. if (thread_.joinable()) { thread_.join(); }
  16967. }
  16968. // Sends `req` and reads until the server closes the connection. Returns
  16969. // false if the read had to wait for the client-side timeout instead.
  16970. bool send_until_closed(const std::string &req, std::string *resp) const {
  16971. auto start = std::chrono::steady_clock::now();
  16972. if (!send_request(3, req, resp, port_)) { return false; }
  16973. auto elapsed = std::chrono::steady_clock::now() - start;
  16974. return elapsed < std::chrono::seconds(2);
  16975. }
  16976. // The final response comes without `100 Continue`, and the server closes
  16977. // the connection since the body may or may not follow.
  16978. void expect_final_without_interim(const std::string &path,
  16979. const char *status_line) const {
  16980. std::string resp;
  16981. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16982. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16983. EXPECT_EQ(0u, resp.find(status_line));
  16984. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16985. }
  16986. Server svr_;
  16987. int port_ = 0;
  16988. thread thread_;
  16989. };
  16990. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16991. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16992. }
  16993. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16994. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16995. }
  16996. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16997. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16998. }
  16999. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17000. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17001. }
  17002. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17003. // The body follows once `100 Continue` has had time to arrive.
  17004. auto req = expect_headers_only("/reader-used");
  17005. req.insert(req.size() - 2, "Connection: close\r\n");
  17006. std::string resp;
  17007. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17008. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17009. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17010. EXPECT_NE(std::string::npos, resp.find("hi"));
  17011. }
  17012. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17013. // Large enough for the client to add `Expect: 100-continue` itself.
  17014. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17015. std::atomic<bool> body_sent{false};
  17016. Client cli(HOST, port_);
  17017. auto res = cli.Post(
  17018. "/pre-request", length,
  17019. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17020. body_sent = true;
  17021. std::string chunk(len, 'x');
  17022. sink.write(chunk.data(), chunk.size());
  17023. return true;
  17024. },
  17025. "application/octet-stream");
  17026. ASSERT_TRUE(res);
  17027. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17028. EXPECT_FALSE(body_sent);
  17029. }
  17030. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17031. Server svr;
  17032. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17033. return StatusCode::ExpectationFailed_417;
  17034. });
  17035. svr.Post("/p", [](const Request &, Response &res) {
  17036. res.set_content("ok", "text/plain");
  17037. });
  17038. auto port = svr.bind_to_any_port(HOST);
  17039. thread t = thread([&] { svr.listen_after_bind(); });
  17040. auto se = detail::scope_exit([&] {
  17041. svr.stop();
  17042. t.join();
  17043. });
  17044. svr.wait_until_ready();
  17045. std::string resp;
  17046. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17047. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17048. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17049. // Exactly one response: the route handler must not run after the 417.
  17050. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17051. }
  17052. #ifndef _WIN32
  17053. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17054. static constexpr char reject[] = "Unauthorized";
  17055. static constexpr char accept[] = "Upload accepted";
  17056. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17057. Server svr;
  17058. svr.set_expect_100_continue_handler(
  17059. [](const Request & /*req*/, Response &res) {
  17060. res.status = StatusCode::Unauthorized_401;
  17061. res.set_content(reject, "text/plain");
  17062. return res.status;
  17063. });
  17064. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17065. res.set_content(accept, "text/plain");
  17066. });
  17067. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17068. auto se = detail::scope_exit([&] {
  17069. svr.stop();
  17070. thread.join();
  17071. ASSERT_FALSE(svr.is_running());
  17072. });
  17073. svr.wait_until_ready();
  17074. {
  17075. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17076. curl_easy_init(), &curl_easy_cleanup};
  17077. ASSERT_NE(curl, nullptr);
  17078. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17079. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17080. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17081. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17082. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17083. &curl_slist_free_all};
  17084. ASSERT_NE(list, nullptr);
  17085. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17086. struct read_data {
  17087. size_t read_size;
  17088. size_t total_size;
  17089. } data = {0, total_size};
  17090. using read_callback_t =
  17091. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17092. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17093. void *userdata) -> size_t {
  17094. read_data *d = (read_data *)userdata;
  17095. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17096. std::fill_n(ptr, size * nmemb, 'A');
  17097. d->read_size += size * nmemb;
  17098. return size * nmemb;
  17099. };
  17100. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17101. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17102. std::vector<char> buffer;
  17103. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17104. using write_callback_t =
  17105. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17106. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17107. void *userdata) -> size_t {
  17108. std::vector<char> *buf = (std::vector<char> *)userdata;
  17109. buf->reserve(buf->size() + size * nmemb + 1);
  17110. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17111. return size * nmemb;
  17112. };
  17113. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17114. {
  17115. const auto res = curl_easy_perform(curl.get());
  17116. ASSERT_EQ(res, CURLE_OK);
  17117. }
  17118. {
  17119. auto response_code = long{};
  17120. const auto res =
  17121. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17122. ASSERT_EQ(res, CURLE_OK);
  17123. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17124. }
  17125. {
  17126. auto dl = curl_off_t{};
  17127. const auto res =
  17128. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17129. ASSERT_EQ(res, CURLE_OK);
  17130. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17131. }
  17132. {
  17133. buffer.push_back('\0');
  17134. ASSERT_STRCASEEQ(buffer.data(), reject);
  17135. }
  17136. }
  17137. }
  17138. #endif
  17139. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17140. // Regression test for #2458.
  17141. //
  17142. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17143. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17144. // ticket can make the client socket spuriously readable during the
  17145. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17146. // the client withholds the body and then blocks reading a response that never
  17147. // comes, failing with `Failed to read connection`.
  17148. //
  17149. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17150. // within the timeout. This raw OpenSSL server deliberately never sends
  17151. // `100 Continue`; the client must still deliver the body and receive 200.
  17152. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17153. signal(SIGPIPE, SIG_IGN);
  17154. const auto port = PORT + 4;
  17155. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17156. ASSERT_NE(srv, INVALID_SOCKET);
  17157. int opt = 1;
  17158. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17159. sockaddr_in addr{};
  17160. addr.sin_family = AF_INET;
  17161. addr.sin_port = htons(static_cast<uint16_t>(port));
  17162. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17163. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17164. ASSERT_EQ(0, ::listen(srv, 1));
  17165. std::atomic<size_t> server_body_bytes{0};
  17166. auto server_thread = std::thread([&] {
  17167. sockaddr_in cli_addr{};
  17168. socklen_t cli_len = sizeof(cli_addr);
  17169. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17170. if (cli == INVALID_SOCKET) { return; }
  17171. // Bound the lifetime of the server side so a buggy client (which never
  17172. // sends the body) cannot make this thread block forever on join.
  17173. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17174. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17175. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17176. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17177. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17178. SSL *ssl = SSL_new(ctx);
  17179. SSL_set_fd(ssl, static_cast<int>(cli));
  17180. if (SSL_accept(ssl) > 0) {
  17181. // Read the request headers. Reading here also flushes the TLS 1.3
  17182. // session tickets to the client. Deliberately do NOT send
  17183. // `100 Continue`.
  17184. std::string buf;
  17185. char tmp[1024];
  17186. while (buf.find("\r\n\r\n") == std::string::npos) {
  17187. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17188. if (n <= 0) { break; }
  17189. buf.append(tmp, static_cast<size_t>(n));
  17190. }
  17191. // A correct client sends the body now; count what arrives.
  17192. auto pos = buf.find("\r\n\r\n");
  17193. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17194. while (body < 4096) {
  17195. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17196. if (n <= 0) { break; }
  17197. body += static_cast<size_t>(n);
  17198. }
  17199. server_body_bytes = body;
  17200. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17201. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17202. SSL_shutdown(ssl);
  17203. }
  17204. SSL_free(ssl);
  17205. detail::close_socket(cli);
  17206. SSL_CTX_free(ctx);
  17207. });
  17208. auto se = detail::scope_exit([&] {
  17209. server_thread.join();
  17210. detail::close_socket(srv);
  17211. });
  17212. SSLClient cli("127.0.0.1", port);
  17213. cli.enable_server_certificate_verification(false);
  17214. cli.set_connection_timeout(5, 0);
  17215. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17216. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17217. std::string body(4096, 'A');
  17218. auto res = cli.Put("/api/test", body, "application/json");
  17219. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17220. EXPECT_EQ(StatusCode::OK_200, res->status);
  17221. EXPECT_EQ(body.size(), server_body_bytes.load());
  17222. }
  17223. #endif
  17224. template <typename S, typename C>
  17225. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17226. svr.Get("/stream", [&](const Request &, Response &res) {
  17227. auto data = new std::string("01234567890123456789");
  17228. res.set_content_provider(
  17229. data->size(), "text/plain",
  17230. [&, data](size_t offset, size_t length, DataSink &sink) {
  17231. const size_t DATA_CHUNK_SIZE = 4;
  17232. const auto &d = *data;
  17233. std::this_thread::sleep_for(std::chrono::seconds(1));
  17234. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17235. return true;
  17236. },
  17237. [data](bool success) {
  17238. EXPECT_FALSE(success);
  17239. delete data;
  17240. });
  17241. });
  17242. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17243. auto i = new size_t(0);
  17244. res.set_content_provider(
  17245. "text/plain",
  17246. [i](size_t, DataSink &sink) {
  17247. if (*i < 5) {
  17248. std::this_thread::sleep_for(std::chrono::seconds(1));
  17249. sink.write("abcd", 4);
  17250. (*i)++;
  17251. } else {
  17252. sink.done();
  17253. }
  17254. return true;
  17255. },
  17256. [i](bool success) {
  17257. EXPECT_FALSE(success);
  17258. delete i;
  17259. });
  17260. });
  17261. svr.Get("/chunked", [&](const Request &, Response &res) {
  17262. auto i = new size_t(0);
  17263. res.set_chunked_content_provider(
  17264. "text/plain",
  17265. [i](size_t, DataSink &sink) {
  17266. if (*i < 5) {
  17267. std::this_thread::sleep_for(std::chrono::seconds(1));
  17268. sink.os << "abcd";
  17269. (*i)++;
  17270. } else {
  17271. sink.done();
  17272. }
  17273. return true;
  17274. },
  17275. [i](bool success) {
  17276. EXPECT_FALSE(success);
  17277. delete i;
  17278. });
  17279. });
  17280. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17281. auto se = detail::scope_exit([&] {
  17282. svr.stop();
  17283. listen_thread.join();
  17284. ASSERT_FALSE(svr.is_running());
  17285. });
  17286. svr.wait_until_ready();
  17287. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17288. {
  17289. auto start = std::chrono::steady_clock::now();
  17290. auto res = cli.Get("/stream");
  17291. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17292. std::chrono::steady_clock::now() - start)
  17293. .count();
  17294. ASSERT_FALSE(res);
  17295. EXPECT_EQ(Error::Read, res.error());
  17296. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17297. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17298. }
  17299. {
  17300. auto start = std::chrono::steady_clock::now();
  17301. auto res = cli.Get("/stream_without_length");
  17302. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17303. std::chrono::steady_clock::now() - start)
  17304. .count();
  17305. ASSERT_FALSE(res);
  17306. EXPECT_EQ(Error::Read, res.error());
  17307. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17308. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17309. }
  17310. {
  17311. auto start = std::chrono::steady_clock::now();
  17312. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17313. EXPECT_EQ("abcd", string(data, data_length));
  17314. return true;
  17315. });
  17316. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17317. std::chrono::steady_clock::now() - start)
  17318. .count();
  17319. ASSERT_FALSE(res);
  17320. EXPECT_EQ(Error::Read, res.error());
  17321. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17322. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17323. }
  17324. }
  17325. TEST(MaxTimeoutTest, ContentStream) {
  17326. time_t timeout = 2000;
  17327. time_t threshold = 200;
  17328. Server svr;
  17329. Client cli("localhost", PORT);
  17330. max_timeout_test(svr, cli, timeout, threshold);
  17331. }
  17332. #ifdef CPPHTTPLIB_SSL_ENABLED
  17333. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17334. time_t timeout = 2000;
  17335. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17337. SSLClient cli("localhost", PORT);
  17338. cli.enable_server_certificate_verification(false);
  17339. max_timeout_test(svr, cli, timeout, threshold);
  17340. }
  17341. #endif
  17342. class EventDispatcher {
  17343. public:
  17344. EventDispatcher() {}
  17345. bool wait_event(DataSink *sink) {
  17346. unique_lock<mutex> lk(m_);
  17347. int id = id_;
  17348. // Wait with timeout to prevent hanging if client disconnects
  17349. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17350. [&] { return cid_ == id; })) {
  17351. return false; // Timeout occurred
  17352. }
  17353. sink->write(message_.data(), message_.size());
  17354. return true;
  17355. }
  17356. void send_event(const string &message) {
  17357. lock_guard<mutex> lk(m_);
  17358. cid_ = id_++;
  17359. message_ = message;
  17360. cv_.notify_all();
  17361. }
  17362. private:
  17363. mutex m_;
  17364. condition_variable cv_;
  17365. atomic_int id_{0};
  17366. atomic_int cid_{-1};
  17367. string message_;
  17368. };
  17369. TEST(ClientInThreadTest, Issue2068) {
  17370. EventDispatcher ed;
  17371. Server svr;
  17372. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17373. res.set_chunked_content_provider("text/event-stream",
  17374. [&](size_t /*offset*/, DataSink &sink) {
  17375. return ed.wait_event(&sink);
  17376. });
  17377. });
  17378. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17379. svr.wait_until_ready();
  17380. thread event_thread([&] {
  17381. int id = 0;
  17382. while (svr.is_running()) {
  17383. this_thread::sleep_for(chrono::milliseconds(500));
  17384. std::stringstream ss;
  17385. ss << "data: " << id << "\n\n";
  17386. ed.send_event(ss.str());
  17387. id++;
  17388. }
  17389. });
  17390. auto se = detail::scope_exit([&] {
  17391. svr.stop();
  17392. listen_thread.join();
  17393. event_thread.join();
  17394. ASSERT_FALSE(svr.is_running());
  17395. });
  17396. {
  17397. auto client = detail::make_unique<Client>(HOST, PORT);
  17398. client->set_read_timeout(std::chrono::minutes(10));
  17399. std::atomic<bool> stop{false};
  17400. std::thread t([&] {
  17401. client->Get("/event1",
  17402. [&](const char *, size_t) -> bool { return !stop; });
  17403. });
  17404. std::this_thread::sleep_for(std::chrono::seconds(2));
  17405. stop = true;
  17406. client->stop();
  17407. t.join();
  17408. // Reset client after thread has finished
  17409. client.reset();
  17410. }
  17411. }
  17412. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17413. auto handled = false;
  17414. Server svr;
  17415. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17416. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17417. auto se = detail::scope_exit([&] {
  17418. svr.stop();
  17419. t.join();
  17420. ASSERT_FALSE(svr.is_running());
  17421. ASSERT_FALSE(handled);
  17422. });
  17423. svr.wait_until_ready();
  17424. // Two Content-Length headers with different values — must be rejected
  17425. auto req = "POST /test HTTP/1.1\r\n"
  17426. "Content-Length: 5\r\n"
  17427. "Content-Length: 10\r\n"
  17428. "\r\n"
  17429. "hello";
  17430. std::string response;
  17431. ASSERT_TRUE(send_request(1, req, &response));
  17432. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17433. response.substr(0, response.find("\r\n")));
  17434. }
  17435. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17436. auto handled = false;
  17437. Server svr;
  17438. svr.Post("/test", [&](const Request &, Response &res) {
  17439. handled = true;
  17440. res.set_content("ok", "text/plain");
  17441. });
  17442. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17443. auto se = detail::scope_exit([&] {
  17444. svr.stop();
  17445. t.join();
  17446. ASSERT_FALSE(svr.is_running());
  17447. ASSERT_TRUE(handled);
  17448. });
  17449. svr.wait_until_ready();
  17450. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17451. auto req = "POST /test HTTP/1.1\r\n"
  17452. "Host: localhost\r\n"
  17453. "Content-Length: 5\r\n"
  17454. "Content-Length: 5\r\n"
  17455. "\r\n"
  17456. "hello";
  17457. std::string response;
  17458. ASSERT_TRUE(send_request(1, req, &response));
  17459. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17460. }
  17461. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17462. Server svr;
  17463. svr.Get("/test", [](const Request &, Response &res) {
  17464. res.set_content("ok", "text/plain");
  17465. });
  17466. auto port = svr.bind_to_any_port(HOST);
  17467. thread t = thread([&] { svr.listen_after_bind(); });
  17468. auto se = detail::scope_exit([&] {
  17469. svr.stop();
  17470. t.join();
  17471. ASSERT_FALSE(svr.is_running());
  17472. });
  17473. svr.wait_until_ready();
  17474. auto status_line = [&](const std::string &host_lines) {
  17475. std::string res;
  17476. send_request(
  17477. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17478. &res, port);
  17479. return res.substr(0, res.find("\r\n"));
  17480. };
  17481. const char *accepted[] = {
  17482. "Host: localhost\r\n",
  17483. "Host: a.example:8080\r\n",
  17484. "Host: my_service\r\n",
  17485. "Host: [::1]:8080\r\n",
  17486. "Host: [fe80::1%25eth0]\r\n",
  17487. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17488. };
  17489. for (auto host_lines : accepted) {
  17490. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17491. }
  17492. const char *rejected[] = {
  17493. "Host: a.example\r\nHost: b.example\r\n",
  17494. "Host: a.example\r\nHost: a.example\r\n",
  17495. "Host: a@b.example\r\n",
  17496. "Host: a.example/b\r\n",
  17497. "Host: a.example\\b\r\n",
  17498. "Host: a.example?b\r\n",
  17499. "Host: a.example#b\r\n",
  17500. "Host: a.example b.example\r\n",
  17501. };
  17502. for (auto host_lines : rejected) {
  17503. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17504. << host_lines;
  17505. }
  17506. }
  17507. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17508. Server svr;
  17509. svr.Get("/", [](const Request &req, Response &res) {
  17510. EXPECT_EQ(2U, req.trailers.size());
  17511. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17512. // Denied
  17513. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17514. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17515. // Accepted
  17516. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17517. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17518. EXPECT_TRUE(req.has_trailer("X-World"));
  17519. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17520. res.set_content("ok", "text/plain");
  17521. });
  17522. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17523. auto se = detail::scope_exit([&] {
  17524. svr.stop();
  17525. t.join();
  17526. ASSERT_FALSE(svr.is_running());
  17527. });
  17528. svr.wait_until_ready();
  17529. const std::string req = "GET / HTTP/1.1\r\n"
  17530. "Transfer-Encoding: chunked\r\n"
  17531. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17532. "\r\n"
  17533. "0\r\n"
  17534. "Content-Length: 10\r\n"
  17535. "Host: internal.local\r\n"
  17536. "Content-Type: malicious/content\r\n"
  17537. "Cookie: any\r\n"
  17538. "Set-Cookie: any\r\n"
  17539. "X-Forwarded-For: attacker.com\r\n"
  17540. "X-Real-Ip: 1.1.1.1\r\n"
  17541. "X-Hello: hello\r\n"
  17542. "X-World: world\r\n"
  17543. "\r\n";
  17544. std::string res;
  17545. ASSERT_TRUE(send_request(1, req, &res));
  17546. }
  17547. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17548. // several field lines, and the combined value is what has to be parsed. A
  17549. // Trailer field split across lines therefore declares every name it lists;
  17550. // reading only the first line silently drops the trailers the later lines
  17551. // declare. The prohibited-trailer filter still applies to every line.
  17552. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17553. Server svr;
  17554. size_t observed_trailer_count = 0;
  17555. std::string observed_hello;
  17556. std::string observed_world;
  17557. bool observed_content_length = true;
  17558. svr.Get("/", [&](const Request &req, Response &res) {
  17559. observed_trailer_count = req.trailers.size();
  17560. observed_hello = req.get_trailer_value("X-Hello");
  17561. observed_world = req.get_trailer_value("X-World");
  17562. observed_content_length = req.has_trailer("Content-Length");
  17563. res.set_content("ok", "text/plain");
  17564. });
  17565. auto port = svr.bind_to_any_port(HOST);
  17566. thread t = thread([&]() { svr.listen_after_bind(); });
  17567. auto se = detail::scope_exit([&] {
  17568. svr.stop();
  17569. t.join();
  17570. ASSERT_FALSE(svr.is_running());
  17571. });
  17572. svr.wait_until_ready();
  17573. const std::string req = "GET / HTTP/1.1\r\n"
  17574. "Host: localhost\r\n"
  17575. "Transfer-Encoding: chunked\r\n"
  17576. "Trailer: X-Hello\r\n"
  17577. "Trailer: X-World, Content-Length\r\n"
  17578. "\r\n"
  17579. "0\r\n"
  17580. "X-Hello: hello\r\n"
  17581. "X-World: world\r\n"
  17582. "Content-Length: 10\r\n"
  17583. "\r\n";
  17584. std::string res;
  17585. ASSERT_TRUE(send_request(1, req, &res, port));
  17586. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17587. // Accepted: both field lines contribute to the declared set
  17588. EXPECT_EQ(2U, observed_trailer_count);
  17589. EXPECT_EQ(observed_hello, "hello");
  17590. EXPECT_EQ(observed_world, "world");
  17591. // Denied: a prohibited name stays prohibited on a later field line
  17592. EXPECT_FALSE(observed_content_length);
  17593. }
  17594. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17595. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17596. // unbounded run of fields that are never declared, because the counter would
  17597. // only advance for declared fields.
  17598. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17599. Server svr;
  17600. bool handler_called = false;
  17601. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17602. handler_called = true;
  17603. res.set_content("ok", "text/plain");
  17604. });
  17605. auto port = svr.bind_to_any_port(HOST);
  17606. thread t = thread([&]() { svr.listen_after_bind(); });
  17607. auto se = detail::scope_exit([&] {
  17608. svr.stop();
  17609. t.join();
  17610. ASSERT_FALSE(svr.is_running());
  17611. });
  17612. svr.wait_until_ready();
  17613. // Declare nothing, then send far more undeclared trailer fields than the
  17614. // header-count limit. Parsing must stop and reject the request rather than
  17615. // read every line.
  17616. std::string req = "GET / HTTP/1.1\r\n"
  17617. "Transfer-Encoding: chunked\r\n"
  17618. "\r\n"
  17619. "0\r\n";
  17620. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17621. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17622. }
  17623. req += "\r\n";
  17624. std::string res;
  17625. ASSERT_TRUE(send_request(1, req, &res, port));
  17626. // The request is rejected before the handler runs.
  17627. EXPECT_FALSE(handler_called);
  17628. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17629. }
  17630. // The set of declared trailer names is capped so a peer cannot grow it without
  17631. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17632. // declared past the cap is not honored, even if the field is actually sent.
  17633. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17634. Server svr;
  17635. // One name inside the cap and one past it, so the test tracks the cap rather
  17636. // than a fixed count.
  17637. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17638. const std::string within_cap_name = "X-T-0";
  17639. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17640. bool observed_within_cap = false;
  17641. bool observed_past_cap = false;
  17642. svr.Get("/", [&](const Request &req, Response &res) {
  17643. observed_within_cap = req.has_trailer(within_cap_name);
  17644. observed_past_cap = req.has_trailer(past_cap_name);
  17645. res.set_content("ok", "text/plain");
  17646. });
  17647. auto port = svr.bind_to_any_port(HOST);
  17648. thread t = thread([&]() { svr.listen_after_bind(); });
  17649. auto se = detail::scope_exit([&] {
  17650. svr.stop();
  17651. t.join();
  17652. ASSERT_FALSE(svr.is_running());
  17653. });
  17654. svr.wait_until_ready();
  17655. // Declare more trailer names than the cap in a single Trailer field, then
  17656. // actually send the first (within the cap) and the last (past it).
  17657. std::string trailer_decl = "Trailer: ";
  17658. for (int i = 0; i < declared_count; i++) {
  17659. if (i != 0) { trailer_decl += ", "; }
  17660. trailer_decl += "X-T-" + std::to_string(i);
  17661. }
  17662. trailer_decl += "\r\n";
  17663. const std::string req = "GET / HTTP/1.1\r\n"
  17664. "Host: localhost\r\n"
  17665. "Transfer-Encoding: chunked\r\n" +
  17666. trailer_decl +
  17667. "\r\n"
  17668. "0\r\n" +
  17669. within_cap_name + ": a\r\n" + past_cap_name +
  17670. ": b\r\n"
  17671. "\r\n";
  17672. std::string res;
  17673. ASSERT_TRUE(send_request(1, req, &res, port));
  17674. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17675. // A name within the cap is honored; one declared past the cap is dropped.
  17676. EXPECT_TRUE(observed_within_cap);
  17677. EXPECT_FALSE(observed_past_cap);
  17678. }
  17679. // A direct client that is not listed in trusted_proxies must not be able to
  17680. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17681. // the peer address on the actual TCP connection determines whether the
  17682. // header is honored.
  17683. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17684. Server svr;
  17685. // Deliberately does NOT include the loopback address the test client
  17686. // actually connects from, so the direct connection is not a trusted proxy.
  17687. svr.set_trusted_proxies({"203.0.113.66"});
  17688. std::string observed_remote_addr;
  17689. svr.Get("/ip", [&](const Request &req, Response &res) {
  17690. observed_remote_addr = req.remote_addr;
  17691. res.set_content("ok", "text/plain");
  17692. });
  17693. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17694. auto se = detail::scope_exit([&] {
  17695. svr.stop();
  17696. t.join();
  17697. ASSERT_FALSE(svr.is_running());
  17698. });
  17699. svr.wait_until_ready();
  17700. Client cli(HOST, PORT);
  17701. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17703. EXPECT_EQ(StatusCode::OK_200, res->status);
  17704. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17705. // ignored entirely and the real connection-level address retained.
  17706. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17707. observed_remote_addr == "127.0.0.1");
  17708. }
  17709. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17710. Server svr;
  17711. std::string observed_remote_addr;
  17712. std::string observed_xff;
  17713. svr.Get("/ip", [&](const Request &req, Response &res) {
  17714. observed_remote_addr = req.remote_addr;
  17715. observed_xff = req.get_header_value("X-Forwarded-For");
  17716. res.set_content("ok", "text/plain");
  17717. });
  17718. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17719. auto se = detail::scope_exit([&] {
  17720. svr.stop();
  17721. t.join();
  17722. ASSERT_FALSE(svr.is_running());
  17723. });
  17724. svr.wait_until_ready();
  17725. Client cli(HOST, PORT);
  17726. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17728. EXPECT_EQ(StatusCode::OK_200, res->status);
  17729. EXPECT_EQ(observed_xff, "203.0.113.66");
  17730. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17731. observed_remote_addr == "127.0.0.1");
  17732. }
  17733. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17734. Server svr;
  17735. svr.set_trusted_proxies({"203.0.113.66"});
  17736. std::string observed_remote_addr;
  17737. std::string observed_xff;
  17738. svr.Get("/ip", [&](const Request &req, Response &res) {
  17739. observed_remote_addr = req.remote_addr;
  17740. observed_xff = req.get_header_value("X-Forwarded-For");
  17741. res.set_content("ok", "text/plain");
  17742. });
  17743. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17744. auto se = detail::scope_exit([&] {
  17745. svr.stop();
  17746. t.join();
  17747. ASSERT_FALSE(svr.is_running());
  17748. });
  17749. svr.wait_until_ready();
  17750. Client cli(HOST, PORT);
  17751. auto res = cli.Get("/ip");
  17752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17753. EXPECT_EQ(StatusCode::OK_200, res->status);
  17754. EXPECT_EQ(observed_xff, "");
  17755. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17756. observed_remote_addr == "127.0.0.1");
  17757. }
  17758. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17759. Server svr;
  17760. // Include the loopback address the test client actually connects from, so
  17761. // the direct connection itself is recognized as the trusted proxy hop.
  17762. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17763. std::string observed_remote_addr;
  17764. std::string observed_xff;
  17765. svr.Get("/ip", [&](const Request &req, Response &res) {
  17766. observed_remote_addr = req.remote_addr;
  17767. observed_xff = req.get_header_value("X-Forwarded-For");
  17768. res.set_content("ok", "text/plain");
  17769. });
  17770. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17771. auto se = detail::scope_exit([&] {
  17772. svr.stop();
  17773. t.join();
  17774. ASSERT_FALSE(svr.is_running());
  17775. });
  17776. svr.wait_until_ready();
  17777. Client cli(HOST, PORT);
  17778. auto res = cli.Get(
  17779. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17781. EXPECT_EQ(StatusCode::OK_200, res->status);
  17782. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17783. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17784. }
  17785. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17786. Server svr;
  17787. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17788. std::string observed_remote_addr;
  17789. std::string observed_xff;
  17790. svr.Get("/ip", [&](const Request &req, Response &res) {
  17791. observed_remote_addr = req.remote_addr;
  17792. observed_xff = req.get_header_value("X-Forwarded-For");
  17793. res.set_content("ok", "text/plain");
  17794. });
  17795. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17796. auto se = detail::scope_exit([&] {
  17797. svr.stop();
  17798. t.join();
  17799. ASSERT_FALSE(svr.is_running());
  17800. });
  17801. svr.wait_until_ready();
  17802. Client cli(HOST, PORT);
  17803. auto res = cli.Get(
  17804. "/ip",
  17805. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17807. EXPECT_EQ(StatusCode::OK_200, res->status);
  17808. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17809. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17810. }
  17811. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17812. Server svr;
  17813. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17814. std::string observed_remote_addr;
  17815. std::string observed_xff;
  17816. svr.Get("/ip", [&](const Request &req, Response &res) {
  17817. observed_remote_addr = req.remote_addr;
  17818. observed_xff = req.get_header_value("X-Forwarded-For");
  17819. res.set_content("ok", "text/plain");
  17820. });
  17821. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17822. auto se = detail::scope_exit([&] {
  17823. svr.stop();
  17824. t.join();
  17825. ASSERT_FALSE(svr.is_running());
  17826. });
  17827. svr.wait_until_ready();
  17828. Client cli(HOST, PORT);
  17829. auto res = cli.Get(
  17830. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17832. EXPECT_EQ(StatusCode::OK_200, res->status);
  17833. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17834. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17835. // and must not be selected.
  17836. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17837. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17838. }
  17839. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17840. Server svr;
  17841. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17842. std::string observed_remote_addr;
  17843. svr.Get("/ip", [&](const Request &req, Response &res) {
  17844. observed_remote_addr = req.remote_addr;
  17845. res.set_content("ok", "text/plain");
  17846. });
  17847. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17848. auto se = detail::scope_exit([&] {
  17849. svr.stop();
  17850. t.join();
  17851. ASSERT_FALSE(svr.is_running());
  17852. });
  17853. svr.wait_until_ready();
  17854. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17855. // a forged address and the trusted proxy's own address; the forged value must
  17856. // not win over the address the trusted proxy actually recorded.
  17857. Client cli(HOST, PORT);
  17858. auto res = cli.Get(
  17859. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17861. EXPECT_EQ(StatusCode::OK_200, res->status);
  17862. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17863. }
  17864. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17865. Server svr;
  17866. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17867. std::string observed_remote_addr;
  17868. std::string observed_xff;
  17869. svr.Get("/ip", [&](const Request &req, Response &res) {
  17870. observed_remote_addr = req.remote_addr;
  17871. observed_xff = req.get_header_value("X-Forwarded-For");
  17872. res.set_content("ok", "text/plain");
  17873. });
  17874. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17875. auto se = detail::scope_exit([&] {
  17876. svr.stop();
  17877. t.join();
  17878. ASSERT_FALSE(svr.is_running());
  17879. });
  17880. svr.wait_until_ready();
  17881. Client cli(HOST, PORT);
  17882. auto res = cli.Get(
  17883. "/ip",
  17884. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17886. EXPECT_EQ(StatusCode::OK_200, res->status);
  17887. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17888. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17889. }
  17890. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17891. Server svr;
  17892. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17893. std::string observed_remote_addr;
  17894. std::string observed_xff;
  17895. svr.Get("/ip", [&](const Request &req, Response &res) {
  17896. observed_remote_addr = req.remote_addr;
  17897. observed_xff = req.get_header_value("X-Forwarded-For");
  17898. res.set_content("ok", "text/plain");
  17899. });
  17900. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17901. auto se = detail::scope_exit([&] {
  17902. svr.stop();
  17903. t.join();
  17904. ASSERT_FALSE(svr.is_running());
  17905. });
  17906. svr.wait_until_ready();
  17907. std::string raw_req =
  17908. "GET /ip HTTP/1.1\r\n"
  17909. "Host: localhost\r\n"
  17910. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17911. "Connection: close\r\n"
  17912. "\r\n";
  17913. std::string out;
  17914. ASSERT_TRUE(send_request(5, raw_req, &out));
  17915. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17916. // Header parser trims surrounding whitespace of the header value
  17917. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17918. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17919. }
  17920. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17921. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17922. // their own X-Forwarded-For as a separate field line rather than extending the
  17923. // one the client sent, so every occurrence has to be taken into account.
  17924. // Reading only the first one hands back the address the client chose.
  17925. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17926. Server svr;
  17927. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17928. std::string observed_remote_addr;
  17929. size_t observed_xff_count = 0;
  17930. svr.Get("/ip", [&](const Request &req, Response &res) {
  17931. observed_remote_addr = req.remote_addr;
  17932. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17933. res.set_content("ok", "text/plain");
  17934. });
  17935. auto port = svr.bind_to_any_port(HOST);
  17936. thread t = thread([&]() { svr.listen_after_bind(); });
  17937. auto se = detail::scope_exit([&] {
  17938. svr.stop();
  17939. t.join();
  17940. ASSERT_FALSE(svr.is_running());
  17941. });
  17942. svr.wait_until_ready();
  17943. // The client supplies the first field line; the trusted proxy appends the
  17944. // address it observed as a second one.
  17945. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17946. "Host: localhost\r\n"
  17947. "X-Forwarded-For: 1.2.3.4\r\n"
  17948. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17949. "Connection: close\r\n"
  17950. "\r\n";
  17951. std::string out;
  17952. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17953. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17954. EXPECT_EQ(observed_xff_count, 2U);
  17955. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17956. // The same chain spread over one field line per hop derives the same client
  17957. // address, i.e. the split and the comma-joined representations agree.
  17958. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17959. "Host: localhost\r\n"
  17960. "X-Forwarded-For: 1.2.3.4\r\n"
  17961. "X-Forwarded-For: 198.51.100.23\r\n"
  17962. "X-Forwarded-For: 192.0.2.45\r\n"
  17963. "Connection: close\r\n"
  17964. "\r\n";
  17965. out.clear();
  17966. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17967. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17968. EXPECT_EQ(observed_xff_count, 3U);
  17969. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17970. }
  17971. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17972. // crash the server (it used to call front() on an empty vector inside
  17973. // get_client_ip). The connection-level remote address must be retained instead.
  17974. static void run_malformed_xff_test(const std::string &xff_value) {
  17975. Server svr;
  17976. svr.set_trusted_proxies({"192.0.2.45"});
  17977. std::string observed_remote_addr;
  17978. svr.Get("/ip", [&](const Request &req, Response &res) {
  17979. observed_remote_addr = req.remote_addr;
  17980. res.set_content("ok", "text/plain");
  17981. });
  17982. int port = 0;
  17983. thread t = thread([&]() {
  17984. port = svr.bind_to_any_port(HOST);
  17985. svr.listen_after_bind();
  17986. });
  17987. auto se = detail::scope_exit([&] {
  17988. svr.stop();
  17989. t.join();
  17990. ASSERT_FALSE(svr.is_running());
  17991. });
  17992. svr.wait_until_ready();
  17993. Client cli(HOST, port);
  17994. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17996. EXPECT_EQ(StatusCode::OK_200, res->status);
  17997. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17998. observed_remote_addr == "127.0.0.1");
  17999. }
  18000. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18001. run_malformed_xff_test("");
  18002. }
  18003. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18004. run_malformed_xff_test(",");
  18005. }
  18006. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18007. run_malformed_xff_test(", , ,");
  18008. }
  18009. // The same rule applies to Accept: a request whose acceptable types are spread
  18010. // over several field lines must be negotiated against all of them.
  18011. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18012. // case-insensitive connection options. Comparing the whole field value against
  18013. // one option misses a client that sends several of them, and misses every
  18014. // casing but the one written in the comparison.
  18015. //
  18016. // Sends req, reads the response, then reuses the same socket for a second
  18017. // request to find out whether the server kept the connection.
  18018. static void probe_connection_reuse(int port, const std::string &req,
  18019. bool *announced_close, bool *reusable) {
  18020. auto error = Error::Success;
  18021. auto sock = detail::create_client_socket(
  18022. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18023. /*connection_timeout_sec=*/5, 0,
  18024. /*read_timeout_sec=*/1, 0,
  18025. /*write_timeout_sec=*/5, 0, std::string(), error);
  18026. ASSERT_NE(sock, INVALID_SOCKET);
  18027. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18028. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18029. "Host: localhost\r\n"
  18030. "Connection: close\r\n"
  18031. "\r\n";
  18032. std::string first_response;
  18033. std::string second_response;
  18034. detail::process_client_socket(
  18035. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18036. [&](Stream &strm) {
  18037. if (strm.write(req.data(), req.size()) !=
  18038. static_cast<ssize_t>(req.size())) {
  18039. return false;
  18040. }
  18041. char buf[512];
  18042. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18043. // Headers plus the two-byte body of the handler below
  18044. while (reader.getline()) {
  18045. first_response += reader.ptr();
  18046. if (first_response.find("ok") != std::string::npos) { break; }
  18047. }
  18048. if (strm.write(second.data(), second.size()) !=
  18049. static_cast<ssize_t>(second.size())) {
  18050. return true;
  18051. }
  18052. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18053. while (reader2.getline()) {
  18054. second_response += reader2.ptr();
  18055. if (second_response.find("ok") != std::string::npos) { break; }
  18056. }
  18057. return true;
  18058. });
  18059. *announced_close =
  18060. first_response.find("Connection: close") != std::string::npos;
  18061. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18062. }
  18063. class ConnectionTokenTest : public ::testing::Test {
  18064. protected:
  18065. void SetUp() override {
  18066. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18067. res.set_content("ok", "text/plain");
  18068. });
  18069. port_ = svr_.bind_to_any_port(HOST);
  18070. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18071. svr_.wait_until_ready();
  18072. }
  18073. void TearDown() override {
  18074. svr_.stop();
  18075. if (thread_.joinable()) { thread_.join(); }
  18076. }
  18077. Server svr_;
  18078. int port_ = 0;
  18079. thread thread_;
  18080. };
  18081. // "close" alongside another option still closes the connection, and the
  18082. // response says so rather than leaving the peer to discover it.
  18083. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18084. bool announced_close = false;
  18085. bool reusable = true;
  18086. probe_connection_reuse(port_,
  18087. "GET /keepalive HTTP/1.1\r\n"
  18088. "Host: localhost\r\n"
  18089. "Connection: keep-alive, close\r\n"
  18090. "\r\n",
  18091. &announced_close, &reusable);
  18092. EXPECT_TRUE(announced_close);
  18093. EXPECT_FALSE(reusable);
  18094. }
  18095. // "close" split over two field lines is the same list, so it is honored too.
  18096. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18097. bool announced_close = false;
  18098. bool reusable = true;
  18099. probe_connection_reuse(port_,
  18100. "GET /keepalive HTTP/1.1\r\n"
  18101. "Host: localhost\r\n"
  18102. "Connection: keep-alive\r\n"
  18103. "Connection: close\r\n"
  18104. "\r\n",
  18105. &announced_close, &reusable);
  18106. EXPECT_TRUE(announced_close);
  18107. EXPECT_FALSE(reusable);
  18108. }
  18109. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18110. // keep-alive in the spelling everyone actually sends keeps its connection.
  18111. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18112. bool announced_close = false;
  18113. bool reusable = false;
  18114. probe_connection_reuse(port_,
  18115. "GET /keepalive HTTP/1.0\r\n"
  18116. "Host: localhost\r\n"
  18117. "Connection: keep-alive\r\n"
  18118. "\r\n",
  18119. &announced_close, &reusable);
  18120. EXPECT_FALSE(announced_close);
  18121. EXPECT_TRUE(reusable);
  18122. }
  18123. // A token the value merely contains is not the token itself.
  18124. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18125. bool announced_close = false;
  18126. bool reusable = false;
  18127. probe_connection_reuse(port_,
  18128. "GET /keepalive HTTP/1.1\r\n"
  18129. "Host: localhost\r\n"
  18130. "Connection: notclose\r\n"
  18131. "\r\n",
  18132. &announced_close, &reusable);
  18133. EXPECT_FALSE(announced_close);
  18134. EXPECT_TRUE(reusable);
  18135. }
  18136. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18137. Server svr;
  18138. std::vector<std::string> observed_types;
  18139. svr.Get("/", [&](const Request &req, Response &res) {
  18140. observed_types = req.accept_content_types;
  18141. res.set_content("ok", "text/plain");
  18142. });
  18143. auto port = svr.bind_to_any_port(HOST);
  18144. thread t = thread([&]() { svr.listen_after_bind(); });
  18145. auto se = detail::scope_exit([&] {
  18146. svr.stop();
  18147. t.join();
  18148. ASSERT_FALSE(svr.is_running());
  18149. });
  18150. svr.wait_until_ready();
  18151. Client cli(HOST, port);
  18152. Headers headers;
  18153. headers.emplace("Accept", "text/plain;q=0.5");
  18154. headers.emplace("Accept", "application/json");
  18155. auto res = cli.Get("/", headers);
  18156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18157. EXPECT_EQ(StatusCode::OK_200, res->status);
  18158. // Sorted by q-value, so the second field line's type comes first
  18159. ASSERT_EQ(2U, observed_types.size());
  18160. EXPECT_EQ("application/json", observed_types[0]);
  18161. EXPECT_EQ("text/plain", observed_types[1]);
  18162. }
  18163. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18164. // empty field line must not contribute a bare comma to the combined value.
  18165. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18166. Server svr;
  18167. std::vector<std::string> observed_types;
  18168. svr.Get("/", [&](const Request &req, Response &res) {
  18169. observed_types = req.accept_content_types;
  18170. res.set_content("ok", "text/plain");
  18171. });
  18172. auto port = svr.bind_to_any_port(HOST);
  18173. thread t = thread([&]() { svr.listen_after_bind(); });
  18174. auto se = detail::scope_exit([&] {
  18175. svr.stop();
  18176. t.join();
  18177. ASSERT_FALSE(svr.is_running());
  18178. });
  18179. svr.wait_until_ready();
  18180. // Empty first field line, then a real one
  18181. std::string raw_req = "GET / HTTP/1.1\r\n"
  18182. "Host: localhost\r\n"
  18183. "Accept:\r\n"
  18184. "Accept: application/json\r\n"
  18185. "Connection: close\r\n"
  18186. "\r\n";
  18187. std::string out;
  18188. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18189. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18190. ASSERT_EQ(1U, observed_types.size());
  18191. EXPECT_EQ("application/json", observed_types[0]);
  18192. }
  18193. // The skip in get_combined_header_value() is what keeps an empty field line
  18194. // from contributing a bare comma. Only a trailing empty field line exercises
  18195. // it: a leading one is already covered by the "combined is still empty" check,
  18196. // and parse_accept_header() now ignores the empty element either way, so the
  18197. // request-level test above can no longer tell the two apart.
  18198. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18199. Headers headers;
  18200. headers.emplace("Accept", "text/html");
  18201. headers.emplace("Accept", "");
  18202. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18203. headers.clear();
  18204. headers.emplace("Accept", "");
  18205. headers.emplace("Accept", "application/json");
  18206. EXPECT_EQ("application/json",
  18207. detail::get_combined_header_value(headers, "Accept"));
  18208. }
  18209. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18210. // An encoding offered on a later Accept-Encoding field line is still offered.
  18211. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18212. Server svr;
  18213. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18214. res.set_content(std::string(1024, 'x'), "text/plain");
  18215. });
  18216. auto port = svr.bind_to_any_port(HOST);
  18217. thread t = thread([&]() { svr.listen_after_bind(); });
  18218. auto se = detail::scope_exit([&] {
  18219. svr.stop();
  18220. t.join();
  18221. ASSERT_FALSE(svr.is_running());
  18222. });
  18223. svr.wait_until_ready();
  18224. Client cli(HOST, port);
  18225. cli.set_decompress(false);
  18226. Headers headers;
  18227. headers.emplace("Accept-Encoding", "identity");
  18228. headers.emplace("Accept-Encoding", "gzip");
  18229. auto res = cli.Get("/", headers);
  18230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18231. EXPECT_EQ(StatusCode::OK_200, res->status);
  18232. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18233. }
  18234. #endif
  18235. #ifndef _WIN32
  18236. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18237. Server svr;
  18238. svr.Post("/post", [&](const Request &req, Response &res) {
  18239. res.set_content(req.body, "text/plain");
  18240. });
  18241. svr.Put("/put", [&](const Request &req, Response &res) {
  18242. res.set_content(req.body, "text/plain");
  18243. });
  18244. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18245. res.set_content(req.body, "text/plain");
  18246. });
  18247. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18248. res.set_content(req.body, "text/plain");
  18249. });
  18250. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18251. auto se = detail::scope_exit([&] {
  18252. svr.stop();
  18253. t.join();
  18254. ASSERT_FALSE(svr.is_running());
  18255. });
  18256. svr.wait_until_ready();
  18257. std::string resp;
  18258. // POST without Content-Length
  18259. ASSERT_TRUE(send_request(5,
  18260. "POST /post HTTP/1.1\r\n"
  18261. "Host: localhost\r\n"
  18262. "Connection: close\r\n"
  18263. "\r\n",
  18264. &resp));
  18265. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18266. // PUT without Content-Length
  18267. resp.clear();
  18268. ASSERT_TRUE(send_request(5,
  18269. "PUT /put HTTP/1.1\r\n"
  18270. "Host: localhost\r\n"
  18271. "Connection: close\r\n"
  18272. "\r\n",
  18273. &resp));
  18274. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18275. // PATCH without Content-Length
  18276. resp.clear();
  18277. ASSERT_TRUE(send_request(5,
  18278. "PATCH /patch HTTP/1.1\r\n"
  18279. "Host: localhost\r\n"
  18280. "Connection: close\r\n"
  18281. "\r\n",
  18282. &resp));
  18283. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18284. // DELETE without Content-Length
  18285. resp.clear();
  18286. ASSERT_TRUE(send_request(5,
  18287. "DELETE /delete HTTP/1.1\r\n"
  18288. "Host: localhost\r\n"
  18289. "Connection: close\r\n"
  18290. "\r\n",
  18291. &resp));
  18292. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18293. }
  18294. #endif
  18295. //==============================================================================
  18296. // open_stream() Tests
  18297. //==============================================================================
  18298. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18299. std::string result;
  18300. char buf[8192];
  18301. ssize_t n;
  18302. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18303. result.append(buf, static_cast<size_t>(n));
  18304. }
  18305. return result;
  18306. }
  18307. // Mock stream for unit tests
  18308. class MockStream : public Stream {
  18309. public:
  18310. std::string data;
  18311. size_t pos = 0;
  18312. ssize_t error_after = -1; // -1 = no error
  18313. explicit MockStream(const std::string &d, ssize_t err = -1)
  18314. : data(d), error_after(err) {}
  18315. bool is_readable() const override { return true; }
  18316. bool wait_readable() const override { return true; }
  18317. bool wait_writable() const override { return true; }
  18318. ssize_t read(char *ptr, size_t size) override {
  18319. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18320. if (pos >= data.size()) return 0;
  18321. size_t limit =
  18322. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18323. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18324. std::memcpy(ptr, data.data() + pos, to_read);
  18325. pos += to_read;
  18326. return static_cast<ssize_t>(to_read);
  18327. }
  18328. ssize_t write(const char *, size_t) override { return -1; }
  18329. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18330. ip = "127.0.0.1";
  18331. port = 0;
  18332. }
  18333. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18334. ip = "127.0.0.1";
  18335. port = 0;
  18336. }
  18337. socket_t socket() const override { return INVALID_SOCKET; }
  18338. time_t duration() const override { return 0; }
  18339. };
  18340. TEST(StreamHandleTest, Basic) {
  18341. ClientImpl::StreamHandle handle;
  18342. EXPECT_FALSE(handle.is_valid());
  18343. handle.response = detail::make_unique<Response>();
  18344. handle.error = Error::Connection;
  18345. EXPECT_FALSE(handle.is_valid());
  18346. handle.error = Error::Success;
  18347. EXPECT_TRUE(handle.is_valid());
  18348. }
  18349. TEST(BodyReaderTest, Basic) {
  18350. MockStream stream("Hello, World!");
  18351. detail::BodyReader reader;
  18352. reader.stream = &stream;
  18353. reader.content_length = 13;
  18354. char buf[32];
  18355. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18356. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18357. EXPECT_TRUE(reader.eof);
  18358. }
  18359. TEST(BodyReaderTest, NoStream) {
  18360. detail::BodyReader reader;
  18361. char buf[32];
  18362. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18363. EXPECT_EQ(Error::Connection, reader.last_error);
  18364. }
  18365. TEST(BodyReaderTest, Error) {
  18366. MockStream stream("Hello, World!", 5);
  18367. detail::BodyReader reader;
  18368. reader.stream = &stream;
  18369. reader.content_length = 13;
  18370. char buf[32];
  18371. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18372. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18373. EXPECT_EQ(Error::Read, reader.last_error);
  18374. }
  18375. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18376. // Mock-based StreamHandle tests relying on private internals are removed.
  18377. class OpenStreamTest : public ::testing::Test {
  18378. protected:
  18379. void SetUp() override {
  18380. svr_.Get("/hello", [](const Request &, Response &res) {
  18381. res.set_content("Hello World!", "text/plain");
  18382. });
  18383. svr_.Get("/large", [](const Request &, Response &res) {
  18384. res.set_content(std::string(10000, 'X'), "text/plain");
  18385. });
  18386. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18387. res.set_content("Hello World!", "image/jpeg");
  18388. res.set_header("Content-Encoding", "UTF-8");
  18389. });
  18390. svr_.Get("/chunked", [](const Request &, Response &res) {
  18391. res.set_chunked_content_provider("text/plain",
  18392. [](size_t offset, DataSink &sink) {
  18393. if (offset < 15) {
  18394. sink.write("chunk", 5);
  18395. return true;
  18396. }
  18397. sink.done();
  18398. return true;
  18399. });
  18400. });
  18401. svr_.Get("/compressible", [](const Request &, Response &res) {
  18402. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18403. DataSink &sink) {
  18404. if (offset < 100 * 1024) {
  18405. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18406. sink.write(chunk.data(), chunk.size());
  18407. return true;
  18408. }
  18409. sink.done();
  18410. return true;
  18411. });
  18412. });
  18413. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18414. [](const Request & /*req*/, Response &res) {
  18415. auto i = new int(0);
  18416. res.set_header("Trailer", "Content-Length, X-Allowed");
  18417. res.set_chunked_content_provider(
  18418. "text/plain",
  18419. [i](size_t /*offset*/, DataSink &sink) {
  18420. switch (*i) {
  18421. case 0: sink.os << "123"; break;
  18422. case 1: sink.os << "456"; break;
  18423. case 2: sink.os << "789"; break;
  18424. case 3: {
  18425. sink.done_with_trailer(
  18426. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18427. } break;
  18428. }
  18429. (*i)++;
  18430. return true;
  18431. },
  18432. [i](bool success) {
  18433. EXPECT_TRUE(success);
  18434. delete i;
  18435. });
  18436. });
  18437. // Echo headers endpoint for header-related tests
  18438. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18439. std::string body;
  18440. for (const auto &h : req.headers) {
  18441. body.append(h.first);
  18442. body.push_back(':');
  18443. body.append(h.second);
  18444. body.push_back('\n');
  18445. }
  18446. res.set_content(body, "text/plain");
  18447. });
  18448. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18449. std::string body;
  18450. for (const auto &h : req.headers) {
  18451. body.append(h.first);
  18452. body.push_back(':');
  18453. body.append(h.second);
  18454. body.push_back('\n');
  18455. }
  18456. res.set_content(body, "text/plain");
  18457. });
  18458. port_ = svr_.bind_to_any_port("127.0.0.1");
  18459. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18460. svr_.wait_until_ready();
  18461. }
  18462. void TearDown() override {
  18463. svr_.stop();
  18464. if (thread_.joinable()) thread_.join();
  18465. }
  18466. Server svr_;
  18467. std::thread thread_;
  18468. int port_ = 0;
  18469. };
  18470. TEST_F(OpenStreamTest, Basic) {
  18471. Client cli("127.0.0.1", port_);
  18472. auto handle = cli.open_stream("GET", "/hello");
  18473. EXPECT_TRUE(handle.is_valid());
  18474. EXPECT_EQ("Hello World!", read_all(handle));
  18475. }
  18476. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18477. Client cli("127.0.0.1", port_);
  18478. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18479. ASSERT_TRUE(handle.is_valid());
  18480. EXPECT_EQ("Hello World!", read_all(handle));
  18481. }
  18482. TEST_F(OpenStreamTest, SmallBuffer) {
  18483. Client cli("127.0.0.1", port_);
  18484. auto handle = cli.open_stream("GET", "/hello");
  18485. std::string result;
  18486. char buf[4];
  18487. ssize_t n;
  18488. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18489. result.append(buf, static_cast<size_t>(n));
  18490. EXPECT_EQ("Hello World!", result);
  18491. }
  18492. TEST_F(OpenStreamTest, DefaultHeaders) {
  18493. Client cli("127.0.0.1", port_);
  18494. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18495. {
  18496. auto handle = cli.open_stream("GET", "/echo-headers");
  18497. ASSERT_TRUE(handle.is_valid());
  18498. auto body = read_all(handle);
  18499. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18500. std::string::npos);
  18501. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18502. std::string::npos);
  18503. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18504. }
  18505. // open_stream POST with body and no explicit content_type should NOT add
  18506. // text/plain Content-Type (behavior differs from non-streaming path), but
  18507. // should include Content-Length
  18508. {
  18509. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18510. ASSERT_TRUE(handle.is_valid());
  18511. auto body = read_all(handle);
  18512. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18513. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18514. }
  18515. // open_stream POST with explicit Content-Type should preserve it
  18516. {
  18517. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18518. {{"Content-Type", "application/custom"}},
  18519. "{}", "application/custom");
  18520. ASSERT_TRUE(handle.is_valid());
  18521. auto body = read_all(handle);
  18522. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18523. }
  18524. // User-specified User-Agent must not be overwritten for stream API
  18525. {
  18526. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18527. {{"User-Agent", "MyAgent/1.2"}});
  18528. ASSERT_TRUE(handle.is_valid());
  18529. auto body = read_all(handle);
  18530. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18531. }
  18532. }
  18533. TEST_F(OpenStreamTest, Large) {
  18534. Client cli("127.0.0.1", port_);
  18535. auto handle = cli.open_stream("GET", "/large");
  18536. EXPECT_EQ(10000u, read_all(handle).size());
  18537. }
  18538. TEST_F(OpenStreamTest, ConnectionError) {
  18539. Client cli("127.0.0.1", 9999);
  18540. auto handle = cli.open_stream("GET", "/hello");
  18541. EXPECT_FALSE(handle.is_valid());
  18542. }
  18543. TEST_F(OpenStreamTest, Chunked) {
  18544. Client cli("127.0.0.1", port_);
  18545. auto handle = cli.open_stream("GET", "/chunked");
  18546. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18547. "Transfer-Encoding") == "chunked");
  18548. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18549. }
  18550. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18551. Client cli("127.0.0.1", port_);
  18552. auto handle =
  18553. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18554. ASSERT_TRUE(handle.is_valid());
  18555. // Consume body to allow trailers to be received/parsed
  18556. auto body = read_all(handle);
  18557. // Explicitly parse trailers (ensure trailers are available for assertion)
  18558. handle.parse_trailers_if_needed();
  18559. EXPECT_EQ(std::string("123456789"), body);
  18560. // The response should include a Trailer header declaring both names
  18561. ASSERT_TRUE(handle.response);
  18562. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18563. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18564. handle.response->get_header_value("Trailer"));
  18565. // Prohibited trailer must not be present
  18566. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18567. // Allowed trailer should be present
  18568. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18569. EXPECT_EQ(std::string("yes"),
  18570. handle.response->get_trailer_value("X-Allowed"));
  18571. // Verify trailers are NOT present as regular headers
  18572. EXPECT_EQ(std::string(""),
  18573. handle.response->get_header_value("Content-Length"));
  18574. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18575. }
  18576. static std::thread serve_single_response(std::promise<int> &port_promise,
  18577. const std::string &response) {
  18578. return std::thread([&port_promise, response] {
  18579. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18580. default_socket_options(srv);
  18581. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18582. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18583. sockaddr_in addr{};
  18584. addr.sin_family = AF_INET;
  18585. addr.sin_port = htons(0); // Let OS assign a free port
  18586. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18587. int opt = 1;
  18588. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18589. #ifdef _WIN32
  18590. reinterpret_cast<const char *>(&opt),
  18591. #else
  18592. &opt,
  18593. #endif
  18594. sizeof(opt));
  18595. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18596. ::listen(srv, 1) != 0) {
  18597. port_promise.set_value(-1);
  18598. detail::close_socket(srv);
  18599. return;
  18600. }
  18601. socklen_t addr_len = sizeof(addr);
  18602. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18603. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18604. sockaddr_in cli_addr{};
  18605. socklen_t cli_len = sizeof(cli_addr);
  18606. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18607. if (cli != INVALID_SOCKET) {
  18608. // Read the complete HTTP request (until the blank line that terminates
  18609. // headers) before sending the response. If the server closes the socket
  18610. // while the client's request data is still unread in the kernel receive
  18611. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18612. // connection on both sides: it discards the client's receive buffer
  18613. // (which already holds our response) and causes any in-progress write on
  18614. // the client to fail with ECONNRESET. Reading all request data first
  18615. // ensures close() emits a graceful FIN.
  18616. {
  18617. char rbuf[256];
  18618. std::string req;
  18619. while (req.find("\r\n\r\n") == std::string::npos) {
  18620. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18621. if (n <= 0) { break; }
  18622. req.append(rbuf, static_cast<size_t>(n));
  18623. }
  18624. }
  18625. ::send(cli,
  18626. #ifdef _WIN32
  18627. static_cast<const char *>(response.c_str()),
  18628. static_cast<int>(response.size()),
  18629. #else
  18630. response.c_str(), response.size(),
  18631. #endif
  18632. 0);
  18633. detail::close_socket(cli);
  18634. }
  18635. detail::close_socket(srv);
  18636. });
  18637. }
  18638. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18639. #ifndef _WIN32
  18640. signal(SIGPIPE, SIG_IGN);
  18641. #endif
  18642. std::promise<int> port_promise;
  18643. auto port_future = port_promise.get_future();
  18644. auto server_thread =
  18645. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18646. "Content-Type: text/plain\r\n"
  18647. "Content-Length: not-a-number\r\n"
  18648. "Connection: close\r\n"
  18649. "\r\n"
  18650. "hello");
  18651. auto port = port_future.get();
  18652. ASSERT_GT(port, 0);
  18653. Client cli("127.0.0.1", port);
  18654. auto handle = cli.open_stream("GET", "/");
  18655. EXPECT_FALSE(handle.is_valid());
  18656. server_thread.join();
  18657. }
  18658. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18659. #ifndef _WIN32
  18660. signal(SIGPIPE, SIG_IGN);
  18661. #endif
  18662. std::promise<int> port_promise;
  18663. auto port_future = port_promise.get_future();
  18664. auto server_thread = serve_single_response(
  18665. port_promise, "HTTP/1.1 200 OK\r\n"
  18666. "Content-Type: text/plain\r\n"
  18667. "Content-Length: 99999999999999999999999999\r\n"
  18668. "Connection: close\r\n"
  18669. "\r\n"
  18670. "hello");
  18671. auto port = port_future.get();
  18672. ASSERT_GT(port, 0);
  18673. // Historically std::stoull would throw std::out_of_range here and crash
  18674. // the process, then parsing silently clamped to a bogus framing length and
  18675. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18676. // so the stream fails to open, matching the not-a-number case above. The
  18677. // process still must NOT terminate.
  18678. Client cli("127.0.0.1", port);
  18679. auto handle = cli.open_stream("GET", "/");
  18680. EXPECT_FALSE(handle.is_valid());
  18681. server_thread.join();
  18682. }
  18683. // Serves `response` to the single request `fn` makes with a fresh client.
  18684. template <typename Fn>
  18685. static void with_single_response(const std::string &response, Fn fn) {
  18686. #ifndef _WIN32
  18687. signal(SIGPIPE, SIG_IGN);
  18688. #endif
  18689. std::promise<int> port_promise;
  18690. auto port_future = port_promise.get_future();
  18691. auto server_thread = serve_single_response(port_promise, response);
  18692. auto se = detail::scope_exit([&] { server_thread.join(); });
  18693. auto port = port_future.get();
  18694. ASSERT_GT(port, 0);
  18695. Client cli("127.0.0.1", port);
  18696. fn(cli);
  18697. }
  18698. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18699. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18700. // the chunked coding and drop Content-Length, so a front-end that trusts
  18701. // Content-Length would disagree about where the body ends (response
  18702. // smuggling). The client must reject such a response.
  18703. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18704. for (const char *te : {"chunked", "gzip, chunked"}) {
  18705. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18706. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18707. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18708. "5\r\nhello\r\n0\r\n\r\n";
  18709. with_single_response(response, [&](Client &cli) {
  18710. auto res = cli.Get("/");
  18711. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18712. EXPECT_EQ(Error::Read, res.error()) << te;
  18713. });
  18714. with_single_response(response, [&](Client &cli) {
  18715. auto handle = cli.open_stream("GET", "/");
  18716. EXPECT_FALSE(handle.is_valid()) << te;
  18717. EXPECT_EQ(Error::Read, handle.error) << te;
  18718. });
  18719. }
  18720. }
  18721. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18722. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18723. // closing the connection (unlike a request, which must be rejected).
  18724. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18725. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18726. "Transfer-Encoding: chunked\r\n"
  18727. "Connection: close\r\n"
  18728. "\r\n"
  18729. "5\r\nhello\r\n0\r\n\r\n",
  18730. "HTTP/1.1 200 OK\r\n"
  18731. "Transfer-Encoding: gzip\r\n"
  18732. "Connection: close\r\n"
  18733. "\r\n"
  18734. "hello"}) {
  18735. with_single_response(response, [&](Client &cli) {
  18736. auto res = cli.Get("/");
  18737. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18738. EXPECT_EQ("hello", res->body);
  18739. });
  18740. with_single_response(response, [&](Client &cli) {
  18741. auto handle = cli.open_stream("GET", "/");
  18742. ASSERT_TRUE(handle.is_valid()) << response;
  18743. EXPECT_EQ("hello", read_all(handle));
  18744. });
  18745. }
  18746. }
  18747. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18748. // framing headers describe nothing to read and must not be rejected.
  18749. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18750. const std::string framing = "Content-Length: 5\r\n"
  18751. "Transfer-Encoding: chunked\r\n"
  18752. "Connection: close\r\n"
  18753. "\r\n";
  18754. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18755. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18756. });
  18757. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18758. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18759. });
  18760. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18761. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18762. with_single_response(response, [&](Client &cli) {
  18763. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18764. });
  18765. with_single_response(response, [&](Client &cli) {
  18766. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18767. });
  18768. }
  18769. }
  18770. // A payload max length of 0 means no limit, however the body is framed.
  18771. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18772. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18773. "Transfer-Encoding: chunked\r\n"
  18774. "\r\n"
  18775. "5\r\nhello\r\n0\r\n\r\n",
  18776. "HTTP/1.1 200 OK\r\n"
  18777. "Connection: close\r\n"
  18778. "\r\n"
  18779. "hello"}) {
  18780. with_single_response(response, [&](Client &cli) {
  18781. cli.set_payload_max_length(0);
  18782. auto res = cli.Get("/");
  18783. ASSERT_TRUE(res) << response;
  18784. EXPECT_EQ("hello", res->body) << response;
  18785. });
  18786. }
  18787. }
  18788. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18789. Server svr;
  18790. svr.set_payload_max_length(0);
  18791. svr.Post("/echo", [](const Request &req, Response &res) {
  18792. res.set_content(req.body, "text/plain");
  18793. });
  18794. auto port = svr.bind_to_any_port(HOST);
  18795. thread t = thread([&] { svr.listen_after_bind(); });
  18796. auto se = detail::scope_exit([&] {
  18797. svr.stop();
  18798. t.join();
  18799. ASSERT_FALSE(svr.is_running());
  18800. });
  18801. svr.wait_until_ready();
  18802. Client cli(HOST, port);
  18803. auto res = cli.Post(
  18804. "/echo",
  18805. [](size_t /*offset*/, DataSink &sink) {
  18806. sink.write("hello", 5);
  18807. sink.done();
  18808. return true;
  18809. },
  18810. "text/plain");
  18811. ASSERT_TRUE(res);
  18812. EXPECT_EQ(StatusCode::OK_200, res->status);
  18813. EXPECT_EQ("hello", res->body);
  18814. }
  18815. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18816. TEST_F(OpenStreamTest, Gzip) {
  18817. Client cli("127.0.0.1", port_);
  18818. auto handle = cli.open_stream("GET", "/compressible", {},
  18819. {{"Accept-Encoding", "gzip"}});
  18820. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18821. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18822. }
  18823. #endif
  18824. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18825. TEST_F(OpenStreamTest, Brotli) {
  18826. Client cli("127.0.0.1", port_);
  18827. auto handle =
  18828. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18829. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18830. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18831. }
  18832. #endif
  18833. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18834. TEST_F(OpenStreamTest, Zstd) {
  18835. Client cli("127.0.0.1", port_);
  18836. auto handle = cli.open_stream("GET", "/compressible", {},
  18837. {{"Accept-Encoding", "zstd"}});
  18838. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18839. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18840. }
  18841. #endif
  18842. #ifdef CPPHTTPLIB_SSL_ENABLED
  18843. class SSLOpenStreamTest : public ::testing::Test {
  18844. protected:
  18845. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18846. void SetUp() override {
  18847. svr_.Get("/hello", [](const Request &, Response &res) {
  18848. res.set_content("Hello SSL World!", "text/plain");
  18849. });
  18850. svr_.Get("/chunked", [](const Request &, Response &res) {
  18851. res.set_chunked_content_provider("text/plain",
  18852. [](size_t offset, DataSink &sink) {
  18853. if (offset < 15) {
  18854. sink.write("chunk", 5);
  18855. return true;
  18856. }
  18857. sink.done();
  18858. return true;
  18859. });
  18860. });
  18861. svr_.Post("/echo", [](const Request &req, Response &res) {
  18862. res.set_content(req.body, req.get_header_value("Content-Type"));
  18863. });
  18864. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18865. std::string body = req.body;
  18866. res.set_chunked_content_provider(
  18867. "text/plain", [body](size_t offset, DataSink &sink) {
  18868. if (offset < body.size()) {
  18869. sink.write(body.data() + offset, body.size() - offset);
  18870. }
  18871. sink.done();
  18872. return true;
  18873. });
  18874. });
  18875. port_ = svr_.bind_to_any_port("127.0.0.1");
  18876. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18877. svr_.wait_until_ready();
  18878. }
  18879. void TearDown() override {
  18880. svr_.stop();
  18881. if (thread_.joinable()) thread_.join();
  18882. }
  18883. SSLServer svr_;
  18884. std::thread thread_;
  18885. int port_ = 0;
  18886. };
  18887. TEST_F(SSLOpenStreamTest, Basic) {
  18888. SSLClient cli("127.0.0.1", port_);
  18889. cli.enable_server_certificate_verification(false);
  18890. auto handle = cli.open_stream("GET", "/hello");
  18891. ASSERT_TRUE(handle.is_valid());
  18892. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18893. }
  18894. TEST_F(SSLOpenStreamTest, Chunked) {
  18895. SSLClient cli("127.0.0.1", port_);
  18896. cli.enable_server_certificate_verification(false);
  18897. auto handle = cli.open_stream("GET", "/chunked");
  18898. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18899. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18900. "Transfer-Encoding") == "chunked");
  18901. auto body = read_all(handle);
  18902. EXPECT_EQ("chunkchunkchunk", body);
  18903. }
  18904. TEST_F(SSLOpenStreamTest, Post) {
  18905. SSLClient cli("127.0.0.1", port_);
  18906. cli.enable_server_certificate_verification(false);
  18907. auto handle =
  18908. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18909. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18910. EXPECT_EQ(200, handle.response->status);
  18911. auto body = read_all(handle);
  18912. EXPECT_EQ("Hello SSL POST", body);
  18913. }
  18914. TEST_F(SSLOpenStreamTest, PostChunked) {
  18915. SSLClient cli("127.0.0.1", port_);
  18916. cli.enable_server_certificate_verification(false);
  18917. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18918. "Chunked SSL Data", "text/plain");
  18919. ASSERT_TRUE(handle.is_valid());
  18920. EXPECT_EQ(200, handle.response->status);
  18921. auto body = read_all(handle);
  18922. EXPECT_EQ("Chunked SSL Data", body);
  18923. }
  18924. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18925. // Content-Length is terminated by the server closing the connection. When the
  18926. // SSL peer sends a close_notify after the body, the client must treat it as a
  18927. // clean EOF and return a successful response rather than an error.
  18928. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18930. ASSERT_TRUE(svr.is_valid());
  18931. svr.set_keep_alive_max_count(1);
  18932. const std::string expected_body = "Hello from connection-close response!";
  18933. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18934. res.set_content_provider("text/plain",
  18935. [&](size_t offset, DataSink &sink) -> bool {
  18936. if (offset < expected_body.size()) {
  18937. sink.write(expected_body.data() + offset,
  18938. expected_body.size() - offset);
  18939. }
  18940. sink.done();
  18941. return true;
  18942. });
  18943. });
  18944. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18945. auto se = detail::scope_exit([&] {
  18946. svr.stop();
  18947. listen_thread.join();
  18948. ASSERT_FALSE(svr.is_running());
  18949. });
  18950. svr.wait_until_ready();
  18951. SSLClient cli(HOST, PORT);
  18952. cli.enable_server_certificate_verification(false);
  18953. auto res = cli.Get("/no-content-length");
  18954. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18955. EXPECT_EQ(StatusCode::OK_200, res->status);
  18956. EXPECT_EQ(expected_body, res->body);
  18957. }
  18958. #endif // CPPHTTPLIB_SSL_ENABLED
  18959. //==============================================================================
  18960. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18961. // results for various scenarios.
  18962. //==============================================================================
  18963. TEST(ParityTest, GetVsOpenStream) {
  18964. Server svr;
  18965. const std::string path = "/parity";
  18966. const std::string content = "Parity test content: hello world";
  18967. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18968. res.set_content(content, "text/plain");
  18969. });
  18970. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18971. auto se = detail::scope_exit([&] {
  18972. svr.stop();
  18973. t.join();
  18974. ASSERT_FALSE(svr.is_running());
  18975. });
  18976. svr.wait_until_ready();
  18977. Client cli(HOST, PORT);
  18978. // Non-stream path
  18979. auto r1 = cli.Get(path);
  18980. ASSERT_TRUE(r1);
  18981. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18982. // Stream path
  18983. auto h = cli.open_stream("GET", path);
  18984. ASSERT_TRUE(h.is_valid());
  18985. EXPECT_EQ(r1->body, read_all(h));
  18986. }
  18987. // Helper to compress data with provided compressor type T
  18988. template <typename Compressor>
  18989. static std::string compress_payload_for_parity(const std::string &in) {
  18990. std::string out;
  18991. Compressor compressor;
  18992. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18993. [&](const char *data, size_t n) {
  18994. out.append(data, n);
  18995. return true;
  18996. });
  18997. EXPECT_TRUE(ok);
  18998. return out;
  18999. }
  19000. // Helper function for compression parity tests
  19001. template <typename Compressor>
  19002. static void test_compression_parity(const std::string &original,
  19003. const std::string &path,
  19004. const std::string &encoding) {
  19005. const std::string compressed =
  19006. compress_payload_for_parity<Compressor>(original);
  19007. Server svr;
  19008. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19009. res.set_content(compressed, "application/octet-stream");
  19010. res.set_header("Content-Encoding", encoding);
  19011. });
  19012. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19013. auto se = detail::scope_exit([&] {
  19014. svr.stop();
  19015. t.join();
  19016. ASSERT_FALSE(svr.is_running());
  19017. });
  19018. svr.wait_until_ready();
  19019. Client cli(HOST, PORT);
  19020. // Non-streaming
  19021. {
  19022. auto res = cli.Get(path);
  19023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19024. EXPECT_EQ(StatusCode::OK_200, res->status);
  19025. EXPECT_EQ(original, res->body);
  19026. }
  19027. // Streaming
  19028. {
  19029. auto h = cli.open_stream("GET", path);
  19030. ASSERT_TRUE(h.is_valid());
  19031. EXPECT_EQ(original, read_all(h));
  19032. }
  19033. }
  19034. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19035. TEST(ParityTest, Gzip) {
  19036. test_compression_parity<detail::gzip_compressor>(
  19037. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19038. }
  19039. #endif
  19040. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19041. TEST(ParityTest, Brotli) {
  19042. test_compression_parity<detail::brotli_compressor>(
  19043. "Hello, brotli parity test payload", "/parity-br", "br");
  19044. }
  19045. #endif
  19046. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19047. TEST(ParityTest, Zstd) {
  19048. test_compression_parity<detail::zstd_compressor>(
  19049. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19050. }
  19051. #endif
  19052. //==============================================================================
  19053. // New Stream API Tests
  19054. //==============================================================================
  19055. inline std::string read_body(httplib::stream::Result &result) {
  19056. std::string body;
  19057. while (result.next()) {
  19058. body.append(result.data(), result.size());
  19059. }
  19060. return body;
  19061. }
  19062. TEST(ClientConnectionTest, Basic) {
  19063. httplib::ClientConnection conn;
  19064. EXPECT_FALSE(conn.is_open());
  19065. conn.sock = 1;
  19066. EXPECT_TRUE(conn.is_open());
  19067. httplib::ClientConnection conn2(std::move(conn));
  19068. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19069. conn2.sock = INVALID_SOCKET;
  19070. }
  19071. // Unified test server for all stream::* tests
  19072. class StreamApiTest : public ::testing::Test {
  19073. protected:
  19074. void SetUp() override {
  19075. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19076. res.set_content("Hello World!", "text/plain");
  19077. });
  19078. svr_.Get("/echo-params",
  19079. [](const httplib::Request &req, httplib::Response &res) {
  19080. std::string r;
  19081. for (const auto &p : req.params) {
  19082. if (!r.empty()) r += "&";
  19083. r += p.first + "=" + p.second;
  19084. }
  19085. res.set_content(r, "text/plain");
  19086. });
  19087. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19088. res.set_content(req.body, req.get_header_value("Content-Type"));
  19089. });
  19090. svr_.Post("/echo-headers",
  19091. [](const httplib::Request &req, httplib::Response &res) {
  19092. std::string r;
  19093. for (const auto &h : req.headers)
  19094. r += h.first + ": " + h.second + "\n";
  19095. res.set_content(r, "text/plain");
  19096. });
  19097. svr_.Post("/echo-params",
  19098. [](const httplib::Request &req, httplib::Response &res) {
  19099. std::string r = "params:";
  19100. for (const auto &p : req.params)
  19101. r += p.first + "=" + p.second + ";";
  19102. res.set_content(r + " body:" + req.body, "text/plain");
  19103. });
  19104. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19105. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19106. });
  19107. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19108. res.set_content("PUT:" + req.body, "text/plain");
  19109. });
  19110. svr_.Patch("/echo",
  19111. [](const httplib::Request &req, httplib::Response &res) {
  19112. res.set_content("PATCH:" + req.body, "text/plain");
  19113. });
  19114. svr_.Delete(
  19115. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19116. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19117. "text/plain");
  19118. });
  19119. svr_.Get("/head-test",
  19120. [](const httplib::Request &, httplib::Response &res) {
  19121. res.set_content("body for HEAD", "text/plain");
  19122. });
  19123. svr_.Options("/options",
  19124. [](const httplib::Request &, httplib::Response &res) {
  19125. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19126. });
  19127. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19128. svr_.wait_until_ready();
  19129. }
  19130. void TearDown() override {
  19131. svr_.stop();
  19132. if (thread_.joinable()) thread_.join();
  19133. }
  19134. httplib::Server svr_;
  19135. std::thread thread_;
  19136. };
  19137. // stream::Get tests
  19138. TEST_F(StreamApiTest, GetBasic) {
  19139. httplib::Client cli(HOST, PORT);
  19140. auto result = httplib::stream::Get(cli, "/hello");
  19141. ASSERT_TRUE(result.is_valid());
  19142. EXPECT_EQ(200, result.status());
  19143. EXPECT_EQ("Hello World!", read_body(result));
  19144. }
  19145. TEST_F(StreamApiTest, GetWithParams) {
  19146. httplib::Client cli(HOST, PORT);
  19147. httplib::Params params{{"foo", "bar"}};
  19148. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19149. ASSERT_TRUE(result.is_valid());
  19150. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19151. }
  19152. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19153. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19154. httplib::Client cli(HOST, PORT);
  19155. cli.set_payload_max_length(0);
  19156. auto result = httplib::stream::Get(cli, "/hello");
  19157. ASSERT_TRUE(result.is_valid());
  19158. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19159. EXPECT_EQ("Hello World!", read_body(result));
  19160. }
  19161. #endif
  19162. TEST_F(StreamApiTest, GetConnectionError) {
  19163. httplib::Client cli(HOST, 9999);
  19164. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19165. }
  19166. TEST_F(StreamApiTest, Get404) {
  19167. httplib::Client cli(HOST, PORT);
  19168. auto result = httplib::stream::Get(cli, "/nonexistent");
  19169. EXPECT_TRUE(result.is_valid());
  19170. EXPECT_EQ(404, result.status());
  19171. }
  19172. // stream::Post tests
  19173. TEST_F(StreamApiTest, PostBasic) {
  19174. httplib::Client cli(HOST, PORT);
  19175. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19176. "application/json");
  19177. ASSERT_TRUE(result.is_valid());
  19178. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19179. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19180. }
  19181. TEST_F(StreamApiTest, PostWithHeaders) {
  19182. httplib::Client cli(HOST, PORT);
  19183. httplib::Headers headers{{"X-Custom", "value"}};
  19184. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19185. "text/plain");
  19186. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19187. }
  19188. TEST_F(StreamApiTest, PostWithParams) {
  19189. httplib::Client cli(HOST, PORT);
  19190. httplib::Params params{{"k", "v"}};
  19191. auto result =
  19192. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19193. auto body = read_body(result);
  19194. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19195. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19196. }
  19197. TEST_F(StreamApiTest, PostLarge) {
  19198. httplib::Client cli(HOST, PORT);
  19199. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19200. size_t total = 0;
  19201. while (result.next()) {
  19202. total += result.size();
  19203. }
  19204. EXPECT_EQ(100u * 1024u, total);
  19205. }
  19206. // stream::Put/Patch tests
  19207. TEST_F(StreamApiTest, PutAndPatch) {
  19208. httplib::Client cli(HOST, PORT);
  19209. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19210. EXPECT_EQ("PUT:test", read_body(put));
  19211. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19212. EXPECT_EQ("PATCH:test", read_body(patch));
  19213. }
  19214. // stream::Delete tests
  19215. TEST_F(StreamApiTest, Delete) {
  19216. httplib::Client cli(HOST, PORT);
  19217. auto del1 = httplib::stream::Delete(cli, "/resource");
  19218. EXPECT_EQ("Deleted", read_body(del1));
  19219. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19220. EXPECT_EQ("Deleted:data", read_body(del2));
  19221. }
  19222. // stream::Head/Options tests
  19223. TEST_F(StreamApiTest, HeadAndOptions) {
  19224. httplib::Client cli(HOST, PORT);
  19225. auto head = httplib::stream::Head(cli, "/head-test");
  19226. EXPECT_TRUE(head.is_valid());
  19227. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19228. auto opts = httplib::stream::Options(cli, "/options");
  19229. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19230. }
  19231. // SSL stream::* tests
  19232. #ifdef CPPHTTPLIB_SSL_ENABLED
  19233. class SSLStreamApiTest : public ::testing::Test {
  19234. protected:
  19235. void SetUp() override {
  19236. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19237. res.set_content("Hello SSL!", "text/plain");
  19238. });
  19239. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19240. res.set_content(req.body, "text/plain");
  19241. });
  19242. port_ = svr_.bind_to_any_port("127.0.0.1");
  19243. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19244. svr_.wait_until_ready();
  19245. }
  19246. void TearDown() override {
  19247. svr_.stop();
  19248. if (thread_.joinable()) thread_.join();
  19249. }
  19250. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19251. std::thread thread_;
  19252. int port_ = 0;
  19253. };
  19254. TEST_F(SSLStreamApiTest, GetAndPost) {
  19255. httplib::SSLClient cli("127.0.0.1", port_);
  19256. cli.enable_server_certificate_verification(false);
  19257. auto get = httplib::stream::Get(cli, "/hello");
  19258. EXPECT_EQ("Hello SSL!", read_body(get));
  19259. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19260. EXPECT_EQ("test", read_body(post));
  19261. }
  19262. #endif
  19263. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19264. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19265. // BodyReader
  19266. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19267. // Test that read timeout during streaming is detected
  19268. // Use a large content-length response where server delays mid-stream
  19269. Server svr;
  19270. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19271. // Send a large response with delay in the middle
  19272. res.set_content_provider(
  19273. 1000, // content_length
  19274. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19275. if (offset < 100) {
  19276. // Send first 100 bytes immediately
  19277. std::string data(100, 'A');
  19278. sink.write(data.c_str(), data.size());
  19279. return true;
  19280. }
  19281. // Then delay longer than client timeout
  19282. std::this_thread::sleep_for(std::chrono::seconds(3));
  19283. std::string data(900, 'B');
  19284. sink.write(data.c_str(), data.size());
  19285. return true;
  19286. });
  19287. });
  19288. auto port = 8091;
  19289. std::thread t([&]() { svr.listen("localhost", port); });
  19290. svr.wait_until_ready();
  19291. Client cli("localhost", port);
  19292. cli.set_read_timeout(1, 0); // 1 second timeout
  19293. auto handle = cli.open_stream("GET", "/slow-stream");
  19294. ASSERT_TRUE(handle.is_valid());
  19295. char buf[256];
  19296. ssize_t total = 0;
  19297. ssize_t n;
  19298. bool got_error = false;
  19299. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19300. total += n;
  19301. }
  19302. if (n < 0) {
  19303. got_error = true;
  19304. // Should be timeout or read error
  19305. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19306. handle.get_read_error() == Error::Read)
  19307. << "Actual error: " << to_string(handle.get_read_error());
  19308. }
  19309. // Either we got an error, or we got less data than expected
  19310. EXPECT_TRUE(got_error || total < 1000)
  19311. << "Expected timeout but got all " << total << " bytes";
  19312. svr.stop();
  19313. t.join();
  19314. }
  19315. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19316. // Test connection closed detection via BodyReader
  19317. Server svr;
  19318. std::atomic<bool> close_now{false};
  19319. svr.Get("/will-close", [&](const Request &, Response &res) {
  19320. res.set_content_provider(
  19321. 10000, // Large content_length that we won't fully send
  19322. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19323. if (offset < 100) {
  19324. std::string data(100, 'X');
  19325. sink.write(data.c_str(), data.size());
  19326. return true;
  19327. }
  19328. // Wait for signal then abort
  19329. while (!close_now) {
  19330. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19331. }
  19332. return false; // Abort - server will close connection
  19333. });
  19334. });
  19335. auto port = 8092;
  19336. std::thread t([&]() { svr.listen("localhost", port); });
  19337. svr.wait_until_ready();
  19338. Client cli("localhost", port);
  19339. auto handle = cli.open_stream("GET", "/will-close");
  19340. ASSERT_TRUE(handle.is_valid());
  19341. char buf[256];
  19342. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19343. EXPECT_GT(n, 0) << "First read should succeed";
  19344. // Signal server to close
  19345. close_now = true;
  19346. // Keep reading until error or EOF
  19347. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19348. // Keep reading
  19349. }
  19350. // Should get an error since content_length wasn't satisfied
  19351. if (n < 0) {
  19352. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19353. handle.get_read_error() == Error::Read)
  19354. << "Actual error: " << to_string(handle.get_read_error());
  19355. }
  19356. svr.stop();
  19357. t.join();
  19358. }
  19359. #ifdef CPPHTTPLIB_SSL_ENABLED
  19360. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19361. // Test that read timeout during SSL streaming is detected
  19362. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19363. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19364. res.set_content_provider(
  19365. 1000, "text/plain",
  19366. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19367. if (offset < 100) {
  19368. std::string data(100, 'A');
  19369. sink.write(data.c_str(), data.size());
  19370. return true;
  19371. }
  19372. std::this_thread::sleep_for(std::chrono::seconds(3));
  19373. std::string data(900, 'B');
  19374. sink.write(data.c_str(), data.size());
  19375. return true;
  19376. });
  19377. });
  19378. auto port = 8093;
  19379. std::thread t([&]() { svr.listen("localhost", port); });
  19380. svr.wait_until_ready();
  19381. SSLClient cli("localhost", port);
  19382. cli.enable_server_certificate_verification(false);
  19383. cli.set_read_timeout(1, 0); // 1 second timeout
  19384. auto handle = cli.open_stream("GET", "/slow-stream");
  19385. ASSERT_TRUE(handle.is_valid());
  19386. char buf[256];
  19387. ssize_t total = 0;
  19388. ssize_t n;
  19389. bool got_error = false;
  19390. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19391. total += n;
  19392. }
  19393. if (n < 0) {
  19394. got_error = true;
  19395. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19396. handle.get_read_error() == Error::Read)
  19397. << "Actual error: " << to_string(handle.get_read_error());
  19398. }
  19399. EXPECT_TRUE(got_error || total < 1000)
  19400. << "Expected timeout but got all " << total << " bytes";
  19401. svr.stop();
  19402. t.join();
  19403. }
  19404. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19405. // Test SSL connection closed detection
  19406. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19407. std::atomic<bool> close_now{false};
  19408. svr.Get("/will-close", [&](const Request &, Response &res) {
  19409. res.set_content_provider(
  19410. 10000, "text/plain",
  19411. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19412. if (offset < 100) {
  19413. std::string data(100, 'X');
  19414. sink.write(data.c_str(), data.size());
  19415. return true;
  19416. }
  19417. while (!close_now) {
  19418. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19419. }
  19420. return false;
  19421. });
  19422. });
  19423. auto port = 8094;
  19424. std::thread t([&]() { svr.listen("localhost", port); });
  19425. svr.wait_until_ready();
  19426. SSLClient cli("localhost", port);
  19427. cli.enable_server_certificate_verification(false);
  19428. auto handle = cli.open_stream("GET", "/will-close");
  19429. ASSERT_TRUE(handle.is_valid());
  19430. char buf[256];
  19431. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19432. EXPECT_GT(n, 0);
  19433. // Signal server to close
  19434. close_now = true;
  19435. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19436. // Keep reading
  19437. }
  19438. if (n < 0) {
  19439. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19440. handle.get_read_error() == Error::Read)
  19441. << "Actual error: " << to_string(handle.get_read_error());
  19442. }
  19443. svr.stop();
  19444. t.join();
  19445. }
  19446. #endif
  19447. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19448. using namespace httplib;
  19449. // Create a test file
  19450. const char *fname = "etag_testfile.txt";
  19451. const char *content = "etag-content";
  19452. {
  19453. std::ofstream ofs(fname);
  19454. ofs << content;
  19455. ASSERT_TRUE(ofs.good());
  19456. }
  19457. Server svr;
  19458. svr.set_mount_point("/static", ".");
  19459. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19460. svr.wait_until_ready();
  19461. Client cli(HOST, PORT);
  19462. // First request: should get 200 with ETag header
  19463. auto res1 = cli.Get("/static/etag_testfile.txt");
  19464. ASSERT_TRUE(res1);
  19465. ASSERT_EQ(200, res1->status);
  19466. ASSERT_TRUE(res1->has_header("ETag"));
  19467. std::string etag = res1->get_header_value("ETag");
  19468. EXPECT_FALSE(etag.empty());
  19469. // Verify ETag format: W/"hex-hex"
  19470. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19471. EXPECT_EQ('W', etag[0]);
  19472. EXPECT_EQ('/', etag[1]);
  19473. EXPECT_EQ('"', etag[2]);
  19474. EXPECT_EQ('"', etag.back());
  19475. // Exact match: expect 304 Not Modified
  19476. Headers h2 = {{"If-None-Match", etag}};
  19477. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19478. ASSERT_TRUE(res2);
  19479. EXPECT_EQ(304, res2->status);
  19480. // Wildcard match: expect 304 Not Modified
  19481. Headers h3 = {{"If-None-Match", "*"}};
  19482. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19483. ASSERT_TRUE(res3);
  19484. EXPECT_EQ(304, res3->status);
  19485. // Non-matching ETag: expect 200
  19486. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19487. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19488. ASSERT_TRUE(res4);
  19489. EXPECT_EQ(200, res4->status);
  19490. // Multiple ETags with one matching: expect 304
  19491. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19492. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19493. ASSERT_TRUE(res5);
  19494. EXPECT_EQ(304, res5->status);
  19495. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19496. // that equivalent to the single comma-separated list above, so the match on
  19497. // the second line must still be found.
  19498. Headers h6;
  19499. h6.emplace("If-None-Match", "W/\"other\"");
  19500. h6.emplace("If-None-Match", etag);
  19501. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19502. ASSERT_TRUE(res6);
  19503. EXPECT_EQ(304, res6->status);
  19504. svr.stop();
  19505. t.join();
  19506. std::remove(fname);
  19507. }
  19508. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19509. using namespace httplib;
  19510. Server svr;
  19511. svr.set_mount_point("/static", ".");
  19512. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19513. svr.wait_until_ready();
  19514. Client cli(HOST, PORT);
  19515. // Send If-None-Match: * to a non-existent file
  19516. Headers h = {{"If-None-Match", "*"}};
  19517. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19519. EXPECT_EQ(404, res->status);
  19520. svr.stop();
  19521. t.join();
  19522. }
  19523. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19524. using namespace httplib;
  19525. // Create a test file
  19526. const char *fname = "etag_boundary_testfile.txt";
  19527. const char *content = "boundary-test";
  19528. {
  19529. std::ofstream ofs(fname);
  19530. ofs << content;
  19531. ASSERT_TRUE(ofs.good());
  19532. }
  19533. Server svr;
  19534. svr.set_mount_point("/static", ".");
  19535. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19536. svr.wait_until_ready();
  19537. Client cli(HOST, PORT);
  19538. // Get the actual ETag
  19539. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19540. ASSERT_TRUE(res1);
  19541. ASSERT_EQ(200, res1->status);
  19542. ASSERT_TRUE(res1->has_header("ETag"));
  19543. std::string etag = res1->get_header_value("ETag");
  19544. // Test 1: Very long ETag value (longer than actual ETag)
  19545. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19546. Headers h1 = {{"If-None-Match", "W/"
  19547. "\"very-long-etag-value-that-is-much-longer-"
  19548. "than-the-actual-etag-value\""}};
  19549. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19550. ASSERT_TRUE(res2);
  19551. EXPECT_EQ(200, res2->status); // Should not match
  19552. // Test 2: Long string followed by wildcard
  19553. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19554. // string)
  19555. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19556. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19557. ASSERT_TRUE(res3);
  19558. EXPECT_EQ(304, res3->status); // Should match on "*"
  19559. // Test 3: Wildcard followed by long string
  19560. // Should match on "*" immediately and return 304
  19561. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19562. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19563. ASSERT_TRUE(res4);
  19564. EXPECT_EQ(304, res4->status); // Should match on "*"
  19565. // Test 4: Multiple long non-matching values
  19566. // Should NOT match and return 200 (test that all comparisons are safe)
  19567. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19568. "W/\"second-long-non-matching-value\", "
  19569. "W/\"third-long-non-matching-value\""}};
  19570. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19571. ASSERT_TRUE(res5);
  19572. EXPECT_EQ(200, res5->status); // Should not match
  19573. // Test 5: Single character that is not "*" (edge case)
  19574. Headers h5 = {{"If-None-Match", "X"}};
  19575. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19576. ASSERT_TRUE(res6);
  19577. EXPECT_EQ(200, res6->status); // Should not match
  19578. svr.stop();
  19579. t.join();
  19580. std::remove(fname);
  19581. }
  19582. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19583. using namespace httplib;
  19584. // Create a test file
  19585. const char *fname = "ims_testfile.txt";
  19586. const char *content = "if-modified-since-test";
  19587. {
  19588. std::ofstream ofs(fname);
  19589. ofs << content;
  19590. ASSERT_TRUE(ofs.good());
  19591. }
  19592. Server svr;
  19593. svr.set_mount_point("/static", ".");
  19594. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19595. svr.wait_until_ready();
  19596. Client cli(HOST, PORT);
  19597. // First request: should get 200 with Last-Modified header
  19598. auto res1 = cli.Get("/static/ims_testfile.txt");
  19599. ASSERT_TRUE(res1);
  19600. ASSERT_EQ(200, res1->status);
  19601. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19602. std::string last_modified = res1->get_header_value("Last-Modified");
  19603. EXPECT_FALSE(last_modified.empty());
  19604. // If-Modified-Since with same time: expect 304
  19605. Headers h2 = {{"If-Modified-Since", last_modified}};
  19606. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19607. ASSERT_TRUE(res2);
  19608. EXPECT_EQ(304, res2->status);
  19609. // If-Modified-Since with future time: expect 304
  19610. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19611. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19612. ASSERT_TRUE(res3);
  19613. EXPECT_EQ(304, res3->status);
  19614. // If-Modified-Since with past time: expect 200
  19615. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19616. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19617. ASSERT_TRUE(res4);
  19618. EXPECT_EQ(200, res4->status);
  19619. // If-None-Match takes precedence over If-Modified-Since
  19620. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19621. ASSERT_TRUE(res1->has_header("ETag"));
  19622. std::string etag = res1->get_header_value("ETag");
  19623. Headers h5 = {{"If-None-Match", etag},
  19624. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19625. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19626. ASSERT_TRUE(res5);
  19627. EXPECT_EQ(304, res5->status);
  19628. svr.stop();
  19629. t.join();
  19630. std::remove(fname);
  19631. }
  19632. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19633. using namespace httplib;
  19634. Server svr;
  19635. // Endpoint that returns compressible content
  19636. svr.Get("/compressible", [](const Request &, Response &res) {
  19637. // Return a large enough body to trigger compression
  19638. std::string body(1000, 'a');
  19639. res.set_content(body, "text/plain");
  19640. });
  19641. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19642. svr.wait_until_ready();
  19643. Client cli(HOST, PORT);
  19644. // Request with gzip support: should get Vary header when compressed
  19645. cli.set_compress(true);
  19646. auto res1 = cli.Get("/compressible");
  19647. ASSERT_TRUE(res1);
  19648. EXPECT_EQ(200, res1->status);
  19649. // If Content-Encoding is set, Vary should also be set
  19650. if (res1->has_header("Content-Encoding")) {
  19651. EXPECT_TRUE(res1->has_header("Vary"));
  19652. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19653. }
  19654. // Request without Accept-Encoding header: should not have compression
  19655. Headers h_no_compress;
  19656. auto res2 = cli.Get("/compressible", h_no_compress);
  19657. ASSERT_TRUE(res2);
  19658. EXPECT_EQ(200, res2->status);
  19659. // Verify Vary header is present when compression is applied
  19660. // (the exact behavior depends on server configuration)
  19661. svr.stop();
  19662. t.join();
  19663. }
  19664. TEST(ETagTest, IfRangeWithETag) {
  19665. using namespace httplib;
  19666. // Create a test file with known content
  19667. const char *fname = "if_range_testfile.txt";
  19668. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19669. {
  19670. std::ofstream ofs(fname);
  19671. ofs << content;
  19672. ASSERT_TRUE(ofs.good());
  19673. }
  19674. Server svr;
  19675. svr.set_mount_point("/static", ".");
  19676. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19677. svr.wait_until_ready();
  19678. Client cli(HOST, PORT);
  19679. // First request: get ETag
  19680. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19681. ASSERT_TRUE(res1);
  19682. ASSERT_EQ(200, res1->status);
  19683. ASSERT_TRUE(res1->has_header("ETag"));
  19684. std::string etag = res1->get_header_value("ETag");
  19685. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19686. // Since our server generates weak ETags (W/"..."), If-Range with our
  19687. // ETag should NOT result in partial content - it should return full content.
  19688. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19689. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19690. ASSERT_TRUE(res2);
  19691. // Weak ETag in If-Range -> full content (200), not partial (206)
  19692. EXPECT_EQ(200, res2->status);
  19693. EXPECT_EQ(content, res2->body);
  19694. EXPECT_FALSE(res2->has_header("Content-Range"));
  19695. // Range request with non-matching If-Range (ETag): should get 200 (full
  19696. // content)
  19697. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19698. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19699. ASSERT_TRUE(res3);
  19700. EXPECT_EQ(200, res3->status);
  19701. EXPECT_EQ(content, res3->body);
  19702. EXPECT_FALSE(res3->has_header("Content-Range"));
  19703. // Range request with strong ETag (hypothetical - our server doesn't generate
  19704. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19705. // should return full content)
  19706. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19707. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19708. ASSERT_TRUE(res4);
  19709. EXPECT_EQ(200, res4->status);
  19710. EXPECT_EQ(content, res4->body);
  19711. EXPECT_FALSE(res4->has_header("Content-Range"));
  19712. svr.stop();
  19713. t.join();
  19714. std::remove(fname);
  19715. }
  19716. TEST(ETagTest, IfRangeWithDate) {
  19717. using namespace httplib;
  19718. // Create a test file
  19719. const char *fname = "if_range_date_testfile.txt";
  19720. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19721. {
  19722. std::ofstream ofs(fname);
  19723. ofs << content;
  19724. ASSERT_TRUE(ofs.good());
  19725. }
  19726. Server svr;
  19727. svr.set_mount_point("/static", ".");
  19728. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19729. svr.wait_until_ready();
  19730. Client cli(HOST, PORT);
  19731. // First request: get Last-Modified
  19732. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19733. ASSERT_TRUE(res1);
  19734. ASSERT_EQ(200, res1->status);
  19735. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19736. std::string last_modified = res1->get_header_value("Last-Modified");
  19737. // Range request with matching If-Range (date): should get 206
  19738. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19739. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19740. ASSERT_TRUE(res2);
  19741. EXPECT_EQ(206, res2->status);
  19742. EXPECT_EQ("FGHIJ", res2->body);
  19743. // Range request with old If-Range date: should get 200 (full content)
  19744. Headers h3 = {{"Range", "bytes=5-9"},
  19745. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19746. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19747. ASSERT_TRUE(res3);
  19748. EXPECT_EQ(200, res3->status);
  19749. EXPECT_EQ(content, res3->body);
  19750. // Range request with future If-Range date: should get 206
  19751. Headers h4 = {{"Range", "bytes=0-4"},
  19752. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19753. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19754. ASSERT_TRUE(res4);
  19755. EXPECT_EQ(206, res4->status);
  19756. EXPECT_EQ("ABCDE", res4->body);
  19757. svr.stop();
  19758. t.join();
  19759. std::remove(fname);
  19760. }
  19761. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19762. using namespace httplib;
  19763. const char *fname = "etag_malformed.txt";
  19764. const char *content = "malformed-etag";
  19765. {
  19766. std::ofstream ofs(fname);
  19767. ofs << content;
  19768. ASSERT_TRUE(ofs.good());
  19769. }
  19770. Server svr;
  19771. svr.set_mount_point("/static", ".");
  19772. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19773. svr.wait_until_ready();
  19774. Client cli(HOST, PORT);
  19775. // baseline: should get 200 and an ETag
  19776. auto res1 = cli.Get("/static/etag_malformed.txt");
  19777. ASSERT_TRUE(res1);
  19778. ASSERT_EQ(200, res1->status);
  19779. ASSERT_TRUE(res1->has_header("ETag"));
  19780. // Malformed ETag value (missing quotes) should be treated as non-matching
  19781. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19782. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19783. ASSERT_TRUE(res_bad);
  19784. EXPECT_EQ(200, res_bad->status);
  19785. // Whitespace-only header value should be considered invalid / non-matching
  19786. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19787. "Host: localhost\r\n"
  19788. "If-None-Match: \r\n"
  19789. "Connection: close\r\n"
  19790. "\r\n";
  19791. std::string out;
  19792. ASSERT_TRUE(send_request(5, raw_req, &out));
  19793. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19794. svr.stop();
  19795. t.join();
  19796. std::remove(fname);
  19797. }
  19798. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19799. using namespace httplib;
  19800. const char *fname = "ims_invalid_format.txt";
  19801. const char *content = "ims-bad-format";
  19802. {
  19803. std::ofstream ofs(fname);
  19804. ofs << content;
  19805. ASSERT_TRUE(ofs.good());
  19806. }
  19807. Server svr;
  19808. svr.set_mount_point("/static", ".");
  19809. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19810. svr.wait_until_ready();
  19811. Client cli(HOST, PORT);
  19812. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19813. ASSERT_TRUE(res1);
  19814. ASSERT_EQ(200, res1->status);
  19815. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19816. // If-Modified-Since with invalid format should not result in 304
  19817. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19818. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19819. ASSERT_TRUE(res_bad);
  19820. EXPECT_EQ(200, res_bad->status);
  19821. // If-Range with invalid date format should be treated as mismatch -> full
  19822. // content (200)
  19823. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19824. {"If-Range", "invalid-date"}};
  19825. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19826. ASSERT_TRUE(res_ifrange);
  19827. EXPECT_EQ(200, res_ifrange->status);
  19828. svr.stop();
  19829. t.join();
  19830. std::remove(fname);
  19831. }
  19832. TEST(ETagTest, IfRangeWithMalformedETag) {
  19833. using namespace httplib;
  19834. const char *fname = "ifrange_malformed.txt";
  19835. const std::string content = "0123456789";
  19836. {
  19837. std::ofstream ofs(fname);
  19838. ofs << content;
  19839. ASSERT_TRUE(ofs.good());
  19840. }
  19841. Server svr;
  19842. svr.set_mount_point("/static", ".");
  19843. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19844. svr.wait_until_ready();
  19845. Client cli(HOST, PORT);
  19846. // First request: get ETag
  19847. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19848. ASSERT_TRUE(res1);
  19849. ASSERT_EQ(200, res1->status);
  19850. ASSERT_TRUE(res1->has_header("ETag"));
  19851. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19852. // full content (200)
  19853. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19854. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19855. ASSERT_TRUE(res2);
  19856. EXPECT_EQ(200, res2->status);
  19857. EXPECT_EQ(content, res2->body);
  19858. svr.stop();
  19859. t.join();
  19860. std::remove(fname);
  19861. }
  19862. TEST(ETagTest, ExtremeLargeDateValues) {
  19863. using namespace httplib;
  19864. const char *fname = "ims_extreme_date.txt";
  19865. const char *content = "ims-extreme-date";
  19866. {
  19867. std::ofstream ofs(fname);
  19868. ofs << content;
  19869. ASSERT_TRUE(ofs.good());
  19870. }
  19871. Server svr;
  19872. svr.set_mount_point("/static", ".");
  19873. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19874. svr.wait_until_ready();
  19875. Client cli(HOST, PORT);
  19876. auto res1 = cli.Get(std::string("/static/") + fname);
  19877. ASSERT_TRUE(res1);
  19878. ASSERT_EQ(200, res1->status);
  19879. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19880. // Extremely large year that may overflow date parsing routines.
  19881. Headers h_large_date = {
  19882. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19883. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19884. ASSERT_TRUE(res_bad);
  19885. // Expect server to treat this as invalid/mismatch and return full content
  19886. EXPECT_EQ(200, res_bad->status);
  19887. // If-Range with extremely large date should be treated as mismatch -> full
  19888. // content (200)
  19889. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19890. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19891. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19892. ASSERT_TRUE(res_ifrange);
  19893. EXPECT_EQ(200, res_ifrange->status);
  19894. svr.stop();
  19895. t.join();
  19896. std::remove(fname);
  19897. }
  19898. TEST(ETagTest, NegativeFileModificationTime) {
  19899. using namespace httplib;
  19900. const char *fname = "ims_negative_mtime.txt";
  19901. const std::string content = "negative-mtime";
  19902. {
  19903. std::ofstream ofs(fname);
  19904. ofs << content;
  19905. ASSERT_TRUE(ofs.good());
  19906. }
  19907. // Try to set file mtime to a negative value. This may fail on some
  19908. // platforms/filesystems; if it fails, the test will still verify server
  19909. // behaves safely by performing a regular conditional request.
  19910. #if defined(__APPLE__) || defined(__linux__)
  19911. bool set_negative = false;
  19912. do {
  19913. struct timeval times[2];
  19914. // access time: now
  19915. times[0].tv_sec = time(nullptr);
  19916. times[0].tv_usec = 0;
  19917. // modification time: negative (e.g., -1)
  19918. times[1].tv_sec = -1;
  19919. times[1].tv_usec = 0;
  19920. if (utimes(fname, times) == 0) { set_negative = true; }
  19921. } while (0);
  19922. #else
  19923. bool set_negative = false;
  19924. #endif
  19925. Server svr;
  19926. svr.set_mount_point("/static", ".");
  19927. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19928. svr.wait_until_ready();
  19929. Client cli(HOST, PORT);
  19930. auto res1 = cli.Get(std::string("/static/") + fname);
  19931. ASSERT_TRUE(res1);
  19932. ASSERT_EQ(200, res1->status);
  19933. bool has_last_modified = res1->has_header("Last-Modified");
  19934. std::string last_modified;
  19935. if (has_last_modified) {
  19936. last_modified = res1->get_header_value("Last-Modified");
  19937. }
  19938. if (set_negative) {
  19939. // If we successfully set a negative mtime, ensure server returns a
  19940. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19941. // with an old date and ensure server handles it without crash.
  19942. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19943. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19944. ASSERT_TRUE(res2);
  19945. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19946. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19947. } else {
  19948. // Could not set negative mtime on this platform; fall back to verifying
  19949. // that normal invalid/malformed dates are treated safely (non-304).
  19950. Headers h_bad_date = {
  19951. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19952. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19953. ASSERT_TRUE(res_bad);
  19954. EXPECT_EQ(200, res_bad->status);
  19955. }
  19956. svr.stop();
  19957. t.join();
  19958. std::remove(fname);
  19959. }
  19960. //==============================================================================
  19961. // Integration Tests with Server
  19962. //==============================================================================
  19963. class SSEIntegrationTest : public ::testing::Test {
  19964. protected:
  19965. void SetUp() override {
  19966. stop_server_.store(false);
  19967. events_.clear();
  19968. server_ = httplib::detail::make_unique<Server>();
  19969. setup_server();
  19970. start_server();
  19971. }
  19972. void TearDown() override {
  19973. stop_server_.store(true);
  19974. event_cv_.notify_all();
  19975. server_->stop();
  19976. if (server_thread_.joinable()) { server_thread_.join(); }
  19977. }
  19978. void setup_server() {
  19979. // Simple SSE endpoint
  19980. server_->Get("/events", [this](const Request &req, Response &res) {
  19981. auto last_id = req.get_header_value("Last-Event-ID");
  19982. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19983. res.set_chunked_content_provider(
  19984. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19985. std::unique_lock<std::mutex> lock(event_mutex_);
  19986. if (event_cv_.wait_for(
  19987. lock, std::chrono::milliseconds(200), [this] {
  19988. return !events_.empty() || stop_server_.load();
  19989. })) {
  19990. if (stop_server_.load()) { return false; }
  19991. if (!events_.empty()) {
  19992. std::string event = events_.front();
  19993. events_.erase(events_.begin());
  19994. sink.write(event.data(), event.size());
  19995. return true;
  19996. }
  19997. }
  19998. return !stop_server_.load();
  19999. });
  20000. });
  20001. // Endpoint that returns error
  20002. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20003. res.status = 500;
  20004. res.set_content("Internal Server Error", "text/plain");
  20005. });
  20006. // Endpoint for custom event types
  20007. server_->Get("/custom-events", [](const Request &, Response &res) {
  20008. res.set_chunked_content_provider(
  20009. "text/event-stream", [](size_t offset, DataSink &sink) {
  20010. if (offset == 0) {
  20011. std::string event = "event: update\ndata: updated\n\n"
  20012. "event: delete\ndata: deleted\n\n";
  20013. sink.write(event.data(), event.size());
  20014. }
  20015. return false; // End stream after sending
  20016. });
  20017. });
  20018. }
  20019. void start_server() {
  20020. port_ = server_->bind_to_any_port(HOST);
  20021. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20022. // Wait for server to start
  20023. while (!server_->is_running()) {
  20024. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20025. }
  20026. }
  20027. int get_port() const { return port_; }
  20028. void send_event(const std::string &event) {
  20029. std::lock_guard<std::mutex> lock(event_mutex_);
  20030. events_.push_back(event);
  20031. event_cv_.notify_all();
  20032. }
  20033. std::unique_ptr<Server> server_;
  20034. std::thread server_thread_;
  20035. std::mutex event_mutex_;
  20036. std::condition_variable event_cv_;
  20037. std::vector<std::string> events_;
  20038. std::atomic<bool> stop_server_{false};
  20039. std::string last_received_event_id_;
  20040. int port_ = 0;
  20041. };
  20042. //==============================================================================
  20043. // SSE Parsing Tests
  20044. //==============================================================================
  20045. class SSEParsingTest : public SSEIntegrationTest {
  20046. protected:
  20047. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20048. // A trailing sentinel event tells when the whole stream has been parsed.
  20049. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20050. auto body = stream + "event: end\ndata: end\n\n";
  20051. server_->Get("/parse", [body](const Request &, Response &res) {
  20052. res.set_content(body, "text/event-stream");
  20053. });
  20054. return collect("/parse");
  20055. }
  20056. // Runs SSEClient against path until an "end" event arrives and returns the
  20057. // messages dispatched before it
  20058. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20059. Client client(HOST, get_port());
  20060. sse::SSEClient sse(client, path);
  20061. std::mutex mutex;
  20062. std::condition_variable cv;
  20063. std::vector<sse::SSEMessage> messages;
  20064. auto done = false;
  20065. sse.on_message([&](const sse::SSEMessage &msg) {
  20066. std::lock_guard<std::mutex> lock(mutex);
  20067. // Ignore a replay from a reconnect that races with stop()
  20068. if (!done) { messages.push_back(msg); }
  20069. });
  20070. sse.on_event("end", [&](const sse::SSEMessage &) {
  20071. std::lock_guard<std::mutex> lock(mutex);
  20072. done = true;
  20073. cv.notify_all();
  20074. });
  20075. sse.set_reconnect_interval(100);
  20076. sse.start_async();
  20077. {
  20078. std::unique_lock<std::mutex> lock(mutex);
  20079. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20080. }
  20081. sse.stop();
  20082. EXPECT_TRUE(done);
  20083. return messages;
  20084. }
  20085. };
  20086. TEST_F(SSEParsingTest, SingleLineData) {
  20087. auto msgs = parse("data: hello\n\n");
  20088. ASSERT_EQ(msgs.size(), 1u);
  20089. EXPECT_EQ(msgs[0].data, "hello");
  20090. EXPECT_EQ(msgs[0].event, "message");
  20091. }
  20092. TEST_F(SSEParsingTest, MultiLineData) {
  20093. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20094. ASSERT_EQ(msgs.size(), 1u);
  20095. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20096. }
  20097. TEST_F(SSEParsingTest, CustomEventType) {
  20098. auto msgs = parse("event: update\ndata: payload\n\n");
  20099. ASSERT_EQ(msgs.size(), 1u);
  20100. EXPECT_EQ(msgs[0].event, "update");
  20101. EXPECT_EQ(msgs[0].data, "payload");
  20102. }
  20103. TEST_F(SSEParsingTest, EventIdHandling) {
  20104. auto msgs = parse("id: 12345\ndata: test\n\n");
  20105. ASSERT_EQ(msgs.size(), 1u);
  20106. EXPECT_EQ(msgs[0].id, "12345");
  20107. }
  20108. TEST_F(SSEParsingTest, EmptyEventId) {
  20109. auto msgs = parse("id:\ndata: test\n\n");
  20110. ASSERT_EQ(msgs.size(), 1u);
  20111. EXPECT_EQ(msgs[0].id, "");
  20112. }
  20113. TEST_F(SSEParsingTest, CommentsIgnored) {
  20114. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20115. ASSERT_EQ(msgs.size(), 1u);
  20116. EXPECT_EQ(msgs[0].data, "hello");
  20117. EXPECT_EQ(msgs[0].event, "message");
  20118. }
  20119. TEST_F(SSEParsingTest, ColonInValue) {
  20120. auto msgs = parse("data: hello:world:test\n\n");
  20121. ASSERT_EQ(msgs.size(), 1u);
  20122. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20123. }
  20124. TEST_F(SSEParsingTest, FieldNameOnly) {
  20125. // A line without a colon is a field name with an empty value
  20126. auto msgs = parse("data\n\n");
  20127. ASSERT_EQ(msgs.size(), 1u);
  20128. EXPECT_EQ(msgs[0].data, "");
  20129. }
  20130. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20131. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20132. ASSERT_EQ(msgs.size(), 1u);
  20133. EXPECT_EQ(msgs[0].event, "update");
  20134. EXPECT_EQ(msgs[0].data, "hello");
  20135. }
  20136. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20137. auto msgs = parse("data\r\n\r\n");
  20138. ASSERT_EQ(msgs.size(), 1u);
  20139. EXPECT_EQ(msgs[0].data, "");
  20140. }
  20141. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20142. auto msgs = parse("event: update\rdata: hello\r\r");
  20143. ASSERT_EQ(msgs.size(), 1u);
  20144. EXPECT_EQ(msgs[0].event, "update");
  20145. EXPECT_EQ(msgs[0].data, "hello");
  20146. }
  20147. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20148. // Chunk boundaries fall inside every \r\n and right before the first one
  20149. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20150. "\n\r", "\nevent: end\ndata: end\n\n"};
  20151. server_->Get("/split", [chunks](const Request &, Response &res) {
  20152. auto i = std::make_shared<size_t>(0);
  20153. res.set_chunked_content_provider(
  20154. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20155. if (*i == chunks.size()) {
  20156. sink.done();
  20157. } else {
  20158. sink.write(chunks[*i].data(), chunks[*i].size());
  20159. (*i)++;
  20160. }
  20161. return true;
  20162. });
  20163. });
  20164. auto msgs = collect("/split");
  20165. ASSERT_EQ(msgs.size(), 1u);
  20166. EXPECT_EQ(msgs[0].event, "update");
  20167. EXPECT_EQ(msgs[0].data, "hello");
  20168. }
  20169. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20170. // Only a BOM at the start of the stream is ignored
  20171. auto msgs = parse("\xEF\xBB\xBF"
  20172. "data: first\n\n"
  20173. "\xEF\xBB\xBF"
  20174. "data: second\n\n");
  20175. ASSERT_EQ(msgs.size(), 1u);
  20176. EXPECT_EQ(msgs[0].data, "first");
  20177. }
  20178. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20179. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20180. ASSERT_EQ(msgs.size(), 1u);
  20181. EXPECT_EQ(msgs[0].data, "hello");
  20182. EXPECT_EQ(msgs[0].event, "message");
  20183. }
  20184. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20185. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20186. ASSERT_EQ(msgs.size(), 2u);
  20187. EXPECT_EQ(msgs[0].data, "hello");
  20188. EXPECT_EQ(msgs[1].data, "hello");
  20189. }
  20190. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20191. // An event without data is not dispatched, and its type must not leak
  20192. // into the next event
  20193. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20194. ASSERT_EQ(msgs.size(), 1u);
  20195. EXPECT_EQ(msgs[0].event, "message");
  20196. EXPECT_EQ(msgs[0].data, "hello");
  20197. }
  20198. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20199. // The first connection sends only an id; the second echoes back the
  20200. // Last-Event-ID it was reconnected with
  20201. std::atomic<int> connection_count{0};
  20202. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20203. if (connection_count++ == 0) {
  20204. res.set_content("id: 42\n\n", "text/event-stream");
  20205. } else {
  20206. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20207. "\n\nevent: end\ndata: end\n\n",
  20208. "text/event-stream");
  20209. }
  20210. });
  20211. auto msgs = collect("/id-only");
  20212. ASSERT_EQ(msgs.size(), 1u);
  20213. EXPECT_EQ(msgs[0].data, "42");
  20214. }
  20215. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20216. // The first connection sets an id and then clears it with an empty one; the
  20217. // second reports whether it was reconnected with a Last-Event-ID
  20218. std::atomic<int> connection_count{0};
  20219. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20220. if (connection_count++ == 0) {
  20221. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20222. "text/event-stream");
  20223. } else {
  20224. res.set_content(
  20225. std::string("data: ") +
  20226. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20227. "\n\nevent: end\ndata: end\n\n",
  20228. "text/event-stream");
  20229. }
  20230. });
  20231. auto msgs = collect("/id-clear");
  20232. ASSERT_EQ(msgs.size(), 3u);
  20233. EXPECT_EQ(msgs[0].id, "1");
  20234. EXPECT_EQ(msgs[1].id, "");
  20235. EXPECT_EQ(msgs[2].data, "not sent");
  20236. }
  20237. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20238. // The first connection sets an id and then sends ids that cannot be carried
  20239. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20240. // with
  20241. std::atomic<int> connection_count{0};
  20242. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20243. if (connection_count++ == 0) {
  20244. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20245. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20246. "text/event-stream");
  20247. } else {
  20248. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20249. "\n\nevent: end\ndata: end\n\n",
  20250. "text/event-stream");
  20251. }
  20252. });
  20253. auto msgs = collect("/id-unsendable");
  20254. ASSERT_EQ(msgs.size(), 1u);
  20255. EXPECT_EQ(msgs[0].data, "42");
  20256. }
  20257. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20258. auto msgs = parse("event: notification\nid: evt-42\n"
  20259. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20260. ASSERT_EQ(msgs.size(), 1u);
  20261. EXPECT_EQ(msgs[0].event, "notification");
  20262. EXPECT_EQ(msgs[0].id, "evt-42");
  20263. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20264. }
  20265. TEST(SSEMessageTest, Clear) {
  20266. sse::SSEMessage msg;
  20267. msg.event = "custom";
  20268. msg.data = "some data";
  20269. msg.id = "123";
  20270. msg.clear();
  20271. EXPECT_EQ(msg.event, "message");
  20272. EXPECT_EQ(msg.data, "");
  20273. EXPECT_EQ(msg.id, "");
  20274. }
  20275. //==============================================================================
  20276. // SSE Integration Tests
  20277. //==============================================================================
  20278. // Test: Successful connection and on_open callback
  20279. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20280. // Add a simple endpoint that sends one event and closes
  20281. server_->Get("/simple-event", [](const Request &, Response &res) {
  20282. res.set_chunked_content_provider(
  20283. "text/event-stream", [](size_t offset, DataSink &sink) {
  20284. if (offset == 0) {
  20285. std::string event = "data: hello\n\n";
  20286. sink.write(event.data(), event.size());
  20287. }
  20288. return false; // Close stream after sending
  20289. });
  20290. });
  20291. Client client("localhost", get_port());
  20292. sse::SSEClient sse(client, "/simple-event");
  20293. std::atomic<bool> open_called{false};
  20294. std::atomic<bool> message_received{false};
  20295. sse.on_open([&open_called]() { open_called.store(true); });
  20296. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20297. if (msg.data == "hello") { message_received.store(true); }
  20298. });
  20299. sse.set_reconnect_interval(100);
  20300. sse.set_max_reconnect_attempts(1);
  20301. // Start async
  20302. sse.start_async();
  20303. // Wait for message to be processed
  20304. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20305. sse.stop();
  20306. EXPECT_TRUE(open_called.load());
  20307. EXPECT_TRUE(message_received.load());
  20308. }
  20309. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20310. // A data line that never ends.
  20311. server_->Get("/endless-line", [](const Request &, Response &res) {
  20312. res.set_chunked_content_provider(
  20313. "text/event-stream", [](size_t offset, DataSink &sink) {
  20314. if (offset == 0) { sink.write("data: ", 6); }
  20315. std::string chunk(64 * 1024, 'A');
  20316. return sink.write(chunk.data(), chunk.size());
  20317. });
  20318. });
  20319. Client client("localhost", get_port());
  20320. // A stream that may run forever, so that only the event is bounded.
  20321. client.set_payload_max_length(0);
  20322. sse::SSEClient sse(client, "/endless-line");
  20323. std::atomic<bool> too_long{false};
  20324. sse.on_error([&](Error err) {
  20325. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20326. });
  20327. sse.set_max_reconnect_attempts(1);
  20328. sse.start_async();
  20329. for (int i = 0; i < 500 && !too_long; i++) {
  20330. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20331. }
  20332. sse.stop();
  20333. EXPECT_TRUE(too_long);
  20334. }
  20335. // Test: on_message callback
  20336. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20337. // Endpoint that sends multiple events then closes
  20338. server_->Get("/multi-event", [](const Request &, Response &res) {
  20339. res.set_chunked_content_provider(
  20340. "text/event-stream", [](size_t offset, DataSink &sink) {
  20341. if (offset == 0) {
  20342. std::string events = "data: message1\n\ndata: message2\n\n";
  20343. sink.write(events.data(), events.size());
  20344. }
  20345. return false;
  20346. });
  20347. });
  20348. Client client("localhost", get_port());
  20349. sse::SSEClient sse(client, "/multi-event");
  20350. std::vector<std::string> received_messages;
  20351. std::mutex messages_mutex;
  20352. sse.on_message([&](const sse::SSEMessage &msg) {
  20353. std::lock_guard<std::mutex> lock(messages_mutex);
  20354. received_messages.push_back(msg.data);
  20355. });
  20356. sse.set_reconnect_interval(100);
  20357. sse.set_max_reconnect_attempts(1);
  20358. sse.start_async();
  20359. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20360. sse.stop();
  20361. std::lock_guard<std::mutex> lock(messages_mutex);
  20362. EXPECT_GE(received_messages.size(), 2u);
  20363. if (received_messages.size() >= 2) {
  20364. EXPECT_EQ(received_messages[0], "message1");
  20365. EXPECT_EQ(received_messages[1], "message2");
  20366. }
  20367. }
  20368. // Test: on_event for specific types
  20369. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20370. Client client("localhost", get_port());
  20371. sse::SSEClient sse(client, "/custom-events");
  20372. std::atomic<bool> update_received{false};
  20373. std::atomic<bool> delete_received{false};
  20374. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20375. if (msg.data == "updated") { update_received.store(true); }
  20376. });
  20377. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20378. if (msg.data == "deleted") { delete_received.store(true); }
  20379. });
  20380. sse.set_max_reconnect_attempts(1);
  20381. sse.start_async();
  20382. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20383. sse.stop();
  20384. EXPECT_TRUE(update_received.load());
  20385. EXPECT_TRUE(delete_received.load());
  20386. }
  20387. // Test: on_error callback on connection failure
  20388. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20389. // Connect to a non-existent port
  20390. Client client("localhost", 59999);
  20391. sse::SSEClient sse(client, "/events");
  20392. std::atomic<bool> error_called{false};
  20393. Error received_error = Error::Success;
  20394. sse.on_error([&](Error err) {
  20395. error_called.store(true);
  20396. received_error = err;
  20397. });
  20398. sse.set_reconnect_interval(50);
  20399. sse.set_max_reconnect_attempts(1);
  20400. sse.start_async();
  20401. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20402. sse.stop();
  20403. EXPECT_TRUE(error_called.load());
  20404. EXPECT_NE(received_error, Error::Success);
  20405. }
  20406. // Test: Last-Event-ID header sent on reconnect
  20407. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20408. // Endpoint that sends event with ID
  20409. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20410. res.set_chunked_content_provider(
  20411. "text/event-stream", [](size_t offset, DataSink &sink) {
  20412. if (offset == 0) {
  20413. std::string event = "id: evt-123\ndata: test\n\n";
  20414. sink.write(event.data(), event.size());
  20415. }
  20416. return false;
  20417. });
  20418. });
  20419. Client client("localhost", get_port());
  20420. sse::SSEClient sse(client, "/event-with-id");
  20421. std::atomic<bool> id_received{false};
  20422. sse.on_message([&](const sse::SSEMessage &msg) {
  20423. if (!msg.id.empty()) { id_received.store(true); }
  20424. });
  20425. sse.set_reconnect_interval(100);
  20426. sse.set_max_reconnect_attempts(1);
  20427. sse.start_async();
  20428. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20429. sse.stop();
  20430. EXPECT_TRUE(id_received.load());
  20431. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20432. }
  20433. // Test: Manual stop
  20434. TEST_F(SSEIntegrationTest, ManualStop) {
  20435. // Endpoint that sends one event and stays open briefly
  20436. std::atomic<bool> handler_running{true};
  20437. server_->Get("/stay-open", [&handler_running](const Request &,
  20438. Response &res) {
  20439. res.set_chunked_content_provider(
  20440. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20441. if (offset == 0) {
  20442. std::string event = "data: connected\n\n";
  20443. sink.write(event.data(), event.size());
  20444. }
  20445. // Keep connection open while handler_running is true
  20446. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20447. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20448. }
  20449. return false;
  20450. });
  20451. });
  20452. Client client("localhost", get_port());
  20453. sse::SSEClient sse(client, "/stay-open");
  20454. std::atomic<bool> connected{false};
  20455. sse.on_open([&connected]() { connected.store(true); });
  20456. sse.set_reconnect_interval(100);
  20457. sse.set_max_reconnect_attempts(1);
  20458. sse.start_async();
  20459. // Wait for connection to establish
  20460. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20461. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20462. }
  20463. EXPECT_TRUE(connected.load());
  20464. EXPECT_TRUE(sse.is_connected());
  20465. // Signal handler to stop
  20466. handler_running.store(false);
  20467. // Stop SSE client
  20468. sse.stop();
  20469. EXPECT_FALSE(sse.is_connected());
  20470. }
  20471. // Test: SSEClient with custom headers
  20472. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20473. // Setup a server endpoint that checks for custom header
  20474. std::atomic<bool> header_received{false};
  20475. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20476. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20477. header_received.store(true);
  20478. }
  20479. res.set_chunked_content_provider("text/event-stream",
  20480. [](size_t, DataSink &) { return false; });
  20481. });
  20482. Client client("localhost", get_port());
  20483. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20484. sse::SSEClient sse(client, "/header-check", headers);
  20485. sse.set_max_reconnect_attempts(1);
  20486. sse.start_async();
  20487. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20488. sse.stop();
  20489. EXPECT_TRUE(header_received.load());
  20490. }
  20491. // Test: Reconnect interval configuration
  20492. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20493. Client client("localhost", get_port());
  20494. sse::SSEClient sse(client, "/events");
  20495. auto &result = sse.set_reconnect_interval(500);
  20496. // Builder pattern should return reference to self
  20497. EXPECT_EQ(&result, &sse);
  20498. }
  20499. // Test: Max reconnect attempts
  20500. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20501. // Connect to non-existent port to force reconnects
  20502. Client client("localhost", 59998);
  20503. sse::SSEClient sse(client, "/events");
  20504. std::atomic<int> error_count{0};
  20505. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20506. sse.set_reconnect_interval(50);
  20507. sse.set_max_reconnect_attempts(2);
  20508. auto start = std::chrono::steady_clock::now();
  20509. sse.start(); // Blocking call
  20510. auto end = std::chrono::steady_clock::now();
  20511. // Should have stopped after 2 failed attempts
  20512. EXPECT_GE(error_count.load(), 2);
  20513. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20514. auto duration =
  20515. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20516. #ifdef _WIN32
  20517. // Windows is much slower for socket connection failures
  20518. EXPECT_LT(duration.count(), 7000);
  20519. #else
  20520. EXPECT_LT(duration.count(), 1000);
  20521. #endif
  20522. }
  20523. // Test: Multi-line data in integration
  20524. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20525. // Endpoint with multi-line data
  20526. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20527. res.set_chunked_content_provider(
  20528. "text/event-stream", [](size_t offset, DataSink &sink) {
  20529. if (offset == 0) {
  20530. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20531. sink.write(event.data(), event.size());
  20532. }
  20533. return false;
  20534. });
  20535. });
  20536. Client client("localhost", get_port());
  20537. sse::SSEClient sse(client, "/multiline-data");
  20538. std::string received_data;
  20539. std::mutex data_mutex;
  20540. sse.on_message([&](const sse::SSEMessage &msg) {
  20541. std::lock_guard<std::mutex> lock(data_mutex);
  20542. received_data = msg.data;
  20543. });
  20544. sse.set_reconnect_interval(100);
  20545. sse.set_max_reconnect_attempts(1);
  20546. sse.start_async();
  20547. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20548. sse.stop();
  20549. std::lock_guard<std::mutex> lock(data_mutex);
  20550. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20551. }
  20552. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20553. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20554. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20555. DataSink &sink) {
  20556. if (offset == 0) {
  20557. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20558. sink.write(events.data(), events.size());
  20559. }
  20560. return false;
  20561. });
  20562. });
  20563. Client client("localhost", get_port());
  20564. sse::SSEClient sse(client, "/empty-data-lines");
  20565. std::mutex mutex;
  20566. std::condition_variable cv;
  20567. std::vector<std::string> received;
  20568. sse.on_message([&](const sse::SSEMessage &msg) {
  20569. std::lock_guard<std::mutex> lock(mutex);
  20570. received.push_back(msg.data);
  20571. cv.notify_all();
  20572. });
  20573. sse.set_max_reconnect_attempts(1);
  20574. sse.start_async();
  20575. {
  20576. std::unique_lock<std::mutex> lock(mutex);
  20577. cv.wait_for(lock, std::chrono::seconds(2),
  20578. [&] { return received.size() >= 3; });
  20579. }
  20580. sse.stop();
  20581. ASSERT_GE(received.size(), 3u);
  20582. EXPECT_EQ(received[0], "");
  20583. EXPECT_EQ(received[1], "\nhello");
  20584. EXPECT_EQ(received[2], "");
  20585. }
  20586. // Test: Auto-reconnect after server disconnection
  20587. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20588. std::atomic<int> connection_count{0};
  20589. std::atomic<int> message_count{0};
  20590. // Endpoint that sends one event and closes, forcing reconnect
  20591. server_->Get("/reconnect-test",
  20592. [&connection_count](const Request &, Response &res) {
  20593. connection_count.fetch_add(1);
  20594. res.set_chunked_content_provider(
  20595. "text/event-stream", [](size_t offset, DataSink &sink) {
  20596. if (offset == 0) {
  20597. std::string event = "data: hello\n\n";
  20598. sink.write(event.data(), event.size());
  20599. }
  20600. return false; // Close connection after sending
  20601. });
  20602. });
  20603. Client client("localhost", get_port());
  20604. sse::SSEClient sse(client, "/reconnect-test");
  20605. sse.on_message([&message_count](const sse::SSEMessage &) {
  20606. message_count.fetch_add(1);
  20607. });
  20608. sse.set_reconnect_interval(100);
  20609. sse.set_max_reconnect_attempts(3);
  20610. sse.start_async();
  20611. // Wait long enough for multiple reconnects
  20612. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20613. sse.stop();
  20614. // Should have connected multiple times (initial + reconnects)
  20615. EXPECT_GE(connection_count.load(), 2);
  20616. // Should have received messages from multiple connections
  20617. EXPECT_GE(message_count.load(), 2);
  20618. }
  20619. // Test: A retry field that is not all ASCII digits is ignored
  20620. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20621. std::atomic<int> connection_count{0};
  20622. server_->Get("/bad-retry",
  20623. [&connection_count](const Request &, Response &res) {
  20624. connection_count.fetch_add(1);
  20625. res.set_chunked_content_provider(
  20626. "text/event-stream", [](size_t offset, DataSink &sink) {
  20627. if (offset == 0) {
  20628. std::string event = "retry: -1\ndata: hello\n\n";
  20629. sink.write(event.data(), event.size());
  20630. }
  20631. return false;
  20632. });
  20633. });
  20634. Client client("localhost", get_port());
  20635. sse::SSEClient sse(client, "/bad-retry");
  20636. sse.set_reconnect_interval(10000);
  20637. sse.start_async();
  20638. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20639. sse.stop();
  20640. EXPECT_EQ(connection_count.load(), 1);
  20641. }
  20642. // Test: A retry field of all ASCII digits sets the reconnection time
  20643. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20644. std::mutex mutex;
  20645. std::condition_variable cv;
  20646. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20647. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20648. {
  20649. std::lock_guard<std::mutex> lock(mutex);
  20650. connected_at.push_back(std::chrono::steady_clock::now());
  20651. cv.notify_all();
  20652. }
  20653. res.set_chunked_content_provider(
  20654. "text/event-stream", [](size_t offset, DataSink &sink) {
  20655. if (offset == 0) {
  20656. std::string event = "retry: 0\ndata: hello\n\n";
  20657. sink.write(event.data(), event.size());
  20658. }
  20659. return false;
  20660. });
  20661. });
  20662. Client client("localhost", get_port());
  20663. sse::SSEClient sse(client, "/zero-retry");
  20664. sse.set_reconnect_interval(10000);
  20665. sse.start_async();
  20666. {
  20667. std::unique_lock<std::mutex> lock(mutex);
  20668. cv.wait_for(lock, std::chrono::seconds(5),
  20669. [&] { return connected_at.size() >= 2; });
  20670. }
  20671. sse.stop();
  20672. // The server-supplied interval is applied, but never below 100ms, so
  20673. // "retry: 0" does not cause a busy reconnect loop
  20674. std::lock_guard<std::mutex> lock(mutex);
  20675. ASSERT_GE(connected_at.size(), 2u);
  20676. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20677. connected_at[1] - connected_at[0])
  20678. .count();
  20679. EXPECT_GE(interval_ms, 100);
  20680. }
  20681. // Test: Last-Event-ID sent on reconnect
  20682. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20683. std::atomic<int> connection_count{0};
  20684. std::vector<std::string> received_last_event_ids;
  20685. std::mutex id_mutex;
  20686. // Endpoint that checks Last-Event-ID header and sends event with ID
  20687. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20688. int conn = connection_count.fetch_add(1);
  20689. // Capture the Last-Event-ID header from each connection
  20690. {
  20691. std::lock_guard<std::mutex> lock(id_mutex);
  20692. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20693. }
  20694. res.set_chunked_content_provider(
  20695. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20696. if (offset == 0) {
  20697. std::string event =
  20698. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20699. sink.write(event.data(), event.size());
  20700. }
  20701. return false;
  20702. });
  20703. });
  20704. Client client("localhost", get_port());
  20705. sse::SSEClient sse(client, "/reconnect-with-id");
  20706. sse.set_reconnect_interval(100);
  20707. sse.set_max_reconnect_attempts(3);
  20708. sse.start_async();
  20709. // Wait for at least 2 connections
  20710. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20711. sse.stop();
  20712. // Verify behavior
  20713. std::lock_guard<std::mutex> lock(id_mutex);
  20714. EXPECT_GE(received_last_event_ids.size(), 2u);
  20715. // First connection should have no Last-Event-ID
  20716. if (!received_last_event_ids.empty()) {
  20717. EXPECT_EQ(received_last_event_ids[0], "");
  20718. }
  20719. // Second connection should have Last-Event-ID from first connection
  20720. if (received_last_event_ids.size() >= 2) {
  20721. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20722. }
  20723. }
  20724. // Test: set_headers updates headers used on reconnect
  20725. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20726. std::vector<std::string> received_tokens;
  20727. std::mutex token_mutex;
  20728. // Endpoint that captures Authorization header
  20729. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20730. {
  20731. std::lock_guard<std::mutex> lock(token_mutex);
  20732. received_tokens.push_back(req.get_header_value("Authorization"));
  20733. }
  20734. res.set_chunked_content_provider(
  20735. "text/event-stream", [](size_t offset, DataSink &sink) {
  20736. if (offset == 0) {
  20737. std::string event = "data: hello\n\n";
  20738. sink.write(event.data(), event.size());
  20739. }
  20740. return false; // Close connection to trigger reconnect
  20741. });
  20742. });
  20743. Client client("localhost", get_port());
  20744. Headers headers = {{"Authorization", "Bearer old-token"}};
  20745. sse::SSEClient sse(client, "/auth-check", headers);
  20746. // Update headers on each successful connection
  20747. sse.on_open(
  20748. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20749. sse.set_reconnect_interval(100);
  20750. sse.set_max_reconnect_attempts(3);
  20751. sse.start_async();
  20752. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20753. sse.stop();
  20754. std::lock_guard<std::mutex> lock(token_mutex);
  20755. ASSERT_GE(received_tokens.size(), 2u);
  20756. // First connection uses original header
  20757. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20758. // Second connection uses updated header from set_headers
  20759. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20760. }
  20761. // Test: 401 allows reconnection (so on_error can refresh headers)
  20762. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20763. std::atomic<int> connection_count{0};
  20764. // Endpoint: returns 401 on first attempt, 200 on second
  20765. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20766. int conn = connection_count.fetch_add(1);
  20767. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20768. res.status = StatusCode::Unauthorized_401;
  20769. res.set_content("Unauthorized", "text/plain");
  20770. return;
  20771. }
  20772. res.set_chunked_content_provider(
  20773. "text/event-stream", [](size_t offset, DataSink &sink) {
  20774. if (offset == 0) {
  20775. std::string event = "data: authenticated\n\n";
  20776. sink.write(event.data(), event.size());
  20777. }
  20778. return false;
  20779. });
  20780. });
  20781. Client client("localhost", get_port());
  20782. Headers headers = {{"Authorization", "Bearer expired"}};
  20783. sse::SSEClient sse(client, "/auth-retry", headers);
  20784. std::atomic<bool> message_received{false};
  20785. // Refresh token on error
  20786. sse.on_error(
  20787. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20788. sse.on_message([&](const sse::SSEMessage &msg) {
  20789. if (msg.data == "authenticated") { message_received.store(true); }
  20790. });
  20791. sse.set_reconnect_interval(100);
  20792. sse.set_max_reconnect_attempts(3);
  20793. sse.start_async();
  20794. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20795. sse.stop();
  20796. // Should have reconnected after 401 and succeeded with new token
  20797. EXPECT_GE(connection_count.load(), 2);
  20798. EXPECT_TRUE(message_received.load());
  20799. }
  20800. TEST(Issue2318Test, EmptyHostString) {
  20801. {
  20802. httplib::Client cli_empty("", PORT);
  20803. auto res = cli_empty.Get("/");
  20804. ASSERT_FALSE(res);
  20805. EXPECT_EQ(httplib::Error::Connection, res.error());
  20806. }
  20807. {
  20808. httplib::Client cli(" ", PORT);
  20809. auto res = cli.Get("/");
  20810. ASSERT_FALSE(res);
  20811. EXPECT_EQ(httplib::Error::Connection, res.error());
  20812. }
  20813. }
  20814. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20815. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20816. Server svr;
  20817. // Set a small payload limit (1KB)
  20818. svr.set_payload_max_length(1024);
  20819. svr.Post("/test", [&](const Request &req, Response &res) {
  20820. res.set_content("Body size: " + std::to_string(req.body.size()),
  20821. "text/plain");
  20822. });
  20823. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20824. auto se = detail::scope_exit([&] {
  20825. svr.stop();
  20826. listen_thread.join();
  20827. });
  20828. svr.wait_until_ready();
  20829. // Create data that compresses well but exceeds limit when decompressed
  20830. // 8KB of repeated null bytes compresses to a very small size
  20831. std::string original_data(8 * 1024, '\0');
  20832. // Compress the data using gzip
  20833. std::string compressed_data;
  20834. detail::gzip_compressor compressor;
  20835. compressor.compress(original_data.data(), original_data.size(), true,
  20836. [&](const char *data, size_t size) {
  20837. compressed_data.append(data, size);
  20838. return true;
  20839. });
  20840. // Verify compression worked (compressed should be much smaller)
  20841. ASSERT_LT(compressed_data.size(), original_data.size());
  20842. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20843. // Send compressed data with Content-Encoding: gzip
  20844. Client cli(HOST, PORT);
  20845. Headers headers = {{"Content-Encoding", "gzip"}};
  20846. auto res =
  20847. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20848. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20850. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20851. }
  20852. #endif
  20853. // ============================================================================
  20854. // OpenSSL-Specific Tests
  20855. // ============================================================================
  20856. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20857. X509 *readCertificate(const std::string &strFileName) {
  20858. std::ifstream inStream(strFileName);
  20859. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20860. std::istreambuf_iterator<char>());
  20861. if (strCertPEM.empty()) return (nullptr);
  20862. BIO *pbCert = BIO_new(BIO_s_mem());
  20863. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20864. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20865. BIO_free(pbCert);
  20866. return (pCert);
  20867. }
  20868. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20869. std::ifstream inStream(strFileName);
  20870. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20871. std::istreambuf_iterator<char>());
  20872. if (strPrivateKeyPEM.empty()) return (nullptr);
  20873. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20874. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20875. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20876. BIO_free(pbPrivKey);
  20877. return (pPrivateKey);
  20878. }
  20879. TEST(BindServerTest, UpdateCerts) {
  20880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20881. int port = svr.bind_to_any_port("0.0.0.0");
  20882. ASSERT_TRUE(svr.is_valid());
  20883. ASSERT_TRUE(port > 0);
  20884. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20885. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20886. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20887. ASSERT_TRUE(cert != nullptr);
  20888. ASSERT_TRUE(ca_cert != nullptr);
  20889. ASSERT_TRUE(key != nullptr);
  20890. X509_STORE *cert_store = X509_STORE_new();
  20891. X509_STORE_add_cert(cert_store, ca_cert);
  20892. // svr.update_certs(cert, key, cert_store); // deprecated
  20893. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20894. CLIENT_CA_CERT_FILE);
  20895. ASSERT_TRUE(svr.is_valid());
  20896. svr.stop();
  20897. X509_STORE_free(cert_store);
  20898. X509_free(cert);
  20899. X509_free(ca_cert);
  20900. EVP_PKEY_free(key);
  20901. }
  20902. // Test that update_certs() updates client CA list correctly
  20903. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20904. // Start with file-based constructor
  20905. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20906. ASSERT_TRUE(svr.is_valid());
  20907. // Initially no client CA list should be set
  20908. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20909. ASSERT_TRUE(ssl_ctx != nullptr);
  20910. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20911. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20912. EXPECT_EQ(0, count_before);
  20913. // Now update with client CA (PEM string)
  20914. std::string cert_pem, key_pem, ca_pem;
  20915. read_file(SERVER_CERT_FILE, cert_pem);
  20916. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20917. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20918. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20919. ASSERT_TRUE(svr.is_valid());
  20920. // Now client CA list should be set
  20921. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20922. ASSERT_TRUE(ca_list_after != nullptr);
  20923. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20924. }
  20925. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20926. // Test that the file-path SSLServer constructor properly sets the client CA
  20927. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20929. ASSERT_TRUE(svr.is_valid());
  20930. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20931. ASSERT_TRUE(ssl_ctx != nullptr);
  20932. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20933. ASSERT_TRUE(ca_list != nullptr);
  20934. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20935. }
  20936. #endif
  20937. // ============================================================================
  20938. // MbedTLS-Specific Tests
  20939. // ============================================================================
  20940. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20941. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20942. using namespace httplib::tls;
  20943. // Track if callback was invoked
  20944. bool callback_invoked = false;
  20945. // The callback receives void* ctx which is actually MbedTlsContext*
  20946. // We can access the mbedtls_ssl_config via the context
  20947. auto setup_callback = [&callback_invoked](void *ctx) {
  20948. callback_invoked = true;
  20949. // Cast to MbedTlsContext* to access the ssl config
  20950. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20951. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20952. // Use static variables to hold certificate data (simplified for test)
  20953. static mbedtls_x509_crt own_cert;
  20954. static mbedtls_pk_context own_key;
  20955. static mbedtls_x509_crt ca_chain;
  20956. static bool initialized = false;
  20957. if (!initialized) {
  20958. mbedtls_x509_crt_init(&own_cert);
  20959. mbedtls_pk_init(&own_key);
  20960. mbedtls_x509_crt_init(&ca_chain);
  20961. // Load server certificate
  20962. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20963. return false;
  20964. }
  20965. // Load server private key.
  20966. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20967. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20968. #if MBEDTLS_VERSION_MAJOR == 3
  20969. ,
  20970. mbedtls_ctr_drbg_random, nullptr
  20971. #endif
  20972. ) != 0) {
  20973. return false;
  20974. }
  20975. // Load CA chain for client verification
  20976. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20977. return false;
  20978. }
  20979. initialized = true;
  20980. }
  20981. // Configure the SSL config
  20982. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20983. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20984. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20985. // Set minimum TLS version using mbedTLS native API
  20986. #if MBEDTLS_VERSION_MAJOR >= 3
  20987. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20988. #else
  20989. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20990. MBEDTLS_SSL_MINOR_VERSION_3);
  20991. #endif
  20992. return true;
  20993. };
  20994. SSLServer svr(setup_callback);
  20995. ASSERT_TRUE(svr.is_valid());
  20996. ASSERT_TRUE(callback_invoked);
  20997. svr.Get("/test", [&](const Request &req, Response &res) {
  20998. res.set_content("test", "text/plain");
  20999. auto cert = req.peer_cert();
  21000. ASSERT_TRUE(static_cast<bool>(cert));
  21001. auto common_name = cert.subject_cn();
  21002. EXPECT_EQ("Common Name", common_name);
  21003. });
  21004. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21005. auto se = detail::scope_exit([&] {
  21006. svr.stop();
  21007. t.join();
  21008. ASSERT_FALSE(svr.is_running());
  21009. });
  21010. svr.wait_until_ready();
  21011. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21012. cli.enable_server_certificate_verification(false);
  21013. cli.set_connection_timeout(30);
  21014. auto res = cli.Get("/test");
  21015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21016. ASSERT_EQ(StatusCode::OK_200, res->status);
  21017. }
  21018. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21019. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21020. // keep-alive SSL session, which reads through that config in
  21021. // mbedtls_ssl_close_notify.
  21022. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21024. ASSERT_TRUE(svr.is_valid());
  21025. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21026. res.set_content("test", "text/plain");
  21027. });
  21028. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21029. auto se = detail::scope_exit([&] {
  21030. svr.stop();
  21031. t.join();
  21032. ASSERT_FALSE(svr.is_running());
  21033. });
  21034. svr.wait_until_ready();
  21035. {
  21036. SSLClient cli(HOST, PORT);
  21037. cli.enable_server_certificate_verification(false);
  21038. cli.set_keep_alive(true);
  21039. auto res = cli.Get("/test");
  21040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21041. ASSERT_EQ(StatusCode::OK_200, res->status);
  21042. // cli is destructed here with the keep-alive SSL session still open.
  21043. }
  21044. }
  21045. #endif
  21046. // WebSocket Tests
  21047. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21048. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21049. // defining the meaning of these bits has been negotiated.
  21050. auto make_frame = [](uint8_t first_byte) {
  21051. std::string frame;
  21052. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21053. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21054. frame += "Hello";
  21055. return frame;
  21056. };
  21057. // RSV1 set (0x40)
  21058. {
  21059. detail::BufferStream strm;
  21060. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21061. ws::Opcode opcode;
  21062. std::string payload;
  21063. bool fin;
  21064. EXPECT_EQ(
  21065. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21066. ws::impl::FrameRead::Fail);
  21067. }
  21068. // RSV2 set (0x20)
  21069. {
  21070. detail::BufferStream strm;
  21071. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21072. ws::Opcode opcode;
  21073. std::string payload;
  21074. bool fin;
  21075. EXPECT_EQ(
  21076. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21077. ws::impl::FrameRead::Fail);
  21078. }
  21079. // RSV3 set (0x10)
  21080. {
  21081. detail::BufferStream strm;
  21082. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21083. ws::Opcode opcode;
  21084. std::string payload;
  21085. bool fin;
  21086. EXPECT_EQ(
  21087. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21088. ws::impl::FrameRead::Fail);
  21089. }
  21090. // No RSV bits set - should succeed
  21091. {
  21092. detail::BufferStream strm;
  21093. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21094. ws::Opcode opcode;
  21095. std::string payload;
  21096. bool fin;
  21097. EXPECT_EQ(
  21098. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21099. ws::impl::FrameRead::Ok);
  21100. EXPECT_EQ(ws::Opcode::Text, opcode);
  21101. EXPECT_EQ("Hello", payload);
  21102. EXPECT_TRUE(fin);
  21103. }
  21104. }
  21105. TEST(WebSocketTest, ControlFrameValidation) {
  21106. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21107. // payload length <= 125.
  21108. // Ping with FIN=0 - must be rejected
  21109. {
  21110. detail::BufferStream strm;
  21111. std::string frame;
  21112. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21113. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21114. strm.write(frame.data(), frame.size());
  21115. ws::Opcode opcode;
  21116. std::string payload;
  21117. bool fin;
  21118. EXPECT_EQ(
  21119. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21120. ws::impl::FrameRead::Fail);
  21121. }
  21122. // Close with FIN=0 - must be rejected
  21123. {
  21124. detail::BufferStream strm;
  21125. std::string frame;
  21126. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21127. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21128. strm.write(frame.data(), frame.size());
  21129. ws::Opcode opcode;
  21130. std::string payload;
  21131. bool fin;
  21132. EXPECT_EQ(
  21133. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21134. ws::impl::FrameRead::Fail);
  21135. }
  21136. // Ping with payload_len=126 (extended length) - must be rejected
  21137. {
  21138. detail::BufferStream strm;
  21139. std::string frame;
  21140. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21141. frame += static_cast<char>(126); // payload_len=126 (>125)
  21142. frame += static_cast<char>(0x00); // extended length high byte
  21143. frame += static_cast<char>(126); // extended length low byte
  21144. frame += std::string(126, 'x');
  21145. strm.write(frame.data(), frame.size());
  21146. ws::Opcode opcode;
  21147. std::string payload;
  21148. bool fin;
  21149. EXPECT_EQ(
  21150. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21151. ws::impl::FrameRead::Fail);
  21152. }
  21153. // Ping with FIN=1 and payload_len=125 - should succeed
  21154. {
  21155. detail::BufferStream strm;
  21156. std::string frame;
  21157. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21158. frame += static_cast<char>(125); // payload_len=125
  21159. frame += std::string(125, 'x');
  21160. strm.write(frame.data(), frame.size());
  21161. ws::Opcode opcode;
  21162. std::string payload;
  21163. bool fin;
  21164. EXPECT_EQ(
  21165. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21166. ws::impl::FrameRead::Ok);
  21167. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21168. EXPECT_EQ(125u, payload.size());
  21169. EXPECT_TRUE(fin);
  21170. }
  21171. }
  21172. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21173. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21174. // length MUST be 0.
  21175. // MSB set - must be rejected
  21176. {
  21177. detail::BufferStream strm;
  21178. std::string frame;
  21179. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21180. frame += static_cast<char>(127); // 64-bit extended length
  21181. frame += static_cast<char>(0x80); // MSB set (invalid)
  21182. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21183. strm.write(frame.data(), frame.size());
  21184. ws::Opcode opcode;
  21185. std::string payload;
  21186. bool fin;
  21187. EXPECT_EQ(
  21188. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21189. ws::impl::FrameRead::Fail);
  21190. }
  21191. // MSB clear - should pass length parsing (will be rejected by max_len,
  21192. // but that's a different check; use a small length to verify)
  21193. {
  21194. detail::BufferStream strm;
  21195. std::string frame;
  21196. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21197. frame += static_cast<char>(127); // 64-bit extended length
  21198. frame += std::string(7, '\0'); // high bytes = 0
  21199. frame += static_cast<char>(0x03); // length = 3
  21200. frame += "abc";
  21201. strm.write(frame.data(), frame.size());
  21202. ws::Opcode opcode;
  21203. std::string payload;
  21204. bool fin;
  21205. EXPECT_EQ(
  21206. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21207. ws::impl::FrameRead::Ok);
  21208. EXPECT_EQ(ws::Opcode::Text, opcode);
  21209. EXPECT_EQ("abc", payload);
  21210. }
  21211. }
  21212. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21213. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21214. // Valid UTF-8
  21215. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21216. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21217. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21218. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21219. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21220. // Invalid UTF-8
  21221. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21222. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21223. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21224. EXPECT_FALSE(
  21225. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21226. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21227. }
  21228. TEST(WebSocketTest, ConnectAndDisconnect) {
  21229. Server svr;
  21230. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21231. std::string msg;
  21232. while (ws.read(msg)) {}
  21233. });
  21234. auto port = svr.bind_to_any_port(HOST);
  21235. std::thread t([&]() { svr.listen_after_bind(); });
  21236. svr.wait_until_ready();
  21237. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21238. auto res = client.connect();
  21239. ASSERT_TRUE(res);
  21240. EXPECT_EQ(Error::Success, res.error());
  21241. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21242. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21243. EXPECT_TRUE(client.is_open());
  21244. client.close();
  21245. EXPECT_FALSE(client.is_open());
  21246. svr.stop();
  21247. t.join();
  21248. }
  21249. TEST(WebSocketTest, ValidURL) {
  21250. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21251. EXPECT_TRUE(ws1.is_valid());
  21252. ws::WebSocketClient ws2("ws://example.com/path");
  21253. EXPECT_TRUE(ws2.is_valid());
  21254. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21255. EXPECT_TRUE(ws3.is_valid());
  21256. #ifdef CPPHTTPLIB_SSL_ENABLED
  21257. ws::WebSocketClient wss1("wss://example.com/path");
  21258. EXPECT_TRUE(wss1.is_valid());
  21259. ws::WebSocketClient wss2("wss://example.com:443/path");
  21260. EXPECT_TRUE(wss2.is_valid());
  21261. #endif
  21262. }
  21263. TEST(WebSocketTest, InvalidURL) {
  21264. // No scheme
  21265. ws::WebSocketClient ws1("localhost:8080/path");
  21266. EXPECT_FALSE(ws1.is_valid());
  21267. // No path
  21268. ws::WebSocketClient ws2("ws://localhost:8080");
  21269. EXPECT_FALSE(ws2.is_valid());
  21270. // Empty string
  21271. ws::WebSocketClient ws3("");
  21272. EXPECT_FALSE(ws3.is_valid());
  21273. // Missing host
  21274. ws::WebSocketClient ws4("ws://:8080/path");
  21275. EXPECT_FALSE(ws4.is_valid());
  21276. // Port number overflow — should not crash
  21277. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21278. EXPECT_FALSE(ws5.is_valid());
  21279. // Port out of range
  21280. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21281. EXPECT_FALSE(ws6.is_valid());
  21282. }
  21283. TEST(WebSocketTest, UnsupportedScheme) {
  21284. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21285. ws::WebSocketClient ws1("http://localhost:8080/path");
  21286. EXPECT_FALSE(ws1.is_valid());
  21287. ws::WebSocketClient ws2("https://localhost:8080/path");
  21288. EXPECT_FALSE(ws2.is_valid());
  21289. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21290. EXPECT_FALSE(ws3.is_valid());
  21291. #else
  21292. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21293. std::invalid_argument);
  21294. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21295. std::invalid_argument);
  21296. #endif
  21297. }
  21298. TEST(WebSocketTest, ConnectWhenInvalid) {
  21299. ws::WebSocketClient ws("not a valid url");
  21300. EXPECT_FALSE(ws.is_valid());
  21301. auto res = ws.connect();
  21302. EXPECT_FALSE(res);
  21303. EXPECT_EQ(Error::Connection, res.error());
  21304. EXPECT_EQ(-1, res.status());
  21305. }
  21306. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21307. // Grab a port that is free, then close it again so nothing listens there
  21308. Server svr;
  21309. auto port = svr.bind_to_any_port(HOST);
  21310. svr.stop();
  21311. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21312. auto res = client.connect();
  21313. ASSERT_FALSE(res);
  21314. EXPECT_EQ(Error::Connection, res.error());
  21315. EXPECT_EQ(-1, res.status());
  21316. }
  21317. TEST(WebSocketTest, DefaultPort) {
  21318. ws::WebSocketClient ws1("ws://example.com/path");
  21319. EXPECT_TRUE(ws1.is_valid());
  21320. // ws:// defaults to port 80 (verified by successful parse)
  21321. #ifdef CPPHTTPLIB_SSL_ENABLED
  21322. ws::WebSocketClient ws2("wss://example.com/path");
  21323. EXPECT_TRUE(ws2.is_valid());
  21324. // wss:// defaults to port 443 (verified by successful parse)
  21325. #endif
  21326. }
  21327. TEST(WebSocketTest, IPv6LiteralAddress) {
  21328. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21329. EXPECT_TRUE(ws1.is_valid());
  21330. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21331. EXPECT_TRUE(ws2.is_valid());
  21332. }
  21333. TEST(WebSocketTest, ComplexPath) {
  21334. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21335. EXPECT_TRUE(ws1.is_valid());
  21336. ws::WebSocketClient ws2("ws://localhost:8080/");
  21337. EXPECT_TRUE(ws2.is_valid());
  21338. }
  21339. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21340. Server svr;
  21341. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21342. std::string msg;
  21343. while (ws.read(msg)) {}
  21344. });
  21345. auto port = svr.bind_to_any_port(HOST);
  21346. std::thread t([&]() { svr.listen_after_bind(); });
  21347. svr.wait_until_ready();
  21348. auto another_host = "example.com";
  21349. auto wrong_ip = "192.0.2.1";
  21350. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21351. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21352. ASSERT_TRUE(client.connect());
  21353. EXPECT_TRUE(client.is_open());
  21354. client.close();
  21355. svr.stop();
  21356. t.join();
  21357. }
  21358. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21359. Server svr;
  21360. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21361. std::string msg;
  21362. while (ws.read(msg)) {}
  21363. });
  21364. auto port = svr.bind_to_any_port(HOST);
  21365. std::thread t([&]() { svr.listen_after_bind(); });
  21366. svr.wait_until_ready();
  21367. auto wrong_ip = "192.0.2.1";
  21368. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21369. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21370. client.set_connection_timeout(1);
  21371. client.set_read_timeout(1);
  21372. client.set_write_timeout(1);
  21373. EXPECT_FALSE(client.connect());
  21374. EXPECT_FALSE(client.is_open());
  21375. svr.stop();
  21376. t.join();
  21377. }
  21378. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21379. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21380. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21381. // (RFC 6761) is only a map key and the Host header value.
  21382. auto host = "target.invalid";
  21383. Server svr;
  21384. std::string received_host;
  21385. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21386. received_host = req.get_header_value("Host");
  21387. std::string msg;
  21388. while (ws.read(msg)) {}
  21389. });
  21390. auto port = svr.bind_to_any_port(HOST);
  21391. std::thread t([&]() { svr.listen_after_bind(); });
  21392. // ASSERT_* below returns from the test body, which would leave t joinable
  21393. // and make ~thread call std::terminate.
  21394. auto se = detail::scope_exit([&] {
  21395. svr.stop();
  21396. if (t.joinable()) { t.join(); }
  21397. });
  21398. svr.wait_until_ready();
  21399. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21400. std::to_string(port) + "/ws");
  21401. client.set_hostname_addr_map({{host, HOST}});
  21402. ASSERT_TRUE(client.connect());
  21403. EXPECT_TRUE(client.is_open());
  21404. client.close();
  21405. svr.stop();
  21406. t.join();
  21407. // The mapping only redirects the connection; the identity stays host_.
  21408. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21409. }
  21410. class WebSocketIntegrationTest : public ::testing::Test {
  21411. protected:
  21412. void SetUp() override {
  21413. server_ = httplib::detail::make_unique<Server>();
  21414. setup_server();
  21415. start_server();
  21416. }
  21417. void TearDown() override {
  21418. server_->stop();
  21419. if (server_thread_.joinable()) { server_thread_.join(); }
  21420. }
  21421. void setup_server() {
  21422. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21423. std::string msg;
  21424. ws::ReadResult ret;
  21425. while ((ret = ws.read(msg))) {
  21426. if (ret == ws::Binary) {
  21427. ws.send(msg.data(), msg.size());
  21428. } else {
  21429. ws.send(msg);
  21430. }
  21431. }
  21432. });
  21433. server_->WebSocket("/ws-echo-string",
  21434. [](const Request &, ws::WebSocket &ws) {
  21435. std::string msg;
  21436. while (ws.read(msg)) {
  21437. ws.send("echo: " + msg);
  21438. }
  21439. });
  21440. server_->WebSocket(
  21441. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21442. // Echo back request metadata
  21443. ws.send("path:" + req.path);
  21444. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21445. std::string msg;
  21446. while (ws.read(msg)) {}
  21447. });
  21448. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21449. std::string msg;
  21450. ws.read(msg); // wait for a message
  21451. ws.close();
  21452. });
  21453. server_->WebSocket("/ws-close-status",
  21454. [](const Request &, ws::WebSocket &ws) {
  21455. std::string msg;
  21456. ws.read(msg); // wait for a message
  21457. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21458. });
  21459. server_->WebSocket(
  21460. "/ws-subprotocol",
  21461. [](const Request &, ws::WebSocket &ws) {
  21462. std::string msg;
  21463. while (ws.read(msg)) {
  21464. ws.send(msg);
  21465. }
  21466. },
  21467. [](const std::vector<std::string> &protocols) -> std::string {
  21468. for (const auto &p : protocols) {
  21469. if (p == "graphql-ws") { return p; }
  21470. }
  21471. return "";
  21472. });
  21473. server_->WebSocket(
  21474. "/ws-subprotocol-unoffered",
  21475. [](const Request &, ws::WebSocket &ws) {
  21476. std::string msg;
  21477. while (ws.read(msg)) {
  21478. ws.send(msg);
  21479. }
  21480. },
  21481. [](const std::vector<std::string> &) -> std::string {
  21482. return "admin";
  21483. });
  21484. }
  21485. void start_server() {
  21486. port_ = server_->bind_to_any_port(HOST);
  21487. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21488. server_->wait_until_ready();
  21489. }
  21490. std::unique_ptr<Server> server_;
  21491. std::thread server_thread_;
  21492. int port_ = 0;
  21493. };
  21494. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21495. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21496. "/ws-echo");
  21497. ASSERT_TRUE(client.connect());
  21498. ASSERT_TRUE(client.is_open());
  21499. ASSERT_TRUE(client.send("Hello WebSocket"));
  21500. std::string msg;
  21501. EXPECT_EQ(ws::Text, client.read(msg));
  21502. EXPECT_EQ("Hello WebSocket", msg);
  21503. client.close();
  21504. }
  21505. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21506. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21507. "/ws-echo");
  21508. ASSERT_TRUE(client.connect());
  21509. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21510. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21511. std::string msg;
  21512. EXPECT_EQ(ws::Binary, client.read(msg));
  21513. EXPECT_EQ(binary_data, msg);
  21514. client.close();
  21515. }
  21516. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21517. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21518. "/ws-echo");
  21519. ASSERT_TRUE(client.connect());
  21520. for (int i = 0; i < 10; i++) {
  21521. auto text = "message " + std::to_string(i);
  21522. ASSERT_TRUE(client.send(text));
  21523. std::string msg;
  21524. ASSERT_TRUE(client.read(msg));
  21525. EXPECT_EQ(text, msg);
  21526. }
  21527. client.close();
  21528. }
  21529. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21530. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21531. "/ws-close");
  21532. ASSERT_TRUE(client.connect());
  21533. // Send a message to trigger the server to close
  21534. ASSERT_TRUE(client.send("trigger close"));
  21535. // The server will close, so read should return false
  21536. std::string msg;
  21537. EXPECT_FALSE(client.read(msg));
  21538. EXPECT_FALSE(client.is_open());
  21539. }
  21540. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21541. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21542. "/ws-echo");
  21543. ASSERT_TRUE(client.connect());
  21544. // 128KB message
  21545. std::string large_data(128 * 1024, 'X');
  21546. ASSERT_TRUE(client.send(large_data));
  21547. std::string msg;
  21548. ASSERT_TRUE(client.read(msg));
  21549. EXPECT_EQ(large_data, msg);
  21550. client.close();
  21551. }
  21552. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21553. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21554. "/ws-echo");
  21555. ASSERT_TRUE(client.connect());
  21556. const int num_threads = 4;
  21557. std::vector<std::thread> threads;
  21558. std::atomic<int> send_count{0};
  21559. for (int t = 0; t < num_threads; t++) {
  21560. threads.emplace_back([&client, &send_count, t]() {
  21561. for (int i = 0; i < 5; i++) {
  21562. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21563. if (client.send(text)) { send_count++; }
  21564. }
  21565. });
  21566. }
  21567. for (auto &th : threads) {
  21568. th.join();
  21569. }
  21570. int received = 0;
  21571. std::string msg;
  21572. while (received < send_count.load()) {
  21573. if (!client.read(msg)) { break; }
  21574. received++;
  21575. }
  21576. EXPECT_EQ(send_count.load(), received);
  21577. client.close();
  21578. }
  21579. TEST_F(WebSocketIntegrationTest, ReadString) {
  21580. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21581. "/ws-echo-string");
  21582. ASSERT_TRUE(client.connect());
  21583. ASSERT_TRUE(client.send("hello"));
  21584. std::string msg;
  21585. ASSERT_TRUE(client.read(msg));
  21586. EXPECT_EQ("echo: hello", msg);
  21587. ASSERT_TRUE(client.send("world"));
  21588. ASSERT_TRUE(client.read(msg));
  21589. EXPECT_EQ("echo: world", msg);
  21590. client.close();
  21591. }
  21592. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21593. Headers headers = {{"X-Test-Header", "test-value"}};
  21594. ws::WebSocketClient client(
  21595. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21596. ASSERT_TRUE(client.connect());
  21597. std::string msg;
  21598. ASSERT_TRUE(client.read(msg));
  21599. EXPECT_EQ("path:/ws-request-info", msg);
  21600. ASSERT_TRUE(client.read(msg));
  21601. EXPECT_EQ("header:test-value", msg);
  21602. client.close();
  21603. }
  21604. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21605. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21606. "/ws-echo");
  21607. client.set_read_timeout(1, 0); // 1 second
  21608. ASSERT_TRUE(client.connect());
  21609. // Don't send anything — server echo handler waits for a message, so read()
  21610. // should time out. The connection survives it: nothing was consumed.
  21611. std::string msg;
  21612. EXPECT_EQ(client.read(msg), ws::Timeout);
  21613. EXPECT_TRUE(client.is_open());
  21614. // And it is still usable afterwards.
  21615. EXPECT_TRUE(client.send("after timeout"));
  21616. EXPECT_EQ(client.read(msg), ws::Text);
  21617. EXPECT_EQ(msg, "after timeout");
  21618. }
  21619. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21620. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21621. "/ws-echo");
  21622. client.set_read_timeout(1, 0);
  21623. ASSERT_TRUE(client.connect());
  21624. ASSERT_TRUE(client.send("first"));
  21625. std::string msg;
  21626. ASSERT_EQ(client.read(msg), ws::Text);
  21627. ASSERT_EQ(msg, "first");
  21628. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21629. // not be used with a read timeout: it would reprocess the previous message.
  21630. EXPECT_EQ(client.read(msg), ws::Timeout);
  21631. EXPECT_EQ(msg, "first");
  21632. }
  21633. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21634. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21635. "/ws-echo");
  21636. ASSERT_TRUE(client.connect());
  21637. // Setting it once the connection is open reaches the live stream, not just
  21638. // the seed for the next connect().
  21639. client.set_read_timeout(1, 0);
  21640. std::string msg;
  21641. EXPECT_EQ(client.read(msg), ws::Timeout);
  21642. EXPECT_TRUE(client.is_open());
  21643. }
  21644. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21645. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21646. "/ws-echo");
  21647. client.set_read_timeout(5, 0);
  21648. ASSERT_TRUE(client.connect());
  21649. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21650. // The server should reject it and close the connection.
  21651. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21652. client.send(oversized);
  21653. // The server's read() should have failed due to payload limit,
  21654. // so our read() should return false (connection closed).
  21655. std::string msg;
  21656. EXPECT_FALSE(client.read(msg));
  21657. }
  21658. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21659. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21660. "/ws-echo");
  21661. client.set_read_timeout(10, 0);
  21662. ASSERT_TRUE(client.connect());
  21663. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21664. // This should succeed.
  21665. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21666. ASSERT_TRUE(client.send(at_limit));
  21667. std::string msg;
  21668. ASSERT_TRUE(client.read(msg));
  21669. EXPECT_EQ(at_limit.size(), msg.size());
  21670. client.close();
  21671. }
  21672. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21673. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21674. "/nonexistent");
  21675. auto res = client.connect();
  21676. EXPECT_FALSE(res);
  21677. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21678. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21679. EXPECT_FALSE(client.is_open());
  21680. }
  21681. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21682. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21683. "/ws-echo");
  21684. ASSERT_TRUE(client.connect());
  21685. ASSERT_TRUE(client.send(""));
  21686. std::string msg;
  21687. EXPECT_EQ(ws::Text, client.read(msg));
  21688. EXPECT_EQ("", msg);
  21689. client.close();
  21690. }
  21691. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21692. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21693. "/ws-echo");
  21694. // First connection
  21695. ASSERT_TRUE(client.connect());
  21696. ASSERT_TRUE(client.send("first"));
  21697. std::string msg;
  21698. ASSERT_TRUE(client.read(msg));
  21699. EXPECT_EQ("first", msg);
  21700. client.close();
  21701. EXPECT_FALSE(client.is_open());
  21702. // Reconnect using the same client object
  21703. ASSERT_TRUE(client.connect());
  21704. ASSERT_TRUE(client.is_open());
  21705. ASSERT_TRUE(client.send("second"));
  21706. ASSERT_TRUE(client.read(msg));
  21707. EXPECT_EQ("second", msg);
  21708. client.close();
  21709. }
  21710. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21711. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21712. "/ws-close-status");
  21713. ASSERT_TRUE(client.connect());
  21714. // Trigger the server to close with GoingAway status
  21715. ASSERT_TRUE(client.send("trigger"));
  21716. // read() should return false after receiving the close frame
  21717. std::string msg;
  21718. EXPECT_FALSE(client.read(msg));
  21719. EXPECT_FALSE(client.is_open());
  21720. }
  21721. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21722. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21723. "/ws-echo");
  21724. ASSERT_TRUE(client.connect());
  21725. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21726. EXPECT_FALSE(client.is_open());
  21727. }
  21728. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21729. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21730. ws::WebSocketClient client(
  21731. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21732. ASSERT_TRUE(client.connect());
  21733. // Server should have selected graphql-ws
  21734. EXPECT_EQ("graphql-ws", client.subprotocol());
  21735. client.close();
  21736. }
  21737. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21738. Headers headers;
  21739. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21740. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21741. ws::WebSocketClient client(
  21742. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21743. ASSERT_TRUE(client.connect());
  21744. // The offer on the second field line counts too, so graphql-ws is selected
  21745. EXPECT_EQ("graphql-ws", client.subprotocol());
  21746. client.close();
  21747. }
  21748. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21749. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21750. ws::WebSocketClient client(
  21751. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21752. ASSERT_TRUE(client.connect());
  21753. // Server should not have selected any subprotocol
  21754. EXPECT_TRUE(client.subprotocol().empty());
  21755. client.close();
  21756. }
  21757. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21758. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21759. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21760. "/ws-subprotocol-unoffered",
  21761. headers);
  21762. ASSERT_TRUE(client.connect());
  21763. EXPECT_TRUE(client.subprotocol().empty());
  21764. client.close();
  21765. }
  21766. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21767. // Connect without requesting any subprotocol
  21768. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21769. "/ws-subprotocol");
  21770. ASSERT_TRUE(client.connect());
  21771. EXPECT_TRUE(client.subprotocol().empty());
  21772. client.close();
  21773. }
  21774. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21775. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21776. "/ws-echo");
  21777. client.set_tcp_nodelay(true);
  21778. client.set_connection_timeout(3, 0);
  21779. bool socket_options_called = false;
  21780. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21781. ASSERT_TRUE(client.connect());
  21782. ASSERT_TRUE(client.is_open());
  21783. EXPECT_TRUE(socket_options_called);
  21784. ASSERT_TRUE(client.send("hello"));
  21785. std::string msg;
  21786. auto result = client.read(msg);
  21787. EXPECT_EQ(result, ws::ReadResult::Text);
  21788. EXPECT_EQ(msg, "hello");
  21789. client.close();
  21790. }
  21791. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21792. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21793. "/ws-echo");
  21794. client.set_connection_timeout(std::chrono::seconds(3));
  21795. client.set_write_timeout(std::chrono::seconds(3));
  21796. // A sub-second remainder exercises the seconds/microseconds split.
  21797. client.set_read_timeout(std::chrono::milliseconds(1500));
  21798. ASSERT_TRUE(client.connect());
  21799. auto start = std::chrono::steady_clock::now();
  21800. std::string msg;
  21801. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21802. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21803. std::chrono::steady_clock::now() - start)
  21804. .count();
  21805. // Above 1s so that dropping the microseconds half of the split fails here.
  21806. // Ignoring the setter altogether would not reach this line at all: a client
  21807. // waits forever by default.
  21808. EXPECT_GE(elapsed, 1400);
  21809. EXPECT_LT(elapsed, 30000);
  21810. }
  21811. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21812. Server svr;
  21813. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21814. if (!req.has_header("Authorization")) {
  21815. res.status = StatusCode::Unauthorized_401;
  21816. res.set_content("Unauthorized", "text/plain");
  21817. return Server::HandlerResponse::Handled;
  21818. }
  21819. return Server::HandlerResponse::Unhandled;
  21820. });
  21821. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21822. std::string msg;
  21823. while (ws.read(msg)) {
  21824. ws.send(msg);
  21825. }
  21826. });
  21827. auto port = svr.bind_to_any_port("localhost");
  21828. std::thread t([&]() { svr.listen_after_bind(); });
  21829. svr.wait_until_ready();
  21830. // Without Authorization header - should be rejected before upgrade
  21831. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21832. EXPECT_FALSE(client1.connect());
  21833. // The rejection is framed like any other HTTP response
  21834. {
  21835. Client cli("localhost", port);
  21836. Headers headers = {{"Upgrade", "websocket"},
  21837. {"Connection", "Upgrade"},
  21838. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21839. {"Sec-WebSocket-Version", "13"}};
  21840. auto res = cli.Get("/ws", headers);
  21841. ASSERT_TRUE(res);
  21842. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21843. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21844. EXPECT_EQ("Unauthorized", res->body);
  21845. }
  21846. // With Authorization header - should succeed
  21847. Headers headers = {{"Authorization", "Bearer token123"}};
  21848. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21849. headers);
  21850. ASSERT_TRUE(client2.connect());
  21851. ASSERT_TRUE(client2.send("hello"));
  21852. std::string msg;
  21853. ASSERT_TRUE(client2.read(msg));
  21854. EXPECT_EQ("hello", msg);
  21855. client2.close();
  21856. svr.stop();
  21857. t.join();
  21858. }
  21859. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21860. Server svr;
  21861. std::atomic<int> pre_request_calls{0};
  21862. std::atomic<bool> route_matched{false};
  21863. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21864. pre_request_calls++;
  21865. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21866. if (req.get_header_value("Authorization") != "Bearer token123") {
  21867. res.status = StatusCode::Unauthorized_401;
  21868. res.set_content("Unauthorized", "text/plain");
  21869. return Server::HandlerResponse::Handled;
  21870. }
  21871. return Server::HandlerResponse::Unhandled;
  21872. });
  21873. std::atomic<bool> handler_called{false};
  21874. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21875. handler_called = true;
  21876. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21877. });
  21878. auto port = svr.bind_to_any_port("localhost");
  21879. std::thread t([&]() { svr.listen_after_bind(); });
  21880. svr.wait_until_ready();
  21881. // Without Authorization header - should be rejected before upgrade
  21882. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21883. "/ws/1");
  21884. EXPECT_FALSE(client1.connect());
  21885. EXPECT_FALSE(handler_called);
  21886. EXPECT_EQ(1, pre_request_calls);
  21887. EXPECT_TRUE(route_matched);
  21888. // The rejection is an ordinary HTTP response, not a protocol switch
  21889. {
  21890. Client cli("localhost", port);
  21891. Headers headers = {{"Upgrade", "websocket"},
  21892. {"Connection", "Upgrade"},
  21893. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21894. {"Sec-WebSocket-Version", "13"}};
  21895. auto res = cli.Get("/ws/1", headers);
  21896. ASSERT_TRUE(res);
  21897. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21898. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21899. EXPECT_EQ("Unauthorized", res->body);
  21900. }
  21901. EXPECT_FALSE(handler_called);
  21902. // With Authorization header - should succeed
  21903. Headers headers = {{"Authorization", "Bearer token123"}};
  21904. ws::WebSocketClient client2(
  21905. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21906. ASSERT_TRUE(client2.connect());
  21907. std::string msg;
  21908. ASSERT_TRUE(client2.read(msg));
  21909. EXPECT_EQ("/ws/:id 2", msg);
  21910. EXPECT_TRUE(handler_called);
  21911. client2.close();
  21912. svr.stop();
  21913. t.join();
  21914. }
  21915. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21916. Server svr;
  21917. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21918. // A read timeout is how a handler gets control back. Without it, a handler
  21919. // parked in read() can never write on the connection it is reading.
  21920. ws.set_read_timeout(std::chrono::milliseconds(100));
  21921. std::string msg;
  21922. while (ws.is_open()) {
  21923. auto r = ws.read(msg);
  21924. if (r == httplib::ws::Timeout) {
  21925. ws.send("tick");
  21926. continue;
  21927. }
  21928. if (r == httplib::ws::Fail) { break; }
  21929. ws.send(msg);
  21930. }
  21931. });
  21932. auto port = svr.bind_to_any_port("localhost");
  21933. std::thread t([&]() { svr.listen_after_bind(); });
  21934. svr.wait_until_ready();
  21935. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21936. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21937. ASSERT_TRUE(client.connect());
  21938. // The client sends nothing, so anything it receives came out of the
  21939. // handler's timeout path.
  21940. std::string msg;
  21941. ASSERT_EQ(client.read(msg), ws::Text);
  21942. EXPECT_EQ("tick", msg);
  21943. client.close();
  21944. svr.stop();
  21945. t.join();
  21946. }
  21947. // Stream::read may return fewer bytes than asked for. This is that contract at
  21948. // its worst -- one byte per call -- which is what a frame header straddling a
  21949. // read buffer's boundary looks like to the frame parser.
  21950. class WsByteAtATimeStream : public Stream {
  21951. public:
  21952. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21953. bool is_readable() const override { return true; }
  21954. bool wait_readable() const override { return true; }
  21955. bool wait_writable() const override { return true; }
  21956. ssize_t read(char *ptr, size_t size) override {
  21957. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21958. *ptr = data_[pos_++];
  21959. return 1;
  21960. }
  21961. ssize_t write(const char *, size_t size) override {
  21962. return static_cast<ssize_t>(size);
  21963. }
  21964. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21965. ip = "127.0.0.1";
  21966. port = 0;
  21967. }
  21968. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21969. ip = "127.0.0.1";
  21970. port = 0;
  21971. }
  21972. socket_t socket() const override { return INVALID_SOCKET; }
  21973. time_t duration() const override { return 0; }
  21974. private:
  21975. std::string data_;
  21976. size_t pos_ = 0;
  21977. };
  21978. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21979. // The payload uses the 16-bit extended length, so the header, the length
  21980. // and the mask key are all multi-byte fields here. Each used to be read
  21981. // with a single read() call, which fails as soon as one is split. The
  21982. // payload is also a little over one read chunk, so it is read in two.
  21983. std::string body;
  21984. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21985. body += static_cast<char>(i % 251);
  21986. }
  21987. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21988. std::string frame;
  21989. frame += static_cast<char>(0x81); // FIN + Text
  21990. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21991. frame += static_cast<char>(body.size() >> 8);
  21992. frame += static_cast<char>(body.size() & 0xff);
  21993. for (size_t i = 0; i < 4; i++) {
  21994. frame += static_cast<char>(mask[i]);
  21995. }
  21996. for (size_t i = 0; i < body.size(); i++) {
  21997. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21998. }
  21999. WsByteAtATimeStream strm(frame);
  22000. ws::Opcode opcode;
  22001. std::string payload;
  22002. bool fin = false;
  22003. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22004. /*expect_masked=*/true, body.size()),
  22005. ws::impl::FrameRead::Ok);
  22006. EXPECT_TRUE(fin);
  22007. EXPECT_EQ(opcode, ws::Opcode::Text);
  22008. EXPECT_EQ(payload, body);
  22009. }
  22010. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22011. std::string body(2000, 'x');
  22012. std::string frame;
  22013. frame += static_cast<char>(0x82); // FIN + Binary
  22014. frame += static_cast<char>(126); // 16-bit length follows
  22015. frame += static_cast<char>(body.size() >> 8);
  22016. frame += static_cast<char>(body.size() & 0xff);
  22017. frame += body;
  22018. detail::BufferStream strm;
  22019. strm.write(frame.data(), frame.size());
  22020. ws::Opcode opcode;
  22021. std::string payload;
  22022. bool fin;
  22023. EXPECT_EQ(
  22024. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22025. ws::impl::FrameRead::Ok);
  22026. EXPECT_EQ(body, payload);
  22027. }
  22028. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22029. // The header announces the largest payload allowed, and only 3 bytes of it
  22030. // ever arrive.
  22031. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22032. std::string frame;
  22033. frame += static_cast<char>(0x82); // FIN + Binary
  22034. frame += static_cast<char>(127); // 64-bit length follows
  22035. for (int shift = 56; shift >= 0; shift -= 8) {
  22036. frame += static_cast<char>((len >> shift) & 0xff);
  22037. }
  22038. frame += "abc";
  22039. detail::BufferStream strm;
  22040. strm.write(frame.data(), frame.size());
  22041. ws::Opcode opcode;
  22042. std::string payload;
  22043. bool fin;
  22044. EXPECT_EQ(
  22045. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22046. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22047. ws::impl::FrameRead::Fail);
  22048. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22049. }
  22050. TEST(WebSocketTest, QueryStringInHandshake) {
  22051. Server svr;
  22052. std::mutex mtx;
  22053. std::string received_target;
  22054. std::string received_token;
  22055. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22056. {
  22057. std::lock_guard<std::mutex> lock(mtx);
  22058. received_target = req.target;
  22059. if (req.has_param("token")) {
  22060. received_token = req.get_param_value("token");
  22061. }
  22062. }
  22063. std::string msg;
  22064. while (ws.read(msg)) {
  22065. ws.send(msg);
  22066. }
  22067. });
  22068. auto port = svr.bind_to_any_port("localhost");
  22069. std::thread t([&]() { svr.listen_after_bind(); });
  22070. svr.wait_until_ready();
  22071. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22072. "/ws?token=ABC&session=123");
  22073. ASSERT_TRUE(client.connect());
  22074. // Round-trip ensures the handler has run and captured the request.
  22075. ASSERT_TRUE(client.send("hello"));
  22076. std::string msg;
  22077. ASSERT_TRUE(client.read(msg));
  22078. EXPECT_EQ("hello", msg);
  22079. client.close();
  22080. {
  22081. std::lock_guard<std::mutex> lock(mtx);
  22082. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22083. EXPECT_EQ("ABC", received_token);
  22084. }
  22085. svr.stop();
  22086. t.join();
  22087. }
  22088. // Run a handshake against a throwaway server and hand the request the server
  22089. // received back to the caller, so tests can assert on the headers the client
  22090. // actually put on the wire.
  22091. static void capture_websocket_handshake_request(
  22092. const Headers &client_headers,
  22093. std::function<void(const Request &, int port)> verify) {
  22094. Server svr;
  22095. std::mutex mtx;
  22096. Request received;
  22097. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22098. {
  22099. std::lock_guard<std::mutex> lock(mtx);
  22100. received = req;
  22101. }
  22102. std::string msg;
  22103. while (ws.read(msg)) {
  22104. ws.send(msg);
  22105. }
  22106. });
  22107. auto port = svr.bind_to_any_port("localhost");
  22108. std::thread t([&]() { svr.listen_after_bind(); });
  22109. auto se = detail::scope_exit([&] {
  22110. svr.stop();
  22111. t.join();
  22112. });
  22113. svr.wait_until_ready();
  22114. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22115. client_headers);
  22116. ASSERT_TRUE(client.connect());
  22117. ASSERT_TRUE(client.send("hello"));
  22118. std::string msg;
  22119. ASSERT_TRUE(client.read(msg));
  22120. client.close();
  22121. {
  22122. std::lock_guard<std::mutex> lock(mtx);
  22123. verify(received, port);
  22124. }
  22125. }
  22126. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22127. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22128. // Non-default port must be present in the Host header. Default ports
  22129. // (80/443) are omitted; that logic is covered by
  22130. // MakeHostAndPortStringTest.
  22131. EXPECT_EQ("localhost:" + std::to_string(port),
  22132. req.get_header_value("Host"));
  22133. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22134. req.get_header_value("User-Agent"));
  22135. EXPECT_FALSE(req.has_header("Accept"));
  22136. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22137. EXPECT_FALSE(req.has_header("Content-Length"));
  22138. });
  22139. }
  22140. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22141. capture_websocket_handshake_request(
  22142. {{"Host", "example.com"},
  22143. {"User-Agent", "custom-agent"},
  22144. {"X-Custom", "value"}},
  22145. [](const Request &req, int) {
  22146. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22147. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22148. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22149. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22150. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22151. });
  22152. }
  22153. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22154. capture_websocket_handshake_request(
  22155. {{"Upgrade", "bogus"},
  22156. {"Connection", "close"},
  22157. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22158. {"Sec-WebSocket-Version", "8"}},
  22159. [](const Request &req, int) {
  22160. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22161. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22162. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22163. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22164. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22165. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22166. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22167. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22168. req.get_header_value("Sec-WebSocket-Key"));
  22169. });
  22170. }
  22171. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22172. // A header the client refuses to send must abort the handshake before any
  22173. // part of it reaches the wire; a lone request line would otherwise sit in
  22174. // the peer's buffer as a truncated request.
  22175. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22176. ASSERT_NE(INVALID_SOCKET, srv);
  22177. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22178. sockaddr_in addr{};
  22179. addr.sin_family = AF_INET;
  22180. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22181. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22182. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22183. ASSERT_EQ(0, ::listen(srv, 1));
  22184. sockaddr_in bound{};
  22185. socklen_t bound_len = sizeof(bound);
  22186. ASSERT_EQ(
  22187. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22188. auto port = ntohs(bound.sin_port);
  22189. ssize_t received = -1;
  22190. std::thread t([&] {
  22191. // Bound every blocking call so a regression fails the test with a bad
  22192. // value instead of hanging the suite.
  22193. fd_set rfds;
  22194. FD_ZERO(&rfds);
  22195. FD_SET(srv, &rfds);
  22196. timeval tv{5, 0};
  22197. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22198. 0) {
  22199. return;
  22200. }
  22201. sockaddr_in cli_addr{};
  22202. socklen_t cli_len = sizeof(cli_addr);
  22203. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22204. if (cli == INVALID_SOCKET) { return; }
  22205. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22206. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22207. char buf[4096];
  22208. received = ::recv(cli, buf, sizeof(buf), 0);
  22209. });
  22210. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22211. // connect() has already shut the socket down by the time it returns false,
  22212. // so the peer sees EOF without waiting for the client to be destroyed.
  22213. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22214. {{"X-Bad", "a\r\nInjected: 1"}});
  22215. EXPECT_FALSE(client.connect());
  22216. t.join();
  22217. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22218. EXPECT_EQ(0, received);
  22219. }
  22220. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22221. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22222. // contains "upgrade" as a substring is a different token and must not
  22223. // start a WebSocket handshake.
  22224. auto make_request = [](const std::vector<std::string> &connection_values) {
  22225. Request req;
  22226. req.method = "GET";
  22227. req.headers.emplace("Upgrade", "websocket");
  22228. for (const auto &value : connection_values) {
  22229. req.headers.emplace("Connection", value);
  22230. }
  22231. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22232. req.headers.emplace("Sec-WebSocket-Version", "13");
  22233. return req;
  22234. };
  22235. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22236. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22237. EXPECT_TRUE(
  22238. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22239. EXPECT_TRUE(
  22240. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22241. EXPECT_TRUE(
  22242. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22243. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22244. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22245. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22246. EXPECT_FALSE(
  22247. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22248. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22249. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22250. }
  22251. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22252. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22253. // asks recipients to match each protocol-name case-insensitively, and RFC
  22254. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22255. // client naming websocket alongside another protocol, or on a second field
  22256. // line, is offering websocket; a value that merely contains "websocket" as a
  22257. // substring is a different protocol name and is not.
  22258. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22259. Request req;
  22260. req.method = "GET";
  22261. for (const auto &value : upgrade_values) {
  22262. req.headers.emplace("Upgrade", value);
  22263. }
  22264. req.headers.emplace("Connection", "Upgrade");
  22265. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22266. req.headers.emplace("Sec-WebSocket-Version", "13");
  22267. return req;
  22268. };
  22269. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22270. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22271. EXPECT_TRUE(
  22272. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22273. EXPECT_TRUE(
  22274. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22275. EXPECT_TRUE(
  22276. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22277. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22278. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22279. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22280. EXPECT_FALSE(
  22281. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22282. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22283. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22284. }
  22285. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22286. Server svr;
  22287. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22288. auto port = svr.bind_to_any_port("localhost");
  22289. std::thread t([&]() { svr.listen_after_bind(); });
  22290. auto se = detail::scope_exit([&] {
  22291. svr.stop();
  22292. t.join();
  22293. });
  22294. svr.wait_until_ready();
  22295. Headers headers = {{"Upgrade", "websocket"},
  22296. {"Connection", "notupgrade"},
  22297. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22298. {"Sec-WebSocket-Version", "13"}};
  22299. Client cli("localhost", port);
  22300. auto res = cli.Get("/ws", headers);
  22301. // The route exists only as a WebSocket route, so a request that fails the
  22302. // handshake check falls through to ordinary routing.
  22303. ASSERT_TRUE(res);
  22304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22305. }
  22306. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22307. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22308. // Connection value is the only thing left for the client to reject.
  22309. Server svr;
  22310. svr.Get("/ws", [](const Request &req, Response &res) {
  22311. res.status = StatusCode::SwitchingProtocol_101;
  22312. res.set_header("Upgrade", "websocket");
  22313. res.set_header("Connection", "notupgrade");
  22314. res.set_header("Sec-WebSocket-Accept",
  22315. detail::websocket_accept_key(
  22316. req.get_header_value("Sec-WebSocket-Key")));
  22317. });
  22318. auto port = svr.bind_to_any_port("localhost");
  22319. std::thread t([&]() { svr.listen_after_bind(); });
  22320. auto se = detail::scope_exit([&] {
  22321. svr.stop();
  22322. t.join();
  22323. });
  22324. svr.wait_until_ready();
  22325. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22326. auto res = client.connect();
  22327. EXPECT_FALSE(res);
  22328. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22329. EXPECT_FALSE(client.is_open());
  22330. }
  22331. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22332. Server svr;
  22333. svr.Get("/ws", [](const Request &req, Response &res) {
  22334. res.status = StatusCode::SwitchingProtocol_101;
  22335. res.set_header("Upgrade", "websocket");
  22336. res.set_header("Connection", "Upgrade");
  22337. res.set_header("Sec-WebSocket-Accept",
  22338. detail::websocket_accept_key(
  22339. req.get_header_value("Sec-WebSocket-Key")));
  22340. res.set_header("Sec-WebSocket-Protocol", "admin");
  22341. });
  22342. auto port = svr.bind_to_any_port("localhost");
  22343. std::thread t([&]() { svr.listen_after_bind(); });
  22344. auto se = detail::scope_exit([&] {
  22345. svr.stop();
  22346. t.join();
  22347. });
  22348. svr.wait_until_ready();
  22349. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22350. // Server selects a subprotocol the client never offered
  22351. {
  22352. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22353. ws::WebSocketClient client(url, headers);
  22354. auto res = client.connect();
  22355. EXPECT_FALSE(res);
  22356. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22357. EXPECT_FALSE(client.is_open());
  22358. EXPECT_TRUE(client.subprotocol().empty());
  22359. }
  22360. // Client offered none but the server named one anyway
  22361. {
  22362. ws::WebSocketClient client(url);
  22363. auto res = client.connect();
  22364. EXPECT_FALSE(res);
  22365. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22366. EXPECT_FALSE(client.is_open());
  22367. EXPECT_TRUE(client.subprotocol().empty());
  22368. }
  22369. }
  22370. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22371. // The socket path doubles as the URL host, so it must not contain '/'.
  22372. const char *shard = getenv("GTEST_SHARD_INDEX");
  22373. const std::string sock_path =
  22374. shard ? std::string("httplib-ws-") + shard + ".sock"
  22375. : std::string("httplib-ws.sock");
  22376. std::remove(sock_path.c_str());
  22377. Server svr;
  22378. std::mutex mtx;
  22379. std::string received_host;
  22380. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22381. {
  22382. std::lock_guard<std::mutex> lock(mtx);
  22383. received_host = req.get_header_value("Host");
  22384. }
  22385. std::string msg;
  22386. while (ws.read(msg)) {
  22387. ws.send(msg);
  22388. }
  22389. });
  22390. svr.set_address_family(AF_UNIX);
  22391. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22392. auto se = detail::scope_exit([&] {
  22393. svr.stop();
  22394. t.join();
  22395. std::remove(sock_path.c_str());
  22396. });
  22397. svr.wait_until_ready();
  22398. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22399. client.set_address_family(AF_UNIX);
  22400. ASSERT_TRUE(client.connect());
  22401. ASSERT_TRUE(client.send("hello"));
  22402. std::string msg;
  22403. ASSERT_TRUE(client.read(msg));
  22404. client.close();
  22405. {
  22406. std::lock_guard<std::mutex> lock(mtx);
  22407. // There is no host:port for a Unix socket, so the same "localhost"
  22408. // placeholder the HTTP client uses is expected.
  22409. EXPECT_EQ("localhost", received_host);
  22410. }
  22411. }
  22412. // Two threads must never parse WebSocket frames from the same stream.
  22413. // close() used to read the peer's Close reply with its own frame read, so it
  22414. // raced a reader thread that was in the middle of a payload: the payload loop
  22415. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22416. // so bytes taken by close() were replaced with bytes from further along the
  22417. // stream. The message kept its length and silently changed content.
  22418. //
  22419. // The raw peer below sends a frame header plus part of the payload, waits for
  22420. // the handler to call close(), and only then sends the rest. Whichever thread
  22421. // would win the race for those bytes, the message must arrive intact, because
  22422. // close() must not touch the stream while read() owns it.
  22423. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22424. #ifndef _WIN32
  22425. signal(SIGPIPE, SIG_IGN);
  22426. #endif
  22427. const size_t payload_len = 120; // fits the 7-bit length field
  22428. const size_t prefix_len = 8;
  22429. const int attempts = 8;
  22430. std::string expected(payload_len, '\0');
  22431. for (size_t i = 0; i < payload_len; i++) {
  22432. expected[i] = static_cast<char>('a' + i % 26);
  22433. }
  22434. std::atomic<bool> peer_stalled{false};
  22435. std::atomic<bool> handler_done{false};
  22436. std::mutex received_mutex;
  22437. std::vector<std::string> received;
  22438. // Bound every wait, so a regression fails the test instead of hanging the
  22439. // suite.
  22440. auto wait_for = [](const std::atomic<bool> &flag) {
  22441. for (int i = 0; i < 500 && !flag; i++) {
  22442. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22443. }
  22444. };
  22445. Server svr;
  22446. svr.set_websocket_ping_interval(0);
  22447. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22448. std::thread reader([&]() {
  22449. std::string msg;
  22450. while (ws.read(msg)) {
  22451. std::lock_guard<std::mutex> guard(received_mutex);
  22452. received.push_back(msg);
  22453. }
  22454. });
  22455. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22456. // inside read_websocket_frame() when close() runs.
  22457. wait_for(peer_stalled);
  22458. ws.close();
  22459. reader.join();
  22460. handler_done = true;
  22461. });
  22462. auto port = svr.bind_to_any_port("127.0.0.1");
  22463. std::thread t([&]() { svr.listen_after_bind(); });
  22464. auto se = detail::scope_exit([&] {
  22465. svr.stop();
  22466. t.join();
  22467. });
  22468. svr.wait_until_ready();
  22469. auto send_bytes = [](socket_t s, const std::string &data) {
  22470. #ifdef _WIN32
  22471. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22472. #else
  22473. auto n = ::send(s, data.data(), data.size(), 0);
  22474. #endif
  22475. return n == static_cast<decltype(n)>(data.size());
  22476. };
  22477. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22478. // Every length used here fits the 7-bit length field.
  22479. auto masked_header = [](uint8_t first_byte, size_t len) {
  22480. std::string h;
  22481. h += static_cast<char>(first_byte);
  22482. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22483. h.append(4, '\0'); // mask key
  22484. return h;
  22485. };
  22486. for (int attempt = 0; attempt < attempts; attempt++) {
  22487. peer_stalled = false;
  22488. handler_done = false;
  22489. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22490. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22491. auto se_sock = detail::scope_exit([&] {
  22492. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22493. });
  22494. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22495. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22496. sockaddr_in addr{};
  22497. addr.sin_family = AF_INET;
  22498. addr.sin_port = htons(static_cast<uint16_t>(port));
  22499. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22500. ASSERT_EQ(
  22501. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22502. << "attempt " << attempt;
  22503. ASSERT_TRUE(send_bytes(sock,
  22504. "GET /ws HTTP/1.1\r\n"
  22505. "Host: 127.0.0.1\r\n"
  22506. "Upgrade: websocket\r\n"
  22507. "Connection: Upgrade\r\n"
  22508. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22509. "Sec-WebSocket-Version: 13\r\n"
  22510. "\r\n"))
  22511. << "attempt " << attempt;
  22512. std::string response;
  22513. while (response.find("\r\n\r\n") == std::string::npos) {
  22514. char buf[512];
  22515. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22516. if (n <= 0) { break; }
  22517. response.append(buf, static_cast<size_t>(n));
  22518. }
  22519. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22520. << "attempt " << attempt;
  22521. // Send the header of a Binary message but only the first prefix_len bytes
  22522. // of its payload, leaving the reader thread stalled inside the payload.
  22523. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22524. expected.substr(0, prefix_len)))
  22525. << "attempt " << attempt;
  22526. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22527. peer_stalled = true;
  22528. // Let close() send its Close frame and park in its own read before the
  22529. // rest of the payload arrives, so both threads are waiting for it.
  22530. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22531. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22532. close_frame += static_cast<char>(0x03); // status 1000
  22533. close_frame += static_cast<char>(0xE8);
  22534. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22535. << "attempt " << attempt;
  22536. // Closing the peer releases the reader thread even on the buggy path,
  22537. // where it waits for bytes another thread already consumed.
  22538. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22539. detail::close_socket(sock);
  22540. sock = INVALID_SOCKET;
  22541. wait_for(handler_done);
  22542. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22543. }
  22544. std::lock_guard<std::mutex> guard(received_mutex);
  22545. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22546. << "a message in flight when close() ran was dropped";
  22547. for (size_t i = 0; i < received.size(); i++) {
  22548. EXPECT_EQ(expected, received[i]) << "message " << i;
  22549. }
  22550. }
  22551. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  22552. // returning the socket, or INVALID_SOCKET.
  22553. static socket_t connect_raw_websocket(int port, const std::string &path) {
  22554. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22555. if (sock == INVALID_SOCKET) { return sock; }
  22556. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22557. sockaddr_in addr{};
  22558. addr.sin_family = AF_INET;
  22559. addr.sin_port = htons(static_cast<uint16_t>(port));
  22560. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22561. std::string req = "GET " + path +
  22562. " HTTP/1.1\r\n"
  22563. "Host: 127.0.0.1\r\n"
  22564. "Upgrade: websocket\r\n"
  22565. "Connection: Upgrade\r\n"
  22566. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22567. "Sec-WebSocket-Version: 13\r\n"
  22568. "\r\n";
  22569. std::string res;
  22570. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  22571. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  22572. static_cast<int>(req.size())) {
  22573. char c;
  22574. while (res.find("\r\n\r\n") == std::string::npos &&
  22575. ::recv(sock, &c, 1, 0) == 1) {
  22576. res += c;
  22577. }
  22578. }
  22579. if (res.find(" 101 ") == std::string::npos) {
  22580. detail::close_socket(sock);
  22581. return INVALID_SOCKET;
  22582. }
  22583. return sock;
  22584. }
  22585. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  22586. // The payload must fit the 7-bit length field.
  22587. static std::string masked_frame(uint8_t first_byte,
  22588. const std::string &payload) {
  22589. std::string f;
  22590. f += static_cast<char>(first_byte);
  22591. f += static_cast<char>(0x80 | payload.size());
  22592. f.append(4, '\0');
  22593. return f + payload;
  22594. }
  22595. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22596. std::atomic<bool> done{false};
  22597. std::string received;
  22598. Server svr;
  22599. svr.set_websocket_ping_interval(0);
  22600. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22601. std::string msg;
  22602. if (ws.read(msg) == ws::Binary) { received = msg; }
  22603. done = true;
  22604. });
  22605. auto port = svr.bind_to_any_port("127.0.0.1");
  22606. std::thread t([&]() { svr.listen_after_bind(); });
  22607. auto se = detail::scope_exit([&] {
  22608. svr.stop();
  22609. t.join();
  22610. });
  22611. svr.wait_until_ready();
  22612. auto sock = connect_raw_websocket(port, "/ws");
  22613. ASSERT_NE(INVALID_SOCKET, sock);
  22614. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22615. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  22616. masked_frame(0x89, "p") + // FIN + Ping
  22617. masked_frame(0x80, "lo"); // FIN + Continuation
  22618. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  22619. for (int i = 0; i < 500 && !done; i++) {
  22620. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22621. }
  22622. ASSERT_TRUE(done);
  22623. EXPECT_EQ("Hello", received);
  22624. }
  22625. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  22626. Server svr;
  22627. svr.set_websocket_ping_interval(0);
  22628. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22629. std::string msg;
  22630. while (ws.read(msg)) {}
  22631. });
  22632. auto port = svr.bind_to_any_port("127.0.0.1");
  22633. std::thread t([&]() { svr.listen_after_bind(); });
  22634. auto se = detail::scope_exit([&] {
  22635. svr.stop();
  22636. t.join();
  22637. });
  22638. svr.wait_until_ready();
  22639. // The Close each payload is answered with: an echo when it is valid, and
  22640. // 1002 otherwise.
  22641. std::vector<std::pair<std::string, std::string>> cases = {
  22642. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  22643. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  22644. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  22645. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  22646. };
  22647. for (const auto &c : cases) {
  22648. auto sock = connect_raw_websocket(port, "/ws");
  22649. ASSERT_NE(INVALID_SOCKET, sock);
  22650. auto close_frame = masked_frame(0x88, c.first);
  22651. ::send(sock, close_frame.data(), static_cast<int>(close_frame.size()), 0);
  22652. std::string reply;
  22653. char buf[256];
  22654. while (reply.size() < 2 + c.second.size()) {
  22655. auto n = ::recv(sock, buf, sizeof(buf), 0);
  22656. if (n <= 0) { break; }
  22657. reply.append(buf, static_cast<size_t>(n));
  22658. }
  22659. detail::close_socket(sock);
  22660. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  22661. c.second,
  22662. reply);
  22663. }
  22664. }
  22665. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22666. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22667. protected:
  22668. void SetUp() override {
  22669. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22670. SERVER_PRIVATE_KEY_FILE);
  22671. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22672. std::string msg;
  22673. ws::ReadResult ret;
  22674. while ((ret = ws.read(msg))) {
  22675. if (ret == ws::Binary) {
  22676. ws.send(msg.data(), msg.size());
  22677. } else {
  22678. ws.send(msg);
  22679. }
  22680. }
  22681. });
  22682. port_ = server_->bind_to_any_port(HOST);
  22683. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22684. server_->wait_until_ready();
  22685. }
  22686. void TearDown() override {
  22687. server_->stop();
  22688. if (server_thread_.joinable()) { server_thread_.join(); }
  22689. }
  22690. std::unique_ptr<SSLServer> server_;
  22691. std::thread server_thread_;
  22692. int port_ = 0;
  22693. };
  22694. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  22695. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22696. {
  22697. ws::WebSocketClient client(url);
  22698. client.enable_server_certificate_verification(false);
  22699. auto calls = 0;
  22700. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  22701. calls++;
  22702. return false;
  22703. });
  22704. EXPECT_FALSE(client.connect());
  22705. EXPECT_GT(calls, 0);
  22706. }
  22707. {
  22708. ws::WebSocketClient client(url);
  22709. client.enable_server_certificate_verification(false);
  22710. client.set_session_verifier([](tls::session_t) {
  22711. return SSLVerifierResponse::CertificateRejected;
  22712. });
  22713. EXPECT_FALSE(client.connect());
  22714. }
  22715. {
  22716. ws::WebSocketClient client(url);
  22717. client.enable_server_certificate_verification(false);
  22718. client.set_session_verifier([](tls::session_t) {
  22719. return SSLVerifierResponse::CertificateAccepted;
  22720. });
  22721. EXPECT_TRUE(client.connect());
  22722. }
  22723. }
  22724. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22725. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22726. "/ws-echo");
  22727. client.enable_server_certificate_verification(false);
  22728. ASSERT_TRUE(client.connect());
  22729. ASSERT_TRUE(client.is_open());
  22730. ASSERT_TRUE(client.send("Hello WSS"));
  22731. std::string msg;
  22732. EXPECT_EQ(ws::Text, client.read(msg));
  22733. EXPECT_EQ("Hello WSS", msg);
  22734. client.close();
  22735. }
  22736. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22737. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22738. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22739. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22740. // client (without calling close() first) is the only path that runs
  22741. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22742. // bug exactly.
  22743. //
  22744. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22745. // when linked against an instrumented libssl; run under Valgrind to catch it
  22746. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22747. // suite (the freed session otherwise stalls on the close handshake) — this test
  22748. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22749. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22750. {
  22751. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22752. "/ws-echo");
  22753. client.enable_server_certificate_verification(false);
  22754. client.set_read_timeout(2, 0);
  22755. client.set_write_timeout(2, 0);
  22756. ASSERT_TRUE(client.connect());
  22757. ASSERT_TRUE(client.is_open());
  22758. ASSERT_TRUE(client.send("still open"));
  22759. // Intentionally do NOT call client.close(): leaving scope runs
  22760. // shutdown_and_close() with the WebSocket still open, which must send the
  22761. // close frame while the TLS session is still alive.
  22762. }
  22763. }
  22764. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22765. // shutdown_and_close() at the start of connect(), reproducing the same
  22766. // use-after-free within the test body rather than at scope exit. The second
  22767. // connect must succeed and echo, proving the close handshake ran over a live
  22768. // session. See the note above about memory-tool requirements.
  22769. TEST_F(WebSocketSSLIntegrationTest,
  22770. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22771. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22772. "/ws-echo");
  22773. client.enable_server_certificate_verification(false);
  22774. client.set_read_timeout(2, 0);
  22775. client.set_write_timeout(2, 0);
  22776. ASSERT_TRUE(client.connect());
  22777. ASSERT_TRUE(client.is_open());
  22778. ASSERT_TRUE(client.send("still open"));
  22779. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22780. // the still-open connection, which must not touch a freed TLS session.
  22781. ASSERT_TRUE(client.connect());
  22782. ASSERT_TRUE(client.is_open());
  22783. ASSERT_TRUE(client.send("after reconnect"));
  22784. std::string msg;
  22785. EXPECT_EQ(ws::Text, client.read(msg));
  22786. EXPECT_EQ("after reconnect", msg);
  22787. client.close();
  22788. }
  22789. #endif
  22790. #ifdef CPPHTTPLIB_SSL_ENABLED
  22791. class WebSocketSSLCATest : public ::testing::Test {
  22792. protected:
  22793. void SetUp() override {
  22794. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22795. SERVER_PRIVATE_KEY_FILE);
  22796. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22797. std::string msg;
  22798. while (ws.read(msg)) {
  22799. ws.send(msg);
  22800. }
  22801. });
  22802. port_ = server_->bind_to_any_port("127.0.0.1");
  22803. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22804. server_->wait_until_ready();
  22805. }
  22806. void TearDown() override {
  22807. server_->stop();
  22808. if (server_thread_.joinable()) { server_thread_.join(); }
  22809. }
  22810. std::string url() const {
  22811. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22812. }
  22813. std::unique_ptr<SSLServer> server_;
  22814. std::thread server_thread_;
  22815. int port_ = 0;
  22816. };
  22817. // A custom CA loaded as PEM verifies the server with full certificate
  22818. // verification enabled
  22819. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22820. ws::WebSocketClient client(url());
  22821. std::string cert;
  22822. read_file(SERVER_CERT2_FILE, cert);
  22823. client.load_ca_cert_store(cert.c_str(), cert.size());
  22824. ASSERT_TRUE(client.connect());
  22825. ASSERT_TRUE(client.send("hello"));
  22826. std::string msg;
  22827. EXPECT_EQ(ws::Text, client.read(msg));
  22828. EXPECT_EQ("hello", msg);
  22829. client.close();
  22830. }
  22831. // A custom CA that does not cover the server must fail verification (the
  22832. // custom CA is exclusive; system certs are not loaded alongside it)
  22833. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22834. ws::WebSocketClient client(url());
  22835. std::string cert;
  22836. read_file(CLIENT_CA_CERT_FILE, cert);
  22837. client.load_ca_cert_store(cert.c_str(), cert.size());
  22838. auto res = client.connect();
  22839. ASSERT_FALSE(res);
  22840. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22841. EXPECT_EQ(-1, res.status());
  22842. EXPECT_NE(0u, res.ssl_backend_error());
  22843. }
  22844. // The same CA as a file path rather than PEM in memory
  22845. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22846. ws::WebSocketClient client(url());
  22847. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22848. ASSERT_TRUE(client.connect());
  22849. ASSERT_TRUE(client.send("hello"));
  22850. std::string msg;
  22851. EXPECT_EQ(ws::Text, client.read(msg));
  22852. EXPECT_EQ("hello", msg);
  22853. client.close();
  22854. }
  22855. // ...and a CA file that does not cover the server still fails, so it is the
  22856. // path above that decides the outcome
  22857. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22858. ws::WebSocketClient client(url());
  22859. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22860. ASSERT_FALSE(client.connect());
  22861. }
  22862. // Regression test: reconnecting with a native custom CA store used to reuse
  22863. // a store handle the previous TLS context had already freed (use-after-free
  22864. // under the OpenSSL backend). The context now lives as long as the client.
  22865. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22866. ws::WebSocketClient client(url());
  22867. std::string cert;
  22868. read_file(SERVER_CERT2_FILE, cert);
  22869. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22870. ASSERT_TRUE(client.connect());
  22871. client.close();
  22872. ASSERT_TRUE(client.connect());
  22873. ASSERT_TRUE(client.send("again"));
  22874. std::string msg;
  22875. EXPECT_EQ(ws::Text, client.read(msg));
  22876. EXPECT_EQ("again", msg);
  22877. client.close();
  22878. }
  22879. // Regression test: a certificate with a trusted chain but no identity match
  22880. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22881. // verification entirely for IP hosts, so this connection succeeded there.
  22882. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22883. // chain verification while the identity check must still fail.
  22884. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22886. ASSERT_TRUE(svr.is_valid());
  22887. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22888. std::string msg;
  22889. while (ws.read(msg)) {
  22890. ws.send(msg);
  22891. }
  22892. });
  22893. auto port = svr.bind_to_any_port("127.0.0.1");
  22894. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22895. auto se = detail::scope_exit([&] {
  22896. svr.stop();
  22897. t.join();
  22898. });
  22899. svr.wait_until_ready();
  22900. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22901. "/echo");
  22902. std::string cert;
  22903. read_file(SERVER_CERT_FILE, cert);
  22904. client.load_ca_cert_store(cert.c_str(), cert.size());
  22905. ASSERT_FALSE(client.connect());
  22906. }
  22907. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22908. // SNI, so nothing binds the host name to the TLS session. These bind the
  22909. // server to "localhost" instead, the only shape that exercises the SNI and
  22910. // hostname-verification path with certificate verification left enabled.
  22911. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22912. protected:
  22913. void Start(const char *cert_file) {
  22914. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22915. SERVER_PRIVATE_KEY_FILE);
  22916. ASSERT_TRUE(server_->is_valid());
  22917. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22918. std::string msg;
  22919. while (ws.read(msg)) {
  22920. ws.send(msg);
  22921. }
  22922. });
  22923. port_ = server_->bind_to_any_port("localhost");
  22924. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22925. server_->wait_until_ready();
  22926. }
  22927. void TearDown() override {
  22928. if (server_) { server_->stop(); }
  22929. if (server_thread_.joinable()) { server_thread_.join(); }
  22930. }
  22931. std::string url() const {
  22932. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22933. }
  22934. std::unique_ptr<SSLServer> server_;
  22935. std::thread server_thread_;
  22936. int port_ = 0;
  22937. };
  22938. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22939. // out and the connection is usable
  22940. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22941. Start(SERVER_CERT2_FILE);
  22942. ws::WebSocketClient client(url());
  22943. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22944. ASSERT_TRUE(client.connect());
  22945. ASSERT_TRUE(client.send("hello"));
  22946. std::string msg;
  22947. EXPECT_EQ(ws::Text, client.read(msg));
  22948. EXPECT_EQ("hello", msg);
  22949. client.close();
  22950. }
  22951. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22952. // while the identity check must still reject "localhost"
  22953. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22954. Start(SERVER_CERT_FILE);
  22955. ws::WebSocketClient client(url());
  22956. client.set_ca_cert_path(SERVER_CERT_FILE);
  22957. auto res = client.connect();
  22958. ASSERT_FALSE(res);
  22959. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22960. EXPECT_EQ(-1, res.status());
  22961. }
  22962. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22963. // disabled: the chain is still checked, only the identity check is skipped
  22964. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22965. Start(SERVER_CERT_FILE);
  22966. ws::WebSocketClient client(url());
  22967. client.set_ca_cert_path(SERVER_CERT_FILE);
  22968. client.enable_server_hostname_verification(false);
  22969. ASSERT_TRUE(client.connect());
  22970. ASSERT_TRUE(client.send("hello"));
  22971. std::string msg;
  22972. EXPECT_EQ(ws::Text, client.read(msg));
  22973. EXPECT_EQ("hello", msg);
  22974. client.close();
  22975. }
  22976. // A CA that did not sign the server certificate fails the chain, even though
  22977. // the name would match
  22978. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22979. Start(SERVER_CERT2_FILE);
  22980. ws::WebSocketClient client(url());
  22981. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22982. ASSERT_FALSE(client.connect());
  22983. }
  22984. // With verification disabled, neither the chain nor the name is checked
  22985. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22986. Start(SERVER_CERT_FILE);
  22987. ws::WebSocketClient client(url());
  22988. client.enable_server_certificate_verification(false);
  22989. ASSERT_TRUE(client.connect());
  22990. ASSERT_TRUE(client.send("hello"));
  22991. std::string msg;
  22992. EXPECT_EQ(ws::Text, client.read(msg));
  22993. EXPECT_EQ("hello", msg);
  22994. client.close();
  22995. }
  22996. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22997. protected:
  22998. void SetUp() override {
  22999. server_ = httplib::detail::make_unique<SSLServer>(
  23000. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23001. ASSERT_TRUE(server_->is_valid());
  23002. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23003. std::string msg;
  23004. while (ws.read(msg)) {
  23005. ws.send(msg);
  23006. }
  23007. });
  23008. port_ = server_->bind_to_any_port("localhost");
  23009. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23010. server_->wait_until_ready();
  23011. }
  23012. void TearDown() override {
  23013. server_->stop();
  23014. if (server_thread_.joinable()) { server_thread_.join(); }
  23015. }
  23016. std::string url() const {
  23017. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23018. }
  23019. void ConnectWithClientCert(const std::string &client_cert_file,
  23020. const std::string &client_private_key_file,
  23021. const char *private_key_password) {
  23022. std::string cert_pem, key_pem;
  23023. read_file(client_cert_file, cert_pem);
  23024. read_file(client_private_key_file, key_pem);
  23025. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23026. key_pem.c_str(), key_pem.size(),
  23027. private_key_password};
  23028. ws::WebSocketClient client(url(), pem);
  23029. ASSERT_TRUE(client.is_valid());
  23030. client.enable_server_certificate_verification(false);
  23031. ASSERT_TRUE(client.connect());
  23032. ASSERT_TRUE(client.send("hello"));
  23033. std::string msg;
  23034. EXPECT_EQ(ws::Text, client.read(msg));
  23035. EXPECT_EQ("hello", msg);
  23036. client.close();
  23037. }
  23038. std::unique_ptr<SSLServer> server_;
  23039. std::thread server_thread_;
  23040. int port_ = 0;
  23041. };
  23042. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23043. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23044. }
  23045. // Control for the tests above: the fixture's server really does require a
  23046. // client certificate, so it is the PEM the constructor installed that decides
  23047. // the outcome.
  23048. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23049. ws::WebSocketClient client(url());
  23050. ASSERT_TRUE(client.is_valid());
  23051. client.enable_server_certificate_verification(false);
  23052. EXPECT_FALSE(client.connect());
  23053. }
  23054. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23055. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23056. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23057. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23058. }
  23059. #endif
  23060. #if !defined(_WIN32)
  23061. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23062. auto secret_dir = std::string("./symlink_test_secret");
  23063. auto served_dir = std::string("./symlink_test_served");
  23064. auto secret_file = secret_dir + "/secret.txt";
  23065. auto symlink_path = served_dir + "/escape";
  23066. // Setup: create directories and files
  23067. mkdir(secret_dir.c_str(), 0755);
  23068. mkdir(served_dir.c_str(), 0755);
  23069. {
  23070. std::ofstream ofs(secret_file);
  23071. ofs << "SECRET_DATA";
  23072. }
  23073. // Create symlink using absolute path so it resolves correctly
  23074. #ifdef PATH_MAX
  23075. char abs_secret[PATH_MAX];
  23076. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23077. #else
  23078. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23079. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23080. ASSERT_NE(nullptr, abs_secret);
  23081. #endif
  23082. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23083. auto se = detail::scope_exit([&] {
  23084. unlink(symlink_path.c_str());
  23085. unlink(secret_file.c_str());
  23086. rmdir(served_dir.c_str());
  23087. rmdir(secret_dir.c_str());
  23088. });
  23089. Server svr;
  23090. svr.set_mount_point("/", served_dir);
  23091. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23092. auto se2 = detail::scope_exit([&] {
  23093. svr.stop();
  23094. listen_thread.join();
  23095. });
  23096. svr.wait_until_ready();
  23097. Client cli("localhost", PORT);
  23098. // Symlink pointing outside base dir should be blocked
  23099. auto res = cli.Get("/escape/secret.txt");
  23100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23101. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23102. }
  23103. #endif
  23104. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23105. // "GET /smuggled" request), reads the first response, and only then sends the
  23106. // embedded request as the body. Returns how many times /smuggled ran.
  23107. //
  23108. // The body is sent AFTER receiving the first response (as in the original
  23109. // PoC) so that the stream_line_reader cannot buffer it together with the
  23110. // headers of the first request.
  23111. static int count_smuggled_requests(const std::string &outer_head,
  23112. std::string &first_response) {
  23113. Server svr;
  23114. svr.set_mount_point("/", "./www");
  23115. std::atomic<int> smuggled_count(0);
  23116. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23117. smuggled_count++;
  23118. res.set_content("oops", "text/plain");
  23119. });
  23120. svr.Post("/post", [&](const Request &req, Response &res) {
  23121. res.set_content(req.body, "text/plain");
  23122. });
  23123. auto port = svr.bind_to_any_port("localhost");
  23124. thread t = thread([&] { svr.listen_after_bind(); });
  23125. auto se = detail::scope_exit([&] {
  23126. svr.stop();
  23127. t.join();
  23128. });
  23129. svr.wait_until_ready();
  23130. auto error = Error::Success;
  23131. auto sock = detail::create_client_socket(
  23132. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23133. /*connection_timeout_sec=*/2, 0,
  23134. /*read_timeout_sec=*/2, 0,
  23135. /*write_timeout_sec=*/2, 0, std::string(), error);
  23136. EXPECT_NE(INVALID_SOCKET, sock);
  23137. if (sock == INVALID_SOCKET) { return -1; }
  23138. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23139. // The "smuggled" request will be sent as the body of the outer request
  23140. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23141. "Host: localhost\r\n"
  23142. "Connection: close\r\n"
  23143. "\r\n";
  23144. auto head = outer_head;
  23145. auto len = std::to_string(smuggled.size());
  23146. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23147. pos = head.find("{len}", pos + len.size())) {
  23148. head.replace(pos, 5, len);
  23149. }
  23150. // Step 1: Send only the outer request headers (no body yet)
  23151. auto sent = send(sock, head.data(), head.size(), 0);
  23152. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23153. // Step 2: Read the first response
  23154. char buf[4096];
  23155. for (;;) {
  23156. auto n = recv(sock, buf, sizeof(buf), 0);
  23157. if (n <= 0) break;
  23158. first_response.append(buf, static_cast<size_t>(n));
  23159. // Stop once we have a complete response (headers + body)
  23160. auto hdr_end = first_response.find("\r\n\r\n");
  23161. if (hdr_end != std::string::npos) {
  23162. // Check for Content-Length to know when the body is complete
  23163. auto cl_pos = first_response.find("Content-Length:");
  23164. if (cl_pos != std::string::npos) {
  23165. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23166. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23167. auto cl = std::stoul(
  23168. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23169. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23170. } else {
  23171. break; // No Content-Length, assume headers-only response
  23172. }
  23173. }
  23174. }
  23175. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23176. // vulnerable server the keep-alive loop reads this as a second request. The
  23177. // server may already have closed the connection, so the result is ignored.
  23178. send(sock, smuggled.data(), smuggled.size(), 0);
  23179. // Half-close so that a server which drained the body sees EOF and closes,
  23180. // instead of the read below waiting for the read timeout.
  23181. #ifdef _WIN32
  23182. ::shutdown(sock, SD_SEND);
  23183. #else
  23184. ::shutdown(sock, SHUT_WR);
  23185. #endif
  23186. // Step 4: Read until the server closes the connection
  23187. for (;;) {
  23188. auto n = recv(sock, buf, sizeof(buf), 0);
  23189. if (n <= 0) break;
  23190. }
  23191. return smuggled_count.load();
  23192. }
  23193. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23194. // A GET request with Content-Length to a static file handler must have its
  23195. // body drained before the keep-alive connection is reused. Otherwise the
  23196. // unread body bytes are interpreted as the next HTTP request.
  23197. std::string first_response;
  23198. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23199. "Host: localhost\r\n"
  23200. "Content-Length: {len}\r\n"
  23201. "\r\n",
  23202. first_response));
  23203. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23204. }
  23205. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23206. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23207. // be answered with 400 and the connection closed. Treating it as "no body"
  23208. // leaves the body to be parsed as the next request.
  23209. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23210. const char *targets[] = {
  23211. "GET /file", // handler that never reads the body
  23212. "GET /not-found", // no handler matches (404)
  23213. "POST /post", // handler that reads the body
  23214. };
  23215. for (auto target : targets) {
  23216. for (auto value : values) {
  23217. std::string first_response;
  23218. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23219. " HTTP/1.1\r\n"
  23220. "Host: localhost\r\n"
  23221. "Content-Length: " +
  23222. value + "\r\n\r\n",
  23223. first_response))
  23224. << target << " with Content-Length: " << value;
  23225. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23226. << target << " with Content-Length: " << value;
  23227. }
  23228. }
  23229. }
  23230. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23231. // A 400 for an unparseable request line leaves the rest of the message
  23232. // unread, so the connection must be closed rather than reused.
  23233. std::string first_response;
  23234. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23235. "Host: localhost\r\n"
  23236. "Content-Length: {len}\r\n"
  23237. "\r\n",
  23238. first_response));
  23239. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23240. }
  23241. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23242. // Same as above for a header block that fails to parse.
  23243. std::string first_response;
  23244. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23245. "Host: localhost\r\n"
  23246. "Bad Header\r\n"
  23247. "Content-Length: {len}\r\n"
  23248. "\r\n",
  23249. first_response));
  23250. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23251. }
  23252. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23253. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23254. // server must not read another request on that connection, even when the
  23255. // request had no body to drain.
  23256. std::string first_response;
  23257. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23258. "Host: localhost\r\n"
  23259. "\r\n",
  23260. first_response));
  23261. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23262. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23263. }
  23264. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23265. // A content reader that stops early leaves the stream inside the body.
  23266. // Draining the whole Content-Length from there, or reading the body again,
  23267. // reads into the next request, and whatever follows is parsed as a request
  23268. // of its own.
  23269. Server svr;
  23270. std::atomic<int> smuggled_count(0);
  23271. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23272. svr.Post("/upload", [](const Request &req, Response &res,
  23273. const ContentReader &content_reader) {
  23274. // Stop at the last chunk, so the whole body has been read however it
  23275. // arrives.
  23276. auto length = req.get_header_value_u64("Content-Length");
  23277. size_t total = 0;
  23278. auto consumed = content_reader([&](const char *, size_t n) {
  23279. total += n;
  23280. return total < length;
  23281. });
  23282. EXPECT_FALSE(consumed);
  23283. if (req.has_param("retry")) {
  23284. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23285. }
  23286. // Replace the 400 the aborted read set, which would close the connection.
  23287. res.set_redirect("/done");
  23288. });
  23289. auto port = svr.bind_to_any_port(HOST);
  23290. thread t = thread([&] { svr.listen_after_bind(); });
  23291. auto se = detail::scope_exit([&] {
  23292. svr.stop();
  23293. t.join();
  23294. });
  23295. svr.wait_until_ready();
  23296. // A front end sees the second request as a POST whose body is the GET. The
  23297. // first body is as long as the POST's headers, so draining it again reads
  23298. // exactly those and leaves the GET to be parsed next.
  23299. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23300. "Host: localhost\r\n"
  23301. "\r\n";
  23302. std::string second_head = "POST /post HTTP/1.1\r\n"
  23303. "Host: localhost\r\n"
  23304. "Content-Length: " +
  23305. std::to_string(inner.size()) +
  23306. "\r\n"
  23307. "\r\n";
  23308. for (auto target : {"/upload", "/upload?retry"}) {
  23309. smuggled_count = 0;
  23310. std::string request = "POST " + std::string(target) +
  23311. " HTTP/1.1\r\n"
  23312. "Host: localhost\r\n"
  23313. "Content-Length: " +
  23314. std::to_string(second_head.size()) +
  23315. "\r\n"
  23316. "\r\n" +
  23317. std::string(second_head.size(), 'A') + second_head +
  23318. inner;
  23319. std::string response;
  23320. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23321. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23322. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23323. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23324. EXPECT_EQ(0, smuggled_count.load()) << target;
  23325. }
  23326. }
  23327. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23328. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23329. // must be rejected with 400 Bad Request.
  23330. Server svr;
  23331. svr.Post("/test", [&](const Request &, Response &res) {
  23332. res.set_content("ok", "text/plain");
  23333. });
  23334. thread t = thread([&] { svr.listen(HOST, PORT); });
  23335. auto se = detail::scope_exit([&] {
  23336. svr.stop();
  23337. t.join();
  23338. ASSERT_FALSE(svr.is_running());
  23339. });
  23340. svr.wait_until_ready();
  23341. // Exact "chunked"
  23342. {
  23343. auto req = "POST /test HTTP/1.1\r\n"
  23344. "Host: localhost\r\n"
  23345. "Content-Length: 5\r\n"
  23346. "Transfer-Encoding: chunked\r\n"
  23347. "Connection: close\r\n"
  23348. "\r\n"
  23349. "hello";
  23350. std::string response;
  23351. ASSERT_TRUE(send_request(1, req, &response));
  23352. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23353. response.substr(0, response.find("\r\n")));
  23354. }
  23355. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23356. {
  23357. auto req = "POST /test HTTP/1.1\r\n"
  23358. "Host: localhost\r\n"
  23359. "Content-Length: 5\r\n"
  23360. "Transfer-Encoding: gzip, chunked\r\n"
  23361. "Connection: close\r\n"
  23362. "\r\n"
  23363. "hello";
  23364. std::string response;
  23365. ASSERT_TRUE(send_request(1, req, &response));
  23366. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23367. response.substr(0, response.find("\r\n")));
  23368. }
  23369. }
  23370. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23371. Server svr;
  23372. svr.Post("/test", [&](const Request &, Response &res) {
  23373. res.set_content("ok", "text/plain");
  23374. });
  23375. thread t = thread([&] { svr.listen(HOST, PORT); });
  23376. auto se = detail::scope_exit([&] {
  23377. svr.stop();
  23378. t.join();
  23379. ASSERT_FALSE(svr.is_running());
  23380. });
  23381. svr.wait_until_ready();
  23382. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23383. // length cannot be determined, so the server must answer 400 and close
  23384. // rather than treat the request as bodyless and leave the body in the
  23385. // socket for the next request to pick up.
  23386. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23387. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23388. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23389. std::string response;
  23390. ASSERT_TRUE(send_request(1, req, &response));
  23391. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23392. response.substr(0, response.find("\r\n")))
  23393. << transfer_encoding;
  23394. }
  23395. // RFC 9110 5.3: the codings may also be split across several
  23396. // Transfer-Encoding lines, which combine in the order they were received.
  23397. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23398. // just like the single-line "chunked, gzip" above.
  23399. {
  23400. auto req = "POST /test HTTP/1.1\r\n"
  23401. "Host: localhost\r\n"
  23402. "Transfer-Encoding: chunked\r\n"
  23403. "Transfer-Encoding: gzip\r\n"
  23404. "\r\n"
  23405. "0\r\n\r\n";
  23406. std::string response;
  23407. ASSERT_TRUE(send_request(1, req, &response));
  23408. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23409. response.substr(0, response.find("\r\n")));
  23410. }
  23411. // A sequence ending in chunked stays valid.
  23412. auto req = "POST /test HTTP/1.1\r\n"
  23413. "Host: localhost\r\n"
  23414. "Transfer-Encoding: gzip, chunked\r\n"
  23415. "Connection: close\r\n"
  23416. "\r\n"
  23417. "0\r\n\r\n";
  23418. std::string response;
  23419. ASSERT_TRUE(send_request(1, req, &response));
  23420. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23421. // ...including when it is spread over several lines.
  23422. auto split_req = "POST /test HTTP/1.1\r\n"
  23423. "Host: localhost\r\n"
  23424. "Transfer-Encoding: gzip\r\n"
  23425. "Transfer-Encoding: chunked\r\n"
  23426. "Connection: close\r\n"
  23427. "\r\n"
  23428. "0\r\n\r\n";
  23429. std::string split_response;
  23430. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23431. EXPECT_EQ("HTTP/1.1 200 OK",
  23432. split_response.substr(0, split_response.find("\r\n")));
  23433. }
  23434. // Regression for issue #2450: a DELETE without Content-Length on a
  23435. // keep-alive connection must not let the post-response drain consume the
  23436. // next request's bytes.
  23437. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23438. Server svr;
  23439. std::atomic<int> delete_count(0);
  23440. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23441. delete_count++;
  23442. res.status = StatusCode::NoContent_204;
  23443. });
  23444. auto port = svr.bind_to_any_port(HOST);
  23445. thread t = thread([&] { svr.listen_after_bind(); });
  23446. auto se = detail::scope_exit([&] {
  23447. svr.stop();
  23448. t.join();
  23449. });
  23450. svr.wait_until_ready();
  23451. auto error = Error::Success;
  23452. auto sock = detail::create_client_socket(
  23453. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23454. /*connection_timeout_sec=*/2, 0,
  23455. /*read_timeout_sec=*/2, 0,
  23456. /*write_timeout_sec=*/2, 0, std::string(), error);
  23457. ASSERT_NE(INVALID_SOCKET, sock);
  23458. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23459. auto send_request_and_read_response = [&](const std::string &req,
  23460. std::string &out) -> bool {
  23461. auto sent = send(sock, req.data(), req.size(), 0);
  23462. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23463. char buf[4096];
  23464. for (;;) {
  23465. auto n = recv(sock, buf, sizeof(buf), 0);
  23466. if (n <= 0) { return !out.empty(); }
  23467. out.append(buf, static_cast<size_t>(n));
  23468. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23469. }
  23470. };
  23471. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23472. "Host: localhost\r\n"
  23473. "\r\n";
  23474. std::string resp1;
  23475. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23476. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23477. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23478. "Host: localhost\r\n"
  23479. "Connection: close\r\n"
  23480. "\r\n";
  23481. std::string resp2;
  23482. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23483. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23484. EXPECT_EQ(2, delete_count.load());
  23485. }
  23486. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23487. Server svr;
  23488. svr.Post("/ingest", [&](const Request &, Response &res,
  23489. const ContentReader &content_reader) {
  23490. auto consumed = content_reader([](const char *, size_t) { return false; });
  23491. EXPECT_FALSE(consumed);
  23492. res.status = StatusCode::Conflict_409;
  23493. res.set_header("Connection", "close");
  23494. });
  23495. auto port = svr.bind_to_any_port(HOST);
  23496. thread t = thread([&] { svr.listen_after_bind(); });
  23497. auto se = detail::scope_exit([&] {
  23498. svr.stop();
  23499. t.join();
  23500. });
  23501. svr.wait_until_ready();
  23502. auto error = Error::Success;
  23503. auto sock = detail::create_client_socket(
  23504. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23505. /*connection_timeout_sec=*/2, 0,
  23506. /*read_timeout_sec=*/1, 0,
  23507. /*write_timeout_sec=*/2, 0, std::string(), error);
  23508. ASSERT_NE(INVALID_SOCKET, sock);
  23509. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23510. std::string request = "POST /ingest HTTP/1.1\r\n"
  23511. "Host: localhost\r\n"
  23512. "Transfer-Encoding: chunked\r\n"
  23513. "\r\n"
  23514. "4\r\n"
  23515. "data\r\n";
  23516. auto sent = send(sock, request.data(), request.size(), 0);
  23517. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23518. std::string response;
  23519. ssize_t received = 0;
  23520. do {
  23521. char buf[4096];
  23522. received = recv(sock, buf, sizeof(buf), 0);
  23523. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23524. } while (received > 0);
  23525. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23526. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23527. EXPECT_EQ(0, received);
  23528. }
  23529. namespace no_proxy_test {
  23530. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23531. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23532. // calling listen().
  23533. class ScopedServer {
  23534. public:
  23535. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23536. ~ScopedServer() {
  23537. svr_.stop();
  23538. if (th_.joinable()) { th_.join(); }
  23539. }
  23540. Server &svr() { return svr_; }
  23541. int port() const { return port_; }
  23542. void listen() {
  23543. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23544. svr_.wait_until_ready();
  23545. }
  23546. private:
  23547. Server svr_;
  23548. std::thread th_;
  23549. int port_ = 0;
  23550. };
  23551. class ProxyAndTargetServers {
  23552. public:
  23553. ProxyAndTargetServers() {
  23554. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23555. proxy_hits_++;
  23556. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23557. res.set_content("via-proxy", "text/plain");
  23558. });
  23559. target_.Get(".*", [this](const Request &req, Response &res) {
  23560. target_hits_++;
  23561. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23562. res.set_content("direct", "text/plain");
  23563. });
  23564. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23565. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23566. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23567. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23568. proxy_mock_.wait_until_ready();
  23569. target_.wait_until_ready();
  23570. }
  23571. ~ProxyAndTargetServers() {
  23572. proxy_mock_.stop();
  23573. target_.stop();
  23574. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23575. if (target_thread_.joinable()) { target_thread_.join(); }
  23576. }
  23577. Server &proxy_mock() { return proxy_mock_; }
  23578. Server &target() { return target_; }
  23579. int proxy_port() const { return proxy_port_; }
  23580. int target_port() const { return target_port_; }
  23581. int proxy_hits() const { return proxy_hits_.load(); }
  23582. int target_hits() const { return target_hits_.load(); }
  23583. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23584. void reset_counters() {
  23585. proxy_hits_ = 0;
  23586. target_hits_ = 0;
  23587. last_had_proxy_authz_ = false;
  23588. }
  23589. private:
  23590. Server proxy_mock_;
  23591. Server target_;
  23592. std::thread proxy_thread_;
  23593. std::thread target_thread_;
  23594. int proxy_port_ = 0;
  23595. int target_port_ = 0;
  23596. std::atomic<int> proxy_hits_{0};
  23597. std::atomic<int> target_hits_{0};
  23598. std::atomic<bool> last_had_proxy_authz_{false};
  23599. };
  23600. inline std::unique_ptr<Client> make_client(const std::string &host,
  23601. ProxyAndTargetServers &s) {
  23602. auto cli = detail::make_unique<Client>(host, s.target_port());
  23603. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23604. cli->set_proxy("127.0.0.1", s.proxy_port());
  23605. return cli;
  23606. }
  23607. } // namespace no_proxy_test
  23608. using no_proxy_test::make_client;
  23609. using no_proxy_test::ProxyAndTargetServers;
  23610. TEST(NoProxyTest, ExactHostnameBypasses) {
  23611. ProxyAndTargetServers s;
  23612. auto cli = make_client("example.com", s);
  23613. cli->set_no_proxy({"example.com"});
  23614. auto res = cli->Get("/");
  23615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23616. EXPECT_EQ(0, s.proxy_hits());
  23617. EXPECT_EQ(1, s.target_hits());
  23618. }
  23619. TEST(NoProxyTest, SubdomainBypasses) {
  23620. ProxyAndTargetServers s;
  23621. auto cli = make_client("foo.example.com", s);
  23622. cli->set_no_proxy({"example.com"});
  23623. auto res = cli->Get("/");
  23624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23625. EXPECT_EQ(0, s.proxy_hits());
  23626. EXPECT_EQ(1, s.target_hits());
  23627. }
  23628. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23629. // Regression guard: "evilexample.com" must not be considered a subdomain
  23630. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23631. // check would let traffic bypass the proxy and leak credentials direct
  23632. // to the attacker host.
  23633. ProxyAndTargetServers s;
  23634. auto cli = make_client("evilexample.com", s);
  23635. cli->set_no_proxy({"example.com"});
  23636. auto res = cli->Get("/");
  23637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23638. EXPECT_GE(s.proxy_hits(), 1);
  23639. EXPECT_EQ(0, s.target_hits());
  23640. }
  23641. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23642. ProxyAndTargetServers s;
  23643. auto cli = make_client("example.com.evil.com", s);
  23644. cli->set_no_proxy({"example.com"});
  23645. auto res = cli->Get("/");
  23646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23647. EXPECT_GE(s.proxy_hits(), 1);
  23648. EXPECT_EQ(0, s.target_hits());
  23649. }
  23650. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23651. ProxyAndTargetServers s;
  23652. auto cli = make_client("example.com", s);
  23653. cli->set_no_proxy({".example.com"});
  23654. auto res = cli->Get("/");
  23655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23656. EXPECT_EQ(0, s.proxy_hits());
  23657. EXPECT_EQ(1, s.target_hits());
  23658. }
  23659. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23660. ProxyAndTargetServers s;
  23661. auto cli = make_client("Example.COM", s);
  23662. cli->set_no_proxy({"EXAMPLE.com"});
  23663. auto res = cli->Get("/");
  23664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23665. EXPECT_EQ(0, s.proxy_hits());
  23666. EXPECT_EQ(1, s.target_hits());
  23667. }
  23668. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23669. ProxyAndTargetServers s;
  23670. auto cli = make_client("example.com.", s);
  23671. cli->set_no_proxy({"example.com"});
  23672. auto res = cli->Get("/");
  23673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23674. EXPECT_EQ(0, s.proxy_hits());
  23675. EXPECT_EQ(1, s.target_hits());
  23676. }
  23677. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23678. // Trailing dots must be normalized on BOTH sides — host and entry.
  23679. // An implementation that only strips the host-side trailing dot would
  23680. // fail to match host "example.com" against entry "example.com." because
  23681. // a literal substring search would compare 11 chars against 12.
  23682. ProxyAndTargetServers s;
  23683. auto cli = make_client("example.com", s);
  23684. cli->set_no_proxy({"example.com."});
  23685. auto res = cli->Get("/");
  23686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23687. EXPECT_EQ(0, s.proxy_hits());
  23688. EXPECT_EQ(1, s.target_hits());
  23689. }
  23690. TEST(NoProxyTest, WildcardBypassesEverything) {
  23691. ProxyAndTargetServers s;
  23692. auto cli = make_client("anything.invalid.test", s);
  23693. cli->set_no_proxy({"*"});
  23694. auto res = cli->Get("/");
  23695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23696. EXPECT_EQ(0, s.proxy_hits());
  23697. EXPECT_EQ(1, s.target_hits());
  23698. }
  23699. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23700. ProxyAndTargetServers s;
  23701. Client cli("127.0.0.1", s.target_port());
  23702. cli.set_proxy("127.0.0.1", s.proxy_port());
  23703. cli.set_no_proxy({"127.0.0.1"});
  23704. auto res = cli.Get("/");
  23705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23706. EXPECT_EQ(0, s.proxy_hits());
  23707. EXPECT_EQ(1, s.target_hits());
  23708. }
  23709. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23710. ProxyAndTargetServers s;
  23711. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23712. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23713. cli.set_proxy("127.0.0.1", s.proxy_port());
  23714. cli.set_no_proxy({"::1"});
  23715. auto res = cli.Get("/");
  23716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23717. EXPECT_EQ(0, s.proxy_hits());
  23718. EXPECT_EQ(1, s.target_hits());
  23719. }
  23720. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23721. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23722. // must still be recognized as IPv6 for CIDR matching. Implementations
  23723. // that detect IPv6 only when the host begins with '[' would parse the
  23724. // host as a hostname and miss the match.
  23725. ProxyAndTargetServers s;
  23726. Client cli("fe80::1", s.target_port());
  23727. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23728. cli.set_proxy("127.0.0.1", s.proxy_port());
  23729. cli.set_no_proxy({"fe80::/10"});
  23730. auto res = cli.Get("/");
  23731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23732. EXPECT_EQ(0, s.proxy_hits());
  23733. EXPECT_EQ(1, s.target_hits());
  23734. }
  23735. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23736. ProxyAndTargetServers s;
  23737. Client cli("::1", s.target_port());
  23738. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23739. cli.set_proxy("127.0.0.1", s.proxy_port());
  23740. cli.set_no_proxy({"[::1]"});
  23741. auto res = cli.Get("/");
  23742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23743. EXPECT_EQ(0, s.proxy_hits());
  23744. EXPECT_EQ(1, s.target_hits());
  23745. }
  23746. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23747. ProxyAndTargetServers s;
  23748. Client cli("fe80::1", s.target_port());
  23749. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23750. cli.set_proxy("127.0.0.1", s.proxy_port());
  23751. cli.set_no_proxy({"[fe80::]/10"});
  23752. auto res = cli.Get("/");
  23753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23754. EXPECT_EQ(0, s.proxy_hits());
  23755. EXPECT_EQ(1, s.target_hits());
  23756. }
  23757. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23758. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23759. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23760. // tricks via address-family conversion.
  23761. ProxyAndTargetServers s;
  23762. Client cli("::ffff:127.0.0.1", s.target_port());
  23763. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23764. cli.set_proxy("127.0.0.1", s.proxy_port());
  23765. cli.set_no_proxy({"127.0.0.1"});
  23766. auto res = cli.Get("/");
  23767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23768. EXPECT_GE(s.proxy_hits(), 1);
  23769. EXPECT_EQ(0, s.target_hits());
  23770. }
  23771. TEST(NoProxyTest, IPv4CidrMatch) {
  23772. ProxyAndTargetServers s;
  23773. Client cli("127.0.0.1", s.target_port());
  23774. cli.set_proxy("127.0.0.1", s.proxy_port());
  23775. cli.set_no_proxy({"127.0.0.0/8"});
  23776. auto res = cli.Get("/");
  23777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23778. EXPECT_EQ(0, s.proxy_hits());
  23779. EXPECT_EQ(1, s.target_hits());
  23780. }
  23781. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23782. ProxyAndTargetServers s;
  23783. Client cli("127.0.0.1", s.target_port());
  23784. cli.set_proxy("127.0.0.1", s.proxy_port());
  23785. cli.set_no_proxy({"10.0.0.0/8"});
  23786. auto res = cli.Get("/");
  23787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23788. EXPECT_GE(s.proxy_hits(), 1);
  23789. EXPECT_EQ(0, s.target_hits());
  23790. }
  23791. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23792. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23793. // IPv4 target matches.
  23794. ProxyAndTargetServers s;
  23795. Client cli("127.0.0.1", s.target_port());
  23796. cli.set_proxy("127.0.0.1", s.proxy_port());
  23797. cli.set_no_proxy({"0.0.0.0/0"});
  23798. auto res = cli.Get("/");
  23799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23800. EXPECT_EQ(0, s.proxy_hits());
  23801. EXPECT_EQ(1, s.target_hits());
  23802. }
  23803. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23804. ProxyAndTargetServers s;
  23805. Client cli("127.0.0.1", s.target_port());
  23806. cli.set_proxy("127.0.0.1", s.proxy_port());
  23807. cli.set_no_proxy({"127.0.0.1"});
  23808. auto res = cli.Get("/");
  23809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23810. EXPECT_EQ(0, s.proxy_hits());
  23811. EXPECT_EQ(1, s.target_hits());
  23812. }
  23813. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23814. ProxyAndTargetServers s;
  23815. Client cli("127.0.0.1", s.target_port());
  23816. cli.set_proxy("127.0.0.1", s.proxy_port());
  23817. cli.set_no_proxy({"127.0.0.0/33"});
  23818. auto res = cli.Get("/");
  23819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23820. EXPECT_GE(s.proxy_hits(), 1);
  23821. EXPECT_EQ(0, s.target_hits());
  23822. }
  23823. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23824. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23825. ProxyAndTargetServers s;
  23826. Client cli("127.0.0.1", s.target_port());
  23827. cli.set_proxy("127.0.0.1", s.proxy_port());
  23828. cli.set_no_proxy({"127.0.0.1/"});
  23829. auto res = cli.Get("/");
  23830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23831. EXPECT_GE(s.proxy_hits(), 1);
  23832. EXPECT_EQ(0, s.target_hits());
  23833. }
  23834. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23835. ProxyAndTargetServers s;
  23836. auto cli = make_client("internal.corp", s);
  23837. cli->set_proxy_basic_auth("u", "p");
  23838. cli->set_no_proxy({"internal.corp"});
  23839. auto res = cli->Get("/");
  23840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23841. EXPECT_EQ(1, s.target_hits());
  23842. EXPECT_EQ(0, s.proxy_hits());
  23843. EXPECT_FALSE(s.last_had_proxy_authz())
  23844. << "Proxy-Authorization must not be sent direct to the target";
  23845. }
  23846. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23847. ProxyAndTargetServers s;
  23848. auto cli = make_client("public.example", s);
  23849. cli->set_proxy_basic_auth("u", "p");
  23850. cli->set_no_proxy({"internal.corp"}); // does not match
  23851. auto res = cli->Get("/");
  23852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23853. EXPECT_GE(s.proxy_hits(), 1);
  23854. EXPECT_TRUE(s.last_had_proxy_authz());
  23855. }
  23856. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23857. std::atomic<int> hits{0};
  23858. std::atomic<int> hits_with_authz{0};
  23859. no_proxy_test::ScopedServer proxy_mock;
  23860. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23861. hits++;
  23862. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23863. if (req.target.find("/redir") != std::string::npos) {
  23864. res.set_redirect("http://other.example/landed");
  23865. } else {
  23866. res.set_content("via-proxy", "text/plain");
  23867. }
  23868. });
  23869. proxy_mock.listen();
  23870. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23871. hits = 0;
  23872. hits_with_authz = 0;
  23873. Client cli("public.example", 80);
  23874. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23875. cli.set_proxy_basic_auth(c.first, c.second);
  23876. cli.set_follow_location(true);
  23877. // The redirect to another host goes through the proxy as well
  23878. auto res = cli.Get("/redir");
  23879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23880. EXPECT_EQ(2, hits.load());
  23881. EXPECT_EQ(2, hits_with_authz.load());
  23882. }
  23883. }
  23884. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23885. ProxyAndTargetServers s;
  23886. auto cli = make_client("anything.test", s);
  23887. auto res = cli->Get("/");
  23888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23889. EXPECT_GE(s.proxy_hits(), 1);
  23890. EXPECT_EQ(0, s.target_hits());
  23891. }
  23892. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23893. ProxyAndTargetServers s;
  23894. auto cli = make_client("example.com", s);
  23895. cli->set_no_proxy({"example.com:8080"});
  23896. auto res = cli->Get("/");
  23897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23898. EXPECT_GE(s.proxy_hits(), 1);
  23899. EXPECT_EQ(0, s.target_hits());
  23900. }
  23901. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23902. ProxyAndTargetServers s;
  23903. auto cli = make_client("anything.test", s);
  23904. cli->set_no_proxy({"", " ", "\t"});
  23905. auto res = cli->Get("/");
  23906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23907. EXPECT_GE(s.proxy_hits(), 1);
  23908. EXPECT_EQ(0, s.target_hits());
  23909. }
  23910. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23911. // An entry with leading/trailing whitespace must still match — env-style
  23912. // values are commonly pasted with stray spaces and an implementation
  23913. // that feeds the raw token directly to inet_pton would fail to match
  23914. // valid CIDRs because of the spaces.
  23915. ProxyAndTargetServers s;
  23916. Client cli("127.0.0.1", s.target_port());
  23917. cli.set_proxy("127.0.0.1", s.proxy_port());
  23918. cli.set_no_proxy({" 127.0.0.0/8 "});
  23919. auto res = cli.Get("/");
  23920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23921. EXPECT_EQ(0, s.proxy_hits());
  23922. EXPECT_EQ(1, s.target_hits());
  23923. }
  23924. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23925. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23926. // go direct and must NOT carry Proxy-Authorization.
  23927. std::atomic<int> proxy_hits{0};
  23928. std::atomic<int> target_hits{0};
  23929. std::atomic<bool> target_saw_authz{false};
  23930. no_proxy_test::ScopedServer proxy_mock, target;
  23931. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23932. proxy_hits++;
  23933. res.status = 302;
  23934. res.set_header("Location", "http://127.0.0.1:" +
  23935. std::to_string(target.port()) + "/landed");
  23936. });
  23937. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23938. target_hits++;
  23939. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23940. res.set_content("direct", "text/plain");
  23941. });
  23942. proxy_mock.listen();
  23943. target.listen();
  23944. Client cli("public.example", target.port());
  23945. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23946. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23947. cli.set_proxy_basic_auth("u", "p");
  23948. cli.set_no_proxy({"127.0.0.1"});
  23949. cli.set_follow_location(true);
  23950. auto res = cli.Get("/redir");
  23951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23952. EXPECT_GE(proxy_hits.load(), 1);
  23953. EXPECT_GE(target_hits.load(), 1);
  23954. EXPECT_FALSE(target_saw_authz.load());
  23955. }
  23956. #ifdef CPPHTTPLIB_SSL_ENABLED
  23957. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23958. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23959. // proxy creds would be sent to the (possibly hostile) origin.
  23960. std::atomic<int> target_hits{0};
  23961. std::atomic<bool> target_saw_proxy_authz{false};
  23962. no_proxy_test::ScopedServer target;
  23963. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23964. target_hits++;
  23965. if (req.has_header("Proxy-Authorization")) {
  23966. target_saw_proxy_authz = true;
  23967. }
  23968. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23969. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23970. "nonce=\"abc\", algorithm=MD5");
  23971. });
  23972. target.listen();
  23973. // The proxy address is set to the target's port: the bypass MUST kick in;
  23974. // if it doesn't, the test still routes "via proxy" to the same server and
  23975. // the Proxy-Authorization assertion below catches the leak.
  23976. Client cli("evil.example", target.port());
  23977. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23978. cli.set_proxy("127.0.0.1", target.port());
  23979. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23980. cli.set_no_proxy({"evil.example"});
  23981. auto res = cli.Get("/x");
  23982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23983. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23984. EXPECT_EQ(1, target_hits.load());
  23985. EXPECT_FALSE(target_saw_proxy_authz.load());
  23986. }
  23987. #endif
  23988. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23989. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23990. std::atomic<int> proxy_hits{0};
  23991. std::atomic<int> bypass_hits{0};
  23992. std::atomic<bool> proxy_saw_c_url{false};
  23993. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23994. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23995. proxy_hits++;
  23996. if (req.path.find("/start") != std::string::npos) {
  23997. res.status = 302;
  23998. res.set_header("Location", "http://127.0.0.1:" +
  23999. std::to_string(bypass_server.port()) +
  24000. "/middle");
  24001. return;
  24002. }
  24003. if (req.path.find("/end") != std::string::npos) {
  24004. proxy_saw_c_url = true;
  24005. res.set_content("c-via-proxy", "text/plain");
  24006. return;
  24007. }
  24008. res.set_content("unexpected", "text/plain");
  24009. });
  24010. // public.example's "advertised" port is arbitrary (the request never lands
  24011. // there — it goes through the proxy), but use a dynamic value to stay
  24012. // friendly with sharded parallel runs.
  24013. int public_port = bypass_server.port();
  24014. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24015. bypass_hits++;
  24016. res.status = 302;
  24017. res.set_header("Location", "http://public.example:" +
  24018. std::to_string(public_port) + "/end");
  24019. });
  24020. proxy_mock.listen();
  24021. bypass_server.listen();
  24022. Client cli("public.example", public_port);
  24023. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24024. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24025. cli.set_no_proxy({"127.0.0.1"});
  24026. cli.set_follow_location(true);
  24027. auto res = cli.Get("/start");
  24028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24029. EXPECT_EQ(StatusCode::OK_200, res->status);
  24030. EXPECT_EQ("c-via-proxy", res->body);
  24031. EXPECT_GE(proxy_hits.load(), 2);
  24032. EXPECT_GE(bypass_hits.load(), 1);
  24033. EXPECT_TRUE(proxy_saw_c_url.load());
  24034. }
  24035. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24036. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24037. // request reconnects to the correct endpoint.
  24038. std::atomic<int> proxy_hits{0};
  24039. std::atomic<int> target_hits{0};
  24040. no_proxy_test::ScopedServer proxy_mock, target;
  24041. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24042. proxy_hits++;
  24043. res.set_content("via-proxy", "text/plain");
  24044. });
  24045. target.svr().Get(".*", [&](const Request &, Response &res) {
  24046. target_hits++;
  24047. res.set_content("direct", "text/plain");
  24048. });
  24049. proxy_mock.listen();
  24050. target.listen();
  24051. Client cli("public.example", target.port());
  24052. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24053. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24054. cli.set_keep_alive(true);
  24055. auto res1 = cli.Get("/a");
  24056. ASSERT_TRUE(res1);
  24057. EXPECT_EQ("via-proxy", res1->body);
  24058. EXPECT_EQ(1, proxy_hits.load());
  24059. EXPECT_EQ(0, target_hits.load());
  24060. cli.set_no_proxy({"public.example"});
  24061. auto res2 = cli.Get("/b");
  24062. ASSERT_TRUE(res2);
  24063. EXPECT_EQ("direct", res2->body);
  24064. EXPECT_EQ(1, proxy_hits.load());
  24065. EXPECT_EQ(1, target_hits.load());
  24066. }
  24067. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24068. namespace proxy_tunnel_test {
  24069. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24070. class ScopedSSLServer {
  24071. public:
  24072. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24073. port_ = svr_.bind_to_any_port("127.0.0.1");
  24074. }
  24075. ~ScopedSSLServer() {
  24076. svr_.stop();
  24077. if (th_.joinable()) { th_.join(); }
  24078. }
  24079. SSLServer &svr() { return svr_; }
  24080. int port() const { return port_; }
  24081. void listen() {
  24082. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24083. svr_.wait_until_ready();
  24084. }
  24085. private:
  24086. SSLServer svr_;
  24087. std::thread th_;
  24088. int port_ = 0;
  24089. };
  24090. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24091. class ScopedConnectProxy {
  24092. public:
  24093. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24094. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24095. if (listen_fd_ < 0) { return; }
  24096. int yes = 1;
  24097. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24098. sockaddr_in a{};
  24099. a.sin_family = AF_INET;
  24100. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24101. a.sin_port = 0;
  24102. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24103. return;
  24104. }
  24105. socklen_t alen = sizeof(a);
  24106. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24107. 0) {
  24108. return;
  24109. }
  24110. port_ = ntohs(a.sin_port);
  24111. if (::listen(listen_fd_, 1) != 0) { return; }
  24112. th_ = std::thread([this] { run(); });
  24113. }
  24114. ~ScopedConnectProxy() {
  24115. stop_ = true;
  24116. if (listen_fd_ >= 0) {
  24117. ::shutdown(listen_fd_, SHUT_RDWR);
  24118. ::close(listen_fd_);
  24119. }
  24120. if (th_.joinable()) { th_.join(); }
  24121. }
  24122. int port() const { return port_; }
  24123. int connect_hits() const { return connect_hits_.load(); }
  24124. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24125. std::string connect_request() const {
  24126. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24127. return connect_request_;
  24128. }
  24129. private:
  24130. void run() {
  24131. while (!stop_.load()) {
  24132. fd_set rfds;
  24133. FD_ZERO(&rfds);
  24134. FD_SET(listen_fd_, &rfds);
  24135. timeval tv{0, 100 * 1000};
  24136. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24137. if (sel <= 0) { continue; }
  24138. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24139. if (client_fd < 0) { continue; }
  24140. std::string req;
  24141. char buf[2048];
  24142. while (req.find("\r\n\r\n") == std::string::npos) {
  24143. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24144. if (n <= 0) { break; }
  24145. req.append(buf, static_cast<size_t>(n));
  24146. }
  24147. if (req.compare(0, 7, "CONNECT") != 0) {
  24148. ::close(client_fd);
  24149. continue;
  24150. }
  24151. connect_hits_++;
  24152. {
  24153. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24154. connect_request_ = req;
  24155. }
  24156. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24157. ::send(client_fd, ok, std::strlen(ok), 0);
  24158. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24159. sockaddr_in o{};
  24160. o.sin_family = AF_INET;
  24161. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24162. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24163. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24164. 0) {
  24165. ::close(client_fd);
  24166. ::close(origin_fd);
  24167. continue;
  24168. }
  24169. auto forward = [](int from, int to) {
  24170. char b[8192];
  24171. for (;;) {
  24172. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24173. if (n <= 0) { break; }
  24174. ssize_t off = 0;
  24175. while (off < n) {
  24176. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24177. if (s <= 0) {
  24178. off = n;
  24179. break;
  24180. }
  24181. off += s;
  24182. }
  24183. }
  24184. ::shutdown(to, SHUT_WR);
  24185. };
  24186. std::thread t1([&] { forward(client_fd, origin_fd); });
  24187. std::thread t2([&] { forward(origin_fd, client_fd); });
  24188. t1.join();
  24189. t2.join();
  24190. ::close(client_fd);
  24191. ::close(origin_fd);
  24192. }
  24193. }
  24194. int forward_port_ = -1;
  24195. int listen_fd_ = -1;
  24196. int port_ = 0;
  24197. std::thread th_;
  24198. std::atomic<bool> stop_{false};
  24199. std::atomic<int> connect_hits_{0};
  24200. mutable std::mutex connect_request_mutex_;
  24201. std::string connect_request_;
  24202. };
  24203. // Sends one request through the CONNECT proxy to the TLS origin with a
  24204. // credential configured for each hop, and checks that each credential reaches
  24205. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24206. // origin's (every header in origin_headers) on the tunnelled request.
  24207. void CredentialsStayWithTheirHop(
  24208. const std::function<void(SSLClient &)> &set_credentials,
  24209. const std::string &scheme,
  24210. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24211. std::atomic<int> origin_hits{0};
  24212. std::atomic<bool> origin_saw_proxy_authz{false};
  24213. std::atomic<bool> origin_saw_headers{false};
  24214. ScopedSSLServer origin;
  24215. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24216. origin_hits++;
  24217. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24218. origin_saw_headers =
  24219. std::all_of(origin_headers.begin(), origin_headers.end(),
  24220. [&](const std::string &h) { return req.has_header(h); });
  24221. res.set_content("ok", "text/plain");
  24222. });
  24223. origin.listen();
  24224. ScopedConnectProxy proxy(origin.port());
  24225. ASSERT_NE(0, proxy.port());
  24226. // Pinned to 127.0.0.1 for the same reason as the test below.
  24227. SSLClient cli("127.0.0.1", origin.port());
  24228. cli.enable_server_certificate_verification(false);
  24229. cli.set_proxy("127.0.0.1", proxy.port());
  24230. set_credentials(cli);
  24231. auto res = cli.Get("/x");
  24232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24233. EXPECT_EQ(StatusCode::OK_200, res->status);
  24234. EXPECT_EQ(1, origin_hits.load());
  24235. EXPECT_EQ(1, proxy.connect_hits());
  24236. EXPECT_TRUE(origin_saw_headers.load());
  24237. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24238. << "Proxy-Authorization must not be sent inside the tunnel";
  24239. auto connect_req = proxy.connect_request();
  24240. EXPECT_NE(std::string::npos,
  24241. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24242. for (const auto &h : origin_headers) {
  24243. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24244. << h << " must not be sent to the proxy on CONNECT";
  24245. }
  24246. }
  24247. } // namespace proxy_tunnel_test
  24248. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24249. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24250. [](SSLClient &cli) {
  24251. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24252. cli.set_basic_auth("origin-user", "origin-pass");
  24253. },
  24254. "Basic");
  24255. }
  24256. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24257. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24258. [](SSLClient &cli) {
  24259. cli.set_proxy_bearer_token_auth("proxy-token");
  24260. cli.set_bearer_token_auth("origin-token");
  24261. },
  24262. "Bearer");
  24263. }
  24264. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24265. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24266. [](SSLClient &cli) {
  24267. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24268. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24269. {"Cookie", "sid=origin-session"},
  24270. {"X-Api-Key", "origin-key"}});
  24271. },
  24272. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24273. }
  24274. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24275. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24276. // retry; otherwise proxy creds would be sent to the origin.
  24277. std::atomic<int> origin_hits{0};
  24278. std::atomic<bool> origin_saw_proxy_authz{false};
  24279. proxy_tunnel_test::ScopedSSLServer origin;
  24280. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24281. origin_hits++;
  24282. if (req.has_header("Proxy-Authorization")) {
  24283. origin_saw_proxy_authz = true;
  24284. }
  24285. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24286. res.set_header("Proxy-Authenticate",
  24287. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24288. "algorithm=MD5");
  24289. });
  24290. origin.listen();
  24291. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24292. ASSERT_NE(0, proxy.port());
  24293. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24294. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24295. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24296. // and answer with its own status, making this test flaky.
  24297. SSLClient cli("127.0.0.1", origin.port());
  24298. cli.enable_server_certificate_verification(false);
  24299. cli.set_proxy("127.0.0.1", proxy.port());
  24300. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24301. auto res = cli.Get("/x");
  24302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24303. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24304. EXPECT_EQ(1, origin_hits.load());
  24305. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24306. EXPECT_EQ(1, proxy.connect_hits());
  24307. }
  24308. #endif