test.cc 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680
  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_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. } // namespace tls
  71. } // namespace httplib
  72. #endif
  73. using namespace std;
  74. using namespace httplib;
  75. const char *HOST = "localhost";
  76. static int get_base_port() {
  77. const char *shard = getenv("GTEST_SHARD_INDEX");
  78. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  79. }
  80. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  81. // New standalone tests MUST use svr.bind_to_any_port() instead.
  82. const int PORT = get_base_port();
  83. const string LONG_QUERY_VALUE = string(25000, '@');
  84. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  85. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  86. const string TOO_LONG_QUERY_URL =
  87. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  88. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  89. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  90. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  91. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  92. return file.name == key;
  93. });
  94. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  95. return *it;
  96. #else
  97. if (it != items.end()) { return *it; }
  98. throw std::runtime_error("invalid multipart form data name error");
  99. #endif
  100. }
  101. static void read_file(const std::string &path, std::string &out) {
  102. std::ifstream fs(path, std::ios_base::binary);
  103. if (!fs) {
  104. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  105. return;
  106. #else
  107. throw std::runtime_error("File not found: " + path);
  108. #endif
  109. }
  110. fs.seekg(0, std::ios_base::end);
  111. auto size = fs.tellg();
  112. fs.seekg(0);
  113. out.resize(static_cast<size_t>(size));
  114. fs.read(&out[0], static_cast<std::streamsize>(size));
  115. }
  116. class UnixSocketTest : public ::testing::Test {
  117. protected:
  118. void TearDown() override { std::remove(pathname_.c_str()); }
  119. void client_GET(const std::string &addr) {
  120. httplib::Client cli{addr};
  121. cli.set_address_family(AF_UNIX);
  122. ASSERT_TRUE(cli.is_valid());
  123. const auto &result = cli.Get(pattern_);
  124. ASSERT_TRUE(result) << "error: " << result.error();
  125. const auto &resp = result.value();
  126. EXPECT_EQ(resp.status, StatusCode::OK_200);
  127. EXPECT_EQ(resp.body, content_);
  128. }
  129. static std::string make_sock_path() {
  130. const char *shard = getenv("GTEST_SHARD_INDEX");
  131. return shard ? std::string("./httplib-server-") + shard + ".sock"
  132. : "./httplib-server.sock";
  133. }
  134. const std::string pathname_{make_sock_path()};
  135. const std::string pattern_{"/hi"};
  136. const std::string content_{"Hello World!"};
  137. };
  138. TEST_F(UnixSocketTest, pathname) {
  139. httplib::Server svr;
  140. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  141. res.set_content(content_, "text/plain");
  142. });
  143. std::thread t{[&] {
  144. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  145. }};
  146. auto se = detail::scope_exit([&] {
  147. svr.stop();
  148. t.join();
  149. ASSERT_FALSE(svr.is_running());
  150. });
  151. svr.wait_until_ready();
  152. ASSERT_TRUE(svr.is_running());
  153. client_GET(pathname_);
  154. // ".//x.sock", which is not taken for a URL
  155. client_GET("./" + pathname_.substr(1));
  156. }
  157. #if defined(__linux__) || \
  158. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  159. TEST_F(UnixSocketTest, PeerPid) {
  160. httplib::Server svr;
  161. std::string remote_port_val;
  162. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  163. res.set_content(content_, "text/plain");
  164. remote_port_val = std::to_string(req.remote_port);
  165. });
  166. std::thread t{[&] {
  167. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  168. }};
  169. auto se = detail::scope_exit([&] {
  170. svr.stop();
  171. t.join();
  172. ASSERT_FALSE(svr.is_running());
  173. });
  174. svr.wait_until_ready();
  175. ASSERT_TRUE(svr.is_running());
  176. client_GET(pathname_);
  177. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  178. }
  179. #endif
  180. #ifdef __linux__
  181. TEST_F(UnixSocketTest, abstract) {
  182. constexpr char svr_path[]{"\x00httplib-server.sock"};
  183. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  184. httplib::Server svr;
  185. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  186. res.set_content(content_, "text/plain");
  187. });
  188. std::thread t{[&] {
  189. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  190. }};
  191. auto se = detail::scope_exit([&] {
  192. svr.stop();
  193. t.join();
  194. ASSERT_FALSE(svr.is_running());
  195. });
  196. svr.wait_until_ready();
  197. ASSERT_TRUE(svr.is_running());
  198. client_GET(abstract_addr);
  199. }
  200. #endif
  201. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  202. httplib::Server svr;
  203. std::string received_host_header;
  204. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  205. // Capture the Host header sent by the client
  206. auto host_iter = req.headers.find("Host");
  207. if (host_iter != req.headers.end()) {
  208. received_host_header = host_iter->second;
  209. }
  210. res.set_content(content_, "text/plain");
  211. });
  212. std::thread t{[&] {
  213. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  214. }};
  215. auto se = detail::scope_exit([&] {
  216. svr.stop();
  217. t.join();
  218. ASSERT_FALSE(svr.is_running());
  219. });
  220. svr.wait_until_ready();
  221. ASSERT_TRUE(svr.is_running());
  222. // Test that Host header is automatically set to "localhost" for Unix socket
  223. // connections
  224. httplib::Client cli{pathname_};
  225. cli.set_address_family(AF_UNIX);
  226. ASSERT_TRUE(cli.is_valid());
  227. const auto &result = cli.Get(pattern_);
  228. ASSERT_TRUE(result) << "error: " << result.error();
  229. const auto &resp = result.value();
  230. EXPECT_EQ(resp.status, StatusCode::OK_200);
  231. EXPECT_EQ(resp.body, content_);
  232. // Verify that Host header was automatically set to "localhost"
  233. EXPECT_EQ(received_host_header, "localhost");
  234. }
  235. #ifndef _WIN32
  236. TEST(SocketStream, wait_writable_UNIX) {
  237. int fds[2];
  238. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  239. const auto asSocketStream = [&](socket_t fd,
  240. std::function<bool(Stream &)> func) {
  241. return detail::process_client_socket(
  242. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  243. };
  244. asSocketStream(fds[0], [&](Stream &s0) {
  245. EXPECT_EQ(s0.socket(), fds[0]);
  246. EXPECT_TRUE(s0.wait_writable());
  247. EXPECT_TRUE(s0.is_peer_alive());
  248. EXPECT_EQ(0, close(fds[1]));
  249. EXPECT_FALSE(s0.is_peer_alive());
  250. return true;
  251. });
  252. EXPECT_EQ(0, close(fds[0]));
  253. }
  254. TEST(SocketStream, wait_writable_INET) {
  255. sockaddr_in addr;
  256. memset(&addr, 0, sizeof(addr));
  257. addr.sin_family = AF_INET;
  258. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  259. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  260. int disconnected_svr_sock = -1;
  261. std::thread svr{[&] {
  262. const int s = socket(AF_INET, SOCK_STREAM, 0);
  263. ASSERT_LE(0, s);
  264. // PORT + 1 is shared with the SSL redirect tests and with
  265. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  266. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  267. // because that happens on a worker thread the ASSERT does not stop the
  268. // test: it runs on and fails at the disconnected_svr_sock check instead.
  269. default_socket_options(s);
  270. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  271. ASSERT_EQ(0, listen(s, 1));
  272. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  276. std::thread cli{[&] {
  277. const int s = socket(AF_INET, SOCK_STREAM, 0);
  278. ASSERT_LE(0, s);
  279. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  280. ASSERT_EQ(0, close(s));
  281. }};
  282. cli.join();
  283. svr.join();
  284. ASSERT_NE(disconnected_svr_sock, -1);
  285. const auto asSocketStream = [&](socket_t fd,
  286. std::function<bool(Stream &)> func) {
  287. return detail::process_client_socket(
  288. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  289. };
  290. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  291. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  292. // wait_writable() returns true because select_write() only checks if the
  293. // send buffer has space. Peer disconnection is detected later by send().
  294. EXPECT_TRUE(ss.wait_writable());
  295. return true;
  296. });
  297. ASSERT_EQ(0, close(disconnected_svr_sock));
  298. }
  299. #endif // #ifndef _WIN32
  300. TEST(SetSocketOptTest, TcpNoDelay) {
  301. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  302. ASSERT_NE(sock, INVALID_SOCKET);
  303. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  304. int val = 0;
  305. socklen_t len = sizeof(val);
  306. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  307. reinterpret_cast<char *>(&val), &len));
  308. EXPECT_NE(val, 0);
  309. detail::close_socket(sock);
  310. }
  311. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  312. // accept() reports failures through WSAGetLastError() on Windows and through
  313. // errno everywhere else. Asking the wrong one is what made the accept loop
  314. // treat every recoverable failure as fatal on Windows.
  315. struct Classification {
  316. bool resource;
  317. bool transient;
  318. };
  319. auto classify = [](int err) {
  320. #ifdef _WIN32
  321. WSASetLastError(err);
  322. #else
  323. errno = err;
  324. #endif
  325. // Read both before asserting: an assertion may clobber the error slot.
  326. Classification c;
  327. c.resource = detail::is_accept_resource_error();
  328. c.transient = detail::is_accept_transient_error();
  329. return c;
  330. };
  331. #ifdef _WIN32
  332. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  333. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  334. WSAECONNRESET, WSAECONNABORTED};
  335. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  336. #else
  337. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  338. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  339. ECONNABORTED};
  340. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  341. #endif
  342. for (auto err : resource_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.resource) << "error " << err;
  345. EXPECT_FALSE(c.transient) << "error " << err;
  346. }
  347. for (auto err : transient_errors) {
  348. const auto c = classify(err);
  349. EXPECT_TRUE(c.transient) << "error " << err;
  350. EXPECT_FALSE(c.resource) << "error " << err;
  351. }
  352. for (auto err : fatal_errors) {
  353. const auto c = classify(err);
  354. EXPECT_FALSE(c.resource) << "error " << err;
  355. EXPECT_FALSE(c.transient) << "error " << err;
  356. }
  357. #ifdef _WIN32
  358. WSASetLastError(0);
  359. #else
  360. errno = 0;
  361. #endif
  362. }
  363. TEST(ClientTest, MoveConstructible) {
  364. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  365. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  366. }
  367. TEST(ClientTest, MoveAssignable) {
  368. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  369. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  370. }
  371. #ifdef _WIN32
  372. TEST(StartupTest, WSAStartup) {
  373. WSADATA wsaData;
  374. int ret = WSAStartup(0x0002, &wsaData);
  375. ASSERT_EQ(0, ret);
  376. }
  377. #endif
  378. TEST(DecodePathTest, PercentCharacter) {
  379. EXPECT_EQ(
  380. decode_path_component(
  381. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  382. U8("descrip=Gastos áéíóúñÑ 6"));
  383. }
  384. TEST(DecodePathTest, PercentCharacterNUL) {
  385. string expected;
  386. expected.push_back('x');
  387. expected.push_back('\0');
  388. expected.push_back('x');
  389. EXPECT_EQ(decode_path_component("x%00x"), expected);
  390. }
  391. TEST(DecodePathTest, UnicodeEncoding) {
  392. // %u0041 = 'A' (1-byte UTF-8)
  393. EXPECT_EQ("A", decode_path_component("%u0041"));
  394. // %u00E9 = 'é' (2-byte UTF-8)
  395. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  396. // %u3042 = 'あ' (3-byte UTF-8)
  397. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  398. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  399. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  400. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  401. // neighbours)
  402. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  403. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  404. }
  405. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  406. // A sign or whitespace inside the two-character escape window must not be
  407. // accepted as a valid percent-encoding; the sequence is passed through
  408. // literally, matching decode_uri_component / decode_path_component.
  409. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  410. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  411. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  412. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  413. // Well-formed escapes still decode.
  414. EXPECT_EQ("-", decode_query_component("%2D", false));
  415. EXPECT_EQ("A", decode_query_component("%41", false));
  416. }
  417. TEST(SanitizeFilenameTest, VariousPatterns) {
  418. // Path traversal
  419. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  420. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  421. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  422. // Normal and edge cases
  423. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  424. EXPECT_EQ("filename.txt",
  425. httplib::sanitize_filename("/path/to/filename.txt"));
  426. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  427. EXPECT_EQ("", httplib::sanitize_filename(".."));
  428. EXPECT_EQ("", httplib::sanitize_filename(""));
  429. // Null bytes stripped
  430. EXPECT_EQ("safe.txt",
  431. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  432. // Whitespace-only rejected
  433. EXPECT_EQ("", httplib::sanitize_filename(" "));
  434. }
  435. // Forward declaration (see the base64_encode note below): split builds move the
  436. // definition into httplib.cc, so re-declaring it here lets the test link.
  437. namespace httplib {
  438. namespace detail {
  439. bool is_chunked_transfer_encoding(const Headers &headers);
  440. } // namespace detail
  441. } // namespace httplib
  442. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  443. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  444. auto make = [](std::initializer_list<const char *> lines) {
  445. Headers h;
  446. for (auto te : lines) {
  447. if (te) { h.emplace("Transfer-Encoding", te); }
  448. }
  449. return h;
  450. };
  451. // Sole coding, matched case-insensitively.
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  455. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  457. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  458. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  459. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  464. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  465. // were received, into one list. Headers preserves that order, so the answer
  466. // is decided by the last coding of the last line and the order the lines
  467. // arrived in is significant.
  468. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  470. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  471. // The split can fall anywhere in the list.
  472. EXPECT_TRUE(
  473. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  474. EXPECT_FALSE(
  475. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  476. // A trailing line naming no coding leaves the list ending in nothing, so it
  477. // must not inherit the chunked from the line before it.
  478. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  479. }
  480. // Forward declarations (see the base64_encode note below).
  481. namespace httplib {
  482. namespace detail {
  483. bool parse_status_line(const char *line, std::string &version, int &status,
  484. std::string &reason);
  485. std::string file_extension(const std::string &path);
  486. std::string
  487. find_content_type(const std::string &path,
  488. const std::map<std::string, std::string> &user_data,
  489. const std::string &default_content_type);
  490. bool can_compress_content_type(const std::string &content_type);
  491. bool is_prohibited_header_name(const std::string &name);
  492. bool is_valid_path(const std::string &path);
  493. #ifdef CPPHTTPLIB_SSL_ENABLED
  494. bool match_hostname(const std::string &pattern, const std::string &hostname);
  495. #endif
  496. } // namespace detail
  497. } // namespace httplib
  498. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  499. struct {
  500. const char *line;
  501. const char *version;
  502. int status;
  503. const char *reason;
  504. } cases[] = {
  505. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  506. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  507. // The reason phrase may be empty, or left out along with its space.
  508. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  509. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  510. };
  511. for (const auto &c : cases) {
  512. std::string version;
  513. int status = 0;
  514. std::string reason = "unset";
  515. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  516. << c.line;
  517. EXPECT_EQ(c.version, version);
  518. EXPECT_EQ(c.status, status);
  519. EXPECT_EQ(c.reason, reason);
  520. }
  521. }
  522. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  523. const char *lines[] = {
  524. "HTTP/2 200 OK\r\n",
  525. "HTTP/1.2 200 OK\r\n",
  526. "HTTP/1.1 20 OK\r\n",
  527. "HTTP/1.1 2000 OK\r\n",
  528. "HTTP/1.1 2x0 OK\r\n",
  529. "HTTP/1.1 200 OK\r\n",
  530. "HTTP/1.1 200OK\r\n",
  531. "HTTP/1.1 200 O\rK\r\n",
  532. "HTTP/1.1 200 OK",
  533. "HTTP/1.1 200 OK\r\nX",
  534. "",
  535. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  536. "HTTP/1.1 200 OK\n",
  537. #endif
  538. };
  539. for (auto line : lines) {
  540. std::string version;
  541. int status = 0;
  542. std::string reason;
  543. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  544. << line;
  545. }
  546. }
  547. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  548. // Long enough to overflow the stack when matched with std::regex.
  549. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  550. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  551. std::string version;
  552. int status = 0;
  553. std::string reason;
  554. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  555. EXPECT_EQ(200, status);
  556. EXPECT_EQ(long_reason, reason);
  557. }
  558. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  559. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  560. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  561. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  562. EXPECT_EQ("", detail::file_extension("noext"));
  563. EXPECT_EQ("", detail::file_extension("a."));
  564. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  565. EXPECT_EQ("", detail::file_extension("a.b-c"));
  566. // Long enough to overflow the stack when matched with std::regex.
  567. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  568. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  569. }
  570. #ifdef CPPHTTPLIB_SSL_ENABLED
  571. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  572. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  573. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  574. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  575. // A wildcard needs two labels after it, in the leftmost label only
  576. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  577. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  578. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  579. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  580. EXPECT_FALSE(
  581. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  582. // No name may have an empty label
  583. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  584. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  585. }
  586. #endif
  587. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  588. detail::case_ignore::hash hash;
  589. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  590. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  591. // Long enough to overflow the stack if hashed one call per character.
  592. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  593. }
  594. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  595. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  596. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  597. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  598. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  599. // Same 26-bit hash as html, svg and js.
  600. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  601. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  602. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  603. }
  604. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  605. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  606. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  607. }
  608. }
  609. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  610. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  611. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  612. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  613. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  614. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  615. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  616. // Same 26-bit hash as application/json.
  617. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  618. }
  619. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  620. Request req;
  621. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  622. EXPECT_TRUE(req.is_multipart_form_data());
  623. std::string boundary;
  624. EXPECT_TRUE(detail::parse_multipart_boundary(
  625. req.get_header_value("Content-Type"), boundary));
  626. EXPECT_EQ("x", boundary);
  627. }
  628. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  629. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  630. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  631. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  632. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  633. // Same 26-bit hash as REMOTE_ADDR.
  634. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  635. }
  636. // Forward declaration: in split builds split.py strips `inline` and moves the
  637. // definition into httplib.cc, so detail::base64_encode is not visible from the
  638. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  639. // in both header-only and split builds.
  640. namespace httplib {
  641. namespace detail {
  642. std::string base64_encode(const std::string &in);
  643. } // namespace detail
  644. } // namespace httplib
  645. TEST(Base64EncodeTest, KnownAnswers) {
  646. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  647. // where the accumulator's top bit is already set before the next shift.
  648. EXPECT_EQ("", detail::base64_encode(""));
  649. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  650. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  651. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  652. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  653. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  654. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  655. // High bytes keep the top bit set across several rounds.
  656. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  657. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  658. }
  659. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  660. string unescapedCharacters = "-_.!~*'()";
  661. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  662. }
  663. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  664. string reservedCharacters = ";,/?:@&=+$";
  665. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  666. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  667. }
  668. TEST(ClientQueryOrder, PreserveOrder) {
  669. // This test reproduces Issue #2259: client may reorder query parameters
  670. // when sending a GET request. The expected behavior is that the client
  671. // preserves the original query string order when the caller supplied it
  672. // as part of the path.
  673. Server svr;
  674. svr.Get("/", [&](const Request &req, Response &res) {
  675. // Echo back the raw target so the test can assert ordering
  676. res.set_content(req.target, "text/plain");
  677. });
  678. std::thread t{[&] { svr.listen(HOST, PORT); }};
  679. auto se = detail::scope_exit([&] {
  680. svr.stop();
  681. t.join();
  682. ASSERT_FALSE(svr.is_running());
  683. });
  684. svr.wait_until_ready();
  685. Client cli(HOST, PORT);
  686. ASSERT_TRUE(cli.is_valid());
  687. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  688. auto res = cli.Get(original);
  689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  690. // Expect the echoed target to exactly match the original path (order
  691. // preserved)
  692. EXPECT_EQ(res->body, original);
  693. }
  694. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  695. string chineseCharacters = U8("中国語");
  696. string russianCharacters = U8("дом");
  697. string brazilianCharacters = U8("óculos");
  698. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  699. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  700. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  701. "%D0%B4%D0%BE%D0%BC");
  702. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  703. }
  704. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  705. string unescapedCharacters = "-_.!~*'()";
  706. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  707. }
  708. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  709. string reservedCharacters = ";,/?:@&=+$";
  710. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  711. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  712. }
  713. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  714. string chineseCharacters = U8("中国語");
  715. string russianCharacters = U8("дом");
  716. string brazilianCharacters = U8("óculos");
  717. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  718. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  719. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  720. "%D0%B4%D0%BE%D0%BC");
  721. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  722. }
  723. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  724. // Issue #2082 use case: encoding path component with ampersand
  725. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  726. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  727. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  728. }
  729. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  730. string unescapedCharacters = "-_.!~*'()";
  731. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  732. }
  733. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  734. string reservedCharacters = ";,/?:@&=+$#";
  735. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  736. }
  737. TEST(EncodeUriTest, TestUTF8Characters) {
  738. string chineseCharacters = U8("中国語");
  739. string russianCharacters = U8("дом");
  740. string brazilianCharacters = U8("óculos");
  741. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  742. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  743. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  744. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  745. }
  746. TEST(EncodeUriTest, TestCompleteUri) {
  747. string uri =
  748. "https://example.com/path/to/resource?query=value&param=test#fragment";
  749. EXPECT_EQ(
  750. httplib::encode_uri(uri),
  751. "https://example.com/path/to/resource?query=value&param=test#fragment");
  752. }
  753. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  754. string uri =
  755. "https://example.com/path with spaces/file name.html?q=hello world";
  756. EXPECT_EQ(httplib::encode_uri(uri),
  757. "https://example.com/path%20with%20spaces/"
  758. "file%20name.html?q=hello%20world");
  759. }
  760. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  761. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  762. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  763. }
  764. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  765. string unescapedCharacters = "-_.!~*'()";
  766. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  767. }
  768. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  769. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  770. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  771. string encodedBrazilian = "%C3%B3culos";
  772. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  773. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  774. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  775. }
  776. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  777. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  778. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  779. "Piri Tommy Villiers - on & on");
  780. }
  781. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  782. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  783. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  784. }
  785. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  786. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  787. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  788. }
  789. TEST(DecodeUriTest, TestUTF8Characters) {
  790. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  791. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  792. string encodedBrazilian = "%C3%B3culos";
  793. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  794. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  795. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  796. }
  797. TEST(DecodeUriTest, TestCompleteUri) {
  798. string encodedUri = "https://example.com/path%20with%20spaces/"
  799. "file%20name.html?q=hello%20world";
  800. EXPECT_EQ(
  801. httplib::decode_uri(encodedUri),
  802. "https://example.com/path with spaces/file name.html?q=hello world");
  803. }
  804. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  805. string original =
  806. "https://example.com/path with spaces/file name.html?q=hello world";
  807. string encoded = httplib::encode_uri(original);
  808. string decoded = httplib::decode_uri(encoded);
  809. EXPECT_EQ(decoded, original);
  810. }
  811. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  812. // decode_uri is the inverse of encode_uri: an escaped reserved character
  813. // stays encoded so it is not promoted into a real delimiter, while
  814. // non-reserved escapes still decode (like JS decodeURI).
  815. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  816. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  817. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  818. "%3F%3A%40%26%3D%2B%24%2C%3B");
  819. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  820. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  821. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  822. "http://example.com/a%2Fb");
  823. // decode_uri_component still decodes the reserved character.
  824. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  825. }
  826. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  827. string original = "Piri Tommy Villiers - on & on";
  828. string encoded = httplib::encode_uri_component(original);
  829. string decoded = httplib::decode_uri_component(encoded);
  830. EXPECT_EQ(decoded, original);
  831. }
  832. TEST(TrimTests, TrimStringTests) {
  833. EXPECT_EQ("abc", detail::trim_copy("abc"));
  834. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  835. EXPECT_TRUE(detail::trim_copy("").empty());
  836. }
  837. TEST(AsciiTest, LocaleIndependentClassification) {
  838. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  839. // which consult the global C locale: std::isalnum(0xC5) can return true
  840. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  841. // helpers must classify every byte by the ASCII grammar alone.
  842. for (int i = 0; i < 256; i++) {
  843. auto c = static_cast<char>(i);
  844. auto is_digit = i >= '0' && i <= '9';
  845. auto is_upper = i >= 'A' && i <= 'Z';
  846. auto is_lower = i >= 'a' && i <= 'z';
  847. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  848. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  849. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  850. << "byte " << i;
  851. }
  852. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  853. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  854. // Non-ASCII bytes must be percent-encoded, never passed through as
  855. // alphanumeric.
  856. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  857. }
  858. TEST(FromCharsTest, Double) {
  859. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  860. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  861. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  862. auto parse = [](const std::string &s, double &v) {
  863. return detail::from_chars(s.data(), s.data() + s.size(), v);
  864. };
  865. double v = -1.0;
  866. // Representative quality values.
  867. EXPECT_EQ(parse("0", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 0.0);
  869. EXPECT_EQ(parse("1", v).ec, std::errc{});
  870. EXPECT_DOUBLE_EQ(v, 1.0);
  871. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  872. EXPECT_DOUBLE_EQ(v, 0.8);
  873. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 0.001);
  875. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 1.0);
  877. // A missing integer or fractional part is tolerated.
  878. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  879. EXPECT_DOUBLE_EQ(v, 0.5);
  880. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  881. EXPECT_DOUBLE_EQ(v, 5.0);
  882. // Values outside [0, 1] still parse; the caller range-checks them.
  883. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  884. EXPECT_DOUBLE_EQ(v, 123.456);
  885. // Stops at the first byte that is not part of the number and reports where.
  886. std::string trailing = "0.9, text/html";
  887. auto r = parse(trailing, v);
  888. EXPECT_EQ(r.ec, std::errc{});
  889. EXPECT_DOUBLE_EQ(v, 0.9);
  890. EXPECT_EQ(*r.ptr, ',');
  891. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  892. // outright, and an 'e'/'E' simply ends the number.
  893. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  895. std::string exp_input = "1.5e3";
  896. r = parse(exp_input, v);
  897. EXPECT_EQ(r.ec, std::errc{});
  898. EXPECT_DOUBLE_EQ(v, 1.5);
  899. EXPECT_EQ(*r.ptr, 'e');
  900. // Invalid inputs.
  901. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  902. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  903. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  904. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  905. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  906. // Pathological but well-formed inputs must stay bounded (no overflow, no
  907. // out-of-bounds table access) and stay within [0, 1] for the caller.
  908. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  909. std::errc{});
  910. EXPECT_DOUBLE_EQ(v, 0.0);
  911. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  912. std::errc{});
  913. EXPECT_GE(v, 0.0);
  914. EXPECT_LE(v, 1.0);
  915. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  916. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  917. }
  918. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  919. // Simple case without quality values
  920. std::vector<std::string> result1;
  921. EXPECT_TRUE(detail::parse_accept_header(
  922. "text/html,application/json,text/plain", result1));
  923. EXPECT_EQ(result1.size(), 3U);
  924. EXPECT_EQ(result1[0], "text/html");
  925. EXPECT_EQ(result1[1], "application/json");
  926. EXPECT_EQ(result1[2], "text/plain");
  927. // With quality values
  928. std::vector<std::string> result2;
  929. EXPECT_TRUE(detail::parse_accept_header(
  930. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  931. EXPECT_EQ(result2.size(), 3U);
  932. EXPECT_EQ(result2[0], "application/json"); // highest q value
  933. EXPECT_EQ(result2[1], "text/html");
  934. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  935. }
  936. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  937. // Mixed with and without quality values
  938. std::vector<std::string> result;
  939. EXPECT_TRUE(detail::parse_accept_header(
  940. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  941. EXPECT_EQ(result.size(), 3U);
  942. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  943. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  944. EXPECT_EQ(result[2], "application/json"); // q=0.5
  945. }
  946. TEST(ParseAcceptHeaderTest, EdgeCases) {
  947. // Empty header
  948. std::vector<std::string> empty_result;
  949. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  950. EXPECT_TRUE(empty_result.empty());
  951. // Single type
  952. std::vector<std::string> single_result;
  953. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  954. EXPECT_EQ(single_result.size(), 1U);
  955. EXPECT_EQ(single_result[0], "application/json");
  956. // Wildcard types
  957. std::vector<std::string> wildcard_result;
  958. EXPECT_TRUE(detail::parse_accept_header(
  959. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  960. EXPECT_EQ(wildcard_result.size(), 3U);
  961. EXPECT_EQ(wildcard_result[0], "application/json");
  962. EXPECT_EQ(wildcard_result[1], "text/*");
  963. EXPECT_EQ(wildcard_result[2], "*/*");
  964. }
  965. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  966. // Common browser Accept header
  967. std::vector<std::string> browser_result;
  968. EXPECT_TRUE(
  969. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  970. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  971. browser_result));
  972. EXPECT_EQ(browser_result.size(), 6U);
  973. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  974. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  975. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  976. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  977. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  978. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  979. // API client header
  980. std::vector<std::string> api_result;
  981. EXPECT_TRUE(detail::parse_accept_header(
  982. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  983. api_result));
  984. EXPECT_EQ(api_result.size(), 3U);
  985. EXPECT_EQ(api_result[0], "application/json");
  986. EXPECT_EQ(api_result[1], "application/xml");
  987. EXPECT_EQ(api_result[2], "text/plain");
  988. }
  989. TEST(ParseAcceptHeaderTest, SpecialCases) {
  990. // Quality value with 3 decimal places
  991. std::vector<std::string> decimal_result;
  992. EXPECT_TRUE(detail::parse_accept_header(
  993. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  994. EXPECT_EQ(decimal_result.size(), 2U);
  995. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  996. EXPECT_EQ(decimal_result[1], "text/html");
  997. // Zero quality (should still be included but with lowest priority)
  998. std::vector<std::string> zero_q_result;
  999. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1000. zero_q_result));
  1001. EXPECT_EQ(zero_q_result.size(), 2U);
  1002. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1003. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1004. // No spaces around commas
  1005. std::vector<std::string> no_space_result;
  1006. EXPECT_TRUE(detail::parse_accept_header(
  1007. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1008. no_space_result));
  1009. EXPECT_EQ(no_space_result.size(), 3U);
  1010. EXPECT_EQ(no_space_result[0], "text/html");
  1011. EXPECT_EQ(no_space_result[1], "application/json");
  1012. EXPECT_EQ(no_space_result[2], "text/plain");
  1013. }
  1014. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1015. // Quality values always use '.' as the decimal separator, so parsing must
  1016. // not depend on the process locale. An embedding application may have
  1017. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1018. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1019. std::string saved = cur ? cur : "C";
  1020. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1021. "fr_FR.UTF-8"};
  1022. bool switched = false;
  1023. for (const auto loc : comma_locales) {
  1024. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1025. std::localeconv()->decimal_point[0] == ',') {
  1026. switched = true;
  1027. break;
  1028. }
  1029. }
  1030. if (!switched) {
  1031. std::setlocale(LC_NUMERIC, saved.c_str());
  1032. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1033. }
  1034. // The higher-weighted type appears later in the list, so a correct parse
  1035. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1036. // sensitive parse reads both weights as 0 and leaves the original order.
  1037. std::vector<std::string> result;
  1038. EXPECT_TRUE(detail::parse_accept_header(
  1039. "application/json;q=0.1,text/html;q=0.9", result));
  1040. ASSERT_EQ(result.size(), 2U);
  1041. EXPECT_EQ(result[0], "text/html");
  1042. EXPECT_EQ(result[1], "application/json");
  1043. std::setlocale(LC_NUMERIC, saved.c_str());
  1044. }
  1045. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1046. std::vector<std::string> result;
  1047. // Invalid quality value (> 1.0)
  1048. EXPECT_FALSE(
  1049. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1050. // Invalid quality value (< 0.0)
  1051. EXPECT_FALSE(
  1052. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1053. // Invalid quality value (not a number)
  1054. EXPECT_FALSE(detail::parse_accept_header(
  1055. "text/html;q=invalid,application/json", result));
  1056. // A valid numeric prefix does not make the entire quality value valid.
  1057. EXPECT_FALSE(detail::parse_accept_header(
  1058. "text/html;q=0.5junk,application/json", result));
  1059. // Empty quality value
  1060. EXPECT_FALSE(
  1061. detail::parse_accept_header("text/html;q=,application/json", result));
  1062. // Invalid media type format (no slash and not wildcard)
  1063. EXPECT_FALSE(
  1064. detail::parse_accept_header("invalidtype,application/json", result));
  1065. // Valid cases should still work
  1066. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1067. EXPECT_EQ(result.size(), 1U);
  1068. EXPECT_EQ(result[0], "*/*");
  1069. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1070. EXPECT_EQ(result.size(), 1U);
  1071. EXPECT_EQ(result[0], "*");
  1072. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1073. EXPECT_EQ(result.size(), 1U);
  1074. EXPECT_EQ(result[0], "text/*");
  1075. }
  1076. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1077. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1078. // and must not be answered with 400 Bad Request.
  1079. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1080. struct {
  1081. const char *value;
  1082. std::vector<std::string> expected;
  1083. } cases[] = {
  1084. {",application/json", {"application/json"}},
  1085. {"text/html,", {"text/html"}},
  1086. {"text/html,,*/*", {"text/html", "*/*"}},
  1087. // An empty element may be spelled with whitespace in it
  1088. {"text/html, , application/json", {"text/html", "application/json"}},
  1089. // Nothing but empty elements is an empty list, which means the same
  1090. // thing as no Accept header at all
  1091. {",,,", {}},
  1092. // Quality values still apply across ignored empty elements
  1093. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1094. };
  1095. for (const auto &c : cases) {
  1096. std::vector<std::string> result;
  1097. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1098. << "value: " << c.value;
  1099. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1100. }
  1101. // An invalid entry is still rejected when empty elements surround it
  1102. std::vector<std::string> result;
  1103. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1104. }
  1105. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1106. // or ';' inside one does not end the list element or the parameter. Section
  1107. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1108. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1109. struct {
  1110. const char *value;
  1111. std::vector<std::string> expected;
  1112. } cases[] = {
  1113. {"text/html;profile=\"a,b\",application/json",
  1114. {"text/html", "application/json"}},
  1115. // A "q=" inside a quoted value is not the weight
  1116. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1117. {"text/html", "application/json"}},
  1118. // The weight after a quoted value still applies
  1119. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1120. {"application/json", "text/html"}},
  1121. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1122. {"application/json", "text/html"}},
  1123. {"text/html;profile=\"a\\\"b\",application/json",
  1124. {"text/html", "application/json"}},
  1125. // An escaped backslash does not escape the '"' after it
  1126. {"text/html;profile=\"a\\\\\",application/json",
  1127. {"text/html", "application/json"}},
  1128. };
  1129. for (const auto &c : cases) {
  1130. std::vector<std::string> result;
  1131. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1132. << "value: " << c.value;
  1133. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1134. }
  1135. }
  1136. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1137. Server svr;
  1138. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1139. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1140. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1141. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1142. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1143. res.set_content("ok", "text/plain");
  1144. });
  1145. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1146. EXPECT_TRUE(false);
  1147. res.set_content("bad request", "text/plain");
  1148. });
  1149. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1150. auto se = detail::scope_exit([&] {
  1151. svr.stop();
  1152. listen_thread.join();
  1153. ASSERT_FALSE(svr.is_running());
  1154. });
  1155. svr.wait_until_ready();
  1156. Client cli("localhost", PORT);
  1157. {
  1158. auto res = cli.Get(
  1159. "/accept_ok",
  1160. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1162. EXPECT_EQ(StatusCode::OK_200, res->status);
  1163. }
  1164. {
  1165. auto res = cli.Get("/accept_bad_request",
  1166. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1168. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1169. }
  1170. }
  1171. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1172. Server svr;
  1173. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1174. res.set_content("ok", "text/plain");
  1175. });
  1176. std::atomic<int> start_count{0};
  1177. std::atomic<bool> running_when_called{false};
  1178. svr.set_start_handler([&]() {
  1179. running_when_called = svr.is_running();
  1180. start_count++;
  1181. });
  1182. auto port = svr.bind_to_any_port(HOST);
  1183. std::thread t([&]() { svr.listen_after_bind(); });
  1184. auto se = detail::scope_exit([&] {
  1185. svr.stop();
  1186. t.join();
  1187. ASSERT_FALSE(svr.is_running());
  1188. });
  1189. svr.wait_until_ready();
  1190. // A successful request proves the accept loop is running, which the start
  1191. // handler precedes; so by now the handler must have run exactly once.
  1192. Client cli(HOST, port);
  1193. cli.set_connection_timeout(std::chrono::seconds(5));
  1194. auto res = cli.Get("/");
  1195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1196. EXPECT_EQ(StatusCode::OK_200, res->status);
  1197. EXPECT_EQ(1, start_count.load());
  1198. EXPECT_TRUE(running_when_called.load());
  1199. }
  1200. TEST(DivideTest, DivideStringTests) {
  1201. auto divide = [](const std::string &str, char d) {
  1202. std::string lhs;
  1203. std::string rhs;
  1204. detail::divide(str, d,
  1205. [&](const char *lhs_data, std::size_t lhs_size,
  1206. const char *rhs_data, std::size_t rhs_size) {
  1207. lhs.assign(lhs_data, lhs_size);
  1208. rhs.assign(rhs_data, rhs_size);
  1209. });
  1210. return std::make_pair(std::move(lhs), std::move(rhs));
  1211. };
  1212. {
  1213. const auto res = divide("", '=');
  1214. EXPECT_EQ(res.first, "");
  1215. EXPECT_EQ(res.second, "");
  1216. }
  1217. {
  1218. const auto res = divide("=", '=');
  1219. EXPECT_EQ(res.first, "");
  1220. EXPECT_EQ(res.second, "");
  1221. }
  1222. {
  1223. const auto res = divide(" ", '=');
  1224. EXPECT_EQ(res.first, " ");
  1225. EXPECT_EQ(res.second, "");
  1226. }
  1227. {
  1228. const auto res = divide("a", '=');
  1229. EXPECT_EQ(res.first, "a");
  1230. EXPECT_EQ(res.second, "");
  1231. }
  1232. {
  1233. const auto res = divide("a=", '=');
  1234. EXPECT_EQ(res.first, "a");
  1235. EXPECT_EQ(res.second, "");
  1236. }
  1237. {
  1238. const auto res = divide("=b", '=');
  1239. EXPECT_EQ(res.first, "");
  1240. EXPECT_EQ(res.second, "b");
  1241. }
  1242. {
  1243. const auto res = divide("a=b", '=');
  1244. EXPECT_EQ(res.first, "a");
  1245. EXPECT_EQ(res.second, "b");
  1246. }
  1247. {
  1248. const auto res = divide("a=b=", '=');
  1249. EXPECT_EQ(res.first, "a");
  1250. EXPECT_EQ(res.second, "b=");
  1251. }
  1252. {
  1253. const auto res = divide("a=b=c", '=');
  1254. EXPECT_EQ(res.first, "a");
  1255. EXPECT_EQ(res.second, "b=c");
  1256. }
  1257. }
  1258. TEST(SplitTest, ParseQueryString) {
  1259. string s = "key1=val1&key2=val2&key3=val3";
  1260. Params dic;
  1261. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1262. [&](const char *b, const char *e) {
  1263. string key, val;
  1264. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1265. if (key.empty()) {
  1266. key.assign(b2, e2);
  1267. } else {
  1268. val.assign(b2, e2);
  1269. }
  1270. });
  1271. dic.emplace(key, val);
  1272. });
  1273. EXPECT_EQ("val1", dic.find("key1")->second);
  1274. EXPECT_EQ("val2", dic.find("key2")->second);
  1275. EXPECT_EQ("val3", dic.find("key3")->second);
  1276. }
  1277. TEST(SplitTest, ParseInvalidQueryTests) {
  1278. {
  1279. string s = " ";
  1280. Params dict;
  1281. detail::parse_query_text(s, dict);
  1282. EXPECT_TRUE(dict.empty());
  1283. }
  1284. {
  1285. string s = " = =";
  1286. Params dict;
  1287. detail::parse_query_text(s, dict);
  1288. EXPECT_TRUE(dict.empty());
  1289. }
  1290. }
  1291. TEST(ParseQueryTest, ParseQueryString) {
  1292. {
  1293. std::string s = "key1=val1&key2=val2&key3=val3";
  1294. Params dic;
  1295. detail::parse_query_text(s, dic);
  1296. EXPECT_EQ("val1", dic.find("key1")->second);
  1297. EXPECT_EQ("val2", dic.find("key2")->second);
  1298. EXPECT_EQ("val3", dic.find("key3")->second);
  1299. }
  1300. {
  1301. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1302. Params dic;
  1303. detail::parse_query_text(s, dic);
  1304. EXPECT_EQ("", dic.find("key1")->second);
  1305. EXPECT_EQ("val1", dic.find("key2")->second);
  1306. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1307. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1308. }
  1309. }
  1310. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1311. Params dic;
  1312. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1313. dic.emplace("key1", "val1");
  1314. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1315. dic.emplace("key2", "val2");
  1316. dic.emplace("key3", "val3");
  1317. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1318. }
  1319. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1320. Params params;
  1321. params.emplace("a", "1");
  1322. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1323. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1324. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1325. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1326. // Long enough to overflow the stack when matched with std::regex.
  1327. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1328. EXPECT_EQ("/p?" + long_query + "&a=1",
  1329. append_query_params("/p?" + long_query, params));
  1330. }
  1331. // Joins every entry of a Headers or Params into "key=value " so a whole
  1332. // traversal can be compared in one assertion. Both are instantiations of the
  1333. // same insertion-ordered container, so one helper serves both.
  1334. template <typename Map> static std::string entries_to_string(const Map &m) {
  1335. std::string s;
  1336. for (const auto &entry : m) {
  1337. s += entry.first + "=" + entry.second + " ";
  1338. }
  1339. return s;
  1340. }
  1341. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1342. // Params used to be a std::multimap, which sorted by name and handed the
  1343. // caller's query back alphabetised. A client signing its query string could
  1344. // not reproduce the order it asked for.
  1345. Params dic;
  1346. dic.emplace("zulu", "1");
  1347. dic.emplace("alpha", "2");
  1348. dic.emplace("mike", "3");
  1349. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1350. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1351. }
  1352. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1353. Params dic;
  1354. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1355. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1356. }
  1357. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1358. Request req;
  1359. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1360. req.params);
  1361. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1362. EXPECT_EQ("first", req.get_param_value("tag"));
  1363. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1364. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1365. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1366. EXPECT_EQ("", req.get_param_value("tag", 3));
  1367. }
  1368. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1369. // Params shares its container with Headers, which matches field names
  1370. // case-insensitively. Parameter names must not pick that up.
  1371. Params dic;
  1372. dic.emplace("Key", "upper");
  1373. dic.emplace("key", "lower");
  1374. EXPECT_EQ(2U, dic.size());
  1375. EXPECT_EQ(1U, dic.count("Key"));
  1376. EXPECT_EQ(1U, dic.count("key"));
  1377. EXPECT_EQ("upper", dic.find("Key")->second);
  1378. EXPECT_EQ("lower", dic.find("key")->second);
  1379. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1380. }
  1381. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1382. Server svr;
  1383. std::string order;
  1384. svr.Get("/order", [&](const Request &req, Response &res) {
  1385. order = entries_to_string(req.params);
  1386. res.set_content("ok", "text/plain");
  1387. });
  1388. auto port = svr.bind_to_any_port(HOST);
  1389. thread t = thread([&] { svr.listen_after_bind(); });
  1390. auto se = detail::scope_exit([&] {
  1391. svr.stop();
  1392. t.join();
  1393. ASSERT_FALSE(svr.is_running());
  1394. });
  1395. svr.wait_until_ready();
  1396. Client cli(HOST, port);
  1397. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1398. ASSERT_TRUE(res);
  1399. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1400. }
  1401. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1402. Server svr;
  1403. std::string field_order, file_order;
  1404. svr.Post("/order", [&](const Request &req, Response &res) {
  1405. for (const auto &field : req.form.fields) {
  1406. field_order += field.first + "=" + field.second.content + " ";
  1407. }
  1408. for (const auto &file : req.form.files) {
  1409. file_order += file.first + "=" + file.second.filename + " ";
  1410. }
  1411. res.set_content("ok", "text/plain");
  1412. });
  1413. auto port = svr.bind_to_any_port(HOST);
  1414. thread t = thread([&] { svr.listen_after_bind(); });
  1415. auto se = detail::scope_exit([&] {
  1416. svr.stop();
  1417. t.join();
  1418. ASSERT_FALSE(svr.is_running());
  1419. });
  1420. svr.wait_until_ready();
  1421. UploadFormDataItems items = {
  1422. {"zulu", "1", "", ""},
  1423. {"alpha", "2", "", ""},
  1424. {"mike", "3", "", ""},
  1425. {"zebra", "z", "z.txt", "text/plain"},
  1426. {"apple", "a", "a.txt", "text/plain"},
  1427. };
  1428. Client cli(HOST, port);
  1429. auto res = cli.Post("/order", items);
  1430. ASSERT_TRUE(res);
  1431. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1432. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1433. }
  1434. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1435. Server svr;
  1436. std::vector<std::string> values;
  1437. std::string first, second, out_of_range, order;
  1438. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1439. values = req.form.get_fields("tag");
  1440. first = req.form.get_field("tag", 0);
  1441. second = req.form.get_field("tag", 1);
  1442. out_of_range = req.form.get_field("tag", 2);
  1443. for (const auto &field : req.form.fields) {
  1444. order += field.first + "=" + field.second.content + " ";
  1445. }
  1446. res.set_content("ok", "text/plain");
  1447. });
  1448. auto port = svr.bind_to_any_port(HOST);
  1449. thread t = thread([&] { svr.listen_after_bind(); });
  1450. auto se = detail::scope_exit([&] {
  1451. svr.stop();
  1452. t.join();
  1453. ASSERT_FALSE(svr.is_running());
  1454. });
  1455. svr.wait_until_ready();
  1456. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1457. // not adjacent in the container.
  1458. UploadFormDataItems items = {
  1459. {"tag", "first", "", ""},
  1460. {"other", "x", "", ""},
  1461. {"tag", "second", "", ""},
  1462. };
  1463. Client cli(HOST, port);
  1464. auto res = cli.Post("/repeated", items);
  1465. ASSERT_TRUE(res);
  1466. ASSERT_EQ(2U, values.size());
  1467. EXPECT_EQ("first", values[0]);
  1468. EXPECT_EQ("second", values[1]);
  1469. EXPECT_EQ("first", first);
  1470. EXPECT_EQ("second", second);
  1471. // std::multimap already kept entries sharing a name in insertion order, so
  1472. // everything above passes without this change too. The whole traversal is
  1473. // what tells the two apart: sorting by name would hoist "other" to the front
  1474. // and the two "tag" parts would end up adjacent.
  1475. EXPECT_EQ("tag=first other=x tag=second ", order);
  1476. // Advancing past the last entry of a name used to run off the container;
  1477. // the container's saturating increment makes it return the default instead.
  1478. EXPECT_EQ("", out_of_range);
  1479. }
  1480. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1481. Server svr;
  1482. std::string file_names;
  1483. svr.Post("/upload", [&](const Request &req, Response &res) {
  1484. for (const auto &file : req.form.files) {
  1485. file_names += file.first + "|" + file.second.filename + " ";
  1486. }
  1487. res.set_content("ok", "text/plain");
  1488. });
  1489. auto port = svr.bind_to_any_port(HOST);
  1490. thread t = thread([&] { svr.listen_after_bind(); });
  1491. auto se = detail::scope_exit([&] {
  1492. svr.stop();
  1493. t.join();
  1494. ASSERT_FALSE(svr.is_running());
  1495. });
  1496. svr.wait_until_ready();
  1497. // A trailing backslash would otherwise escape the closing quote.
  1498. UploadFormDataItems items = {
  1499. {"dir\\", "x", "a.txt", "text/plain"},
  1500. {"b", "y", "a\\\\b.txt", "text/plain"},
  1501. };
  1502. Client cli(HOST, port);
  1503. auto res = cli.Post("/upload", items);
  1504. ASSERT_TRUE(res);
  1505. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1506. }
  1507. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1508. // Server::read_content() keeps a FormFields::iterator alive across the
  1509. // content callbacks that fill the part it points at. The container is
  1510. // vector-backed, so a later emplace can reallocate and invalidate an older
  1511. // iterator; 64 parts grow the vector through seven reallocations, which
  1512. // checks that every part's content still lands in its own entry.
  1513. const size_t part_count = 64;
  1514. // One formula for both the parts sent and the values expected back, so the
  1515. // two cannot drift apart.
  1516. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1517. auto content_of = [](size_t i) {
  1518. return std::string(64, static_cast<char>('a' + (i % 26)));
  1519. };
  1520. Server svr;
  1521. std::vector<std::pair<std::string, std::string>> received;
  1522. svr.Post("/many", [&](const Request &req, Response &res) {
  1523. for (const auto &field : req.form.fields) {
  1524. received.emplace_back(field.first, field.second.content);
  1525. }
  1526. res.set_content("ok", "text/plain");
  1527. });
  1528. auto port = svr.bind_to_any_port(HOST);
  1529. thread t = thread([&] { svr.listen_after_bind(); });
  1530. auto se = detail::scope_exit([&] {
  1531. svr.stop();
  1532. t.join();
  1533. ASSERT_FALSE(svr.is_running());
  1534. });
  1535. svr.wait_until_ready();
  1536. UploadFormDataItems items;
  1537. for (size_t i = 0; i < part_count; i++) {
  1538. items.push_back({name_of(i), content_of(i), "", ""});
  1539. }
  1540. Client cli(HOST, port);
  1541. auto res = cli.Post("/many", items);
  1542. ASSERT_TRUE(res);
  1543. ASSERT_EQ(part_count, received.size());
  1544. for (size_t i = 0; i < part_count; i++) {
  1545. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1546. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1547. }
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1550. string content_type = "multipart/form-data; boundary=something";
  1551. string boundary;
  1552. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1553. EXPECT_TRUE(ret);
  1554. EXPECT_EQ(boundary, "something");
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1557. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1558. string boundary;
  1559. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1562. }
  1563. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1564. string content_type =
  1565. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1566. string boundary;
  1567. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1568. EXPECT_TRUE(ret);
  1569. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1570. }
  1571. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1572. string content_type =
  1573. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1574. string boundary;
  1575. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1576. EXPECT_TRUE(ret);
  1577. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1578. }
  1579. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1580. const string boundary(70, 'a');
  1581. string content_type = "multipart/form-data; boundary=" + boundary;
  1582. string parsed;
  1583. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1584. EXPECT_TRUE(ret);
  1585. EXPECT_EQ(parsed, boundary);
  1586. }
  1587. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1588. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1589. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1590. string parsed;
  1591. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1592. EXPECT_FALSE(ret);
  1593. }
  1594. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1595. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1596. // is 72 characters on the wire and still valid.
  1597. const string boundary(70, 'a');
  1598. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1599. string parsed;
  1600. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1601. EXPECT_EQ(parsed, boundary);
  1602. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1603. parsed.clear();
  1604. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1605. }
  1606. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1607. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1608. // The parameter parser must not treat that '=' as the key/value separator.
  1609. string content_type =
  1610. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1611. "charset=UTF-8";
  1612. string parsed;
  1613. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1614. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1615. }
  1616. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1617. // A ';' inside the quoted-string is part of the value, not a parameter
  1618. // separator, so it must not truncate the boundary.
  1619. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1620. string parsed;
  1621. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1622. EXPECT_EQ(parsed, "a;b");
  1623. }
  1624. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1625. string parsed;
  1626. EXPECT_TRUE(detail::parse_multipart_boundary(
  1627. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1628. EXPECT_EQ("a\\b", parsed);
  1629. EXPECT_TRUE(detail::parse_multipart_boundary(
  1630. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1631. EXPECT_EQ("a\"b", parsed);
  1632. }
  1633. TEST(ParseDispositionParamsTest, QuotedValues) {
  1634. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1635. // ';' and '=' are ordinary characters inside one.
  1636. struct {
  1637. const char *value;
  1638. std::vector<std::pair<const char *, const char *>> expected;
  1639. } cases[] = {
  1640. {"name=\"file1\"; filename=\"a.txt\"",
  1641. {{"name", "file1"}, {"filename", "a.txt"}}},
  1642. // Whitespace around '=' and ';' is still trimmed
  1643. {"name=\"file2\" ;filename = \"a.html\"",
  1644. {{"name", "file2"}, {"filename", "a.html"}}},
  1645. // '=' inside the value used to leave only the text after the last one
  1646. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1647. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1648. {"name=\"x=y\"", {{"name", "x=y"}}},
  1649. // ';' inside the value used to truncate the pair and leave a bogus one
  1650. {"name=\"file3\"; filename=\"a;b.txt\"",
  1651. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1652. // An unquoted value keeps working, and so does filename*
  1653. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1654. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1655. // A parameter with no key is dropped rather than turned into one whose
  1656. // key is the value
  1657. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1658. // An escaped quote does not end the value
  1659. {"name=\"a\\\"; filename=evil.php\"",
  1660. {{"name", "a\"; filename=evil.php"}}},
  1661. // Other backslashes, as in a Windows path, are kept
  1662. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1663. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1664. };
  1665. for (const auto &c : cases) {
  1666. Params params;
  1667. detail::parse_disposition_params(c.value, params);
  1668. for (const auto &kv : c.expected) {
  1669. auto it = params.find(kv.first);
  1670. ASSERT_NE(it, params.end())
  1671. << "value: " << c.value << ", key: " << kv.first;
  1672. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1673. }
  1674. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1675. }
  1676. }
  1677. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1678. Server svr;
  1679. std::string filename;
  1680. std::string content;
  1681. svr.Post("/upload", [&](const Request &req, Response &) {
  1682. const auto &file = req.form.get_file("file");
  1683. filename = file.filename;
  1684. content = file.content;
  1685. });
  1686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1687. auto se = detail::scope_exit([&] {
  1688. svr.stop();
  1689. thread.join();
  1690. ASSERT_FALSE(svr.is_running());
  1691. });
  1692. svr.wait_until_ready();
  1693. std::string body = "--B\r\n"
  1694. "Content-Disposition: form-data; name=\"file\"; "
  1695. "filename=\"a.txt\"\r\n"
  1696. "Content-Type: text/plain\r\n"
  1697. "\r\n"
  1698. "hello\r\n"
  1699. "--B--\r\n";
  1700. Client cli(HOST, PORT);
  1701. auto res = cli.Post(
  1702. "/upload",
  1703. [&](size_t offset, DataSink &sink) {
  1704. if (offset < body.size()) {
  1705. sink.write(&body[offset], 1);
  1706. } else {
  1707. sink.done();
  1708. }
  1709. return true;
  1710. },
  1711. "multipart/form-data; boundary=B");
  1712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1713. EXPECT_EQ(StatusCode::OK_200, res->status);
  1714. EXPECT_EQ("a.txt", filename);
  1715. EXPECT_EQ("hello", content);
  1716. }
  1717. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1718. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1719. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1720. Server svr;
  1721. std::string field_value, file_name, file_filename;
  1722. bool has_field = false, has_file = false;
  1723. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1724. has_field = req.form.has_field("x=y");
  1725. field_value = req.form.get_field("x=y");
  1726. has_file = req.form.has_file("file1");
  1727. const auto &file = req.form.get_file("file1");
  1728. file_name = file.name;
  1729. file_filename = file.filename;
  1730. res.set_content("ok", "text/plain");
  1731. });
  1732. auto port = svr.bind_to_any_port(HOST);
  1733. thread t = thread([&] { svr.listen_after_bind(); });
  1734. auto se = detail::scope_exit([&] {
  1735. svr.stop();
  1736. t.join();
  1737. ASSERT_FALSE(svr.is_running());
  1738. });
  1739. svr.wait_until_ready();
  1740. UploadFormDataItems items = {
  1741. {"x=y", "field-value", "", ""},
  1742. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1743. };
  1744. Client cli(HOST, port);
  1745. auto res = cli.Post("/quoted", items);
  1746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1747. ASSERT_EQ(StatusCode::OK_200, res->status);
  1748. EXPECT_TRUE(has_field);
  1749. EXPECT_EQ("field-value", field_value);
  1750. EXPECT_TRUE(has_file);
  1751. EXPECT_EQ("file1", file_name);
  1752. EXPECT_EQ("a;b=report.pdf", file_filename);
  1753. }
  1754. TEST(GetHeaderValueTest, DefaultValue) {
  1755. Headers headers = {{"Dummy", "Dummy"}};
  1756. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1757. EXPECT_STREQ("text/plain", val);
  1758. }
  1759. TEST(GetHeaderValueTest, DefaultValueInt) {
  1760. Headers headers = {{"Dummy", "Dummy"}};
  1761. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1762. EXPECT_EQ(100ull, val);
  1763. }
  1764. TEST(GetHeaderValueTest, RegularValue) {
  1765. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1766. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1767. EXPECT_STREQ("text/html", val);
  1768. }
  1769. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1770. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1771. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1772. EXPECT_STREQ("text/html", val);
  1773. }
  1774. TEST(GetHeaderValueTest, SetContent) {
  1775. Response res;
  1776. res.set_content("html", "text/html");
  1777. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1778. res.set_content("text", "text/plain");
  1779. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1780. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1781. }
  1782. TEST(GetHeaderValueTest, RegularValueInt) {
  1783. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1784. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1785. EXPECT_EQ(100ull, val);
  1786. }
  1787. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1788. Headers headers = {{"Content-Length", "x"}};
  1789. auto is_invalid_value = false;
  1790. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1791. is_invalid_value);
  1792. EXPECT_EQ(0ull, val);
  1793. EXPECT_TRUE(is_invalid_value);
  1794. }
  1795. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1796. // An all-digit value that overflows size_t must be reported as invalid, not
  1797. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1798. // a large length to a small one on 32-bit builds, leaving the framing length
  1799. // wrong while is_invalid_value stayed false.
  1800. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1801. auto is_invalid_value = false;
  1802. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1803. is_invalid_value);
  1804. EXPECT_TRUE(is_invalid_value);
  1805. // A well-formed length is unaffected.
  1806. Headers ok = {{"Content-Length", "1234"}};
  1807. is_invalid_value = false;
  1808. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1809. is_invalid_value);
  1810. EXPECT_EQ(1234ull, val);
  1811. EXPECT_FALSE(is_invalid_value);
  1812. }
  1813. TEST(GetHeaderValueTest, Range) {
  1814. {
  1815. Headers headers = {make_range_header({{1, -1}})};
  1816. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1817. EXPECT_STREQ("bytes=1-", val);
  1818. }
  1819. {
  1820. Headers headers = {make_range_header({{-1, 1}})};
  1821. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1822. EXPECT_STREQ("bytes=-1", val);
  1823. }
  1824. {
  1825. Headers headers = {make_range_header({{1, 10}})};
  1826. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1827. EXPECT_STREQ("bytes=1-10", val);
  1828. }
  1829. {
  1830. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1831. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1832. EXPECT_STREQ("bytes=1-10, 100-", val);
  1833. }
  1834. {
  1835. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1836. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1837. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1838. }
  1839. {
  1840. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1841. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1842. EXPECT_STREQ("bytes=0-0, -1", val);
  1843. }
  1844. }
  1845. TEST(BearerTokenAuthTest, SchemeValidation) {
  1846. // A value shorter than "Bearer " must not throw from the fixed-length
  1847. // substr, and a non-Bearer scheme must not be reported as a token.
  1848. struct {
  1849. const char *value;
  1850. const char *expected;
  1851. } cases[] = {
  1852. {"x", ""},
  1853. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1854. {"Bearer abc123", "abc123"},
  1855. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1856. };
  1857. for (const auto &c : cases) {
  1858. Request req;
  1859. req.set_header("Authorization", c.value);
  1860. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1861. }
  1862. }
  1863. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1864. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1865. // to depend on the standard library (libstdc++ handed back duplicates in
  1866. // reverse insertion order, libc++ in insertion order).
  1867. Request req;
  1868. req.set_header("Accept-Encoding", "gzip");
  1869. req.set_header("Accept-Encoding", "deflate");
  1870. req.set_header("Accept-Encoding", "br");
  1871. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1872. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1873. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1874. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1875. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1876. }
  1877. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1878. Request req;
  1879. req.set_header("X-Test", "only");
  1880. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1881. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1882. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1883. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1884. }
  1885. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1886. Request req;
  1887. req.set_header("X-First", "1");
  1888. req.set_header("X-Test", "2");
  1889. req.params.emplace("first", "1");
  1890. req.params.emplace("test", "2");
  1891. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1892. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1893. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1894. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1895. // The second one is negative when read as a signed value
  1896. const auto max_id = (std::numeric_limits<size_t>::max)();
  1897. for (auto id : {max_id / 2, max_id}) {
  1898. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1899. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1900. EXPECT_EQ("", req.get_param_value("test", id));
  1901. EXPECT_EQ("", req.form.get_field("test", id));
  1902. EXPECT_EQ("", req.form.get_file("test", id).content);
  1903. }
  1904. }
  1905. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1906. Headers headers;
  1907. headers.emplace("Host", "example.com");
  1908. headers.emplace("Accept-Encoding", "gzip");
  1909. headers.emplace("User-Agent", "test");
  1910. headers.emplace("Accept-Encoding", "deflate");
  1911. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1912. "Accept-Encoding=deflate ",
  1913. entries_to_string(headers));
  1914. }
  1915. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1916. Headers headers = {{"Content-Type", "text/html"},
  1917. {"CONTENT-TYPE", "text/xml"}};
  1918. EXPECT_EQ(2U, headers.count("content-type"));
  1919. auto it = headers.find("content-type");
  1920. ASSERT_TRUE(it != headers.end());
  1921. EXPECT_EQ("text/html", it->second);
  1922. }
  1923. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1924. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1925. // drop only those fields and leave everything positioned between them.
  1926. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1927. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1928. auto rng = headers.equal_range("a");
  1929. headers.erase(rng.first, rng.second);
  1930. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1931. }
  1932. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1933. Headers headers = {
  1934. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1935. EXPECT_EQ(3U, headers.erase("A"));
  1936. EXPECT_EQ(0U, headers.count("A"));
  1937. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1938. }
  1939. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1940. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1941. headers.emplace_front("Host", "example.com");
  1942. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1943. entries_to_string(headers));
  1944. }
  1945. TEST(ParseHeaderValueTest, Range) {
  1946. {
  1947. Ranges ranges;
  1948. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1949. EXPECT_TRUE(ret);
  1950. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1951. }
  1952. {
  1953. Ranges ranges;
  1954. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1955. EXPECT_TRUE(ret);
  1956. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1957. }
  1958. {
  1959. Ranges ranges;
  1960. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1961. EXPECT_TRUE(ret);
  1962. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1963. }
  1964. {
  1965. Ranges ranges;
  1966. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1967. EXPECT_FALSE(ret);
  1968. }
  1969. {
  1970. Ranges ranges;
  1971. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1972. EXPECT_TRUE(ret);
  1973. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. auto ret =
  1978. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1979. EXPECT_TRUE(ret);
  1980. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1981. }
  1982. {
  1983. Ranges ranges;
  1984. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1990. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1997. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1998. EXPECT_FALSE(
  1999. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2000. EXPECT_TRUE(ranges.empty());
  2001. }
  2002. {
  2003. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2004. // remainder of the representation, so it stays accepted.
  2005. Ranges ranges;
  2006. auto ret =
  2007. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2008. EXPECT_TRUE(ret);
  2009. ASSERT_EQ(1u, ranges.size());
  2010. EXPECT_EQ(0, ranges[0].first);
  2011. EXPECT_EQ(-1, ranges[0].second);
  2012. }
  2013. // RFC 9110 14.1: range unit names are case-insensitive.
  2014. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2015. Ranges ranges;
  2016. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2017. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2018. }
  2019. }
  2020. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2021. Request req;
  2022. req.set_header("Accept-Encoding", "gzip");
  2023. Response res;
  2024. res.set_header("Content-Type", "text/plain");
  2025. auto ret = detail::encoding_type(req, res);
  2026. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2027. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2028. #else
  2029. EXPECT_TRUE(ret == detail::EncodingType::None);
  2030. #endif
  2031. }
  2032. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2033. Request req;
  2034. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2035. Response res;
  2036. res.set_header("Content-Type", "text/plain");
  2037. auto ret = detail::encoding_type(req, res);
  2038. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2039. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2040. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2041. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2042. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2043. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2044. #else
  2045. EXPECT_TRUE(ret == detail::EncodingType::None);
  2046. #endif
  2047. }
  2048. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2049. Request req;
  2050. req.set_header("Accept-Encoding",
  2051. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2052. Response res;
  2053. res.set_header("Content-Type", "text/plain");
  2054. auto ret = detail::encoding_type(req, res);
  2055. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2056. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2057. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2058. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2059. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2060. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2061. #else
  2062. EXPECT_TRUE(ret == detail::EncodingType::None);
  2063. #endif
  2064. }
  2065. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2066. // All supported encodings rejected with q=0 should return None
  2067. Request req;
  2068. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2069. Response res;
  2070. res.set_header("Content-Type", "text/plain");
  2071. auto ret = detail::encoding_type(req, res);
  2072. EXPECT_TRUE(ret == detail::EncodingType::None);
  2073. }
  2074. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2075. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2076. Request req;
  2077. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2078. Response res;
  2079. res.set_header("Content-Type", "text/plain");
  2080. auto ret = detail::encoding_type(req, res);
  2081. EXPECT_TRUE(ret == detail::EncodingType::None);
  2082. }
  2083. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2084. Request req;
  2085. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2086. Response res;
  2087. res.set_header("Content-Type", "text/plain");
  2088. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2089. }
  2090. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2091. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2092. Request req;
  2093. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2094. Response res;
  2095. res.set_header("Content-Type", "text/plain");
  2096. auto ret = detail::encoding_type(req, res);
  2097. EXPECT_TRUE(ret == detail::EncodingType::None);
  2098. }
  2099. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2100. // RFC 7231: Accept-Encoding values are case-insensitive
  2101. Request req;
  2102. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2103. Response res;
  2104. res.set_header("Content-Type", "text/plain");
  2105. auto ret = detail::encoding_type(req, res);
  2106. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2107. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2108. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2109. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2110. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2111. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2112. #else
  2113. EXPECT_TRUE(ret == detail::EncodingType::None);
  2114. #endif
  2115. }
  2116. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2117. // q value should determine priority, not hardcoded order
  2118. Request req;
  2119. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2120. Response res;
  2121. res.set_header("Content-Type", "text/plain");
  2122. auto ret = detail::encoding_type(req, res);
  2123. // gzip has highest q=1.0, so it should be selected even though
  2124. // br and zstd are also supported
  2125. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2126. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2127. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2128. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2129. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2130. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2131. #else
  2132. EXPECT_TRUE(ret == detail::EncodingType::None);
  2133. #endif
  2134. }
  2135. TEST(BufferStreamTest, read) {
  2136. detail::BufferStream strm1;
  2137. Stream &strm = strm1;
  2138. EXPECT_EQ(5, strm.write("hello"));
  2139. char buf[512];
  2140. EXPECT_EQ(2, strm.read(buf, 2));
  2141. EXPECT_EQ('h', buf[0]);
  2142. EXPECT_EQ('e', buf[1]);
  2143. EXPECT_EQ(2, strm.read(buf, 2));
  2144. EXPECT_EQ('l', buf[0]);
  2145. EXPECT_EQ('l', buf[1]);
  2146. EXPECT_EQ(1, strm.read(buf, 1));
  2147. EXPECT_EQ('o', buf[0]);
  2148. EXPECT_EQ(0, strm.read(buf, 1));
  2149. }
  2150. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2151. auto host = "www.httpwatch.com";
  2152. auto ip = hosted_at(host);
  2153. EXPECT_EQ("23.96.13.243", ip);
  2154. std::vector<std::string> addrs;
  2155. hosted_at(host, addrs);
  2156. EXPECT_EQ(1u, addrs.size());
  2157. }
  2158. #if 0 // It depends on each test environment...
  2159. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2160. auto host = "www.youtube.com";
  2161. std::vector<std::string> addrs;
  2162. hosted_at(host, addrs);
  2163. EXPECT_EQ(20u, addrs.size());
  2164. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2165. EXPECT_TRUE(it != addrs.end());
  2166. }
  2167. #endif
  2168. class ChunkedEncodingTest : public ::testing::Test {
  2169. protected:
  2170. ChunkedEncodingTest()
  2171. : cli_(HOST, PORT)
  2172. #ifdef CPPHTTPLIB_SSL_ENABLED
  2173. ,
  2174. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2175. #endif
  2176. {
  2177. cli_.set_connection_timeout(2);
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. cli_.enable_server_certificate_verification(false);
  2180. #endif
  2181. }
  2182. virtual void SetUp() {
  2183. read_file("./image.jpg", image_data_);
  2184. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2185. res.set_content("Hello World!", "text/plain");
  2186. });
  2187. svr_.Get(
  2188. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2189. res.set_chunked_content_provider(
  2190. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2191. size_t remaining = image_data_.size() - offset;
  2192. if (remaining == 0) {
  2193. sink.done();
  2194. } else {
  2195. constexpr size_t CHUNK_SIZE = 1024;
  2196. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2197. sink.write(&image_data_[offset], send_size);
  2198. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2199. }
  2200. return true;
  2201. });
  2202. });
  2203. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2204. svr_.wait_until_ready();
  2205. }
  2206. virtual void TearDown() {
  2207. svr_.stop();
  2208. if (!request_threads_.empty()) {
  2209. std::this_thread::sleep_for(std::chrono::seconds(1));
  2210. for (auto &t : request_threads_) {
  2211. t.join();
  2212. }
  2213. }
  2214. t_.join();
  2215. }
  2216. #ifdef CPPHTTPLIB_SSL_ENABLED
  2217. SSLClient cli_;
  2218. SSLServer svr_;
  2219. #else
  2220. Client cli_;
  2221. Server svr_;
  2222. #endif
  2223. thread t_;
  2224. std::vector<thread> request_threads_;
  2225. std::string image_data_;
  2226. };
  2227. TEST_F(ChunkedEncodingTest, NormalGet) {
  2228. auto res = cli_.Get("/chunked");
  2229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2230. std::string out;
  2231. read_file("./image.jpg", out);
  2232. EXPECT_EQ(StatusCode::OK_200, res->status);
  2233. EXPECT_EQ(out, res->body);
  2234. }
  2235. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2236. std::string body;
  2237. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2238. body.append(data, data_length);
  2239. return true;
  2240. });
  2241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2242. std::string out;
  2243. read_file("./image.jpg", out);
  2244. EXPECT_EQ(StatusCode::OK_200, res->status);
  2245. EXPECT_EQ(out, body);
  2246. }
  2247. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2248. std::string body;
  2249. auto res = cli_.Get(
  2250. "/chunked",
  2251. [&](const Response &response) {
  2252. EXPECT_EQ(StatusCode::OK_200, response.status);
  2253. return true;
  2254. },
  2255. [&](const char *data, size_t data_length) {
  2256. body.append(data, data_length);
  2257. return true;
  2258. });
  2259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2260. std::string out;
  2261. read_file("./image.jpg", out);
  2262. EXPECT_EQ(StatusCode::OK_200, res->status);
  2263. EXPECT_EQ(out, body);
  2264. }
  2265. TEST(RangeTest, FromHTTPBin_Online) {
  2266. auto host = "httpbingo.org";
  2267. auto path = std::string{"/range/32"};
  2268. #ifdef CPPHTTPLIB_SSL_ENABLED
  2269. auto port = 443;
  2270. SSLClient cli(host, port);
  2271. #else
  2272. auto port = 80;
  2273. Client cli(host, port);
  2274. #endif
  2275. cli.set_connection_timeout(5);
  2276. {
  2277. auto res = cli.Get(path);
  2278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2279. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2280. EXPECT_EQ(StatusCode::OK_200, res->status);
  2281. }
  2282. {
  2283. Headers headers = {make_range_header({{1, -1}})};
  2284. auto res = cli.Get(path, headers);
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2287. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2288. }
  2289. {
  2290. Headers headers = {make_range_header({{1, 10}})};
  2291. auto res = cli.Get(path, headers);
  2292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2293. EXPECT_EQ("bcdefghijk", res->body);
  2294. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2295. }
  2296. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2297. // entire resource, while the original httpbin returned 200. Both are
  2298. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2299. {
  2300. Headers headers = {make_range_header({{0, 31}})};
  2301. auto res = cli.Get(path, headers);
  2302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2303. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2304. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2305. res->status == StatusCode::PartialContent_206);
  2306. }
  2307. {
  2308. Headers headers = {make_range_header({{0, -1}})};
  2309. auto res = cli.Get(path, headers);
  2310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2311. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2312. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2313. res->status == StatusCode::PartialContent_206);
  2314. }
  2315. // go-httpbin returns 206 with clamped range for over-range requests,
  2316. // while the original httpbin returned 416. Both behaviors are observed
  2317. // in real servers, so we only verify the request succeeds.
  2318. {
  2319. Headers headers = {make_range_header({{0, 32}})};
  2320. auto res = cli.Get(path, headers);
  2321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2322. }
  2323. }
  2324. TEST(RangeTest, IgnoredForPost) {
  2325. Server svr;
  2326. svr.Post("/", [](const Request &, Response &res) {
  2327. res.set_content("abcdefg", "text/plain");
  2328. });
  2329. auto port = svr.bind_to_any_port(HOST);
  2330. ASSERT_GT(port, 0);
  2331. thread t = thread([&] { svr.listen_after_bind(); });
  2332. auto se = detail::scope_exit([&] {
  2333. svr.stop();
  2334. t.join();
  2335. ASSERT_FALSE(svr.is_running());
  2336. });
  2337. svr.wait_until_ready();
  2338. Client cli(HOST, port);
  2339. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2340. auto res = cli.Post("/", Headers{{"Range", range}});
  2341. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2342. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2343. EXPECT_EQ("abcdefg", res->body) << range;
  2344. }
  2345. }
  2346. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2347. auto host = "unresolvableaddress.local";
  2348. auto path = std::string{"/"};
  2349. #ifdef CPPHTTPLIB_SSL_ENABLED
  2350. auto port = 443;
  2351. SSLClient cli(host, port);
  2352. #else
  2353. auto port = 80;
  2354. Client cli(host, port);
  2355. #endif
  2356. cli.set_connection_timeout(1);
  2357. {
  2358. auto res = cli.Get(path);
  2359. ASSERT_FALSE(res);
  2360. }
  2361. std::this_thread::sleep_for(std::chrono::seconds(8));
  2362. }
  2363. #if defined(__linux__) && defined(__GLIBC__) && \
  2364. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2365. // Forward declaration: in split builds split.py strips `inline` and moves the
  2366. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2367. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2368. // against the symbol in both header-only and split builds.
  2369. namespace httplib {
  2370. namespace detail {
  2371. int getaddrinfo_with_timeout(const char *node, const char *service,
  2372. const struct addrinfo *hints,
  2373. struct addrinfo **res, time_t timeout_sec);
  2374. } // namespace detail
  2375. } // namespace httplib
  2376. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2377. //
  2378. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2379. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2380. // gai_suspend() call hits the connection timeout the function calls
  2381. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2382. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2383. // still alive and still references the now-destroyed stack frame.
  2384. //
  2385. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2386. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2387. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2388. // and runs them in a container.
  2389. namespace {
  2390. bool should_run_issue_2431_tests() {
  2391. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2392. return v && *v && std::string(v) != "0";
  2393. }
  2394. std::string unique_unresolvable_host(int n) {
  2395. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2396. // glibc still asks the configured nameserver — which is exactly the path
  2397. // we want to exercise. A unique label per call avoids the resolver cache.
  2398. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2399. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2400. std::to_string(n) + ".invalid";
  2401. }
  2402. } // namespace
  2403. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2404. if (!should_run_issue_2431_tests()) {
  2405. GTEST_SKIP()
  2406. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2407. }
  2408. for (int i = 0; i < 8; ++i) {
  2409. struct addrinfo hints;
  2410. memset(&hints, 0, sizeof(hints));
  2411. hints.ai_family = AF_UNSPEC;
  2412. hints.ai_socktype = SOCK_STREAM;
  2413. auto host = unique_unresolvable_host(i);
  2414. struct addrinfo *result = nullptr;
  2415. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2416. &result, /*timeout_sec=*/1);
  2417. if (rc == 0 && result) { freeaddrinfo(result); }
  2418. }
  2419. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2420. // stack region they still believe holds their gaicb.
  2421. std::this_thread::sleep_for(std::chrono::seconds(3));
  2422. }
  2423. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2424. if (!should_run_issue_2431_tests()) {
  2425. GTEST_SKIP()
  2426. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2427. }
  2428. std::atomic<bool> stop{false};
  2429. std::vector<std::thread> threads;
  2430. for (int t = 0; t < 8; ++t) {
  2431. threads.emplace_back([t, &stop] {
  2432. int i = 0;
  2433. while (!stop.load(std::memory_order_relaxed)) {
  2434. struct addrinfo hints;
  2435. memset(&hints, 0, sizeof(hints));
  2436. hints.ai_family = AF_UNSPEC;
  2437. hints.ai_socktype = SOCK_STREAM;
  2438. auto host = unique_unresolvable_host(t * 100000 + i++);
  2439. struct addrinfo *result = nullptr;
  2440. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2441. &result, /*timeout_sec=*/1);
  2442. if (rc == 0 && result) { freeaddrinfo(result); }
  2443. }
  2444. });
  2445. }
  2446. std::this_thread::sleep_for(std::chrono::seconds(8));
  2447. stop.store(true, std::memory_order_relaxed);
  2448. for (auto &th : threads) {
  2449. th.join();
  2450. }
  2451. std::this_thread::sleep_for(std::chrono::seconds(3));
  2452. }
  2453. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2454. if (!should_run_issue_2431_tests()) {
  2455. GTEST_SKIP()
  2456. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2457. }
  2458. std::atomic<bool> stop{false};
  2459. std::vector<std::thread> threads;
  2460. for (int t = 0; t < 8; ++t) {
  2461. threads.emplace_back([t, &stop] {
  2462. int i = 0;
  2463. while (!stop.load(std::memory_order_relaxed)) {
  2464. auto host = unique_unresolvable_host(t * 100000 + i++);
  2465. Client cli(host, 80);
  2466. cli.set_connection_timeout(1, 0);
  2467. cli.set_read_timeout(1, 0);
  2468. cli.set_write_timeout(1, 0);
  2469. (void)cli.Get("/");
  2470. }
  2471. });
  2472. }
  2473. std::this_thread::sleep_for(std::chrono::seconds(8));
  2474. stop.store(true, std::memory_order_relaxed);
  2475. for (auto &th : threads) {
  2476. th.join();
  2477. }
  2478. std::this_thread::sleep_for(std::chrono::seconds(3));
  2479. }
  2480. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2481. TEST(ConnectionErrorTest, InvalidHost) {
  2482. auto host = "-abcde.com";
  2483. #ifdef CPPHTTPLIB_SSL_ENABLED
  2484. auto port = 443;
  2485. SSLClient cli(host, port);
  2486. #else
  2487. auto port = 80;
  2488. Client cli(host, port);
  2489. #endif
  2490. cli.set_connection_timeout(std::chrono::seconds(2));
  2491. auto res = cli.Get("/");
  2492. ASSERT_TRUE(!res);
  2493. EXPECT_EQ(Error::Connection, res.error());
  2494. }
  2495. TEST(ConnectionErrorTest, InvalidHost2) {
  2496. auto host = "httpcan.org/";
  2497. #ifdef CPPHTTPLIB_SSL_ENABLED
  2498. SSLClient cli(host);
  2499. #else
  2500. Client cli(host);
  2501. #endif
  2502. cli.set_connection_timeout(std::chrono::seconds(2));
  2503. auto res = cli.Get("/");
  2504. ASSERT_TRUE(!res);
  2505. EXPECT_EQ(Error::Connection, res.error());
  2506. }
  2507. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2508. auto host = "httpcan.org/";
  2509. #ifdef CPPHTTPLIB_SSL_ENABLED
  2510. SSLClient cli(host);
  2511. #else
  2512. Client cli(host);
  2513. #endif
  2514. cli.set_connection_timeout(std::chrono::seconds(2));
  2515. auto res = cli.Get("/");
  2516. ASSERT_TRUE(!res);
  2517. stringstream s;
  2518. s << "error code: " << res.error();
  2519. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2520. }
  2521. TEST(ConnectionErrorTest, InvalidPort) {
  2522. auto host = "localhost";
  2523. auto port = 44380;
  2524. #ifdef CPPHTTPLIB_SSL_ENABLED
  2525. SSLClient cli(host, port);
  2526. #else
  2527. Client cli(host, port);
  2528. #endif
  2529. cli.set_connection_timeout(std::chrono::seconds(2));
  2530. auto res = cli.Get("/");
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_TRUE(Error::Connection == res.error() ||
  2533. Error::ConnectionTimeout == res.error());
  2534. }
  2535. TEST(ConnectionErrorTest, Timeout_Online) {
  2536. auto host = "google.com";
  2537. #ifdef CPPHTTPLIB_SSL_ENABLED
  2538. auto port = 44380;
  2539. SSLClient cli(host, port);
  2540. #else
  2541. auto port = 8080;
  2542. Client cli(host, port);
  2543. #endif
  2544. cli.set_connection_timeout(std::chrono::seconds(2));
  2545. // only probe one address type so that the error reason
  2546. // correlates to the timed-out IPv4, not the unsupported
  2547. // IPv6 connection attempt
  2548. cli.set_address_family(AF_INET);
  2549. auto res = cli.Get("/");
  2550. ASSERT_TRUE(!res);
  2551. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2552. }
  2553. TEST(CancelTest, NoCancel_Online) {
  2554. auto host = "httpbingo.org";
  2555. auto path = std::string{"/range/32"};
  2556. #ifdef CPPHTTPLIB_SSL_ENABLED
  2557. auto port = 443;
  2558. SSLClient cli(host, port);
  2559. #else
  2560. auto port = 80;
  2561. Client cli(host, port);
  2562. #endif
  2563. cli.set_connection_timeout(std::chrono::seconds(5));
  2564. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2566. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2567. EXPECT_EQ(StatusCode::OK_200, res->status);
  2568. }
  2569. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2570. // Use /bytes with a large payload so that the DownloadProgress callback
  2571. // (which only fires for Content-Length responses) is invoked before the
  2572. // entire body is received, giving cancellation a chance to fire.
  2573. auto host = "httpbingo.org";
  2574. auto path = std::string{"/bytes/524288"};
  2575. #ifdef CPPHTTPLIB_SSL_ENABLED
  2576. auto port = 443;
  2577. SSLClient cli(host, port);
  2578. #else
  2579. auto port = 80;
  2580. Client cli(host, port);
  2581. #endif
  2582. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2583. cli.set_connection_timeout(std::chrono::seconds(5));
  2584. ASSERT_TRUE(!res);
  2585. EXPECT_EQ(Error::Canceled, res.error());
  2586. }
  2587. TEST(CancelTest, WithCancelLargePayload_Online) {
  2588. auto host = "httpbingo.org";
  2589. auto path = std::string{"/bytes/524288"};
  2590. #ifdef CPPHTTPLIB_SSL_ENABLED
  2591. auto port = 443;
  2592. SSLClient cli(host, port);
  2593. #else
  2594. auto port = 80;
  2595. Client cli(host, port);
  2596. #endif
  2597. cli.set_connection_timeout(std::chrono::seconds(5));
  2598. uint32_t count = 0;
  2599. auto res =
  2600. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2601. ASSERT_TRUE(!res);
  2602. EXPECT_EQ(Error::Canceled, res.error());
  2603. }
  2604. TEST(CancelTest, NoCancelPost) {
  2605. Server svr;
  2606. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2607. res.set_content("Hello World!", "text/plain");
  2608. });
  2609. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2610. auto se = detail::scope_exit([&] {
  2611. svr.stop();
  2612. thread.join();
  2613. ASSERT_FALSE(svr.is_running());
  2614. });
  2615. svr.wait_until_ready();
  2616. Client cli(HOST, PORT);
  2617. cli.set_connection_timeout(std::chrono::seconds(5));
  2618. auto res =
  2619. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2620. "application/json", [](uint64_t, uint64_t) { return true; });
  2621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2622. EXPECT_EQ("Hello World!", res->body);
  2623. EXPECT_EQ(StatusCode::OK_200, res->status);
  2624. }
  2625. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2626. Server svr;
  2627. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2628. res.set_content("Hello World!", "text/plain");
  2629. });
  2630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2631. auto se = detail::scope_exit([&] {
  2632. svr.stop();
  2633. thread.join();
  2634. ASSERT_FALSE(svr.is_running());
  2635. });
  2636. svr.wait_until_ready();
  2637. Client cli(HOST, PORT);
  2638. cli.set_connection_timeout(std::chrono::seconds(5));
  2639. auto res =
  2640. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2641. "application/json", [](uint64_t, uint64_t) { return false; });
  2642. ASSERT_TRUE(!res);
  2643. EXPECT_EQ(Error::Canceled, res.error());
  2644. }
  2645. TEST(CancelTest, WithCancelLargePayloadPost) {
  2646. Server svr;
  2647. svr.set_payload_max_length(200 * 1024 * 1024);
  2648. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2649. res.set_content(LARGE_DATA, "text/plain");
  2650. });
  2651. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2652. auto se = detail::scope_exit([&] {
  2653. svr.stop();
  2654. thread.join();
  2655. ASSERT_FALSE(svr.is_running());
  2656. });
  2657. svr.wait_until_ready();
  2658. Client cli(HOST, PORT);
  2659. cli.set_payload_max_length(200 * 1024 * 1024);
  2660. cli.set_connection_timeout(std::chrono::seconds(5));
  2661. auto res =
  2662. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2663. "application/json", [](uint64_t, uint64_t) { return false; });
  2664. ASSERT_TRUE(!res);
  2665. EXPECT_EQ(Error::Canceled, res.error());
  2666. }
  2667. TEST(CancelTest, NoCancelPut) {
  2668. Server svr;
  2669. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2670. res.set_content("Hello World!", "text/plain");
  2671. });
  2672. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2673. auto se = detail::scope_exit([&] {
  2674. svr.stop();
  2675. thread.join();
  2676. ASSERT_FALSE(svr.is_running());
  2677. });
  2678. svr.wait_until_ready();
  2679. Client cli(HOST, PORT);
  2680. cli.set_connection_timeout(std::chrono::seconds(5));
  2681. auto res =
  2682. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2683. "application/json", [](uint64_t, uint64_t) { return true; });
  2684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2685. EXPECT_EQ("Hello World!", res->body);
  2686. EXPECT_EQ(StatusCode::OK_200, res->status);
  2687. }
  2688. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2689. Server svr;
  2690. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2691. res.set_content("Hello World!", "text/plain");
  2692. });
  2693. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2694. auto se = detail::scope_exit([&] {
  2695. svr.stop();
  2696. thread.join();
  2697. ASSERT_FALSE(svr.is_running());
  2698. });
  2699. svr.wait_until_ready();
  2700. Client cli(HOST, PORT);
  2701. cli.set_connection_timeout(std::chrono::seconds(5));
  2702. auto res =
  2703. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2704. "application/json", [](uint64_t, uint64_t) { return false; });
  2705. ASSERT_TRUE(!res);
  2706. EXPECT_EQ(Error::Canceled, res.error());
  2707. }
  2708. TEST(CancelTest, WithCancelLargePayloadPut) {
  2709. Server svr;
  2710. svr.set_payload_max_length(200 * 1024 * 1024);
  2711. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2712. res.set_content(LARGE_DATA, "text/plain");
  2713. });
  2714. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2715. auto se = detail::scope_exit([&] {
  2716. svr.stop();
  2717. thread.join();
  2718. ASSERT_FALSE(svr.is_running());
  2719. });
  2720. svr.wait_until_ready();
  2721. Client cli(HOST, PORT);
  2722. cli.set_payload_max_length(200 * 1024 * 1024);
  2723. cli.set_connection_timeout(std::chrono::seconds(5));
  2724. auto res =
  2725. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2726. "application/json", [](uint64_t, uint64_t) { return false; });
  2727. ASSERT_TRUE(!res);
  2728. EXPECT_EQ(Error::Canceled, res.error());
  2729. }
  2730. TEST(CancelTest, NoCancelPatch) {
  2731. Server svr;
  2732. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2733. res.set_content("Hello World!", "text/plain");
  2734. });
  2735. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2736. auto se = detail::scope_exit([&] {
  2737. svr.stop();
  2738. thread.join();
  2739. ASSERT_FALSE(svr.is_running());
  2740. });
  2741. svr.wait_until_ready();
  2742. Client cli(HOST, PORT);
  2743. cli.set_connection_timeout(std::chrono::seconds(5));
  2744. auto res =
  2745. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2746. "application/json", [](uint64_t, uint64_t) { return true; });
  2747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2748. EXPECT_EQ("Hello World!", res->body);
  2749. EXPECT_EQ(StatusCode::OK_200, res->status);
  2750. }
  2751. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2752. Server svr;
  2753. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2754. res.set_content("Hello World!", "text/plain");
  2755. });
  2756. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2757. auto se = detail::scope_exit([&] {
  2758. svr.stop();
  2759. thread.join();
  2760. ASSERT_FALSE(svr.is_running());
  2761. });
  2762. svr.wait_until_ready();
  2763. Client cli(HOST, PORT);
  2764. cli.set_connection_timeout(std::chrono::seconds(5));
  2765. auto res =
  2766. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2767. "application/json", [](uint64_t, uint64_t) { return false; });
  2768. ASSERT_TRUE(!res);
  2769. EXPECT_EQ(Error::Canceled, res.error());
  2770. }
  2771. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2772. Server svr;
  2773. svr.set_payload_max_length(200 * 1024 * 1024);
  2774. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2775. res.set_content(LARGE_DATA, "text/plain");
  2776. });
  2777. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2778. auto se = detail::scope_exit([&] {
  2779. svr.stop();
  2780. thread.join();
  2781. ASSERT_FALSE(svr.is_running());
  2782. });
  2783. svr.wait_until_ready();
  2784. Client cli(HOST, PORT);
  2785. cli.set_payload_max_length(200 * 1024 * 1024);
  2786. cli.set_connection_timeout(std::chrono::seconds(5));
  2787. auto res =
  2788. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2789. "application/json", [](uint64_t, uint64_t) { return false; });
  2790. ASSERT_TRUE(!res);
  2791. EXPECT_EQ(Error::Canceled, res.error());
  2792. }
  2793. TEST(CancelTest, NoCancelDelete) {
  2794. Server svr;
  2795. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2796. res.set_content("Hello World!", "text/plain");
  2797. });
  2798. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2799. auto se = detail::scope_exit([&] {
  2800. svr.stop();
  2801. thread.join();
  2802. ASSERT_FALSE(svr.is_running());
  2803. });
  2804. svr.wait_until_ready();
  2805. Client cli(HOST, PORT);
  2806. cli.set_connection_timeout(std::chrono::seconds(5));
  2807. auto res =
  2808. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2809. "application/json", [](uint64_t, uint64_t) { return true; });
  2810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2811. EXPECT_EQ("Hello World!", res->body);
  2812. EXPECT_EQ(StatusCode::OK_200, res->status);
  2813. }
  2814. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2815. Server svr;
  2816. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2817. res.set_content("Hello World!", "text/plain");
  2818. });
  2819. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2820. auto se = detail::scope_exit([&] {
  2821. svr.stop();
  2822. thread.join();
  2823. ASSERT_FALSE(svr.is_running());
  2824. });
  2825. svr.wait_until_ready();
  2826. Client cli(HOST, PORT);
  2827. cli.set_connection_timeout(std::chrono::seconds(5));
  2828. auto res =
  2829. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2830. "application/json", [](uint64_t, uint64_t) { return false; });
  2831. ASSERT_TRUE(!res);
  2832. EXPECT_EQ(Error::Canceled, res.error());
  2833. }
  2834. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2835. Server svr;
  2836. svr.set_payload_max_length(200 * 1024 * 1024);
  2837. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2838. res.set_content(LARGE_DATA, "text/plain");
  2839. });
  2840. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2841. auto se = detail::scope_exit([&] {
  2842. svr.stop();
  2843. thread.join();
  2844. ASSERT_FALSE(svr.is_running());
  2845. });
  2846. svr.wait_until_ready();
  2847. Client cli(HOST, PORT);
  2848. cli.set_payload_max_length(200 * 1024 * 1024);
  2849. cli.set_connection_timeout(std::chrono::seconds(5));
  2850. auto res =
  2851. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2852. "application/json", [](uint64_t, uint64_t) { return false; });
  2853. ASSERT_TRUE(!res);
  2854. EXPECT_EQ(Error::Canceled, res.error());
  2855. }
  2856. static std::string remove_whitespace(const std::string &input) {
  2857. std::string output;
  2858. output.reserve(input.size());
  2859. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2860. [](unsigned char c) { return !std::isspace(c); });
  2861. return output;
  2862. }
  2863. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2864. auto host = "httpbingo.org";
  2865. auto path = std::string{"/basic-auth/hello/world"};
  2866. #ifdef CPPHTTPLIB_SSL_ENABLED
  2867. auto port = 443;
  2868. SSLClient cli(host, port);
  2869. #else
  2870. auto port = 80;
  2871. Client cli(host, port);
  2872. #endif
  2873. {
  2874. auto res = cli.Get(path);
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2877. }
  2878. {
  2879. auto res = cli.Get(
  2880. path, Headers{make_basic_authentication_header("hello", "world")});
  2881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2882. auto body = remove_whitespace(res->body);
  2883. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2884. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2885. EXPECT_EQ(StatusCode::OK_200, res->status);
  2886. }
  2887. {
  2888. cli.set_basic_auth("hello", "world");
  2889. auto res = cli.Get(path);
  2890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2891. auto body = remove_whitespace(res->body);
  2892. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2893. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2894. EXPECT_EQ(StatusCode::OK_200, res->status);
  2895. }
  2896. {
  2897. cli.set_basic_auth("hello", "bad");
  2898. auto res = cli.Get(path);
  2899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2900. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2901. }
  2902. {
  2903. cli.set_basic_auth("bad", "world");
  2904. auto res = cli.Get(path);
  2905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2906. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2907. }
  2908. }
  2909. #ifdef CPPHTTPLIB_SSL_ENABLED
  2910. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2911. auto host = "httpbingo.org";
  2912. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2913. auto paths = std::vector<std::string>{
  2914. "/digest-auth/auth/hello/world/MD5",
  2915. "/digest-auth/auth/hello/world/SHA-256",
  2916. };
  2917. auto port = 443;
  2918. SSLClient cli(host, port);
  2919. {
  2920. auto res = cli.Get(unauth_path);
  2921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2922. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2923. }
  2924. {
  2925. cli.set_digest_auth("hello", "world");
  2926. for (const auto &path : paths) {
  2927. auto res = cli.Get(path.c_str());
  2928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2929. auto body = remove_whitespace(res->body);
  2930. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2931. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2932. EXPECT_EQ(StatusCode::OK_200, res->status);
  2933. }
  2934. cli.set_digest_auth("hello", "bad");
  2935. for (const auto &path : paths) {
  2936. auto res = cli.Get(path.c_str());
  2937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2938. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2939. }
  2940. }
  2941. }
  2942. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2943. // comma-separated list of challenges, and each challenge may itself carry a
  2944. // comma-separated auth-param list, so a server can legally offer Basic
  2945. // before Digest, either as two field lines or packed into one. Runs one 401
  2946. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2947. // value() joins them in receipt order) and checks that the retry carries a
  2948. // well-formed Digest Authorization header naming expected_realm.
  2949. static void
  2950. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2951. const std::string &expected_realm) {
  2952. std::atomic<int> hits{0};
  2953. Server svr;
  2954. svr.Get("/x", [&](const Request &req, Response &res) {
  2955. if (++hits == 1) {
  2956. res.status = StatusCode::Unauthorized_401;
  2957. for (const auto &challenge : challenges) {
  2958. res.set_header("WWW-Authenticate", challenge);
  2959. }
  2960. } else {
  2961. auto authorization = req.get_header_value("Authorization");
  2962. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2963. EXPECT_NE(std::string::npos,
  2964. authorization.find("realm=\"" + expected_realm + "\""));
  2965. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2966. res.set_content("ok", "text/plain");
  2967. }
  2968. });
  2969. auto port = svr.bind_to_any_port(HOST);
  2970. std::thread t([&]() { svr.listen_after_bind(); });
  2971. auto se = detail::scope_exit([&] {
  2972. svr.stop();
  2973. t.join();
  2974. });
  2975. svr.wait_until_ready();
  2976. Client cli(HOST, port);
  2977. cli.set_digest_auth("hello", "world");
  2978. auto res = cli.Get("/x");
  2979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2980. EXPECT_EQ(2, hits.load());
  2981. }
  2982. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2983. static const char *kDigestChallenge =
  2984. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2985. "algorithm=MD5";
  2986. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2987. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2988. "testrealm");
  2989. }
  2990. // Same challenge list with the schemes in the opposite order, to make sure
  2991. // the fix above didn't just special-case "Basic first".
  2992. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2993. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2994. "testrealm");
  2995. }
  2996. // A comma inside a quoted auth-param value must not be mistaken for the
  2997. // separator between two challenges (or two auth-params).
  2998. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2999. run_digest_challenge_list_test(
  3000. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3001. "algorithm=MD5"},
  3002. "test,realm");
  3003. }
  3004. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3005. // the params and leaves out the fragment.
  3006. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3007. Server svr;
  3008. std::string uri, target;
  3009. svr.Get("/a b", [&](const Request &req, Response &res) {
  3010. auto auth = req.get_header_value("Authorization");
  3011. if (auth.empty()) {
  3012. res.status = StatusCode::Unauthorized_401;
  3013. res.set_header("WWW-Authenticate",
  3014. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3015. return;
  3016. }
  3017. auto b = auth.find("uri=\"") + 5;
  3018. uri = auth.substr(b, auth.find('"', b) - b);
  3019. target = req.target;
  3020. });
  3021. auto port = svr.bind_to_any_port(HOST);
  3022. std::thread t([&]() { svr.listen_after_bind(); });
  3023. auto se = detail::scope_exit([&] {
  3024. svr.stop();
  3025. t.join();
  3026. });
  3027. svr.wait_until_ready();
  3028. Client cli(HOST, port);
  3029. cli.set_digest_auth("hello", "world");
  3030. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3032. EXPECT_EQ("/a%20b?x=1", target);
  3033. EXPECT_EQ(target, uri);
  3034. }
  3035. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3036. // make_digest_authentication_header() dereferences both unconditionally, so
  3037. // a server sending a challenge missing either one must not be treated as
  3038. // usable -- doing so used to crash the client with std::out_of_range.
  3039. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3040. Server svr;
  3041. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3042. res.status = StatusCode::Unauthorized_401;
  3043. res.set_header("WWW-Authenticate", challenge);
  3044. });
  3045. auto port = svr.bind_to_any_port(HOST);
  3046. std::thread t([&]() { svr.listen_after_bind(); });
  3047. auto se = detail::scope_exit([&] {
  3048. svr.stop();
  3049. t.join();
  3050. });
  3051. svr.wait_until_ready();
  3052. Client cli(HOST, port);
  3053. cli.set_digest_auth("hello", "world");
  3054. auto res = cli.Get("/x");
  3055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3056. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3057. }
  3058. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3059. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3060. }
  3061. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3062. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3063. }
  3064. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3065. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3066. }
  3067. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3068. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3069. // when storing the values, so the header builder has to re-escape them (and
  3070. // keep algorithm a bare token); otherwise the value breaks out of its
  3071. // quoted-string and injects extra auth-params into the client's Authorization.
  3072. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3073. std::atomic<int> hits{0};
  3074. std::string authorization;
  3075. Server svr;
  3076. svr.Get("/x", [&](const Request &req, Response &res) {
  3077. if (++hits == 1) {
  3078. res.status = StatusCode::Unauthorized_401;
  3079. // On the wire the quotes embedded in the values are backslash-escaped.
  3080. res.set_header("WWW-Authenticate",
  3081. "Digest realm=\"testrealm\", "
  3082. "nonce=\"n\\\"; injected=\\\"x\", "
  3083. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3084. } else {
  3085. authorization = req.get_header_value("Authorization");
  3086. res.set_content("ok", "text/plain");
  3087. }
  3088. });
  3089. auto port = svr.bind_to_any_port(HOST);
  3090. std::thread t([&]() { svr.listen_after_bind(); });
  3091. auto se = detail::scope_exit([&] {
  3092. svr.stop();
  3093. t.join();
  3094. });
  3095. svr.wait_until_ready();
  3096. Client cli(HOST, port);
  3097. cli.set_digest_auth("hello", "world");
  3098. auto res = cli.Get("/x");
  3099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3100. EXPECT_EQ(2, hits.load());
  3101. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3102. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3103. // inside its quoted-string rather than starting an "injected" auth-param.
  3104. EXPECT_NE(std::string::npos,
  3105. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3106. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3107. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3108. }
  3109. #endif
  3110. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3111. auto host = "google.com";
  3112. auto another_host = "example.com";
  3113. auto wrong_ip = "0.0.0.0";
  3114. #ifdef CPPHTTPLIB_SSL_ENABLED
  3115. SSLClient cli(host);
  3116. #else
  3117. Client cli(host);
  3118. #endif
  3119. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3120. auto res = cli.Get("/");
  3121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3122. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3123. }
  3124. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3125. auto host = "google.com";
  3126. auto wrong_ip = "0.0.0.0";
  3127. #ifdef CPPHTTPLIB_SSL_ENABLED
  3128. SSLClient cli(host);
  3129. #else
  3130. Client cli(host);
  3131. #endif
  3132. cli.set_hostname_addr_map({{host, wrong_ip}});
  3133. auto res = cli.Get("/");
  3134. ASSERT_TRUE(!res);
  3135. EXPECT_EQ(Error::Connection, res.error());
  3136. }
  3137. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3138. // A mapped value that is not an IP literal must be resolved. "localhost"
  3139. // resolves from the hosts file, so this test needs no external DNS.
  3140. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3141. auto host = "target.invalid";
  3142. Server svr;
  3143. std::string received_host;
  3144. svr.Get("/hi", [&](const Request &req, Response &res) {
  3145. received_host = req.get_header_value("Host");
  3146. res.set_content("Hello World!", "text/plain");
  3147. });
  3148. auto port = svr.bind_to_any_port(HOST);
  3149. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3150. auto se = detail::scope_exit([&] {
  3151. svr.stop();
  3152. thread.join();
  3153. ASSERT_FALSE(svr.is_running());
  3154. });
  3155. svr.wait_until_ready();
  3156. Client cli(host, port);
  3157. cli.set_hostname_addr_map({{host, HOST}});
  3158. auto res = cli.Get("/hi");
  3159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3160. EXPECT_EQ(StatusCode::OK_200, res->status);
  3161. // The mapping only redirects the connection; the identity stays host_.
  3162. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3163. }
  3164. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3165. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3166. auto host = "target.invalid";
  3167. Server svr;
  3168. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3169. res.set_content("Hello World!", "text/plain");
  3170. });
  3171. auto port = svr.bind_to_any_port("127.0.0.1");
  3172. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3173. auto se = detail::scope_exit([&] {
  3174. svr.stop();
  3175. thread.join();
  3176. ASSERT_FALSE(svr.is_running());
  3177. });
  3178. svr.wait_until_ready();
  3179. Client cli(host, port);
  3180. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3181. auto res = cli.Get("/hi");
  3182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3183. EXPECT_EQ(StatusCode::OK_200, res->status);
  3184. }
  3185. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3186. // An empty mapped value must leave host_ as the connection target. Without
  3187. // that guard the empty value would become the host argument, getaddrinfo
  3188. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3189. // loopback - silently connecting somewhere the caller never asked for.
  3190. // The server listens on loopback, so such a fallback would succeed and is
  3191. // therefore observable as a failure of this test.
  3192. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3193. Server svr;
  3194. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3195. res.set_content("Hello World!", "text/plain");
  3196. });
  3197. auto port = svr.bind_to_any_port(HOST);
  3198. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3199. auto se = detail::scope_exit([&] {
  3200. svr.stop();
  3201. thread.join();
  3202. ASSERT_FALSE(svr.is_running());
  3203. });
  3204. svr.wait_until_ready();
  3205. Client cli(blackhole, port);
  3206. cli.set_hostname_addr_map({{blackhole, ""}});
  3207. cli.set_connection_timeout(1);
  3208. auto res = cli.Get("/hi");
  3209. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3210. }
  3211. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3212. auto host = "httpbingo.org";
  3213. auto path = std::string{"/absolute-redirect/3"};
  3214. #ifdef CPPHTTPLIB_SSL_ENABLED
  3215. SSLClient cli(host);
  3216. #else
  3217. Client cli(host);
  3218. #endif
  3219. cli.set_follow_location(true);
  3220. auto res = cli.Get(path);
  3221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3222. EXPECT_EQ(StatusCode::OK_200, res->status);
  3223. }
  3224. TEST(RedirectTest, Redirect_Online) {
  3225. auto host = "httpbingo.org";
  3226. auto path = std::string{"/redirect/3"};
  3227. #ifdef CPPHTTPLIB_SSL_ENABLED
  3228. SSLClient cli(host);
  3229. #else
  3230. Client cli(host);
  3231. #endif
  3232. cli.set_follow_location(true);
  3233. auto res = cli.Get(path);
  3234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3235. EXPECT_EQ(StatusCode::OK_200, res->status);
  3236. }
  3237. TEST(RelativeRedirectTest, Redirect_Online) {
  3238. auto host = "httpbingo.org";
  3239. auto path = std::string{"/relative-redirect/3"};
  3240. #ifdef CPPHTTPLIB_SSL_ENABLED
  3241. SSLClient cli(host);
  3242. #else
  3243. Client cli(host);
  3244. #endif
  3245. cli.set_follow_location(true);
  3246. auto res = cli.Get(path);
  3247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3248. EXPECT_EQ(StatusCode::OK_200, res->status);
  3249. }
  3250. TEST(TooManyRedirectTest, Redirect_Online) {
  3251. auto host = "httpbingo.org";
  3252. auto path = std::string{"/redirect/21"};
  3253. #ifdef CPPHTTPLIB_SSL_ENABLED
  3254. SSLClient cli(host);
  3255. #else
  3256. Client cli(host);
  3257. #endif
  3258. cli.set_follow_location(true);
  3259. auto res = cli.Get(path);
  3260. ASSERT_TRUE(!res);
  3261. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3262. }
  3263. #ifdef CPPHTTPLIB_SSL_ENABLED
  3264. TEST(YahooRedirectTest, Redirect_Online) {
  3265. Client cli("yahoo.com");
  3266. auto res = cli.Get("/");
  3267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3268. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3269. cli.set_follow_location(true);
  3270. res = cli.Get("/");
  3271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3272. EXPECT_EQ(StatusCode::OK_200, res->status);
  3273. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3274. }
  3275. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3276. #define REDIR_HOST "httpbingo.org"
  3277. #define REDIR_PATH "/redirect-to"
  3278. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3279. SSLClient cli(REDIR_HOST);
  3280. cli.set_follow_location(true);
  3281. auto res =
  3282. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3284. EXPECT_EQ(StatusCode::OK_200, res->status);
  3285. }
  3286. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3287. SSLClient cli(REDIR_HOST);
  3288. cli.set_follow_location(true);
  3289. Params params;
  3290. params.emplace("url", "http://example.com");
  3291. params.emplace("status_code", "302");
  3292. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3294. EXPECT_EQ(StatusCode::OK_200, res->status);
  3295. }
  3296. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3297. SSLClient cli(REDIR_HOST);
  3298. cli.set_follow_location(true);
  3299. Params params;
  3300. params.emplace("url", "http://example.com");
  3301. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3303. EXPECT_EQ(StatusCode::OK_200, res->status);
  3304. }
  3305. TEST(UrlWithSpace, Redirect_Online) {
  3306. SSLClient cli("edge.forgecdn.net");
  3307. cli.set_follow_location(true);
  3308. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3310. EXPECT_EQ(StatusCode::OK_200, res->status);
  3311. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3312. }
  3313. #endif
  3314. #if !defined(_WIN32) && !defined(_WIN64)
  3315. TEST(ReceiveSignals, Signal) {
  3316. auto setupSignalHandlers = []() {
  3317. struct sigaction act;
  3318. sigemptyset(&act.sa_mask);
  3319. act.sa_flags = SA_SIGINFO;
  3320. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3321. switch (sig) {
  3322. case SIGINT:
  3323. default: break;
  3324. }
  3325. };
  3326. ::sigaction(SIGINT, &act, nullptr);
  3327. };
  3328. Server svr;
  3329. int port = 0;
  3330. auto thread = std::thread([&]() {
  3331. setupSignalHandlers();
  3332. port = svr.bind_to_any_port(HOST);
  3333. svr.listen_after_bind();
  3334. });
  3335. auto se = detail::scope_exit([&] {
  3336. svr.stop();
  3337. thread.join();
  3338. ASSERT_FALSE(svr.is_running());
  3339. });
  3340. svr.wait_until_ready();
  3341. ASSERT_TRUE(svr.is_running());
  3342. pthread_kill(thread.native_handle(), SIGINT);
  3343. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3344. ASSERT_TRUE(svr.is_running());
  3345. }
  3346. #endif
  3347. TEST(RedirectToDifferentPort, Redirect) {
  3348. Server svr1;
  3349. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3350. res.set_content("Hello World!", "text/plain");
  3351. });
  3352. int svr1_port = 0;
  3353. auto thread1 = std::thread([&]() {
  3354. svr1_port = svr1.bind_to_any_port(HOST);
  3355. svr1.listen_after_bind();
  3356. });
  3357. Server svr2;
  3358. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3359. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3360. });
  3361. int svr2_port = 0;
  3362. auto thread2 = std::thread([&]() {
  3363. svr2_port = svr2.bind_to_any_port(HOST);
  3364. svr2.listen_after_bind();
  3365. });
  3366. auto se = detail::scope_exit([&] {
  3367. svr2.stop();
  3368. thread2.join();
  3369. svr1.stop();
  3370. thread1.join();
  3371. ASSERT_FALSE(svr2.is_running());
  3372. ASSERT_FALSE(svr1.is_running());
  3373. });
  3374. svr1.wait_until_ready();
  3375. svr2.wait_until_ready();
  3376. Client cli("localhost", svr2_port);
  3377. cli.set_follow_location(true);
  3378. auto res = cli.Get("/2");
  3379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3380. EXPECT_EQ(StatusCode::OK_200, res->status);
  3381. EXPECT_EQ("Hello World!", res->body);
  3382. }
  3383. // GET /redir on one server redirects to /target on another port, so the
  3384. // client follows it with a new client.
  3385. static Result
  3386. GetThroughRedirectToDifferentPort(Server::Handler target,
  3387. const std::function<void(Client &)> &setup,
  3388. const Headers &headers = Headers()) {
  3389. Server target_svr;
  3390. target_svr.Get("/target", target);
  3391. int target_port = 0;
  3392. auto target_thread = std::thread([&]() {
  3393. target_port = target_svr.bind_to_any_port(HOST);
  3394. target_svr.listen_after_bind();
  3395. });
  3396. Server origin_svr;
  3397. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3398. res.set_redirect(
  3399. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3400. });
  3401. int origin_port = 0;
  3402. auto origin_thread = std::thread([&]() {
  3403. origin_port = origin_svr.bind_to_any_port(HOST);
  3404. origin_svr.listen_after_bind();
  3405. });
  3406. auto se = detail::scope_exit([&] {
  3407. origin_svr.stop();
  3408. origin_thread.join();
  3409. target_svr.stop();
  3410. target_thread.join();
  3411. });
  3412. target_svr.wait_until_ready();
  3413. origin_svr.wait_until_ready();
  3414. Client cli("localhost", origin_port);
  3415. cli.set_follow_location(true);
  3416. setup(cli);
  3417. return cli.Get("/redir", headers);
  3418. }
  3419. static void
  3420. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3421. std::string captured_authorization;
  3422. auto result = GetThroughRedirectToDifferentPort(
  3423. [&](const Request &req, Response &res) {
  3424. captured_authorization = req.get_header_value("Authorization");
  3425. res.set_content("OK", "text/plain");
  3426. },
  3427. set_auth);
  3428. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3429. EXPECT_EQ(StatusCode::OK_200, result->status);
  3430. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3431. EXPECT_TRUE(captured_authorization.empty());
  3432. }
  3433. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3434. TestDoNotForwardCredentialsOnRedirect(
  3435. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3436. }
  3437. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3438. TestDoNotForwardCredentialsOnRedirect(
  3439. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3440. }
  3441. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3442. std::string captured_cookie;
  3443. auto result = GetThroughRedirectToDifferentPort(
  3444. [&](const Request &req, Response &res) {
  3445. captured_cookie = req.get_header_value("Cookie");
  3446. res.set_content("OK", "text/plain");
  3447. },
  3448. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3449. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3450. EXPECT_EQ(StatusCode::OK_200, result->status);
  3451. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3452. EXPECT_TRUE(captured_cookie.empty());
  3453. }
  3454. TEST(RedirectToSamePort, ForwardCookie) {
  3455. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3456. // header so that ordinary session flows keep working.
  3457. Server svr;
  3458. std::string captured_cookie;
  3459. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3460. res.set_redirect("/target", 302);
  3461. });
  3462. svr.Get("/target", [&](const Request &req, Response &res) {
  3463. captured_cookie = req.get_header_value("Cookie");
  3464. res.set_content("OK", "text/plain");
  3465. });
  3466. auto port = svr.bind_to_any_port(HOST);
  3467. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3468. auto se = detail::scope_exit([&] {
  3469. svr.stop();
  3470. thread.join();
  3471. ASSERT_FALSE(svr.is_running());
  3472. });
  3473. svr.wait_until_ready();
  3474. Client cli(HOST, port);
  3475. cli.set_follow_location(true);
  3476. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3477. auto res = cli.Get("/redir", headers);
  3478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3479. EXPECT_EQ(StatusCode::OK_200, res->status);
  3480. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3481. }
  3482. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3483. std::string authorization;
  3484. std::string trace_id;
  3485. auto result = GetThroughRedirectToDifferentPort(
  3486. [&](const Request &req, Response &res) {
  3487. authorization = req.get_header_value("Authorization");
  3488. trace_id = req.get_header_value("X-Trace-Id");
  3489. res.set_content("OK", "text/plain");
  3490. },
  3491. [](Client &cli) {
  3492. cli.set_default_headers(
  3493. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3494. });
  3495. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3496. EXPECT_EQ(StatusCode::OK_200, result->status);
  3497. // Like a header given with the request, a default one goes along unless it
  3498. // carries credentials (RFC 9110 15.4).
  3499. EXPECT_TRUE(authorization.empty());
  3500. EXPECT_EQ("42", trace_id);
  3501. }
  3502. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3503. auto result = GetThroughRedirectToDifferentPort(
  3504. [](const Request &, Response &res) {
  3505. res.set_content(std::string(2048, 'x'), "text/plain");
  3506. },
  3507. [](Client &cli) { cli.set_payload_max_length(1024); });
  3508. EXPECT_FALSE(result);
  3509. }
  3510. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3511. auto result = GetThroughRedirectToDifferentPort(
  3512. [](const Request &req, Response &res) {
  3513. // Answer after a second, or once the client gives up.
  3514. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3515. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3516. }
  3517. res.set_content("late", "text/plain");
  3518. },
  3519. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3520. ASSERT_FALSE(result);
  3521. EXPECT_EQ(Error::Read, result.error());
  3522. }
  3523. #ifdef CPPHTTPLIB_SSL_ENABLED
  3524. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3525. auto result = GetThroughRedirectToDifferentPort(
  3526. [](const Request &, Response &res) {
  3527. res.status = StatusCode::Unauthorized_401;
  3528. res.set_header("WWW-Authenticate",
  3529. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3530. },
  3531. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3532. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3533. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3534. }
  3535. #endif
  3536. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3537. Server svr;
  3538. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3539. // Port number that overflows int — should not crash
  3540. res.set_redirect("http://localhost:99999999999999999999/target");
  3541. });
  3542. auto port = svr.bind_to_any_port(HOST);
  3543. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3544. auto se = detail::scope_exit([&] {
  3545. svr.stop();
  3546. thread.join();
  3547. ASSERT_FALSE(svr.is_running());
  3548. });
  3549. svr.wait_until_ready();
  3550. Client cli(HOST, port);
  3551. cli.set_follow_location(true);
  3552. auto res = cli.Get("/redir");
  3553. // Should fail gracefully, not crash (no valid response due to bad port)
  3554. EXPECT_FALSE(res);
  3555. }
  3556. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3557. Server svr;
  3558. auto port = svr.bind_to_any_port(HOST);
  3559. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3560. // The server's own port followed by junk must not be followed
  3561. res.set_redirect("http://" + std::string(HOST) + ":" +
  3562. std::to_string(port) + "junk/target");
  3563. });
  3564. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3565. res.set_content("target", "text/plain");
  3566. });
  3567. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3568. auto se = detail::scope_exit([&] {
  3569. svr.stop();
  3570. thread.join();
  3571. ASSERT_FALSE(svr.is_running());
  3572. });
  3573. svr.wait_until_ready();
  3574. Client cli(HOST, port);
  3575. cli.set_follow_location(true);
  3576. auto res = cli.Get("/redir");
  3577. EXPECT_FALSE(res);
  3578. }
  3579. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3580. Server svr;
  3581. std::atomic<bool> followed{false};
  3582. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3583. res.status = StatusCode::NotModified_304;
  3584. res.set_header("Location", "/target");
  3585. });
  3586. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3587. res.status = StatusCode::UseProxy_305;
  3588. res.set_header("Location", "/target");
  3589. });
  3590. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3591. followed = true;
  3592. res.set_content("target", "text/plain");
  3593. });
  3594. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3595. auto se = detail::scope_exit([&] {
  3596. svr.stop();
  3597. th.join();
  3598. ASSERT_FALSE(svr.is_running());
  3599. });
  3600. svr.wait_until_ready();
  3601. Client cli("localhost", PORT);
  3602. cli.set_follow_location(true);
  3603. auto res = cli.Get("/304");
  3604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3605. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3606. res = cli.Get("/305");
  3607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3608. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3609. EXPECT_FALSE(followed);
  3610. }
  3611. TEST(RedirectFromPageWithContent, Redirect) {
  3612. Server svr;
  3613. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3614. res.set_content("___", "text/plain");
  3615. res.set_redirect("/2");
  3616. });
  3617. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3618. res.set_content("Hello World!", "text/plain");
  3619. });
  3620. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3621. auto se = detail::scope_exit([&] {
  3622. svr.stop();
  3623. th.join();
  3624. ASSERT_FALSE(svr.is_running());
  3625. });
  3626. svr.wait_until_ready();
  3627. {
  3628. Client cli("localhost", PORT);
  3629. cli.set_follow_location(true);
  3630. std::string body;
  3631. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3632. body.append(data, data_length);
  3633. return true;
  3634. });
  3635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3636. EXPECT_EQ(StatusCode::OK_200, res->status);
  3637. EXPECT_EQ("Hello World!", body);
  3638. }
  3639. {
  3640. Client cli("localhost", PORT);
  3641. std::string body;
  3642. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3643. body.append(data, data_length);
  3644. return true;
  3645. });
  3646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3647. EXPECT_EQ(StatusCode::Found_302, res->status);
  3648. EXPECT_EQ("___", body);
  3649. }
  3650. }
  3651. // A server can close the connection after a request with "Connection: close"
  3652. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3653. // redirected request must go out on a new connection.
  3654. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3655. #ifndef _WIN32
  3656. signal(SIGPIPE, SIG_IGN);
  3657. #endif
  3658. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3659. default_socket_options(srv);
  3660. sockaddr_in addr{};
  3661. addr.sin_family = AF_INET;
  3662. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3663. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3664. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3665. ASSERT_EQ(0, ::listen(srv, 2));
  3666. auto send_text = [](socket_t sock, const std::string &text) {
  3667. ::send(sock,
  3668. #ifdef _WIN32
  3669. static_cast<const char *>(text.c_str()),
  3670. static_cast<int>(text.size()),
  3671. #else
  3672. text.c_str(), text.size(),
  3673. #endif
  3674. 0);
  3675. };
  3676. auto reused = false;
  3677. auto server_thread = std::thread([&] {
  3678. char buf[4096];
  3679. auto first = ::accept(srv, nullptr, nullptr);
  3680. if (first == INVALID_SOCKET) { return; }
  3681. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3682. ::recv(first, buf, sizeof(buf), 0);
  3683. send_text(
  3684. first,
  3685. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3686. auto next = first;
  3687. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3688. reused = true;
  3689. } else {
  3690. detail::close_socket(first);
  3691. next = ::accept(srv, nullptr, nullptr);
  3692. if (next == INVALID_SOCKET) { return; }
  3693. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3694. ::recv(next, buf, sizeof(buf), 0);
  3695. }
  3696. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3697. "Connection: close\r\n\r\nok");
  3698. detail::close_socket(next);
  3699. });
  3700. Client cli("127.0.0.1", PORT + 2);
  3701. cli.set_follow_location(true);
  3702. cli.set_read_timeout(5, 0);
  3703. auto res = cli.Get("/1");
  3704. server_thread.join();
  3705. detail::close_socket(srv);
  3706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3707. EXPECT_EQ(StatusCode::OK_200, res->status);
  3708. EXPECT_EQ("ok", res->body);
  3709. EXPECT_FALSE(reused);
  3710. }
  3711. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3712. Server svr;
  3713. auto port_str = std::to_string(PORT);
  3714. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3715. auto expected_host = "[::1]:" + port_str;
  3716. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3717. res.set_content("___", "text/plain");
  3718. // res.set_redirect("/2");
  3719. res.set_redirect(redirect_url);
  3720. });
  3721. svr.Get("/2", [&](const Request &req, Response &res) {
  3722. auto host_header = req.headers.find("Host");
  3723. ASSERT_TRUE(host_header != req.headers.end());
  3724. EXPECT_EQ(expected_host, host_header->second);
  3725. res.set_content("Hello World!", "text/plain");
  3726. });
  3727. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3728. auto se = detail::scope_exit([&] {
  3729. svr.stop();
  3730. th.join();
  3731. ASSERT_FALSE(svr.is_running());
  3732. });
  3733. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3734. // actually starts anything, so the condition !svr.is_running() will
  3735. // always remain true, and the loop never stops.
  3736. // This basically counts how many milliseconds have passed since the
  3737. // call to svr.listen(), and if after 5 seconds nothing started yet
  3738. // aborts the test.
  3739. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3740. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3741. ASSERT_LT(milliseconds, 5000U);
  3742. }
  3743. {
  3744. Client cli("::1", PORT);
  3745. cli.set_follow_location(true);
  3746. std::string body;
  3747. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3748. body.append(data, data_length);
  3749. return true;
  3750. });
  3751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3752. EXPECT_EQ(StatusCode::OK_200, res->status);
  3753. EXPECT_EQ("Hello World!", body);
  3754. }
  3755. {
  3756. Client cli("::1", PORT);
  3757. std::string body;
  3758. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3759. body.append(data, data_length);
  3760. return true;
  3761. });
  3762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3763. EXPECT_EQ(StatusCode::Found_302, res->status);
  3764. EXPECT_EQ("___", body);
  3765. }
  3766. }
  3767. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3768. Server svr;
  3769. svr.Get("/foo", [](const Request &req, Response &res) {
  3770. auto a = req.params.find("a");
  3771. if (a != req.params.end()) {
  3772. res.set_content((*a).second, "text/plain");
  3773. res.status = StatusCode::OK_200;
  3774. } else {
  3775. res.status = StatusCode::BadRequest_400;
  3776. }
  3777. });
  3778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3779. auto se = detail::scope_exit([&] {
  3780. svr.stop();
  3781. thread.join();
  3782. ASSERT_FALSE(svr.is_running());
  3783. });
  3784. svr.wait_until_ready();
  3785. {
  3786. Client cli(HOST, PORT);
  3787. cli.set_path_encode(false);
  3788. auto res = cli.Get("/foo?a=explicitly+encoded");
  3789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3790. EXPECT_EQ(StatusCode::OK_200, res->status);
  3791. // This expects it back with a space, as the `+` won't have been
  3792. // url-encoded, and server-side the params get decoded turning `+`
  3793. // into spaces.
  3794. EXPECT_EQ("explicitly encoded", res->body);
  3795. }
  3796. }
  3797. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3798. // When path encoding is disabled the client must transmit the supplied
  3799. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3800. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3801. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3802. // than a space (0x20). Assert on the raw wire target to catch this.
  3803. Server svr;
  3804. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3805. svr.Get("/foo", [&](const Request &req, Response &res) {
  3806. EXPECT_EQ(expected_target, req.target);
  3807. res.status = StatusCode::OK_200;
  3808. });
  3809. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. {
  3817. Client cli(HOST, PORT);
  3818. cli.set_path_encode(false);
  3819. auto res = cli.Get(expected_target.c_str());
  3820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3821. EXPECT_EQ(StatusCode::OK_200, res->status);
  3822. }
  3823. }
  3824. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3825. // `open_stream()` used to skip the path encoding that the buffered send
  3826. // path applies, so the same `path` produced different bytes in the request
  3827. // line depending on which API was used. Assert the two agree.
  3828. Server svr;
  3829. std::string target;
  3830. svr.Get(".*", [&](const Request &req, Response &res) {
  3831. target = req.target;
  3832. res.status = StatusCode::OK_200;
  3833. });
  3834. auto port = svr.bind_to_any_port(HOST);
  3835. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3836. auto se = detail::scope_exit([&] {
  3837. svr.stop();
  3838. thread.join();
  3839. ASSERT_FALSE(svr.is_running());
  3840. });
  3841. svr.wait_until_ready();
  3842. struct {
  3843. const char *path;
  3844. const char *expected;
  3845. } cases[] = {
  3846. {"/a b?x=1", "/a%20b?x=1"},
  3847. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3848. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3849. };
  3850. for (const auto &c : cases) {
  3851. Client cli(HOST, port);
  3852. target.clear();
  3853. auto res = cli.Get(c.path);
  3854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3855. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3856. auto buffered_target = target;
  3857. target.clear();
  3858. auto handle = cli.open_stream("GET", c.path);
  3859. EXPECT_TRUE(handle.is_valid())
  3860. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3861. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3862. }
  3863. }
  3864. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3865. // The `set_path_encode(false)` contract — transmit the supplied target
  3866. // verbatim — must hold for the streaming API too.
  3867. Server svr;
  3868. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3869. std::string target;
  3870. svr.Get("/foo", [&](const Request &req, Response &res) {
  3871. target = req.target;
  3872. res.status = StatusCode::OK_200;
  3873. });
  3874. auto port = svr.bind_to_any_port(HOST);
  3875. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3876. auto se = detail::scope_exit([&] {
  3877. svr.stop();
  3878. thread.join();
  3879. ASSERT_FALSE(svr.is_running());
  3880. });
  3881. svr.wait_until_ready();
  3882. {
  3883. Client cli(HOST, port);
  3884. cli.set_path_encode(false);
  3885. auto handle = cli.open_stream("GET", expected_target);
  3886. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3887. EXPECT_EQ(expected_target, target);
  3888. }
  3889. }
  3890. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3891. // With path encoding enabled a CR/LF in the target is percent-encoded
  3892. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3893. // write_request_line still backstops `set_path_encode(false)`, which is
  3894. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3895. Server svr;
  3896. // Captured before routing: the decoded path contains a newline, which a
  3897. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3898. std::string target;
  3899. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3900. target = req.target;
  3901. res.status = StatusCode::OK_200;
  3902. return Server::HandlerResponse::Handled;
  3903. });
  3904. auto port = svr.bind_to_any_port(HOST);
  3905. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3906. auto se = detail::scope_exit([&] {
  3907. svr.stop();
  3908. thread.join();
  3909. ASSERT_FALSE(svr.is_running());
  3910. });
  3911. svr.wait_until_ready();
  3912. {
  3913. Client cli(HOST, port);
  3914. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3915. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3916. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3917. }
  3918. }
  3919. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3920. // Every control character is percent-encoded, not just CR/LF, so the target
  3921. // passes the request-target check in write_request_line.
  3922. Server svr;
  3923. std::string target;
  3924. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3925. target = req.target;
  3926. res.status = StatusCode::OK_200;
  3927. return Server::HandlerResponse::Handled;
  3928. });
  3929. auto port = svr.bind_to_any_port(HOST);
  3930. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3931. auto se = detail::scope_exit([&] {
  3932. svr.stop();
  3933. thread.join();
  3934. ASSERT_FALSE(svr.is_running());
  3935. });
  3936. svr.wait_until_ready();
  3937. {
  3938. Client cli(HOST, port);
  3939. auto res = cli.Get("/a\tb\x1b\x7f");
  3940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3941. EXPECT_EQ("/a%09b%1B%7F", target);
  3942. }
  3943. }
  3944. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3945. // Nothing may reach the wire: a raw CR/LF target would split the request
  3946. // line and inject headers.
  3947. Server svr;
  3948. // Pre-routing so that "not called" means nothing reached the server at all,
  3949. // rather than merely failing to match a handler pattern.
  3950. auto handler_called = false;
  3951. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3952. handler_called = true;
  3953. res.status = StatusCode::OK_200;
  3954. return Server::HandlerResponse::Handled;
  3955. });
  3956. auto port = svr.bind_to_any_port(HOST);
  3957. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3958. auto se = detail::scope_exit([&] {
  3959. svr.stop();
  3960. thread.join();
  3961. ASSERT_FALSE(svr.is_running());
  3962. });
  3963. svr.wait_until_ready();
  3964. {
  3965. Client cli(HOST, port);
  3966. cli.set_path_encode(false);
  3967. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3968. EXPECT_FALSE(handle.is_valid());
  3969. EXPECT_EQ(Error::Write, handle.error);
  3970. EXPECT_FALSE(handler_called);
  3971. }
  3972. }
  3973. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3974. // Which of the two branches runs is decided by whether the query component
  3975. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3976. // an empty query and must still fall back to building one from
  3977. // `req.params`, while a non-empty query must win over `req.params`.
  3978. Server svr;
  3979. std::string target;
  3980. svr.Get("/foo", [&](const Request &req, Response &res) {
  3981. target = req.target;
  3982. res.status = StatusCode::OK_200;
  3983. });
  3984. auto port = svr.bind_to_any_port(HOST);
  3985. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3986. auto se = detail::scope_exit([&] {
  3987. svr.stop();
  3988. thread.join();
  3989. ASSERT_FALSE(svr.is_running());
  3990. });
  3991. svr.wait_until_ready();
  3992. {
  3993. // Trailing `?` -> empty query component -> `req.params` is used.
  3994. Client cli(HOST, port);
  3995. Request req;
  3996. req.method = "GET";
  3997. req.path = "/foo?";
  3998. req.params.emplace("a", "1");
  3999. target.clear();
  4000. auto res = cli.send(req);
  4001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4002. EXPECT_EQ("/foo?a=1", target);
  4003. }
  4004. {
  4005. // Non-empty query in `req.path` -> `req.params` is not appended.
  4006. Client cli(HOST, port);
  4007. Request req;
  4008. req.method = "GET";
  4009. req.path = "/foo?b=2";
  4010. req.params.emplace("a", "1");
  4011. target.clear();
  4012. auto res = cli.send(req);
  4013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4014. EXPECT_EQ("/foo?b=2", target);
  4015. }
  4016. }
  4017. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4018. Server svr;
  4019. svr.Get("/", [](const Request &req, Response &) {
  4020. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4021. });
  4022. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4023. auto se = detail::scope_exit([&] {
  4024. svr.stop();
  4025. thread.join();
  4026. ASSERT_FALSE(svr.is_running());
  4027. });
  4028. svr.wait_until_ready();
  4029. {
  4030. Client cli(HOST, PORT);
  4031. cli.set_path_encode(false);
  4032. auto res = cli.Get("/?something=%0A");
  4033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4034. EXPECT_EQ(StatusCode::OK_200, res->status);
  4035. }
  4036. }
  4037. TEST(BindServerTest, BindDualStack) {
  4038. Server svr;
  4039. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4040. res.set_content("Hello World!", "text/plain");
  4041. });
  4042. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4043. auto se = detail::scope_exit([&] {
  4044. svr.stop();
  4045. thread.join();
  4046. ASSERT_FALSE(svr.is_running());
  4047. });
  4048. svr.wait_until_ready();
  4049. {
  4050. Client cli("127.0.0.1", PORT);
  4051. auto res = cli.Get("/1");
  4052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4053. EXPECT_EQ(StatusCode::OK_200, res->status);
  4054. EXPECT_EQ("Hello World!", res->body);
  4055. }
  4056. {
  4057. Client cli("::1", PORT);
  4058. auto res = cli.Get("/1");
  4059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4060. EXPECT_EQ(StatusCode::OK_200, res->status);
  4061. EXPECT_EQ("Hello World!", res->body);
  4062. }
  4063. }
  4064. TEST(BindServerTest, BindAndListenSeparately) {
  4065. Server svr;
  4066. int port = svr.bind_to_any_port("0.0.0.0");
  4067. ASSERT_TRUE(svr.is_valid());
  4068. ASSERT_TRUE(port > 0);
  4069. svr.stop();
  4070. }
  4071. // Reports whether anything is still listening on a loopback port. A plain
  4072. // connect() is used instead of a Client request because a socket left bound by
  4073. // mistake accepts the connection into its backlog and never answers, which
  4074. // would hang the test instead of failing it.
  4075. static bool is_loopback_port_accepting(int port) {
  4076. sockaddr_in addr{};
  4077. addr.sin_family = AF_INET;
  4078. addr.sin_port = htons(static_cast<uint16_t>(port));
  4079. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4080. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4081. EXPECT_NE(sock, INVALID_SOCKET);
  4082. if (sock == INVALID_SOCKET) { return false; }
  4083. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4084. static_cast<socklen_t>(sizeof(addr)));
  4085. detail::close_socket(sock);
  4086. return ret == 0;
  4087. }
  4088. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4089. Server svr;
  4090. auto port = svr.bind_to_any_port("127.0.0.1");
  4091. ASSERT_TRUE(port > 0);
  4092. svr.stop();
  4093. // bind_to_any_port() already called listen(2), so until stop() closed the
  4094. // descriptor the port kept accepting connections into the backlog. ASSERT
  4095. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4096. // below blocks forever in the accept loop.
  4097. ASSERT_FALSE(is_loopback_port_accepting(port));
  4098. // Nothing is left to accept on, so listen_after_bind() must report failure
  4099. // instead of returning success without ever serving.
  4100. EXPECT_FALSE(svr.listen_after_bind());
  4101. // The failed listen marks the server decommissioned, so a waiter returns
  4102. // instead of spinning forever.
  4103. svr.wait_until_ready();
  4104. }
  4105. #ifdef CPPHTTPLIB_SSL_ENABLED
  4106. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4107. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4108. CLIENT_CA_CERT_DIR);
  4109. int port = svr.bind_to_any_port("0.0.0.0");
  4110. ASSERT_TRUE(svr.is_valid());
  4111. ASSERT_TRUE(port > 0);
  4112. svr.stop();
  4113. }
  4114. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4115. // or a rejected CustomRoute() registration would not stop the server binding.
  4116. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4118. CLIENT_CA_CERT_DIR);
  4119. ASSERT_TRUE(svr.is_valid());
  4120. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4121. EXPECT_FALSE(svr.is_valid());
  4122. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4123. }
  4124. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4125. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4126. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4127. int port = svr.bind_to_any_port("0.0.0.0");
  4128. ASSERT_TRUE(svr.is_valid());
  4129. ASSERT_TRUE(port > 0);
  4130. svr.stop();
  4131. }
  4132. TEST(BindServerTest, UpdateCertsPem) {
  4133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4134. int port = svr.bind_to_any_port("0.0.0.0");
  4135. ASSERT_TRUE(svr.is_valid());
  4136. ASSERT_TRUE(port > 0);
  4137. // Read PEM files
  4138. std::string cert_pem, key_pem, ca_pem;
  4139. read_file(SERVER_CERT_FILE, cert_pem);
  4140. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4141. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4142. // Update server certificates using PEM API
  4143. ASSERT_TRUE(
  4144. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4145. ASSERT_TRUE(svr.is_valid());
  4146. svr.stop();
  4147. }
  4148. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4149. // Start server with client CA (enables client auth)
  4150. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4151. ASSERT_TRUE(svr.is_valid());
  4152. bool handler_called = false;
  4153. svr.Get("/test", [&](const Request &req, Response &res) {
  4154. handler_called = true;
  4155. // Verify client certificate is present
  4156. auto cert = req.peer_cert();
  4157. EXPECT_TRUE(static_cast<bool>(cert));
  4158. res.set_content("ok", "text/plain");
  4159. });
  4160. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4161. auto se = detail::scope_exit([&] {
  4162. svr.stop();
  4163. t.join();
  4164. ASSERT_FALSE(svr.is_running());
  4165. });
  4166. svr.wait_until_ready();
  4167. // Read PEM files
  4168. std::string cert_pem, key_pem, ca_pem;
  4169. read_file(SERVER_CERT_FILE, cert_pem);
  4170. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4171. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4172. // Update server certificates and client CA using PEM API while server running
  4173. ASSERT_TRUE(
  4174. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4175. // Connect with client certificate
  4176. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4177. cli.enable_server_certificate_verification(false);
  4178. cli.set_connection_timeout(30);
  4179. auto res = cli.Get("/test");
  4180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4181. ASSERT_EQ(StatusCode::OK_200, res->status);
  4182. ASSERT_TRUE(handler_called);
  4183. EXPECT_EQ("ok", res->body);
  4184. }
  4185. // Puts a CA that did not sign the client's certificate in the old one's place.
  4186. static bool replace_client_ca(SSLServer &svr) {
  4187. std::string cert_pem, key_pem, ca_pem;
  4188. read_file(SERVER_CERT_FILE, cert_pem);
  4189. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4190. read_file(SERVER_CERT2_FILE, ca_pem);
  4191. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4192. ca_pem.c_str());
  4193. }
  4194. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4195. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4196. ASSERT_TRUE(svr.is_valid());
  4197. svr.Get("/test", [](const Request &, Response &res) {
  4198. res.set_content("ok", "text/plain");
  4199. });
  4200. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4201. auto se = detail::scope_exit([&] {
  4202. svr.stop();
  4203. t.join();
  4204. ASSERT_FALSE(svr.is_running());
  4205. });
  4206. svr.wait_until_ready();
  4207. auto get = [] {
  4208. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4209. cli.enable_server_certificate_verification(false);
  4210. return cli.Get("/test");
  4211. };
  4212. ASSERT_TRUE(get());
  4213. ASSERT_TRUE(replace_client_ca(svr));
  4214. EXPECT_FALSE(get());
  4215. }
  4216. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4217. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4219. ASSERT_TRUE(svr.is_valid());
  4220. tls::set_verify_callback(svr.tls_context(),
  4221. [](const tls::VerifyContext &) -> bool {
  4222. throw std::runtime_error("verify");
  4223. });
  4224. svr.Get("/test", [](const Request &, Response &res) {
  4225. res.set_content("ok", "text/plain");
  4226. });
  4227. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4228. auto se = detail::scope_exit([&] {
  4229. svr.stop();
  4230. t.join();
  4231. ASSERT_FALSE(svr.is_running());
  4232. });
  4233. svr.wait_until_ready();
  4234. auto get = [] {
  4235. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4236. cli.enable_server_certificate_verification(false);
  4237. return cli.Get("/test");
  4238. };
  4239. EXPECT_FALSE(get());
  4240. // The handshake is over, so an update does not wait for it.
  4241. std::string cert_pem, key_pem;
  4242. read_file(SERVER_CERT_FILE, cert_pem);
  4243. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4244. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4245. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4246. return v.preverify_ok;
  4247. });
  4248. auto res = get();
  4249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4250. EXPECT_EQ("ok", res->body);
  4251. }
  4252. #endif
  4253. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4254. // Sends each request over a new connection with a client certificate,
  4255. // resuming the session of the one before when there is one.
  4256. class ResumingClient {
  4257. public:
  4258. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4259. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4260. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4261. SSL_FILETYPE_PEM);
  4262. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4263. // callback, not through SSL_get1_session().
  4264. SSL_CTX_set_app_data(ctx_, this);
  4265. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4266. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4267. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4268. auto self = static_cast<ResumingClient *>(
  4269. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4270. SSL_SESSION_free(self->session_);
  4271. self->session_ = session;
  4272. return 1; // Keeps the reference
  4273. });
  4274. }
  4275. ~ResumingClient() {
  4276. SSL_SESSION_free(session_);
  4277. SSL_CTX_free(ctx_);
  4278. }
  4279. // Tells whether the request was answered.
  4280. bool get() {
  4281. auto error = Error::Success;
  4282. auto sock = detail::create_client_socket(
  4283. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4284. /*connection_timeout_sec=*/5, 0,
  4285. /*read_timeout_sec=*/5, 0,
  4286. /*write_timeout_sec=*/5, 0, std::string(), error);
  4287. if (sock == INVALID_SOCKET) { return false; }
  4288. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4289. auto ssl = SSL_new(ctx_);
  4290. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4291. SSL_set_fd(ssl, static_cast<int>(sock));
  4292. if (session_) { SSL_set_session(ssl, session_); }
  4293. if (SSL_connect(ssl) != 1) { return false; }
  4294. reused_ = SSL_session_reused(ssl) == 1;
  4295. // Reading the response also takes in a TLS 1.3 session ticket.
  4296. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4297. "Connection: close\r\n\r\n";
  4298. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4299. std::string res;
  4300. char buf[256];
  4301. int n;
  4302. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4303. res.append(buf, static_cast<size_t>(n));
  4304. }
  4305. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4306. SSL_shutdown(ssl);
  4307. return res.find("200 OK") != std::string::npos;
  4308. }
  4309. // Whether the last connection resumed a session
  4310. bool reused() const { return reused_; }
  4311. private:
  4312. SSL_CTX *ctx_;
  4313. SSL_SESSION *session_ = nullptr;
  4314. bool reused_ = false;
  4315. };
  4316. // A client that resumes its session gets through, but not once the client CA
  4317. // has changed, as a resumed session does not show the certificate again.
  4318. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4320. ASSERT_TRUE(svr.is_valid());
  4321. svr.Get("/test", [](const Request &, Response &res) {
  4322. res.set_content("ok", "text/plain");
  4323. });
  4324. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4325. auto se = detail::scope_exit([&] {
  4326. svr.stop();
  4327. t.join();
  4328. ASSERT_FALSE(svr.is_running());
  4329. });
  4330. svr.wait_until_ready();
  4331. ResumingClient cli;
  4332. ASSERT_TRUE(cli.get());
  4333. ASSERT_TRUE(cli.get());
  4334. EXPECT_TRUE(cli.reused());
  4335. ASSERT_TRUE(replace_client_ca(svr));
  4336. EXPECT_FALSE(cli.get());
  4337. }
  4338. // A resumed session does not show the certificate again, so the server does
  4339. // not resume one with a verify callback to run on it.
  4340. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4342. ASSERT_TRUE(svr.is_valid());
  4343. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4344. return v.preverify_ok;
  4345. });
  4346. svr.Get("/test", [](const Request &, Response &res) {
  4347. res.set_content("ok", "text/plain");
  4348. });
  4349. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4350. auto se = detail::scope_exit([&] {
  4351. svr.stop();
  4352. t.join();
  4353. ASSERT_FALSE(svr.is_running());
  4354. });
  4355. svr.wait_until_ready();
  4356. ResumingClient cli;
  4357. ASSERT_TRUE(cli.get());
  4358. ASSERT_TRUE(cli.get());
  4359. EXPECT_FALSE(cli.reused());
  4360. }
  4361. #endif
  4362. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4363. // wolfSSL shares its session cache between contexts, so a resumed session
  4364. // could carry a client certificate checked against another server's CA, or
  4365. // against a client CA since replaced.
  4366. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4367. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4368. ASSERT_TRUE(svr.is_valid());
  4369. // Trusts a CA that did not sign the client's certificate.
  4370. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4371. ASSERT_TRUE(other.is_valid());
  4372. for (auto s : {&svr, &other}) {
  4373. s->Get("/test", [](const Request &, Response &res) {
  4374. res.set_content("ok", "text/plain");
  4375. });
  4376. }
  4377. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4378. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4379. auto se = detail::scope_exit([&] {
  4380. other.stop();
  4381. svr.stop();
  4382. t2.join();
  4383. t.join();
  4384. });
  4385. svr.wait_until_ready();
  4386. other.wait_until_ready();
  4387. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4388. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4389. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4390. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4391. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4392. ASSERT_EQ(WOLFSSL_SUCCESS,
  4393. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4394. WOLFSSL_FILETYPE_PEM));
  4395. WOLFSSL_SESSION *session = nullptr;
  4396. auto session_se = detail::scope_exit([&] {
  4397. if (session) { wolfSSL_SESSION_free(session); }
  4398. });
  4399. // A request over a new connection, resuming `session` when there is one and
  4400. // keeping the connection's own in its place. Tells whether it was answered.
  4401. auto get = [&](int port) {
  4402. auto error = Error::Success;
  4403. auto sock = detail::create_client_socket(
  4404. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4405. /*connection_timeout_sec=*/5, 0,
  4406. /*read_timeout_sec=*/5, 0,
  4407. /*write_timeout_sec=*/5, 0, std::string(), error);
  4408. if (sock == INVALID_SOCKET) { return false; }
  4409. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4410. auto ssl = wolfSSL_new(ctx);
  4411. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4412. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4413. if (session) { wolfSSL_set_session(ssl, session); }
  4414. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4415. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4416. "Connection: close\r\n\r\n";
  4417. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4418. std::string res;
  4419. char buf[256];
  4420. int n;
  4421. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4422. res.append(buf, static_cast<size_t>(n));
  4423. }
  4424. wolfSSL_shutdown(ssl);
  4425. if (session) { wolfSSL_SESSION_free(session); }
  4426. session = wolfSSL_get1_session(ssl);
  4427. return res.find("200 OK") != std::string::npos;
  4428. };
  4429. ASSERT_TRUE(get(PORT));
  4430. EXPECT_FALSE(get(PORT + 1));
  4431. ASSERT_TRUE(get(PORT));
  4432. ASSERT_TRUE(replace_client_ca(svr));
  4433. EXPECT_FALSE(get(PORT));
  4434. }
  4435. #endif
  4436. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4437. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4438. ASSERT_TRUE(svr.is_valid());
  4439. svr.Get("/test", [](const Request &, Response &res) {
  4440. res.set_content("ok", "text/plain");
  4441. });
  4442. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4443. auto se = detail::scope_exit([&] {
  4444. svr.stop();
  4445. t.join();
  4446. ASSERT_FALSE(svr.is_running());
  4447. });
  4448. svr.wait_until_ready();
  4449. // A connection that sends no ClientHello keeps its handshake in progress,
  4450. // once the server has had a moment to start it.
  4451. auto error = Error::Success;
  4452. auto sock = detail::create_client_socket(
  4453. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4454. /*connection_timeout_sec=*/5, 0,
  4455. /*read_timeout_sec=*/5, 0,
  4456. /*write_timeout_sec=*/5, 0, std::string(), error);
  4457. ASSERT_NE(INVALID_SOCKET, sock);
  4458. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4459. std::string cert_pem, key_pem;
  4460. read_file(SERVER_CERT_FILE, cert_pem);
  4461. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4462. auto update = std::async(std::launch::async, [&]() {
  4463. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4464. });
  4465. EXPECT_EQ(std::future_status::timeout,
  4466. update.wait_for(std::chrono::milliseconds(200)));
  4467. detail::close_socket(sock);
  4468. EXPECT_TRUE(update.get());
  4469. SSLClient cli(HOST, PORT);
  4470. cli.enable_server_certificate_verification(false);
  4471. auto res = cli.Get("/test");
  4472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4473. EXPECT_EQ(StatusCode::OK_200, res->status);
  4474. }
  4475. #endif
  4476. TEST(ErrorHandlerTest, ContentLength) {
  4477. Server svr;
  4478. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4479. res.status = StatusCode::OK_200;
  4480. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4481. "text/html"); // <= Content-Length still 13
  4482. });
  4483. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4484. res.set_content("Hello World!\n", "text/plain");
  4485. res.status = 524;
  4486. });
  4487. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4488. auto se = detail::scope_exit([&] {
  4489. svr.stop();
  4490. thread.join();
  4491. ASSERT_FALSE(svr.is_running());
  4492. });
  4493. svr.wait_until_ready();
  4494. {
  4495. Client cli(HOST, PORT);
  4496. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4498. EXPECT_EQ(StatusCode::OK_200, res->status);
  4499. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4500. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4501. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4502. }
  4503. }
  4504. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4505. TEST(ExceptionTest, WithoutExceptionHandler) {
  4506. Server svr;
  4507. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4508. throw std::runtime_error("exception...");
  4509. });
  4510. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4511. throw std::runtime_error("exception\r\n...");
  4512. });
  4513. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4514. auto se = detail::scope_exit([&] {
  4515. svr.stop();
  4516. listen_thread.join();
  4517. ASSERT_FALSE(svr.is_running());
  4518. });
  4519. svr.wait_until_ready();
  4520. Client cli("localhost", PORT);
  4521. {
  4522. auto res = cli.Get("/exception");
  4523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4524. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4525. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4526. }
  4527. {
  4528. auto res = cli.Get("/unknown");
  4529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4530. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4531. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4532. }
  4533. }
  4534. TEST(ExceptionTest, WithExceptionHandler) {
  4535. Server svr;
  4536. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4537. std::exception_ptr ep) {
  4538. EXPECT_FALSE(ep == nullptr);
  4539. try {
  4540. std::rethrow_exception(ep);
  4541. } catch (std::exception &e) {
  4542. EXPECT_EQ("abc", std::string(e.what()));
  4543. } catch (...) {}
  4544. res.status = StatusCode::InternalServerError_500;
  4545. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4546. "text/html"); // <= Content-Length still 13 at this point
  4547. });
  4548. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4549. res.set_content("Hello World!\n", "text/plain");
  4550. throw std::runtime_error("abc");
  4551. });
  4552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4553. auto se = detail::scope_exit([&] {
  4554. svr.stop();
  4555. thread.join();
  4556. ASSERT_FALSE(svr.is_running());
  4557. });
  4558. svr.wait_until_ready();
  4559. for (size_t i = 0; i < 10; i++) {
  4560. Client cli(HOST, PORT);
  4561. for (size_t j = 0; j < 100; j++) {
  4562. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4564. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4565. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4566. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4567. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4568. }
  4569. cli.set_keep_alive(true);
  4570. for (size_t j = 0; j < 100; j++) {
  4571. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4573. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4574. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4575. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4576. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4577. }
  4578. }
  4579. }
  4580. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4581. Server svr;
  4582. svr.set_exception_handler(
  4583. [](const Request &, Response &res, std::exception_ptr) {
  4584. res.set_content("oops", "text/plain");
  4585. });
  4586. svr.Get("/throw", [](const Request &, Response &) {
  4587. throw std::runtime_error("throw");
  4588. });
  4589. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4590. res.status = StatusCode::Created_201;
  4591. throw std::runtime_error("created-then-throw");
  4592. });
  4593. auto port = svr.bind_to_any_port(HOST);
  4594. ASSERT_GT(port, 0);
  4595. thread t = thread([&] { svr.listen_after_bind(); });
  4596. auto se = detail::scope_exit([&] {
  4597. svr.stop();
  4598. t.join();
  4599. ASSERT_FALSE(svr.is_running());
  4600. });
  4601. svr.wait_until_ready();
  4602. Client cli(HOST, port);
  4603. for (auto path : {"/throw", "/created-then-throw"}) {
  4604. auto res = cli.Get(path);
  4605. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4606. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4607. }
  4608. }
  4609. TEST(ExceptionTest, AndErrorHandler) {
  4610. Server svr;
  4611. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4612. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4613. });
  4614. svr.set_exception_handler(
  4615. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4616. EXPECT_FALSE(ep == nullptr);
  4617. try {
  4618. std::rethrow_exception(ep);
  4619. } catch (std::exception &e) {
  4620. res.set_content(e.what(), "text/html");
  4621. } catch (...) {}
  4622. res.status = StatusCode::InternalServerError_500;
  4623. });
  4624. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4625. throw std::runtime_error("EXCEPTION");
  4626. });
  4627. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4628. res.set_content("ERROR", "text/html");
  4629. res.status = StatusCode::InternalServerError_500;
  4630. });
  4631. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4632. auto se = detail::scope_exit([&] {
  4633. svr.stop();
  4634. thread.join();
  4635. ASSERT_FALSE(svr.is_running());
  4636. });
  4637. svr.wait_until_ready();
  4638. Client cli(HOST, PORT);
  4639. {
  4640. auto res = cli.Get("/exception");
  4641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4642. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4643. EXPECT_EQ("EXCEPTION", res->body);
  4644. }
  4645. {
  4646. auto res = cli.Get("/error");
  4647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4648. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4649. EXPECT_EQ("ERROR", res->body);
  4650. }
  4651. {
  4652. auto res = cli.Get("/invalid");
  4653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4654. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4655. EXPECT_EQ("NOT_FOUND", res->body);
  4656. }
  4657. }
  4658. #endif
  4659. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4660. // An exception from a user callback outside process_request()'s try/catch
  4661. // used to unwind into the task queue - which does not catch - and terminate
  4662. // the process. Each test below runs the server on a single worker thread: a
  4663. // guard that catches the exception but still loses the thread would otherwise
  4664. // be hidden by a spare worker serving the follow-up request. Note that a
  4665. // regression here aborts the whole test binary rather than failing one test.
  4666. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4667. Server svr;
  4668. svr.new_task_queue = [] { return new ThreadPool(1); };
  4669. std::atomic<int> reported{0};
  4670. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4671. if (err == Error::UserCallbackException) { reported++; }
  4672. });
  4673. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4674. res.set_content_provider(
  4675. 1024, "text/plain",
  4676. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4677. sink.write("hello", 5);
  4678. throw std::runtime_error("from the content provider");
  4679. });
  4680. });
  4681. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4682. res.set_content("ok", "text/plain");
  4683. });
  4684. auto port = svr.bind_to_any_port(HOST);
  4685. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4686. auto se = detail::scope_exit([&] {
  4687. svr.stop();
  4688. listen_thread.join();
  4689. ASSERT_FALSE(svr.is_running());
  4690. });
  4691. svr.wait_until_ready();
  4692. {
  4693. Client cli(HOST, port);
  4694. cli.set_read_timeout(5, 0);
  4695. EXPECT_FALSE(cli.Get("/throw"));
  4696. }
  4697. EXPECT_TRUE(svr.is_running());
  4698. EXPECT_EQ(1, reported.load());
  4699. // A request on a fresh connection is still served.
  4700. {
  4701. Client cli(HOST, port);
  4702. auto res = cli.Get("/ok");
  4703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4704. EXPECT_EQ(StatusCode::OK_200, res->status);
  4705. EXPECT_EQ("ok", res->body);
  4706. }
  4707. }
  4708. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4709. Server svr;
  4710. svr.new_task_queue = [] { return new ThreadPool(1); };
  4711. std::atomic<bool> should_throw{true};
  4712. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4713. res.set_content("hi", "text/plain");
  4714. });
  4715. svr.set_post_routing_handler(
  4716. [&](const Request & /*req*/, Response & /*res*/) {
  4717. if (should_throw) {
  4718. throw std::runtime_error("from the post-routing handler");
  4719. }
  4720. });
  4721. auto port = svr.bind_to_any_port(HOST);
  4722. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4723. auto se = detail::scope_exit([&] {
  4724. svr.stop();
  4725. listen_thread.join();
  4726. ASSERT_FALSE(svr.is_running());
  4727. });
  4728. svr.wait_until_ready();
  4729. {
  4730. Client cli(HOST, port);
  4731. cli.set_read_timeout(5, 0);
  4732. EXPECT_FALSE(cli.Get("/hi"));
  4733. }
  4734. EXPECT_TRUE(svr.is_running());
  4735. should_throw = false;
  4736. {
  4737. Client cli(HOST, port);
  4738. auto res = cli.Get("/hi");
  4739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4740. EXPECT_EQ(StatusCode::OK_200, res->status);
  4741. EXPECT_EQ("hi", res->body);
  4742. }
  4743. }
  4744. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4745. // The guard reports the caught exception through the error logger, which is
  4746. // a user callback too. A logger that throws has to be contained as well, or
  4747. // the process would terminate from inside the catch.
  4748. Server svr;
  4749. svr.new_task_queue = [] { return new ThreadPool(1); };
  4750. std::atomic<int> reported{0};
  4751. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4752. if (err == Error::UserCallbackException) {
  4753. reported++;
  4754. throw std::runtime_error("from the error logger");
  4755. }
  4756. });
  4757. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4758. res.set_content_provider(
  4759. 1024, "text/plain",
  4760. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4761. sink.write("hello", 5);
  4762. throw std::runtime_error("from the content provider");
  4763. });
  4764. });
  4765. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4766. res.set_content("ok", "text/plain");
  4767. });
  4768. auto port = svr.bind_to_any_port(HOST);
  4769. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4770. auto se = detail::scope_exit([&] {
  4771. svr.stop();
  4772. listen_thread.join();
  4773. ASSERT_FALSE(svr.is_running());
  4774. });
  4775. svr.wait_until_ready();
  4776. {
  4777. Client cli(HOST, port);
  4778. cli.set_read_timeout(5, 0);
  4779. EXPECT_FALSE(cli.Get("/throw"));
  4780. }
  4781. EXPECT_TRUE(svr.is_running());
  4782. EXPECT_EQ(1, reported.load());
  4783. {
  4784. Client cli(HOST, port);
  4785. auto res = cli.Get("/ok");
  4786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4787. EXPECT_EQ(StatusCode::OK_200, res->status);
  4788. EXPECT_EQ("ok", res->body);
  4789. }
  4790. }
  4791. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4792. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4793. // so the exception unwinds through the ws::WebSocket object on its way to
  4794. // the guard. None of the HTTP cases above cross that.
  4795. Server svr;
  4796. svr.new_task_queue = [] { return new ThreadPool(1); };
  4797. std::atomic<int> reported{0};
  4798. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4799. if (err == Error::UserCallbackException) { reported++; }
  4800. });
  4801. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4802. throw std::runtime_error("from the WebSocket handler");
  4803. });
  4804. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4805. res.set_content("ok", "text/plain");
  4806. });
  4807. auto port = svr.bind_to_any_port(HOST);
  4808. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4809. auto se = detail::scope_exit([&] {
  4810. svr.stop();
  4811. listen_thread.join();
  4812. ASSERT_FALSE(svr.is_running());
  4813. });
  4814. svr.wait_until_ready();
  4815. {
  4816. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4817. "/ws");
  4818. auto res = client.connect();
  4819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4820. // The server dropped the connection instead of dying.
  4821. std::string msg;
  4822. EXPECT_FALSE(client.read(msg));
  4823. client.close();
  4824. }
  4825. EXPECT_TRUE(svr.is_running());
  4826. EXPECT_EQ(1, reported.load());
  4827. {
  4828. Client cli(HOST, port);
  4829. auto res = cli.Get("/ok");
  4830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4831. EXPECT_EQ(StatusCode::OK_200, res->status);
  4832. EXPECT_EQ("ok", res->body);
  4833. }
  4834. }
  4835. #ifdef CPPHTTPLIB_SSL_ENABLED
  4836. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4837. // SSLServer::process_and_close_socket() is a separate overload with its own
  4838. // guard, so it is exercised on its own.
  4839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4840. ASSERT_TRUE(svr.is_valid());
  4841. svr.new_task_queue = [] { return new ThreadPool(1); };
  4842. std::atomic<int> reported{0};
  4843. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4844. if (err == Error::UserCallbackException) { reported++; }
  4845. });
  4846. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4847. res.set_content_provider(
  4848. 1024, "text/plain",
  4849. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4850. sink.write("hello", 5);
  4851. throw std::runtime_error("from the content provider");
  4852. });
  4853. });
  4854. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4855. res.set_content("ok", "text/plain");
  4856. });
  4857. auto port = svr.bind_to_any_port(HOST);
  4858. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4859. auto se = detail::scope_exit([&] {
  4860. svr.stop();
  4861. listen_thread.join();
  4862. ASSERT_FALSE(svr.is_running());
  4863. });
  4864. svr.wait_until_ready();
  4865. {
  4866. SSLClient cli(HOST, port);
  4867. cli.enable_server_certificate_verification(false);
  4868. cli.set_read_timeout(5, 0);
  4869. EXPECT_FALSE(cli.Get("/throw"));
  4870. }
  4871. EXPECT_TRUE(svr.is_running());
  4872. EXPECT_EQ(1, reported.load());
  4873. {
  4874. SSLClient cli(HOST, port);
  4875. cli.enable_server_certificate_verification(false);
  4876. auto res = cli.Get("/ok");
  4877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4878. EXPECT_EQ(StatusCode::OK_200, res->status);
  4879. EXPECT_EQ("ok", res->body);
  4880. }
  4881. }
  4882. #endif
  4883. #endif
  4884. TEST(NoContentTest, ContentLength) {
  4885. Server svr;
  4886. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4887. res.status = StatusCode::NoContent_204;
  4888. });
  4889. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4890. auto se = detail::scope_exit([&] {
  4891. svr.stop();
  4892. thread.join();
  4893. ASSERT_FALSE(svr.is_running());
  4894. });
  4895. svr.wait_until_ready();
  4896. {
  4897. Client cli(HOST, PORT);
  4898. auto res = cli.Get("/hi");
  4899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4900. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4901. // RFC 9110 8.6: none in a 204 response
  4902. EXPECT_FALSE(res->has_header("Content-Length"));
  4903. }
  4904. }
  4905. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4906. Server svr;
  4907. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4908. res.set_header("Content-Length", "5");
  4909. res.set_content("hello world", "text/plain");
  4910. });
  4911. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4912. // A body that reads as the last chunk, were it taken as chunked
  4913. res.set_header("Transfer-Encoding", "chunked");
  4914. res.set_content("0\r\n\r\n", "text/plain");
  4915. });
  4916. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4917. res.set_header("Content-Length", "2");
  4918. res.set_content_provider(5, "text/plain",
  4919. [](size_t offset, size_t length, DataSink &sink) {
  4920. sink.write(&"hello"[offset], length);
  4921. return true;
  4922. });
  4923. });
  4924. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4925. res.set_header("Content-Length", "1234");
  4926. });
  4927. thread t = thread([&] { svr.listen(HOST, PORT); });
  4928. auto se = detail::scope_exit([&] {
  4929. svr.stop();
  4930. t.join();
  4931. ASSERT_FALSE(svr.is_running());
  4932. });
  4933. svr.wait_until_ready();
  4934. Client cli(HOST, PORT);
  4935. cli.set_read_timeout(1, 0);
  4936. auto expect_body = [&](const Result &res, const std::string &body) {
  4937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4938. EXPECT_EQ(body, res->body);
  4939. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4940. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4941. };
  4942. Headers identity{{"Accept-Encoding", ""}};
  4943. expect_body(cli.Get("/body", identity), "hello world");
  4944. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4945. expect_body(cli.Get("/body",
  4946. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4947. "he");
  4948. expect_body(cli.Get("/provider", identity), "hello");
  4949. expect_body(cli.Get("/empty", identity), "");
  4950. // A HEAD response may give the length of the body a GET would get.
  4951. auto res = cli.Head("/empty");
  4952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4953. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4954. }
  4955. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4956. Server svr;
  4957. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4958. res.set_content("short", "text/plain");
  4959. });
  4960. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4961. res.body += " with a footer";
  4962. res.set_header("Transfer-Encoding", "chunked");
  4963. });
  4964. thread t = thread([&] { svr.listen(HOST, PORT); });
  4965. auto se = detail::scope_exit([&] {
  4966. svr.stop();
  4967. t.join();
  4968. ASSERT_FALSE(svr.is_running());
  4969. });
  4970. svr.wait_until_ready();
  4971. Client cli(HOST, PORT);
  4972. cli.set_read_timeout(1, 0);
  4973. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. EXPECT_EQ("short with a footer", res->body);
  4976. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4977. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4978. }
  4979. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4980. Server svr;
  4981. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4982. res.set_header("Content-Length", "3");
  4983. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4984. sink.write("abc", 3);
  4985. sink.done();
  4986. return true;
  4987. });
  4988. });
  4989. thread t = thread([&] { svr.listen(HOST, PORT); });
  4990. auto se = detail::scope_exit([&] {
  4991. svr.stop();
  4992. t.join();
  4993. ASSERT_FALSE(svr.is_running());
  4994. });
  4995. svr.wait_until_ready();
  4996. Client cli(HOST, PORT);
  4997. cli.set_keep_alive(true);
  4998. auto res = cli.Get("/");
  4999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5000. EXPECT_EQ("abc", res->body);
  5001. EXPECT_FALSE(res->has_header("Content-Length"));
  5002. EXPECT_EQ("close", res->get_header_value("Connection"));
  5003. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5004. // No body to delimit
  5005. auto head = cli.Head("/");
  5006. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5007. EXPECT_FALSE(head->has_header("Connection"));
  5008. }
  5009. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5010. #ifdef CPPHTTPLIB_SSL_ENABLED
  5011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5012. ASSERT_TRUE(svr.is_valid());
  5013. #else
  5014. Server svr;
  5015. #endif
  5016. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5017. if (req.path == "/routing_handler") {
  5018. res.set_header("PRE_ROUTING", "on");
  5019. res.set_content("Routing Handler", "text/plain");
  5020. return httplib::Server::HandlerResponse::Handled;
  5021. }
  5022. return httplib::Server::HandlerResponse::Unhandled;
  5023. });
  5024. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5025. res.set_content("Error", "text/html");
  5026. });
  5027. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5028. if (req.path == "/routing_handler") {
  5029. res.set_header("POST_ROUTING", "on");
  5030. }
  5031. });
  5032. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5033. res.set_content("Hello World!\n", "text/plain");
  5034. });
  5035. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5036. auto se = detail::scope_exit([&] {
  5037. svr.stop();
  5038. thread.join();
  5039. ASSERT_FALSE(svr.is_running());
  5040. });
  5041. svr.wait_until_ready();
  5042. {
  5043. #ifdef CPPHTTPLIB_SSL_ENABLED
  5044. SSLClient cli(HOST, PORT);
  5045. cli.enable_server_certificate_verification(false);
  5046. #else
  5047. Client cli(HOST, PORT);
  5048. #endif
  5049. auto res = cli.Get("/routing_handler");
  5050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5051. EXPECT_EQ(StatusCode::OK_200, res->status);
  5052. EXPECT_EQ("Routing Handler", res->body);
  5053. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5054. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5055. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5056. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5057. }
  5058. {
  5059. #ifdef CPPHTTPLIB_SSL_ENABLED
  5060. SSLClient cli(HOST, PORT);
  5061. cli.enable_server_certificate_verification(false);
  5062. #else
  5063. Client cli(HOST, PORT);
  5064. #endif
  5065. auto res = cli.Get("/hi");
  5066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5067. EXPECT_EQ(StatusCode::OK_200, res->status);
  5068. EXPECT_EQ("Hello World!\n", res->body);
  5069. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5070. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5071. }
  5072. {
  5073. #ifdef CPPHTTPLIB_SSL_ENABLED
  5074. SSLClient cli(HOST, PORT);
  5075. cli.enable_server_certificate_verification(false);
  5076. #else
  5077. Client cli(HOST, PORT);
  5078. #endif
  5079. auto res = cli.Get("/aaa");
  5080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5081. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5082. EXPECT_EQ("Error", res->body);
  5083. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5084. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5085. }
  5086. }
  5087. TEST(RequestHandlerTest, PreRequestHandler) {
  5088. auto route_path = "/user/:user";
  5089. Server svr;
  5090. svr.Get("/hi", [](const Request &, Response &res) {
  5091. res.set_content("hi", "text/plain");
  5092. });
  5093. svr.Get(route_path, [](const Request &req, Response &res) {
  5094. res.set_content(req.path_params.at("user"), "text/plain");
  5095. });
  5096. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5097. if (req.matched_route == route_path) {
  5098. auto user = req.path_params.at("user");
  5099. if (user != "john") {
  5100. res.status = StatusCode::Forbidden_403;
  5101. res.set_content("error", "text/html");
  5102. return Server::HandlerResponse::Handled;
  5103. }
  5104. }
  5105. return Server::HandlerResponse::Unhandled;
  5106. });
  5107. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5108. auto se = detail::scope_exit([&] {
  5109. svr.stop();
  5110. thread.join();
  5111. ASSERT_FALSE(svr.is_running());
  5112. });
  5113. svr.wait_until_ready();
  5114. Client cli(HOST, PORT);
  5115. {
  5116. auto res = cli.Get("/hi");
  5117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5118. EXPECT_EQ(StatusCode::OK_200, res->status);
  5119. EXPECT_EQ("hi", res->body);
  5120. }
  5121. {
  5122. auto res = cli.Get("/user/john");
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. EXPECT_EQ(StatusCode::OK_200, res->status);
  5125. EXPECT_EQ("john", res->body);
  5126. }
  5127. {
  5128. auto res = cli.Get("/user/invalid-user");
  5129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5130. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5131. EXPECT_EQ("error", res->body);
  5132. }
  5133. }
  5134. // The pre-request handler must run before the request body is read, so a
  5135. // rejected request never forces the server to buffer a (potentially large)
  5136. // body. Here the posted body is larger than the payload limit: if the body
  5137. // were read first the server would answer 413, but because the pre-request
  5138. // handler runs first it answers 403 and the body is never read.
  5139. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5140. Server svr;
  5141. svr.set_payload_max_length(8);
  5142. auto handler_ran = false;
  5143. svr.Post("/reject", [&](const Request &req, Response &res) {
  5144. handler_ran = true;
  5145. res.set_content(req.body, "text/plain");
  5146. });
  5147. svr.Post("/accept", [](const Request &req, Response &res) {
  5148. res.set_content(req.body, "text/plain");
  5149. });
  5150. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5151. if (req.matched_route == "/reject") {
  5152. res.status = StatusCode::Forbidden_403;
  5153. res.set_content("denied", "text/plain");
  5154. return Server::HandlerResponse::Handled;
  5155. }
  5156. return Server::HandlerResponse::Unhandled;
  5157. });
  5158. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5159. auto se = detail::scope_exit([&] {
  5160. svr.stop();
  5161. thread.join();
  5162. ASSERT_FALSE(svr.is_running());
  5163. });
  5164. svr.wait_until_ready();
  5165. Client cli(HOST, PORT);
  5166. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5167. // rejects with 403 before the body is read, so 413 is never reached.
  5168. {
  5169. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5171. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5172. EXPECT_EQ("denied", res->body);
  5173. EXPECT_FALSE(handler_ran);
  5174. }
  5175. // An approved route still reads the body and enforces the payload limit.
  5176. {
  5177. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5179. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5180. }
  5181. }
  5182. TEST(UserDataTest, BasicOperations) {
  5183. httplib::UserData ud;
  5184. // Initially empty
  5185. EXPECT_FALSE(ud.has("key"));
  5186. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5187. // set and get
  5188. ud.set("key", 42);
  5189. EXPECT_TRUE(ud.has("key"));
  5190. auto *p = ud.get<int>("key");
  5191. ASSERT_NE(nullptr, p);
  5192. EXPECT_EQ(42, *p);
  5193. // Type mismatch → nullptr
  5194. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5195. // Overwrite with different type
  5196. ud.set("key", std::string("hello"));
  5197. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5198. auto *s = ud.get<std::string>("key");
  5199. ASSERT_NE(nullptr, s);
  5200. EXPECT_EQ("hello", *s);
  5201. // erase
  5202. ud.erase("key");
  5203. EXPECT_FALSE(ud.has("key"));
  5204. // clear
  5205. ud.set("a", 1);
  5206. ud.set("b", 2);
  5207. ud.clear();
  5208. EXPECT_FALSE(ud.has("a"));
  5209. EXPECT_FALSE(ud.has("b"));
  5210. }
  5211. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5212. struct AuthCtx {
  5213. std::string user_id;
  5214. };
  5215. Server svr;
  5216. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5217. res.user_data.set("auth", AuthCtx{"alice"});
  5218. return Server::HandlerResponse::Unhandled;
  5219. });
  5220. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5221. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5222. ASSERT_NE(nullptr, ctx);
  5223. res.set_content("Hello " + ctx->user_id, "text/plain");
  5224. });
  5225. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5226. auto se = detail::scope_exit([&] {
  5227. svr.stop();
  5228. thread.join();
  5229. ASSERT_FALSE(svr.is_running());
  5230. });
  5231. svr.wait_until_ready();
  5232. Client cli(HOST, PORT);
  5233. auto res = cli.Get("/me");
  5234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5235. EXPECT_EQ(StatusCode::OK_200, res->status);
  5236. EXPECT_EQ("Hello alice", res->body);
  5237. }
  5238. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5239. struct RoleCtx {
  5240. std::string role;
  5241. };
  5242. Server svr;
  5243. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5244. res.user_data.set("role", RoleCtx{"admin"});
  5245. return Server::HandlerResponse::Unhandled;
  5246. });
  5247. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5248. auto *ctx = res.user_data.get<RoleCtx>("role");
  5249. ASSERT_NE(nullptr, ctx);
  5250. res.set_content(ctx->role, "text/plain");
  5251. });
  5252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5253. auto se = detail::scope_exit([&] {
  5254. svr.stop();
  5255. thread.join();
  5256. ASSERT_FALSE(svr.is_running());
  5257. });
  5258. svr.wait_until_ready();
  5259. Client cli(HOST, PORT);
  5260. auto res = cli.Get("/role");
  5261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5262. EXPECT_EQ(StatusCode::OK_200, res->status);
  5263. EXPECT_EQ("admin", res->body);
  5264. }
  5265. TEST(InvalidFormatTest, StatusCode) {
  5266. Server svr;
  5267. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5268. res.set_content("Hello World!\n", "text/plain");
  5269. res.status = 9999; // Status should be a three-digit code...
  5270. });
  5271. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5272. auto se = detail::scope_exit([&] {
  5273. svr.stop();
  5274. thread.join();
  5275. ASSERT_FALSE(svr.is_running());
  5276. });
  5277. svr.wait_until_ready();
  5278. {
  5279. Client cli(HOST, PORT);
  5280. auto res = cli.Get("/hi");
  5281. ASSERT_FALSE(res);
  5282. }
  5283. }
  5284. TEST(URLFragmentTest, WithFragment) {
  5285. Server svr;
  5286. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5287. EXPECT_TRUE(req.target == "/hi");
  5288. });
  5289. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5290. auto se = detail::scope_exit([&] {
  5291. svr.stop();
  5292. thread.join();
  5293. ASSERT_FALSE(svr.is_running());
  5294. });
  5295. svr.wait_until_ready();
  5296. {
  5297. Client cli(HOST, PORT);
  5298. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5299. EXPECT_TRUE(res);
  5300. EXPECT_EQ(StatusCode::OK_200, res->status);
  5301. res = cli.Get("/hi%23key1=val1=key2=val2");
  5302. EXPECT_TRUE(res);
  5303. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5304. }
  5305. }
  5306. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5307. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5308. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5309. Server svr;
  5310. std::vector<std::string> targets;
  5311. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5312. targets.push_back(req.target);
  5313. });
  5314. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5315. auto se = detail::scope_exit([&] {
  5316. svr.stop();
  5317. thread.join();
  5318. ASSERT_FALSE(svr.is_running());
  5319. });
  5320. svr.wait_until_ready();
  5321. Client cli(HOST, PORT);
  5322. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5323. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5324. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5325. // A '?' after the '#' belongs to the fragment, not to the query.
  5326. Request req;
  5327. req.method = "GET";
  5328. req.path = "/hi#f?x=1";
  5329. req.params.emplace("a", "1");
  5330. Response res;
  5331. auto error = Error::Success;
  5332. EXPECT_TRUE(cli.send(req, res, error));
  5333. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5334. "/hi?a=1"}),
  5335. targets);
  5336. }
  5337. TEST(HeaderWriter, SetHeaderWriter) {
  5338. Server svr;
  5339. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5340. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5341. return detail::write_headers(strm, hdrs);
  5342. });
  5343. svr.Get("/hi", [](const Request &req, Response &res) {
  5344. auto it = req.headers.find("CustomClientHeader");
  5345. EXPECT_TRUE(it != req.headers.end());
  5346. EXPECT_EQ(it->second, "CustomClientValue");
  5347. res.set_content("Hello World!\n", "text/plain");
  5348. });
  5349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5350. auto se = detail::scope_exit([&] {
  5351. svr.stop();
  5352. thread.join();
  5353. ASSERT_FALSE(svr.is_running());
  5354. });
  5355. svr.wait_until_ready();
  5356. {
  5357. Client cli(HOST, PORT);
  5358. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5359. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5360. return detail::write_headers(strm, hdrs);
  5361. });
  5362. auto res = cli.Get("/hi");
  5363. EXPECT_TRUE(res);
  5364. EXPECT_EQ(StatusCode::OK_200, res->status);
  5365. auto it = res->headers.find("CustomServerHeader");
  5366. EXPECT_TRUE(it != res->headers.end());
  5367. EXPECT_EQ(it->second, "CustomServerValue");
  5368. }
  5369. }
  5370. class ServerTest : public ::testing::Test {
  5371. protected:
  5372. ServerTest()
  5373. : cli_(HOST, PORT)
  5374. #ifdef CPPHTTPLIB_SSL_ENABLED
  5375. ,
  5376. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5377. #endif
  5378. {
  5379. #ifdef CPPHTTPLIB_SSL_ENABLED
  5380. cli_.enable_server_certificate_verification(false);
  5381. #endif
  5382. // Allow LARGE_DATA (100MB) responses
  5383. cli_.set_payload_max_length(200 * 1024 * 1024);
  5384. }
  5385. virtual void SetUp() {
  5386. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5387. svr_.set_payload_max_length(200 * 1024 * 1024);
  5388. svr_.set_mount_point("/", "./www");
  5389. svr_.set_mount_point("/mount", "./www2");
  5390. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5391. svr_.Get("/hi",
  5392. [&](const Request & /*req*/, Response &res) {
  5393. res.set_content("Hello World!", "text/plain");
  5394. })
  5395. .Get("/file_content",
  5396. [&](const Request & /*req*/, Response &res) {
  5397. res.set_file_content("./www/dir/test.html");
  5398. })
  5399. .Get("/file_content_with_content_type",
  5400. [&](const Request & /*req*/, Response &res) {
  5401. res.set_file_content("./www/file", "text/plain");
  5402. })
  5403. .Get("/invalid_file_content",
  5404. [&](const Request & /*req*/, Response &res) {
  5405. res.set_file_content("./www/dir/invalid_file_path");
  5406. })
  5407. .Get("/http_response_splitting",
  5408. [&](const Request & /*req*/, Response &res) {
  5409. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5410. EXPECT_EQ(0U, res.headers.size());
  5411. EXPECT_FALSE(res.has_header("a"));
  5412. res.set_header("a", "1\nSet-Cookie: a=1");
  5413. EXPECT_EQ(0U, res.headers.size());
  5414. EXPECT_FALSE(res.has_header("a"));
  5415. res.set_header("a", "1\rSet-Cookie: a=1");
  5416. EXPECT_EQ(0U, res.headers.size());
  5417. EXPECT_FALSE(res.has_header("a"));
  5418. res.set_header("a\r\nb", "0");
  5419. EXPECT_EQ(0U, res.headers.size());
  5420. EXPECT_FALSE(res.has_header("a"));
  5421. res.set_header("a\rb", "0");
  5422. EXPECT_EQ(0U, res.headers.size());
  5423. EXPECT_FALSE(res.has_header("a"));
  5424. res.set_header("a\nb", "0");
  5425. EXPECT_EQ(0U, res.headers.size());
  5426. EXPECT_FALSE(res.has_header("a"));
  5427. res.set_redirect("1\r\nSet-Cookie: a=1");
  5428. EXPECT_EQ(0U, res.headers.size());
  5429. EXPECT_FALSE(res.has_header("Location"));
  5430. })
  5431. .Get("/slow",
  5432. [&](const Request & /*req*/, Response &res) {
  5433. std::this_thread::sleep_for(std::chrono::seconds(4));
  5434. res.set_content("slow", "text/plain");
  5435. })
  5436. #if 0
  5437. .Post("/slowpost",
  5438. [&](const Request & /*req*/, Response &res) {
  5439. std::this_thread::sleep_for(std::chrono::seconds(2));
  5440. res.set_content("slow", "text/plain");
  5441. })
  5442. #endif
  5443. .Get("/remote_addr",
  5444. [&](const Request &req, Response &res) {
  5445. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5446. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5447. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5448. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5449. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5450. #endif
  5451. res.set_content(req.remote_addr, "text/plain");
  5452. })
  5453. .Get("/local_addr",
  5454. [&](const Request &req, Response &res) {
  5455. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5456. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5457. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5458. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5459. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5460. #endif
  5461. auto local_addr = req.local_addr;
  5462. auto local_port = std::to_string(req.local_port);
  5463. res.set_content(local_addr.append(":").append(local_port),
  5464. "text/plain");
  5465. })
  5466. .Get("/endwith%",
  5467. [&](const Request & /*req*/, Response &res) {
  5468. res.set_content("Hello World!", "text/plain");
  5469. })
  5470. .Get("/a\\+\\+b",
  5471. [&](const Request &req, Response &res) {
  5472. ASSERT_TRUE(req.has_param("a +b"));
  5473. auto val = req.get_param_value("a +b");
  5474. res.set_content(val, "text/plain");
  5475. })
  5476. .Get("/", [&](const Request & /*req*/,
  5477. Response &res) { res.set_redirect("/hi"); })
  5478. .Post("/1",
  5479. [](const Request & /*req*/, Response &res) {
  5480. res.set_redirect("/2", StatusCode::SeeOther_303);
  5481. })
  5482. .Get("/2",
  5483. [](const Request & /*req*/, Response &res) {
  5484. res.set_content("redirected.", "text/plain");
  5485. res.status = StatusCode::OK_200;
  5486. })
  5487. .Post("/person",
  5488. [&](const Request &req, Response &res) {
  5489. if (req.has_param("name") && req.has_param("note")) {
  5490. persons_[req.get_param_value("name")] =
  5491. req.get_param_value("note");
  5492. } else {
  5493. res.status = StatusCode::BadRequest_400;
  5494. }
  5495. })
  5496. .Put("/person",
  5497. [&](const Request &req, Response &res) {
  5498. if (req.has_param("name") && req.has_param("note")) {
  5499. persons_[req.get_param_value("name")] =
  5500. req.get_param_value("note");
  5501. } else {
  5502. res.status = StatusCode::BadRequest_400;
  5503. }
  5504. })
  5505. .Get("/person/(.*)",
  5506. [&](const Request &req, Response &res) {
  5507. string name = req.matches[1];
  5508. if (persons_.find(name) != persons_.end()) {
  5509. auto note = persons_[name];
  5510. res.set_content(note, "text/plain");
  5511. } else {
  5512. res.status = StatusCode::NotFound_404;
  5513. }
  5514. })
  5515. .Delete("/person",
  5516. [&](const Request &req, Response &res) {
  5517. if (req.has_param("name")) {
  5518. string name = req.get_param_value("name");
  5519. if (persons_.find(name) != persons_.end()) {
  5520. persons_.erase(name);
  5521. res.set_content("DELETED", "text/plain");
  5522. } else {
  5523. res.status = StatusCode::NotFound_404;
  5524. }
  5525. } else {
  5526. res.status = StatusCode::BadRequest_400;
  5527. }
  5528. })
  5529. .Post("/x-www-form-urlencoded-json",
  5530. [&](const Request &req, Response &res) {
  5531. auto json = req.get_param_value("json");
  5532. ASSERT_EQ(JSON_DATA, json);
  5533. res.set_content(json, "appliation/json");
  5534. res.status = StatusCode::OK_200;
  5535. })
  5536. .Get("/streamed-chunked",
  5537. [&](const Request & /*req*/, Response &res) {
  5538. res.set_chunked_content_provider(
  5539. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5540. sink.os << "123";
  5541. sink.os << "456";
  5542. sink.os << "789";
  5543. sink.done();
  5544. return true;
  5545. });
  5546. })
  5547. .Get("/streamed-chunked-with-prohibited-trailer",
  5548. [&](const Request & /*req*/, Response &res) {
  5549. auto i = new int(0);
  5550. // Declare both a prohibited trailer (Content-Length) and an
  5551. // allowed one
  5552. res.set_header("Trailer", "Content-Length, X-Allowed");
  5553. res.set_chunked_content_provider(
  5554. "text/plain",
  5555. [i](size_t /*offset*/, DataSink &sink) {
  5556. switch (*i) {
  5557. case 0: sink.os << "123"; break;
  5558. case 1: sink.os << "456"; break;
  5559. case 2: sink.os << "789"; break;
  5560. case 3: {
  5561. sink.done_with_trailer(
  5562. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5563. } break;
  5564. }
  5565. (*i)++;
  5566. return true;
  5567. },
  5568. [i](bool success) {
  5569. EXPECT_TRUE(success);
  5570. delete i;
  5571. });
  5572. })
  5573. .Get("/streamed-chunked2",
  5574. [&](const Request & /*req*/, Response &res) {
  5575. auto i = new int(0);
  5576. res.set_chunked_content_provider(
  5577. "text/plain",
  5578. [i](size_t /*offset*/, DataSink &sink) {
  5579. switch (*i) {
  5580. case 0: sink.os << "123"; break;
  5581. case 1: sink.os << "456"; break;
  5582. case 2: sink.os << "789"; break;
  5583. case 3: sink.done(); break;
  5584. }
  5585. (*i)++;
  5586. return true;
  5587. },
  5588. [i](bool success) {
  5589. EXPECT_TRUE(success);
  5590. delete i;
  5591. });
  5592. })
  5593. .Get("/streamed-chunked-with-trailer",
  5594. [&](const Request & /*req*/, Response &res) {
  5595. auto i = new int(0);
  5596. res.set_header("Trailer", "Dummy1, Dummy2");
  5597. res.set_chunked_content_provider(
  5598. "text/plain",
  5599. [i](size_t /*offset*/, DataSink &sink) {
  5600. switch (*i) {
  5601. case 0: sink.os << "123"; break;
  5602. case 1: sink.os << "456"; break;
  5603. case 2: sink.os << "789"; break;
  5604. case 3: {
  5605. sink.done_with_trailer(
  5606. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5607. } break;
  5608. }
  5609. (*i)++;
  5610. return true;
  5611. },
  5612. [i](bool success) {
  5613. EXPECT_TRUE(success);
  5614. delete i;
  5615. });
  5616. })
  5617. .Get("/streamed",
  5618. [&](const Request & /*req*/, Response &res) {
  5619. res.set_content_provider(
  5620. 6, "text/plain",
  5621. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5622. sink.os << (offset < 3 ? "a" : "b");
  5623. return true;
  5624. });
  5625. })
  5626. .Get("/streamed-without-length",
  5627. [&](const Request & /*req*/, Response &res) {
  5628. auto data = new std::string("abcdefg");
  5629. res.set_content_provider(
  5630. "text/plain",
  5631. [data](size_t offset, DataSink &sink) {
  5632. if (offset < data->size()) {
  5633. sink.os << data->substr(offset);
  5634. }
  5635. sink.done();
  5636. return true;
  5637. },
  5638. [data](bool success) {
  5639. EXPECT_TRUE(success);
  5640. delete data;
  5641. });
  5642. })
  5643. .Get("/streamed-with-range",
  5644. [&](const Request &req, Response &res) {
  5645. auto data = new std::string("abcdefg");
  5646. // An explicit status keeps the server from picking the 206 it
  5647. // would otherwise choose for a ranged request, so the response
  5648. // is not a partial representation.
  5649. auto status = req.get_param_value("status");
  5650. if (status == "200") {
  5651. res.status = StatusCode::OK_200;
  5652. } else if (status == "403") {
  5653. res.status = StatusCode::Forbidden_403;
  5654. }
  5655. res.set_content_provider(
  5656. data->size(), "text/plain",
  5657. [data](size_t offset, size_t length, DataSink &sink) {
  5658. size_t DATA_CHUNK_SIZE = 4;
  5659. const auto &d = *data;
  5660. auto out_len =
  5661. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5662. auto ret =
  5663. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5664. EXPECT_TRUE(ret);
  5665. return true;
  5666. },
  5667. [data, &req](bool success) {
  5668. EXPECT_EQ(success, !req.has_param("error"));
  5669. delete data;
  5670. });
  5671. })
  5672. .Get("/streamed-cancel",
  5673. [&](const Request & /*req*/, Response &res) {
  5674. res.set_content_provider(
  5675. size_t(-1), "text/plain",
  5676. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5677. sink.os << "data_chunk";
  5678. return true;
  5679. });
  5680. })
  5681. .Get("/regex-with-delimiter",
  5682. [&](const Request &req, Response & /*res*/) {
  5683. ASSERT_TRUE(req.has_param("key"));
  5684. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5685. })
  5686. .Get("/with-range",
  5687. [&](const Request & /*req*/, Response &res) {
  5688. res.set_content("abcdefg", "text/plain");
  5689. })
  5690. .Get("/test-start-time",
  5691. [&](const Request &req, Response & /*res*/) {
  5692. EXPECT_NE(req.start_time_,
  5693. std::chrono::steady_clock::time_point::min());
  5694. })
  5695. .Get("/with-range-customized-response",
  5696. [&](const Request & /*req*/, Response &res) {
  5697. res.status = StatusCode::BadRequest_400;
  5698. res.set_content(JSON_DATA, "application/json");
  5699. })
  5700. .Post("/chunked",
  5701. [&](const Request &req, Response & /*res*/) {
  5702. EXPECT_EQ(req.body, "dechunked post body");
  5703. })
  5704. .Post("/large-chunked",
  5705. [&](const Request &req, Response & /*res*/) {
  5706. std::string expected(6 * 30 * 1024u, 'a');
  5707. EXPECT_EQ(req.body, expected);
  5708. })
  5709. .Post("/multipart",
  5710. [&](const Request &req, Response & /*res*/) {
  5711. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5712. req.form.get_field_count("text2") +
  5713. req.form.get_field_count("file3") +
  5714. req.form.get_field_count("file4"));
  5715. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5716. req.form.get_file_count("file2"));
  5717. ASSERT_TRUE(!req.form.has_file("???"));
  5718. ASSERT_TRUE(!req.form.has_field("???"));
  5719. ASSERT_TRUE(req.body.empty());
  5720. {
  5721. const auto &text = req.form.get_field("text1");
  5722. EXPECT_EQ("text default", text);
  5723. }
  5724. {
  5725. const auto &text = req.form.get_field("text2");
  5726. EXPECT_EQ("aωb", text);
  5727. }
  5728. {
  5729. const auto &file = req.form.get_file("file1");
  5730. EXPECT_EQ("hello.txt", file.filename);
  5731. EXPECT_EQ("text/plain", file.content_type);
  5732. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5733. }
  5734. {
  5735. const auto &file = req.form.get_file("file2");
  5736. EXPECT_EQ("world.json", file.filename);
  5737. EXPECT_EQ("application/json", file.content_type);
  5738. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5739. }
  5740. {
  5741. const auto &text = req.form.get_field("file3");
  5742. EXPECT_EQ(0u, text.size());
  5743. }
  5744. {
  5745. const auto &text = req.form.get_field("file4");
  5746. EXPECT_EQ(0u, text.size());
  5747. }
  5748. })
  5749. .Post("/multipart/multi_file_values",
  5750. [&](const Request &req, Response & /*res*/) {
  5751. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5752. req.form.get_field_count("multi_text1"));
  5753. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5754. ASSERT_TRUE(!req.form.has_file("???"));
  5755. ASSERT_TRUE(!req.form.has_field("???"));
  5756. ASSERT_TRUE(req.body.empty());
  5757. {
  5758. const auto &text = req.form.get_field("text");
  5759. EXPECT_EQ("default text", text);
  5760. }
  5761. {
  5762. const auto &text1_values = req.form.get_fields("multi_text1");
  5763. EXPECT_EQ(2u, text1_values.size());
  5764. EXPECT_EQ("aaaaa", text1_values[0]);
  5765. EXPECT_EQ("bbbbb", text1_values[1]);
  5766. }
  5767. {
  5768. const auto &file1_values = req.form.get_files("multi_file1");
  5769. EXPECT_EQ(2u, file1_values.size());
  5770. auto file1 = file1_values[0];
  5771. EXPECT_EQ(file1.filename, "hello.txt");
  5772. EXPECT_EQ(file1.content_type, "text/plain");
  5773. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5774. auto file2 = file1_values[1];
  5775. EXPECT_EQ(file2.filename, "world.json");
  5776. EXPECT_EQ(file2.content_type, "application/json");
  5777. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5778. }
  5779. })
  5780. .Post("/empty",
  5781. [&](const Request &req, Response &res) {
  5782. EXPECT_EQ(req.body, "");
  5783. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5784. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5785. res.set_content("empty", "text/plain");
  5786. })
  5787. .Post("/empty-no-content-type",
  5788. [&](const Request &req, Response &res) {
  5789. EXPECT_EQ(req.body, "");
  5790. EXPECT_FALSE(req.has_header("Content-Type"));
  5791. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5792. res.set_content("empty-no-content-type", "text/plain");
  5793. })
  5794. .Post("/path-only",
  5795. [&](const Request &req, Response &res) {
  5796. EXPECT_EQ(req.body, "");
  5797. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5798. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5799. res.set_content("path-only", "text/plain");
  5800. })
  5801. .Post("/path-headers-only",
  5802. [&](const Request &req, Response &res) {
  5803. EXPECT_EQ(req.body, "");
  5804. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5805. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5806. EXPECT_EQ("world", req.get_header_value("hello"));
  5807. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5808. res.set_content("path-headers-only", "text/plain");
  5809. })
  5810. .Post("/post-large",
  5811. [&](const Request &req, Response &res) {
  5812. EXPECT_EQ(req.body, LARGE_DATA);
  5813. res.set_content(req.body, "text/plain");
  5814. })
  5815. .Post("/post-loopback",
  5816. [&](const Request &, Response &res,
  5817. ContentReader const &content_reader) {
  5818. std::string body;
  5819. content_reader([&](const char *data, size_t data_length) {
  5820. body.append(data, data_length);
  5821. return true;
  5822. });
  5823. res.set_content(body, "text/plain");
  5824. })
  5825. .Put("/put-loopback",
  5826. [&](const Request &, Response &res,
  5827. ContentReader const &content_reader) {
  5828. std::string body;
  5829. content_reader([&](const char *data, size_t data_length) {
  5830. body.append(data, data_length);
  5831. return true;
  5832. });
  5833. res.set_content(body, "text/plain");
  5834. })
  5835. .Patch("/patch-loopback",
  5836. [&](const Request &, Response &res,
  5837. ContentReader const &content_reader) {
  5838. std::string body;
  5839. content_reader([&](const char *data, size_t data_length) {
  5840. body.append(data, data_length);
  5841. return true;
  5842. });
  5843. res.set_content(body, "text/plain");
  5844. })
  5845. .Put("/empty-no-content-type",
  5846. [&](const Request &req, Response &res) {
  5847. EXPECT_EQ(req.body, "");
  5848. EXPECT_FALSE(req.has_header("Content-Type"));
  5849. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5850. res.set_content("empty-no-content-type", "text/plain");
  5851. })
  5852. .Put("/put",
  5853. [&](const Request &req, Response &res) {
  5854. EXPECT_EQ(req.body, "PUT");
  5855. res.set_content(req.body, "text/plain");
  5856. })
  5857. .Put("/put-large",
  5858. [&](const Request &req, Response &res) {
  5859. EXPECT_EQ(req.body, LARGE_DATA);
  5860. res.set_content(req.body, "text/plain");
  5861. })
  5862. .Patch("/patch",
  5863. [&](const Request &req, Response &res) {
  5864. EXPECT_EQ(req.body, "PATCH");
  5865. res.set_content(req.body, "text/plain");
  5866. })
  5867. .Delete("/delete",
  5868. [&](const Request & /*req*/, Response &res) {
  5869. res.set_content("DELETE", "text/plain");
  5870. })
  5871. .Delete("/delete-body",
  5872. [&](const Request &req, Response &res) {
  5873. EXPECT_EQ(req.body, "content");
  5874. res.set_content(req.body, "text/plain");
  5875. })
  5876. .Options(R"(\*)",
  5877. [&](const Request & /*req*/, Response &res) {
  5878. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5879. })
  5880. .CustomRoute("PROPFIND", "/dav/:id",
  5881. [&](const Request &req, Response &res) {
  5882. res.set_header("x-body-size",
  5883. std::to_string(req.body.size()));
  5884. res.set_header("x-matched-route", req.matched_route);
  5885. res.set_header("x-dav-id", req.path_params.at("id"));
  5886. res.status = StatusCode::MultiStatus_207;
  5887. res.set_content(req.body, "application/xml");
  5888. })
  5889. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5890. [&](const Request &req, Response &res) {
  5891. res.set_header("x-dav-match", req.matches[1]);
  5892. res.status = StatusCode::MultiStatus_207;
  5893. })
  5894. .CustomRoute("MKCOL", "/dav-mkcol",
  5895. [&](const Request &req, Response &res) {
  5896. EXPECT_TRUE(req.body.empty());
  5897. res.status = StatusCode::Created_201;
  5898. })
  5899. .CustomRoute(
  5900. "REPORT", "/dav-report",
  5901. [&](const Request & /*req*/, Response &res,
  5902. const ContentReader &content_reader) {
  5903. std::string body;
  5904. content_reader([&](const char *data, size_t data_length) {
  5905. body.append(data, data_length);
  5906. return true;
  5907. });
  5908. res.set_header("x-body-size", std::to_string(body.size()));
  5909. res.status = StatusCode::MultiStatus_207;
  5910. res.set_content(body, "application/xml");
  5911. })
  5912. .Get("/request-target",
  5913. [&](const Request &req, Response & /*res*/) {
  5914. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5915. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5916. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5917. })
  5918. .Get("/long-query-value",
  5919. [&](const Request &req, Response & /*res*/) {
  5920. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5921. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5922. })
  5923. .Get("/too-long-query-value",
  5924. [&](const Request &req, Response & /*res*/) {
  5925. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5926. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5927. })
  5928. .Get("/array-param",
  5929. [&](const Request &req, Response & /*res*/) {
  5930. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5931. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5932. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5933. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5934. })
  5935. .Get("/array-param-values",
  5936. [&](const Request &req, Response & /*res*/) {
  5937. auto values = req.get_param_values("array");
  5938. EXPECT_EQ(3u, values.size());
  5939. EXPECT_EQ("value1", values[0]);
  5940. EXPECT_EQ("value2", values[1]);
  5941. EXPECT_EQ("value3", values[2]);
  5942. auto empty = req.get_param_values("nonexistent");
  5943. EXPECT_TRUE(empty.empty());
  5944. })
  5945. .Post("/validate-no-multiple-headers",
  5946. [&](const Request &req, Response & /*res*/) {
  5947. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5948. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5949. })
  5950. .Post("/content_receiver",
  5951. [&](const Request &req, Response &res,
  5952. const ContentReader &content_reader) {
  5953. if (req.is_multipart_form_data()) {
  5954. std::vector<FormData> items;
  5955. content_reader(
  5956. [&](const FormData &file) {
  5957. items.push_back(file);
  5958. return true;
  5959. },
  5960. [&](const char *data, size_t data_length) {
  5961. items.back().content.append(data, data_length);
  5962. return true;
  5963. });
  5964. EXPECT_EQ(5u, items.size());
  5965. {
  5966. const auto &file = get_file_value(items, "text1");
  5967. EXPECT_TRUE(file.filename.empty());
  5968. EXPECT_EQ("text default", file.content);
  5969. }
  5970. {
  5971. const auto &file = get_file_value(items, "text2");
  5972. EXPECT_TRUE(file.filename.empty());
  5973. EXPECT_EQ("aωb", file.content);
  5974. }
  5975. {
  5976. const auto &file = get_file_value(items, "file1");
  5977. EXPECT_EQ("hello.txt", file.filename);
  5978. EXPECT_EQ("text/plain", file.content_type);
  5979. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5980. }
  5981. {
  5982. const auto &file = get_file_value(items, "file2");
  5983. EXPECT_EQ("world.json", file.filename);
  5984. EXPECT_EQ("application/json", file.content_type);
  5985. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5986. }
  5987. {
  5988. const auto &file = get_file_value(items, "file3");
  5989. EXPECT_TRUE(file.filename.empty());
  5990. EXPECT_EQ("application/octet-stream", file.content_type);
  5991. EXPECT_EQ(0u, file.content.size());
  5992. }
  5993. } else {
  5994. std::string body;
  5995. content_reader([&](const char *data, size_t data_length) {
  5996. EXPECT_EQ(7U, data_length);
  5997. body.append(data, data_length);
  5998. return true;
  5999. });
  6000. EXPECT_EQ(body, "content");
  6001. res.set_content(body, "text/plain");
  6002. }
  6003. })
  6004. .Put("/content_receiver",
  6005. [&](const Request & /*req*/, Response &res,
  6006. const ContentReader &content_reader) {
  6007. std::string body;
  6008. content_reader([&](const char *data, size_t data_length) {
  6009. body.append(data, data_length);
  6010. return true;
  6011. });
  6012. EXPECT_EQ(body, "content");
  6013. res.set_content(body, "text/plain");
  6014. })
  6015. .Patch("/content_receiver",
  6016. [&](const Request & /*req*/, Response &res,
  6017. const ContentReader &content_reader) {
  6018. std::string body;
  6019. content_reader([&](const char *data, size_t data_length) {
  6020. body.append(data, data_length);
  6021. return true;
  6022. });
  6023. EXPECT_EQ(body, "content");
  6024. res.set_content(body, "text/plain");
  6025. })
  6026. .Post("/query-string-and-body",
  6027. [&](const Request &req, Response & /*res*/) {
  6028. ASSERT_TRUE(req.has_param("key"));
  6029. EXPECT_EQ(req.get_param_value("key"), "value");
  6030. EXPECT_EQ(req.body, "content");
  6031. })
  6032. .Get("/last-request",
  6033. [&](const Request &req, Response & /*res*/) {
  6034. EXPECT_EQ("close", req.get_header_value("Connection"));
  6035. })
  6036. .Get(R"(/redirect/(\d+))",
  6037. [&](const Request &req, Response &res) {
  6038. auto num = std::stoi(req.matches[1]) + 1;
  6039. std::string url = "/redirect/" + std::to_string(num);
  6040. res.set_redirect(url);
  6041. })
  6042. .Post("/binary",
  6043. [&](const Request &req, Response &res) {
  6044. EXPECT_EQ(4U, req.body.size());
  6045. EXPECT_EQ("application/octet-stream",
  6046. req.get_header_value("Content-Type"));
  6047. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6048. res.set_content(req.body, "application/octet-stream");
  6049. })
  6050. .Put("/binary",
  6051. [&](const Request &req, Response &res) {
  6052. EXPECT_EQ(4U, req.body.size());
  6053. EXPECT_EQ("application/octet-stream",
  6054. req.get_header_value("Content-Type"));
  6055. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6056. res.set_content(req.body, "application/octet-stream");
  6057. })
  6058. .Patch("/binary",
  6059. [&](const Request &req, Response &res) {
  6060. EXPECT_EQ(4U, req.body.size());
  6061. EXPECT_EQ("application/octet-stream",
  6062. req.get_header_value("Content-Type"));
  6063. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6064. res.set_content(req.body, "application/octet-stream");
  6065. })
  6066. .Delete("/binary",
  6067. [&](const Request &req, Response &res) {
  6068. EXPECT_EQ(4U, req.body.size());
  6069. EXPECT_EQ("application/octet-stream",
  6070. req.get_header_value("Content-Type"));
  6071. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6072. res.set_content(req.body, "application/octet-stream");
  6073. })
  6074. .Get("/issue1772",
  6075. [&](const Request & /*req*/, Response &res) {
  6076. res.status = 401;
  6077. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6078. })
  6079. .Delete("/issue609",
  6080. [](const httplib::Request &, httplib::Response &res,
  6081. const httplib::ContentReader &) {
  6082. res.set_content("ok", "text/plain");
  6083. })
  6084. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6085. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6086. .Get("/compress",
  6087. [&](const Request & /*req*/, Response &res) {
  6088. res.set_content(
  6089. "12345678901234567890123456789012345678901234567890123456789"
  6090. "01234567890123456789012345678901234567890",
  6091. "text/plain");
  6092. })
  6093. .Get("/compress-with-charset",
  6094. [&](const Request & /*req*/, Response &res) {
  6095. res.set_content(
  6096. "12345678901234567890123456789012345678901234567890123456789"
  6097. "01234567890123456789012345678901234567890",
  6098. "application/json; charset=utf-8");
  6099. })
  6100. .Get("/nocompress",
  6101. [&](const Request & /*req*/, Response &res) {
  6102. res.set_content(
  6103. "12345678901234567890123456789012345678901234567890123456789"
  6104. "01234567890123456789012345678901234567890",
  6105. "application/octet-stream");
  6106. })
  6107. .Post("/compress-multipart",
  6108. [&](const Request &req, Response & /*res*/) {
  6109. EXPECT_EQ(2u, req.form.fields.size());
  6110. ASSERT_TRUE(!req.form.has_field("???"));
  6111. {
  6112. const auto &text = req.form.get_field("key1");
  6113. EXPECT_EQ("test", text);
  6114. }
  6115. {
  6116. const auto &text = req.form.get_field("key2");
  6117. EXPECT_EQ("--abcdefg123", text);
  6118. }
  6119. })
  6120. #endif
  6121. ;
  6122. persons_["john"] = "programmer";
  6123. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6124. svr_.wait_until_ready();
  6125. }
  6126. virtual void TearDown() {
  6127. svr_.stop();
  6128. if (!request_threads_.empty()) {
  6129. std::this_thread::sleep_for(std::chrono::seconds(1));
  6130. for (auto &t : request_threads_) {
  6131. t.join();
  6132. }
  6133. }
  6134. t_.join();
  6135. }
  6136. map<string, string> persons_;
  6137. #ifdef CPPHTTPLIB_SSL_ENABLED
  6138. SSLClient cli_;
  6139. SSLServer svr_;
  6140. #else
  6141. Client cli_;
  6142. Server svr_;
  6143. #endif
  6144. thread t_;
  6145. std::vector<thread> request_threads_;
  6146. };
  6147. TEST_F(ServerTest, GetMethod200) {
  6148. auto res = cli_.Get("/hi");
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. EXPECT_EQ("HTTP/1.1", res->version);
  6151. EXPECT_EQ(StatusCode::OK_200, res->status);
  6152. EXPECT_EQ("OK", res->reason);
  6153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6154. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6155. EXPECT_EQ("Hello World!", res->body);
  6156. }
  6157. TEST_F(ServerTest, GetEmptyFile) {
  6158. auto res = cli_.Get("/empty_file");
  6159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6160. EXPECT_EQ(StatusCode::OK_200, res->status);
  6161. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6162. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6163. EXPECT_EQ("", res->body);
  6164. }
  6165. TEST_F(ServerTest, GetFileContent) {
  6166. auto res = cli_.Get("/file_content");
  6167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6168. EXPECT_EQ(StatusCode::OK_200, res->status);
  6169. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6170. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6171. EXPECT_EQ("test.html", res->body);
  6172. }
  6173. TEST_F(ServerTest, GetFileContentWithRange) {
  6174. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6177. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6178. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6179. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6180. EXPECT_EQ("est", res->body);
  6181. }
  6182. TEST_F(ServerTest, GetFileContentWithContentType) {
  6183. auto res = cli_.Get("/file_content_with_content_type");
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. EXPECT_EQ(StatusCode::OK_200, res->status);
  6186. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6187. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6188. EXPECT_EQ("file\n", res->body);
  6189. }
  6190. TEST_F(ServerTest, GetInvalidFileContent) {
  6191. auto res = cli_.Get("/invalid_file_content");
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6194. }
  6195. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6196. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. EXPECT_EQ("HTTP/1.1", res->version);
  6199. EXPECT_EQ(StatusCode::OK_200, res->status);
  6200. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6201. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6202. EXPECT_EQ("Hello World!", res->body);
  6203. }
  6204. TEST_F(ServerTest, GetMethod302) {
  6205. auto res = cli_.Get("/");
  6206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6207. EXPECT_EQ(StatusCode::Found_302, res->status);
  6208. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6209. }
  6210. TEST_F(ServerTest, GetMethod302Redirect) {
  6211. cli_.set_follow_location(true);
  6212. auto res = cli_.Get("/");
  6213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. EXPECT_EQ("Hello World!", res->body);
  6216. EXPECT_EQ("/hi", res->location);
  6217. }
  6218. TEST_F(ServerTest, GetMethod404) {
  6219. auto res = cli_.Get("/invalid");
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6222. }
  6223. TEST_F(ServerTest, HeadMethod200) {
  6224. auto res = cli_.Head("/hi");
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. EXPECT_EQ(StatusCode::OK_200, res->status);
  6227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6228. EXPECT_TRUE(res->body.empty());
  6229. }
  6230. TEST_F(ServerTest, HeadMethod200Static) {
  6231. auto res = cli_.Head("/mount/dir/index.html");
  6232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6233. EXPECT_EQ(StatusCode::OK_200, res->status);
  6234. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6235. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6236. EXPECT_TRUE(res->body.empty());
  6237. }
  6238. TEST_F(ServerTest, HeadMethod404) {
  6239. auto res = cli_.Head("/invalid");
  6240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6241. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6242. EXPECT_TRUE(res->body.empty());
  6243. }
  6244. TEST_F(ServerTest, GetMethodPersonJohn) {
  6245. auto res = cli_.Get("/person/john");
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. EXPECT_EQ(StatusCode::OK_200, res->status);
  6248. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6249. EXPECT_EQ("programmer", res->body);
  6250. }
  6251. TEST_F(ServerTest, PostMethod1) {
  6252. auto res = cli_.Get("/person/john1");
  6253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6254. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6255. res = cli_.Post("/person", "name=john1&note=coder",
  6256. "application/x-www-form-urlencoded");
  6257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6258. ASSERT_EQ(StatusCode::OK_200, res->status);
  6259. res = cli_.Get("/person/john1");
  6260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6261. ASSERT_EQ(StatusCode::OK_200, res->status);
  6262. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6263. ASSERT_EQ("coder", res->body);
  6264. }
  6265. TEST_F(ServerTest, PostMethod2) {
  6266. auto res = cli_.Get("/person/john2");
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6269. Params params;
  6270. params.emplace("name", "john2");
  6271. params.emplace("note", "coder");
  6272. res = cli_.Post("/person", params);
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. ASSERT_EQ(StatusCode::OK_200, res->status);
  6275. res = cli_.Get("/person/john2");
  6276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6277. ASSERT_EQ(StatusCode::OK_200, res->status);
  6278. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6279. ASSERT_EQ("coder", res->body);
  6280. }
  6281. TEST_F(ServerTest, PutMethod3) {
  6282. auto res = cli_.Get("/person/john3");
  6283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6284. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6285. Params params;
  6286. params.emplace("name", "john3");
  6287. params.emplace("note", "coder");
  6288. res = cli_.Put("/person", params);
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. ASSERT_EQ(StatusCode::OK_200, res->status);
  6291. res = cli_.Get("/person/john3");
  6292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6293. ASSERT_EQ(StatusCode::OK_200, res->status);
  6294. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6295. ASSERT_EQ("coder", res->body);
  6296. }
  6297. TEST_F(ServerTest, DeleteMethod1) {
  6298. auto res = cli_.Get("/person/john4");
  6299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6300. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6301. Params params;
  6302. params.emplace("name", "john4");
  6303. params.emplace("note", "coder");
  6304. res = cli_.Post("/person", params);
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. ASSERT_EQ(StatusCode::OK_200, res->status);
  6307. res = cli_.Get("/person/john4");
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. ASSERT_EQ(StatusCode::OK_200, res->status);
  6310. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6311. ASSERT_EQ("coder", res->body);
  6312. Params delete_params;
  6313. delete_params.emplace("name", "john4");
  6314. res = cli_.Delete("/person", delete_params);
  6315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6316. ASSERT_EQ(StatusCode::OK_200, res->status);
  6317. ASSERT_EQ("DELETED", res->body);
  6318. res = cli_.Get("/person/john4");
  6319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6320. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6321. }
  6322. TEST_F(ServerTest, DeleteMethod2) {
  6323. auto res = cli_.Get("/person/john5");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6326. Params params;
  6327. params.emplace("name", "john5");
  6328. params.emplace("note", "developer");
  6329. res = cli_.Post("/person", params);
  6330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6331. ASSERT_EQ(StatusCode::OK_200, res->status);
  6332. res = cli_.Get("/person/john5");
  6333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6334. ASSERT_EQ(StatusCode::OK_200, res->status);
  6335. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6336. ASSERT_EQ("developer", res->body);
  6337. Params delete_params;
  6338. delete_params.emplace("name", "john5");
  6339. Headers headers;
  6340. headers.emplace("Custom-Header", "test-value");
  6341. res = cli_.Delete("/person", headers, delete_params);
  6342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6343. ASSERT_EQ(StatusCode::OK_200, res->status);
  6344. ASSERT_EQ("DELETED", res->body);
  6345. res = cli_.Get("/person/john5");
  6346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6347. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6348. }
  6349. TEST_F(ServerTest, DeleteMethod3) {
  6350. auto res = cli_.Get("/person/john6");
  6351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6352. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6353. Params params;
  6354. params.emplace("name", "john6");
  6355. params.emplace("note", "tester");
  6356. res = cli_.Post("/person", params);
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. ASSERT_EQ(StatusCode::OK_200, res->status);
  6359. res = cli_.Get("/person/john6");
  6360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6361. ASSERT_EQ(StatusCode::OK_200, res->status);
  6362. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6363. ASSERT_EQ("tester", res->body);
  6364. Params delete_params;
  6365. delete_params.emplace("name", "john6");
  6366. Headers headers;
  6367. headers.emplace("Custom-Header", "test-value");
  6368. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. ASSERT_EQ(StatusCode::OK_200, res->status);
  6371. ASSERT_EQ("DELETED", res->body);
  6372. res = cli_.Get("/person/john6");
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6375. }
  6376. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6377. Params params;
  6378. params.emplace("json", JSON_DATA);
  6379. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. ASSERT_EQ(StatusCode::OK_200, res->status);
  6382. ASSERT_EQ(JSON_DATA, res->body);
  6383. }
  6384. TEST_F(ServerTest, PostEmptyContent) {
  6385. auto res = cli_.Post("/empty", "", "text/plain");
  6386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6387. ASSERT_EQ(StatusCode::OK_200, res->status);
  6388. ASSERT_EQ("empty", res->body);
  6389. }
  6390. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6391. auto res = cli_.Post("/empty-no-content-type");
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. ASSERT_EQ(StatusCode::OK_200, res->status);
  6394. ASSERT_EQ("empty-no-content-type", res->body);
  6395. }
  6396. TEST_F(ServerTest, PostPathOnly) {
  6397. auto res = cli_.Post("/path-only");
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. ASSERT_EQ(StatusCode::OK_200, res->status);
  6400. ASSERT_EQ("path-only", res->body);
  6401. }
  6402. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6403. auto res = cli_.Post("/path-headers-only",
  6404. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6406. ASSERT_EQ(StatusCode::OK_200, res->status);
  6407. ASSERT_EQ("path-headers-only", res->body);
  6408. }
  6409. TEST_F(ServerTest, PostLarge) {
  6410. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6412. ASSERT_EQ(StatusCode::OK_200, res->status);
  6413. EXPECT_EQ(LARGE_DATA, res->body);
  6414. }
  6415. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6416. auto res = cli_.Put("/empty-no-content-type");
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. ASSERT_EQ(StatusCode::OK_200, res->status);
  6419. ASSERT_EQ("empty-no-content-type", res->body);
  6420. }
  6421. TEST_F(ServerTest, GetMethodDir) {
  6422. auto res = cli_.Get("/dir/");
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. EXPECT_EQ(StatusCode::OK_200, res->status);
  6425. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6426. auto body = R"(<html>
  6427. <head>
  6428. </head>
  6429. <body>
  6430. <a href="/dir/test.html">Test</a>
  6431. <a href="/hi">hi</a>
  6432. </body>
  6433. </html>
  6434. )";
  6435. EXPECT_EQ(body, res->body);
  6436. }
  6437. TEST_F(ServerTest, GetMethodDirTest) {
  6438. auto res = cli_.Get("/dir/test.html");
  6439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6440. EXPECT_EQ(StatusCode::OK_200, res->status);
  6441. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6442. EXPECT_EQ("test.html", res->body);
  6443. }
  6444. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6445. auto res = cli_.Get("/dir/../dir/test.html");
  6446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6447. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6448. }
  6449. TEST_F(ServerTest, GetMethodInvalidPath) {
  6450. auto res = cli_.Get("/dir/../test.html");
  6451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6452. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6453. }
  6454. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6455. auto res = cli_.Get("/../www/dir/test.html");
  6456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6457. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6458. }
  6459. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6460. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6462. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6463. }
  6464. TEST_F(ServerTest, GetMethodDirMountTest) {
  6465. auto res = cli_.Get("/mount/dir/test.html");
  6466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6467. EXPECT_EQ(StatusCode::OK_200, res->status);
  6468. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6469. EXPECT_EQ("test.html", res->body);
  6470. }
  6471. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6472. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6474. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6475. }
  6476. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6477. auto res = cli_.Get("/mount/dir/../test.html");
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6480. }
  6481. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6482. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6485. }
  6486. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6487. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6489. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6490. }
  6491. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6492. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6494. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6495. }
  6496. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6497. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6499. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6500. }
  6501. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6502. auto res = cli_.Get("/mount/dir");
  6503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6504. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6505. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6506. }
  6507. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6508. auto res = cli_.Get("//dir");
  6509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6510. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6511. EXPECT_FALSE(res->has_header("Location"));
  6512. }
  6513. TEST_F(ServerTest, PostMethod303) {
  6514. auto res = cli_.Post("/1", "body", "text/plain");
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6517. EXPECT_EQ("/2", res->get_header_value("Location"));
  6518. }
  6519. TEST_F(ServerTest, PostMethod303Redirect) {
  6520. cli_.set_follow_location(true);
  6521. auto res = cli_.Post("/1", "body", "text/plain");
  6522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6523. EXPECT_EQ(StatusCode::OK_200, res->status);
  6524. EXPECT_EQ("redirected.", res->body);
  6525. EXPECT_EQ("/2", res->location);
  6526. }
  6527. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6528. auto res = cli_.Get("/dir/test.abcde");
  6529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6530. EXPECT_EQ(StatusCode::OK_200, res->status);
  6531. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6532. EXPECT_EQ("abcde", res->body);
  6533. }
  6534. TEST_F(ServerTest, StaticFileRange) {
  6535. auto res =
  6536. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6538. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6539. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6540. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6541. EXPECT_EQ(true, res->has_header("Content-Range"));
  6542. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6543. EXPECT_EQ(std::string("cd"), res->body);
  6544. }
  6545. TEST_F(ServerTest, StaticFileRanges) {
  6546. auto res = cli_.Get("/dir/test.abcde",
  6547. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6549. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6550. EXPECT_TRUE(
  6551. res->get_header_value("Content-Type")
  6552. .find(
  6553. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6554. 0);
  6555. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6556. }
  6557. TEST_F(ServerTest, StaticFileRangeHead) {
  6558. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6560. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6561. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6562. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6563. EXPECT_EQ(true, res->has_header("Content-Range"));
  6564. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6565. }
  6566. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6567. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6569. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6570. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6571. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6572. EXPECT_EQ(true, res->has_header("Content-Range"));
  6573. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6574. res->get_header_value("Content-Range"));
  6575. EXPECT_EQ("LAST\n", res->body);
  6576. }
  6577. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6578. auto res =
  6579. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6581. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6583. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6584. EXPECT_EQ(true, res->has_header("Content-Range"));
  6585. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6586. }
  6587. TEST_F(ServerTest, StaticFileBigFile) {
  6588. auto res = cli_.Get("/dir/1MB.txt");
  6589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6590. EXPECT_EQ(StatusCode::OK_200, res->status);
  6591. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6592. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6593. }
  6594. TEST_F(ServerTest, InvalidBaseDirMount) {
  6595. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6596. }
  6597. TEST_F(ServerTest, Binary) {
  6598. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6599. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6600. "application/octet-stream");
  6601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6602. ASSERT_EQ(StatusCode::OK_200, res->status);
  6603. ASSERT_EQ(4U, res->body.size());
  6604. res = cli_.Put("/binary", binary.data(), binary.size(),
  6605. "application/octet-stream");
  6606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6607. ASSERT_EQ(StatusCode::OK_200, res->status);
  6608. ASSERT_EQ(4U, res->body.size());
  6609. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6610. "application/octet-stream");
  6611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6612. ASSERT_EQ(StatusCode::OK_200, res->status);
  6613. ASSERT_EQ(4U, res->body.size());
  6614. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6615. "application/octet-stream");
  6616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6617. ASSERT_EQ(StatusCode::OK_200, res->status);
  6618. ASSERT_EQ(4U, res->body.size());
  6619. }
  6620. TEST_F(ServerTest, BinaryString) {
  6621. auto binary = std::string("\x00\x01\x02\x03", 4);
  6622. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6624. ASSERT_EQ(StatusCode::OK_200, res->status);
  6625. ASSERT_EQ(4U, res->body.size());
  6626. res = cli_.Put("/binary", binary, "application/octet-stream");
  6627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6628. ASSERT_EQ(StatusCode::OK_200, res->status);
  6629. ASSERT_EQ(4U, res->body.size());
  6630. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. ASSERT_EQ(StatusCode::OK_200, res->status);
  6633. ASSERT_EQ(4U, res->body.size());
  6634. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6636. ASSERT_EQ(StatusCode::OK_200, res->status);
  6637. ASSERT_EQ(4U, res->body.size());
  6638. }
  6639. TEST_F(ServerTest, EmptyRequest) {
  6640. auto res = cli_.Get("");
  6641. ASSERT_TRUE(!res);
  6642. EXPECT_EQ(Error::Connection, res.error());
  6643. }
  6644. TEST_F(ServerTest, LongRequest) {
  6645. std::string request;
  6646. for (size_t i = 0; i < 545; i++) {
  6647. request += "/TooLongRequest";
  6648. }
  6649. request += "OK";
  6650. auto res = cli_.Get(request.c_str());
  6651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6653. }
  6654. TEST_F(ServerTest, TooLongRequest) {
  6655. std::string request;
  6656. for (size_t i = 0; i < 546; i++) {
  6657. request += "/TooLongRequest";
  6658. }
  6659. request += "_NG";
  6660. auto start = std::chrono::high_resolution_clock::now();
  6661. cli_.set_keep_alive(true);
  6662. auto res = cli_.Get(request.c_str());
  6663. auto end = std::chrono::high_resolution_clock::now();
  6664. auto elapsed =
  6665. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6666. .count();
  6667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6668. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6669. EXPECT_LE(elapsed, 1000);
  6670. EXPECT_EQ("close", res->get_header_value("Connection"));
  6671. EXPECT_FALSE(cli_.is_socket_open());
  6672. }
  6673. TEST_F(ServerTest, AlmostTooLongRequest) {
  6674. // test for #2046 - URI length check shouldn't include other content on req
  6675. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6676. // leading /, space, HTTP/1.1)
  6677. std::string request =
  6678. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6679. auto res = cli_.Get(request.c_str());
  6680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6681. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6682. }
  6683. TEST_F(ServerTest, LongHeader) {
  6684. Request req;
  6685. req.method = "GET";
  6686. req.path = "/hi";
  6687. std::string host_and_port;
  6688. host_and_port += HOST;
  6689. host_and_port += ":";
  6690. host_and_port += std::to_string(PORT);
  6691. req.headers.emplace("Host", host_and_port.c_str());
  6692. req.headers.emplace("Accept", "*/*");
  6693. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6694. req.headers.emplace(
  6695. "Header-Name",
  6696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6724. "@@@@@@@@@@@@@@@@");
  6725. auto res = std::make_shared<Response>();
  6726. auto error = Error::Success;
  6727. auto ret = cli_.send(req, *res, error);
  6728. ASSERT_TRUE(ret);
  6729. EXPECT_EQ(StatusCode::OK_200, res->status);
  6730. }
  6731. TEST_F(ServerTest, LongQueryValue) {
  6732. auto start = std::chrono::high_resolution_clock::now();
  6733. cli_.set_keep_alive(true);
  6734. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6735. auto end = std::chrono::high_resolution_clock::now();
  6736. auto elapsed =
  6737. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6738. .count();
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6741. EXPECT_LE(elapsed, 1000);
  6742. EXPECT_EQ("close", res->get_header_value("Connection"));
  6743. EXPECT_FALSE(cli_.is_socket_open());
  6744. }
  6745. TEST_F(ServerTest, TooLongQueryValue) {
  6746. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6747. ASSERT_FALSE(res);
  6748. EXPECT_EQ(Error::Read, res.error());
  6749. }
  6750. TEST_F(ServerTest, TooLongHeader) {
  6751. Request req;
  6752. req.method = "GET";
  6753. req.path = "/hi";
  6754. std::string host_and_port;
  6755. host_and_port += HOST;
  6756. host_and_port += ":";
  6757. host_and_port += std::to_string(PORT);
  6758. req.headers.emplace("Host", host_and_port.c_str());
  6759. req.headers.emplace("Accept", "*/*");
  6760. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6761. req.headers.emplace(
  6762. "Header-Name",
  6763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6791. "@@@@@@@@@@@@@@@@@");
  6792. auto res = std::make_shared<Response>();
  6793. auto error = Error::Success;
  6794. auto ret = cli_.send(req, *res, error);
  6795. ASSERT_TRUE(ret);
  6796. EXPECT_EQ(StatusCode::OK_200, res->status);
  6797. }
  6798. TEST_F(ServerTest, HeaderCountAtLimit) {
  6799. // Test with headers just under the 100 limit
  6800. httplib::Headers headers;
  6801. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6802. // This should keep us just under the 100 header limit
  6803. for (int i = 0; i < 95; i++) {
  6804. std::string name = "X-Test-Header-" + std::to_string(i);
  6805. std::string value = "value" + std::to_string(i);
  6806. headers.emplace(name, value);
  6807. }
  6808. // This should work fine as we're under the limit
  6809. auto res = cli_.Get("/hi", headers);
  6810. EXPECT_TRUE(res);
  6811. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6812. }
  6813. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6814. // Test with many headers to exceed the 100 limit
  6815. httplib::Headers headers;
  6816. // Add 150 headers to definitely exceed the 100 limit
  6817. for (int i = 0; i < 150; i++) {
  6818. std::string name = "X-Test-Header-" + std::to_string(i);
  6819. std::string value = "value" + std::to_string(i);
  6820. headers.emplace(name, value);
  6821. }
  6822. // This should fail due to exceeding header count limit
  6823. cli_.set_keep_alive(true);
  6824. auto res = cli_.Get("/hi", headers);
  6825. // The server should respond with 400 Bad Request
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6828. EXPECT_EQ("close", res->get_header_value("Connection"));
  6829. EXPECT_FALSE(cli_.is_socket_open());
  6830. }
  6831. TEST_F(ServerTest, PercentEncoding) {
  6832. auto res = cli_.Get("/e%6edwith%");
  6833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6834. EXPECT_EQ(StatusCode::OK_200, res->status);
  6835. }
  6836. TEST_F(ServerTest, PercentEncodingUnicode) {
  6837. auto res = cli_.Get("/e%u006edwith%");
  6838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6839. EXPECT_EQ(StatusCode::OK_200, res->status);
  6840. }
  6841. TEST_F(ServerTest, InvalidPercentEncoding) {
  6842. auto res = cli_.Get("/%endwith%");
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6845. }
  6846. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6847. auto res = cli_.Get("/%uendwith%");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6850. }
  6851. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6852. auto res = cli_.Get("/hello?aaa=bbb%");
  6853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6855. }
  6856. TEST_F(ServerTest, PlusSignEncoding) {
  6857. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6859. EXPECT_EQ(StatusCode::OK_200, res->status);
  6860. EXPECT_EQ("a +b", res->body);
  6861. }
  6862. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6863. // This test simulates a potential DoS attack using many headers
  6864. // to verify our security fix prevents memory exhaustion
  6865. httplib::Headers attack_headers;
  6866. // Attempt to add many headers like an attacker would (200 headers to far
  6867. // exceed limit)
  6868. for (int i = 0; i < 200; i++) {
  6869. std::string name = "X-Attack-Header-" + std::to_string(i);
  6870. std::string value = "attack_payload_" + std::to_string(i);
  6871. attack_headers.emplace(name, value);
  6872. }
  6873. // Try to POST with excessive headers
  6874. cli_.set_keep_alive(true);
  6875. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6876. // Should either fail or return 400 Bad Request due to security limit
  6877. if (res) {
  6878. // If we get a response, it should be 400 Bad Request
  6879. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6880. EXPECT_EQ("close", res->get_header_value("Connection"));
  6881. }
  6882. EXPECT_FALSE(cli_.is_socket_open());
  6883. }
  6884. TEST_F(ServerTest, MultipartFormData) {
  6885. UploadFormDataItems items = {
  6886. {"text1", "text default", "", ""},
  6887. {"text2", "aωb", "", ""},
  6888. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6889. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6890. {"file3", "", "", "application/octet-stream"},
  6891. {"file4", "", "", " application/json tmp-string "}};
  6892. auto res = cli_.Post("/multipart", items);
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. EXPECT_EQ(StatusCode::OK_200, res->status);
  6895. }
  6896. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6897. UploadFormDataItems items = {
  6898. {"text", "default text", "", ""},
  6899. {"multi_text1", "aaaaa", "", ""},
  6900. {"multi_text1", "bbbbb", "", ""},
  6901. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6902. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6903. "application/json"},
  6904. };
  6905. auto res = cli_.Post("/multipart/multi_file_values", items);
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(StatusCode::OK_200, res->status);
  6908. }
  6909. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6910. auto res = cli_.Get("/hi");
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. EXPECT_EQ(StatusCode::OK_200, res->status);
  6913. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6914. EXPECT_EQ("Hello World!", res->body);
  6915. }
  6916. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6917. Request req;
  6918. req.method = "POST";
  6919. req.path = "/chunked";
  6920. std::string host_and_port;
  6921. host_and_port += HOST;
  6922. host_and_port += ":";
  6923. host_and_port += std::to_string(PORT);
  6924. req.headers.emplace("Host", host_and_port.c_str());
  6925. req.headers.emplace("Accept", "*/*");
  6926. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6927. req.headers.emplace("Content-Type", "text/plain");
  6928. req.headers.emplace("Content-Length", "0");
  6929. req.headers.emplace(
  6930. "Transfer-Encoding",
  6931. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6932. // Client does not chunk, so make a chunked body manually.
  6933. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6934. auto res = std::make_shared<Response>();
  6935. auto error = Error::Success;
  6936. auto ret = cli_.send(req, *res, error);
  6937. ASSERT_TRUE(ret);
  6938. EXPECT_EQ(StatusCode::OK_200, res->status);
  6939. }
  6940. template <typename ClientT>
  6941. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6942. int expected_status) {
  6943. Request req;
  6944. req.method = "POST";
  6945. req.path = "/chunked";
  6946. std::string host_and_port;
  6947. host_and_port += HOST;
  6948. host_and_port += ":";
  6949. host_and_port += std::to_string(PORT);
  6950. req.headers.emplace("Host", host_and_port.c_str());
  6951. req.headers.emplace("Content-Length", "0");
  6952. req.headers.emplace("Transfer-Encoding", "chunked");
  6953. req.body = body;
  6954. auto res = std::make_shared<Response>();
  6955. auto error = Error::Success;
  6956. ASSERT_TRUE(cli.send(req, *res, error));
  6957. EXPECT_EQ(expected_status, res->status);
  6958. }
  6959. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6960. // rather than treat them as valid lengths.
  6961. template <typename ClientT>
  6962. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6963. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6964. }
  6965. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6966. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6967. }
  6968. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6969. expect_chunked_body_rejected(
  6970. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6971. }
  6972. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6973. // chunk-size line carries no CR, LF or other control character ahead of its
  6974. // terminator. Such a line must be refused rather than read as extension text.
  6975. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6976. expect_chunked_body_rejected(
  6977. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6978. }
  6979. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6980. expect_chunked_body_rejected(
  6981. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6982. }
  6983. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6984. expect_chunked_body_rejected(
  6985. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6986. }
  6987. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6988. // The literal stays split: a hex escape consumes every hex digit that
  6989. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6990. expect_chunked_body_rejected(
  6991. cli_, "4;a\x01"
  6992. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6993. }
  6994. // The bytes around chunk data are no payload, so they cannot ride on the
  6995. // payload limit
  6996. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6997. // Small enough that the whole request is sent before the server turns it
  6998. // down, yet past the limit by the last chunks
  6999. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7000. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7001. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7002. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7003. SCOPED_TRACE(size_line.substr(0, 2));
  7004. std::string body;
  7005. for (auto c : std::string("dechunked post body")) {
  7006. body += size_line + "\r\n" + c + "\r\n";
  7007. }
  7008. body += "0\r\n\r\n";
  7009. expect_chunked_body_rejected(cli_, body.c_str());
  7010. }
  7011. }
  7012. TEST_F(ServerTest, AcceptsChunkExtension) {
  7013. expect_chunked_body_status(cli_,
  7014. "4;name=value\r\ndech\r\n"
  7015. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7016. "0;last\r\n\r\n",
  7017. StatusCode::OK_200);
  7018. }
  7019. TEST_F(ServerTest, GetStreamed2) {
  7020. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7022. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7023. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7024. EXPECT_EQ(true, res->has_header("Content-Range"));
  7025. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7026. EXPECT_EQ(std::string("ab"), res->body);
  7027. }
  7028. TEST_F(ServerTest, GetStreamed) {
  7029. auto res = cli_.Get("/streamed");
  7030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7031. EXPECT_EQ(StatusCode::OK_200, res->status);
  7032. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7033. EXPECT_EQ(std::string("aaabbb"), res->body);
  7034. }
  7035. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7036. auto res = cli_.Get("/streamed-without-length",
  7037. Headers{make_range_header({{0, -1}})});
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ(StatusCode::OK_200, res->status);
  7040. EXPECT_EQ(false, res->has_header("Content-Length"));
  7041. EXPECT_EQ(false, res->has_header("Content-Range"));
  7042. EXPECT_EQ(std::string("abcdefg"), res->body);
  7043. }
  7044. TEST_F(ServerTest, GetStreamedWithRange1) {
  7045. auto res =
  7046. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7049. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7050. EXPECT_EQ(true, res->has_header("Content-Range"));
  7051. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7052. EXPECT_EQ(std::string("def"), res->body);
  7053. }
  7054. TEST_F(ServerTest, GetStreamedWithRange2) {
  7055. auto res =
  7056. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7059. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7060. EXPECT_EQ(true, res->has_header("Content-Range"));
  7061. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7062. EXPECT_EQ(std::string("bcdefg"), res->body);
  7063. }
  7064. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7065. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7067. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7068. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7069. EXPECT_EQ(true, res->has_header("Content-Range"));
  7070. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7071. EXPECT_EQ(std::string("efg"), res->body);
  7072. }
  7073. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7074. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7075. // the entire representation.
  7076. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7077. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7079. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7080. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7081. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7082. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7083. }
  7084. }
  7085. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7086. auto res =
  7087. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7089. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7090. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7091. EXPECT_EQ(false, res->has_header("Content-Range"));
  7092. EXPECT_EQ(0U, res->body.size());
  7093. }
  7094. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7095. // Only a 206 is served as a partial representation. Under any other status
  7096. // `apply_ranges()` reported the full content length, so the body must match
  7097. // that header, and the content provider must never be asked for an offset
  7098. // outside the representation.
  7099. auto check = [&](int status, const char *range) {
  7100. auto path =
  7101. std::string("/streamed-with-range?status=") + std::to_string(status);
  7102. auto ctx = path + " Range: " + range;
  7103. auto res = cli_.Get(path, Headers{{"Range", range}});
  7104. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7105. EXPECT_EQ(status, res->status) << ctx;
  7106. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7108. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7109. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7110. };
  7111. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7112. check(403, "bytes=3-5");
  7113. // The offset is far past the representation.
  7114. check(403, "bytes=100000-100200");
  7115. // `first_pos` is still -1 here, and the bounds asserts in
  7116. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7117. check(403, "bytes=-3");
  7118. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7119. // multipart branch would have written one that is empty.
  7120. check(403, "bytes=1-2, 4-5");
  7121. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7122. // covers the whole representation.
  7123. check(200, "bytes=3-5");
  7124. check(200, "bytes=1-2, 4-5");
  7125. }
  7126. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7127. auto res =
  7128. cli_.Get("/streamed-with-range",
  7129. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7130. "92233720368547758079223372036854775807"}});
  7131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7132. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7133. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7134. EXPECT_EQ(false, res->has_header("Content-Range"));
  7135. EXPECT_EQ(0U, res->body.size());
  7136. }
  7137. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7138. auto res = cli_.Get(
  7139. "/with-range",
  7140. Headers{{"Range",
  7141. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7142. {"Accept-Encoding", ""}});
  7143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7144. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7145. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7146. EXPECT_EQ(true, res->has_header("Content-Range"));
  7147. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7148. EXPECT_EQ(std::string("abcdefg"), res->body);
  7149. }
  7150. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7151. auto res = cli_.Get("/with-range", Headers{
  7152. {"Range", "bytes=0-"},
  7153. {"Accept-Encoding", ""},
  7154. });
  7155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7156. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7157. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7158. EXPECT_EQ(true, res->has_header("Content-Range"));
  7159. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7160. EXPECT_EQ(std::string("abcdefg"), res->body);
  7161. }
  7162. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7163. auto res = cli_.Get("/streamed-with-range",
  7164. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7167. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7168. EXPECT_EQ(false, res->has_header("Content-Range"));
  7169. EXPECT_EQ(267U, res->body.size());
  7170. // Check that both range contents are present
  7171. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7172. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7173. // Check that Content-Range headers are present for both ranges
  7174. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7175. std::string::npos);
  7176. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7177. std::string::npos);
  7178. }
  7179. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7180. Ranges ranges;
  7181. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7182. ranges.emplace_back(0, -1);
  7183. }
  7184. auto res = cli_.Get("/streamed-with-range?error",
  7185. Headers{{make_range_header(ranges)}});
  7186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7187. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7188. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7189. EXPECT_EQ(false, res->has_header("Content-Range"));
  7190. EXPECT_EQ(0U, res->body.size());
  7191. }
  7192. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7193. auto res = cli_.Get("/streamed-with-range",
  7194. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7197. EXPECT_EQ(5U, res->body.size());
  7198. // Check that overlapping ranges are coalesced into a single range
  7199. EXPECT_EQ("bcdef", res->body);
  7200. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7201. // Should be single range, not multipart
  7202. EXPECT_TRUE(res->has_header("Content-Range"));
  7203. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7204. }
  7205. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7206. auto res = cli_.Get("/streamed-with-range",
  7207. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7210. EXPECT_EQ(268U, res->body.size());
  7211. // Check that both range contents are present
  7212. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7213. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7214. // Check that Content-Range headers are present for both ranges
  7215. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7216. std::string::npos);
  7217. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7218. std::string::npos);
  7219. }
  7220. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7221. auto res = cli_.Get("/streamed-with-range",
  7222. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7224. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7225. EXPECT_EQ(269U, res->body.size());
  7226. // Check that both duplicate range contents are present
  7227. size_t first_abc = res->body.find("abc\r\n");
  7228. EXPECT_TRUE(first_abc != std::string::npos);
  7229. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7230. EXPECT_TRUE(second_abc != std::string::npos);
  7231. // Check that Content-Range headers are present for both ranges
  7232. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7233. EXPECT_TRUE(first_range != std::string::npos);
  7234. size_t second_range =
  7235. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7236. EXPECT_TRUE(second_range != std::string::npos);
  7237. }
  7238. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7239. auto res =
  7240. cli_.Get("/streamed-with-range?error",
  7241. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7243. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7244. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7245. EXPECT_EQ(false, res->has_header("Content-Range"));
  7246. EXPECT_EQ(0U, res->body.size());
  7247. }
  7248. TEST_F(ServerTest, GetStreamedEndless) {
  7249. uint64_t offset = 0;
  7250. auto res = cli_.Get("/streamed-cancel",
  7251. [&](const char * /*data*/, uint64_t data_length) {
  7252. if (offset < 100) {
  7253. offset += data_length;
  7254. return true;
  7255. }
  7256. return false;
  7257. });
  7258. ASSERT_TRUE(!res);
  7259. EXPECT_EQ(Error::Canceled, res.error());
  7260. }
  7261. TEST_F(ServerTest, ClientStop) {
  7262. std::atomic_size_t count{4};
  7263. std::vector<std::thread> threads;
  7264. for (auto i = count.load(); i != 0; --i) {
  7265. threads.emplace_back([&]() {
  7266. auto res = cli_.Get("/streamed-cancel",
  7267. [&](const char *, uint64_t) { return true; });
  7268. --count;
  7269. ASSERT_TRUE(!res);
  7270. EXPECT_TRUE(res.error() == Error::Canceled ||
  7271. res.error() == Error::Read || res.error() == Error::Write);
  7272. });
  7273. }
  7274. std::this_thread::sleep_for(std::chrono::seconds(2));
  7275. while (count != 0) {
  7276. cli_.stop();
  7277. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7278. }
  7279. for (auto &t : threads) {
  7280. t.join();
  7281. }
  7282. }
  7283. TEST_F(ServerTest, GetWithRange1) {
  7284. auto res = cli_.Get("/with-range", Headers{
  7285. make_range_header({{3, 5}}),
  7286. {"Accept-Encoding", ""},
  7287. });
  7288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7289. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7290. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7291. EXPECT_EQ(true, res->has_header("Content-Range"));
  7292. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7293. EXPECT_EQ(std::string("def"), res->body);
  7294. }
  7295. TEST_F(ServerTest, GetWithRange2) {
  7296. auto res = cli_.Get("/with-range", Headers{
  7297. make_range_header({{1, -1}}),
  7298. {"Accept-Encoding", ""},
  7299. });
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7302. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7303. EXPECT_EQ(true, res->has_header("Content-Range"));
  7304. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7305. EXPECT_EQ(std::string("bcdefg"), res->body);
  7306. }
  7307. TEST_F(ServerTest, GetWithRange3) {
  7308. auto res = cli_.Get("/with-range", Headers{
  7309. make_range_header({{0, 0}}),
  7310. {"Accept-Encoding", ""},
  7311. });
  7312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7313. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7314. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7315. EXPECT_EQ(true, res->has_header("Content-Range"));
  7316. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7317. EXPECT_EQ(std::string("a"), res->body);
  7318. }
  7319. TEST_F(ServerTest, GetWithRange4) {
  7320. auto res = cli_.Get("/with-range", Headers{
  7321. make_range_header({{-1, 2}}),
  7322. {"Accept-Encoding", ""},
  7323. });
  7324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7325. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7326. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7327. EXPECT_EQ(true, res->has_header("Content-Range"));
  7328. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7329. EXPECT_EQ(std::string("fg"), res->body);
  7330. }
  7331. TEST_F(ServerTest, GetWithRange5) {
  7332. auto res = cli_.Get("/with-range", Headers{
  7333. make_range_header({{0, 5}}),
  7334. {"Accept-Encoding", ""},
  7335. });
  7336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7337. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7338. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7339. EXPECT_EQ(true, res->has_header("Content-Range"));
  7340. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7341. EXPECT_EQ(std::string("abcdef"), res->body);
  7342. }
  7343. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7344. auto res =
  7345. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7347. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7348. }
  7349. TEST_F(ServerTest, GetWithRangeMultipart) {
  7350. auto res =
  7351. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7353. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7354. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7355. EXPECT_EQ(false, res->has_header("Content-Range"));
  7356. EXPECT_EQ(267U, res->body.size());
  7357. }
  7358. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7359. auto res = cli_.Get("/with-range",
  7360. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7362. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7363. }
  7364. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7365. auto res = cli_.Get("/with-range-customized-response",
  7366. Headers{{make_range_header({{1, 2}})}});
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7369. EXPECT_EQ(true, res->has_header("Content-Length"));
  7370. EXPECT_EQ(false, res->has_header("Content-Range"));
  7371. EXPECT_EQ(JSON_DATA, res->body);
  7372. }
  7373. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7374. auto res = cli_.Get("/with-range-customized-response",
  7375. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7377. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7378. EXPECT_EQ(true, res->has_header("Content-Length"));
  7379. EXPECT_EQ(false, res->has_header("Content-Range"));
  7380. EXPECT_EQ(JSON_DATA, res->body);
  7381. }
  7382. TEST_F(ServerTest, Issue1772) {
  7383. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7385. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7386. }
  7387. TEST_F(ServerTest, Issue609) {
  7388. auto res = cli_.Delete("/issue609");
  7389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7390. EXPECT_EQ(StatusCode::OK_200, res->status);
  7391. EXPECT_EQ(std::string("ok"), res->body);
  7392. }
  7393. TEST_F(ServerTest, GetStreamedChunked) {
  7394. auto res = cli_.Get("/streamed-chunked");
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::OK_200, res->status);
  7397. EXPECT_EQ(std::string("123456789"), res->body);
  7398. }
  7399. TEST_F(ServerTest, GetStreamedChunked2) {
  7400. auto res = cli_.Get("/streamed-chunked2");
  7401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7402. EXPECT_EQ(StatusCode::OK_200, res->status);
  7403. EXPECT_EQ(std::string("123456789"), res->body);
  7404. }
  7405. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7406. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7408. EXPECT_EQ(StatusCode::OK_200, res->status);
  7409. EXPECT_EQ(std::string("123456789"), res->body);
  7410. EXPECT_TRUE(res->has_header("Trailer"));
  7411. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7412. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7413. // Trailers are now stored separately from headers (security fix)
  7414. EXPECT_EQ(2U, res->trailers.size());
  7415. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7416. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7417. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7418. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7419. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7420. // Verify trailers are NOT in headers (security verification)
  7421. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7422. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7423. }
  7424. TEST_F(ServerTest, LargeChunkedPost) {
  7425. Request req;
  7426. req.method = "POST";
  7427. req.path = "/large-chunked";
  7428. std::string host_and_port;
  7429. host_and_port += HOST;
  7430. host_and_port += ":";
  7431. host_and_port += std::to_string(PORT);
  7432. req.headers.emplace("Host", host_and_port.c_str());
  7433. req.headers.emplace("Accept", "*/*");
  7434. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7435. req.headers.emplace("Content-Type", "text/plain");
  7436. req.headers.emplace("Content-Length", "0");
  7437. req.headers.emplace("Transfer-Encoding", "chunked");
  7438. std::string long_string(30 * 1024u, 'a');
  7439. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7440. // Attempt to make a large enough post to exceed OS buffers, to test that
  7441. // the server handles short reads if the full chunk data isn't available.
  7442. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7443. auto res = std::make_shared<Response>();
  7444. auto error = Error::Success;
  7445. auto ret = cli_.send(req, *res, error);
  7446. ASSERT_TRUE(ret);
  7447. EXPECT_EQ(StatusCode::OK_200, res->status);
  7448. }
  7449. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7450. auto res = cli_.Get("/remote_addr");
  7451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7452. EXPECT_EQ(StatusCode::OK_200, res->status);
  7453. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7454. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7455. }
  7456. TEST_F(ServerTest, GetMethodLocalAddr) {
  7457. auto res = cli_.Get("/local_addr");
  7458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7459. EXPECT_EQ(StatusCode::OK_200, res->status);
  7460. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7461. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7462. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7463. }
  7464. TEST_F(ServerTest, HTTPResponseSplitting) {
  7465. auto res = cli_.Get("/http_response_splitting");
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. }
  7469. TEST_F(ServerTest, SlowRequest) {
  7470. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7471. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7472. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7473. }
  7474. #if 0
  7475. TEST_F(ServerTest, SlowPost) {
  7476. char buffer[64 * 1024];
  7477. memset(buffer, 0x42, sizeof(buffer));
  7478. auto res = cli_.Post(
  7479. "/slowpost", 64 * 1024 * 1024,
  7480. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7481. auto ret = sink.write(buffer, sizeof(buffer));
  7482. EXPECT_TRUE(ret);
  7483. return true;
  7484. },
  7485. "text/plain");
  7486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7487. EXPECT_EQ(StatusCode::OK_200, res->status);
  7488. }
  7489. TEST_F(ServerTest, SlowPostFail) {
  7490. char buffer[64 * 1024];
  7491. memset(buffer, 0x42, sizeof(buffer));
  7492. cli_.set_write_timeout(std::chrono::seconds(0));
  7493. auto res = cli_.Post(
  7494. "/slowpost", 64 * 1024 * 1024,
  7495. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7496. sink.write(buffer, sizeof(buffer));
  7497. return true;
  7498. },
  7499. "text/plain");
  7500. ASSERT_TRUE(!res);
  7501. EXPECT_EQ(Error::Write, res.error());
  7502. }
  7503. #endif
  7504. TEST_F(ServerTest, Put) {
  7505. auto res = cli_.Put("/put", "PUT", "text/plain");
  7506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7507. EXPECT_EQ(StatusCode::OK_200, res->status);
  7508. EXPECT_EQ("PUT", res->body);
  7509. }
  7510. TEST_F(ServerTest, PutWithContentProvider) {
  7511. auto res = cli_.Put(
  7512. "/put", 3,
  7513. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7514. sink.os << "PUT";
  7515. return true;
  7516. },
  7517. "text/plain");
  7518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7519. EXPECT_EQ(StatusCode::OK_200, res->status);
  7520. EXPECT_EQ("PUT", res->body);
  7521. }
  7522. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7523. auto res = cli_.Post(
  7524. "/post", 42,
  7525. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7526. return false;
  7527. },
  7528. "text/plain");
  7529. ASSERT_TRUE(!res);
  7530. EXPECT_EQ(Error::Canceled, res.error());
  7531. }
  7532. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7533. auto res = cli_.Put(
  7534. "/put",
  7535. [](size_t /*offset*/, DataSink &sink) {
  7536. sink.os << "PUT";
  7537. sink.done();
  7538. return true;
  7539. },
  7540. "text/plain");
  7541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7542. EXPECT_EQ(StatusCode::OK_200, res->status);
  7543. EXPECT_EQ("PUT", res->body);
  7544. }
  7545. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7546. auto res = cli_.Post(
  7547. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7548. "text/plain");
  7549. ASSERT_TRUE(!res);
  7550. EXPECT_EQ(Error::Canceled, res.error());
  7551. }
  7552. TEST_F(ServerTest, PostLoopBack) {
  7553. std::string body;
  7554. auto res = cli_.Post(
  7555. "/post-loopback", 9,
  7556. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7557. EXPECT_EQ(9u, length);
  7558. sink.write("123", 3);
  7559. sink.write("456", 3);
  7560. sink.write("789", 3);
  7561. return true;
  7562. },
  7563. "text/plain",
  7564. [&body](const char *data, size_t data_length) {
  7565. body.append(data, data_length);
  7566. return true;
  7567. });
  7568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7569. EXPECT_EQ(StatusCode::OK_200, res->status);
  7570. EXPECT_EQ("123456789", body);
  7571. }
  7572. TEST_F(ServerTest, PutLoopBack) {
  7573. std::string body;
  7574. auto res = cli_.Put(
  7575. "/put-loopback", 9,
  7576. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7577. EXPECT_EQ(9u, length);
  7578. sink.write("123", 3);
  7579. sink.write("456", 3);
  7580. sink.write("789", 3);
  7581. return true;
  7582. },
  7583. "text/plain",
  7584. [&body](const char *data, size_t data_length) {
  7585. body.append(data, data_length);
  7586. return true;
  7587. });
  7588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7589. EXPECT_EQ(StatusCode::OK_200, res->status);
  7590. EXPECT_EQ("123456789", body);
  7591. }
  7592. TEST_F(ServerTest, PatchLoopBack) {
  7593. std::string body;
  7594. auto res = cli_.Patch(
  7595. "/patch-loopback", 9,
  7596. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7597. EXPECT_EQ(9u, length);
  7598. sink.write("123", 3);
  7599. sink.write("456", 3);
  7600. sink.write("789", 3);
  7601. return true;
  7602. },
  7603. "text/plain",
  7604. [&body](const char *data, size_t data_length) {
  7605. body.append(data, data_length);
  7606. return true;
  7607. });
  7608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7609. EXPECT_EQ(StatusCode::OK_200, res->status);
  7610. EXPECT_EQ("123456789", body);
  7611. }
  7612. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7613. std::string body;
  7614. auto res = cli_.Post(
  7615. "/post-loopback",
  7616. [](size_t /*offset*/, DataSink &sink) {
  7617. sink.write("123", 3);
  7618. sink.write("456", 3);
  7619. sink.write("789", 3);
  7620. sink.done();
  7621. return true;
  7622. },
  7623. "text/plain",
  7624. [&body](const char *data, size_t data_length) {
  7625. body.append(data, data_length);
  7626. return true;
  7627. });
  7628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7629. EXPECT_EQ(StatusCode::OK_200, res->status);
  7630. EXPECT_EQ("123456789", body);
  7631. }
  7632. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7633. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7634. cli_.set_compress(true);
  7635. auto res = cli_.Put(
  7636. "/put", 3,
  7637. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7638. sink.os << "PUT";
  7639. return true;
  7640. },
  7641. "text/plain");
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(StatusCode::OK_200, res->status);
  7644. EXPECT_EQ("PUT", res->body);
  7645. }
  7646. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7647. cli_.set_compress(true);
  7648. auto res = cli_.Post(
  7649. "/post", 42,
  7650. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7651. return false;
  7652. },
  7653. "text/plain");
  7654. ASSERT_TRUE(!res);
  7655. EXPECT_EQ(Error::Canceled, res.error());
  7656. }
  7657. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7658. cli_.set_compress(true);
  7659. auto res = cli_.Put(
  7660. "/put",
  7661. [](size_t /*offset*/, DataSink &sink) {
  7662. sink.os << "PUT";
  7663. sink.done();
  7664. return true;
  7665. },
  7666. "text/plain");
  7667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7668. EXPECT_EQ(StatusCode::OK_200, res->status);
  7669. EXPECT_EQ("PUT", res->body);
  7670. }
  7671. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7672. cli_.set_compress(true);
  7673. auto res = cli_.Post(
  7674. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7675. "text/plain");
  7676. ASSERT_TRUE(!res);
  7677. EXPECT_EQ(Error::Canceled, res.error());
  7678. }
  7679. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7680. cli_.set_compress(true);
  7681. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7683. EXPECT_EQ(StatusCode::OK_200, res->status);
  7684. EXPECT_EQ(LARGE_DATA, res->body);
  7685. }
  7686. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7687. #ifdef CPPHTTPLIB_SSL_ENABLED
  7688. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7689. Client cli(s.c_str());
  7690. cli.enable_server_certificate_verification(false);
  7691. #else
  7692. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7693. Client cli(s.c_str());
  7694. #endif
  7695. cli.set_compress(true);
  7696. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7698. EXPECT_EQ(StatusCode::OK_200, res->status);
  7699. EXPECT_EQ(LARGE_DATA, res->body);
  7700. // The compressed size should be less than a 10th of the original. May vary
  7701. // depending on the zlib library.
  7702. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7703. static_cast<uint64_t>(10 * 1024 * 1024));
  7704. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7705. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7706. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7707. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7708. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7709. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7710. #endif
  7711. }
  7712. TEST_F(ServerTest, PutContentWithDeflate) {
  7713. cli_.set_compress(false);
  7714. Headers headers;
  7715. headers.emplace("Content-Encoding", "deflate");
  7716. // PUT in deflate format:
  7717. auto res = cli_.Put("/put", headers,
  7718. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7720. EXPECT_EQ(StatusCode::OK_200, res->status);
  7721. EXPECT_EQ("PUT", res->body);
  7722. }
  7723. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7724. Headers headers;
  7725. headers.emplace("Accept-Encoding", "gzip, deflate");
  7726. auto res = cli_.Get("/streamed-chunked", headers);
  7727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7728. EXPECT_EQ(StatusCode::OK_200, res->status);
  7729. EXPECT_EQ(std::string("123456789"), res->body);
  7730. }
  7731. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7732. Headers headers;
  7733. headers.emplace("Accept-Encoding", "gzip, deflate");
  7734. auto res = cli_.Get("/streamed-chunked2", headers);
  7735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7736. EXPECT_EQ(StatusCode::OK_200, res->status);
  7737. EXPECT_EQ(std::string("123456789"), res->body);
  7738. }
  7739. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7740. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ(StatusCode::OK_200, res->status);
  7743. }
  7744. TEST(GzipDecompressor, ChunkedDecompression) {
  7745. std::string data;
  7746. for (size_t i = 0; i < 32 * 1024; ++i) {
  7747. data.push_back(static_cast<char>('a' + i % 26));
  7748. }
  7749. std::string compressed_data;
  7750. {
  7751. httplib::detail::gzip_compressor compressor;
  7752. bool result = compressor.compress(
  7753. data.data(), data.size(),
  7754. /*last=*/true,
  7755. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7756. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7757. compressed_data_size);
  7758. return true;
  7759. });
  7760. ASSERT_TRUE(result);
  7761. }
  7762. std::string decompressed_data;
  7763. {
  7764. httplib::detail::gzip_decompressor decompressor;
  7765. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7766. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7767. size_t chunk_size = 130;
  7768. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7769. chunk_begin += chunk_size) {
  7770. size_t current_chunk_size =
  7771. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7772. bool result = decompressor.decompress(
  7773. compressed_data.data() + chunk_begin, current_chunk_size,
  7774. [&](const char *decompressed_data_chunk,
  7775. size_t decompressed_data_chunk_size) {
  7776. decompressed_data.insert(decompressed_data.size(),
  7777. decompressed_data_chunk,
  7778. decompressed_data_chunk_size);
  7779. return true;
  7780. });
  7781. ASSERT_TRUE(result);
  7782. }
  7783. }
  7784. ASSERT_EQ(data, decompressed_data);
  7785. }
  7786. TEST(GzipDecompressor, DeflateDecompression) {
  7787. std::string original_text = "Raw deflate without gzip";
  7788. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7789. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7790. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7791. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7792. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7793. std::string decompressed_data;
  7794. {
  7795. httplib::detail::gzip_decompressor decompressor;
  7796. bool result = decompressor.decompress(
  7797. compressed_data.data(), compressed_data.size(),
  7798. [&](const char *decompressed_data_chunk,
  7799. size_t decompressed_data_chunk_size) {
  7800. decompressed_data.insert(decompressed_data.size(),
  7801. decompressed_data_chunk,
  7802. decompressed_data_chunk_size);
  7803. return true;
  7804. });
  7805. ASSERT_TRUE(result);
  7806. }
  7807. ASSERT_EQ(original_text, decompressed_data);
  7808. }
  7809. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7810. std::string original_text = "Raw deflate without gzip";
  7811. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7812. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7813. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7814. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7815. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7816. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7817. std::string decompressed_data;
  7818. {
  7819. httplib::detail::gzip_decompressor decompressor;
  7820. bool result = decompressor.decompress(
  7821. compressed_data.data(), compressed_data.size(),
  7822. [&](const char *decompressed_data_chunk,
  7823. size_t decompressed_data_chunk_size) {
  7824. decompressed_data.insert(decompressed_data.size(),
  7825. decompressed_data_chunk,
  7826. decompressed_data_chunk_size);
  7827. return true;
  7828. });
  7829. ASSERT_TRUE(result);
  7830. }
  7831. ASSERT_EQ(original_text, decompressed_data);
  7832. }
  7833. #endif
  7834. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7835. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7836. Headers headers;
  7837. headers.emplace("Accept-Encoding", "br");
  7838. auto res = cli_.Get("/streamed-chunked", headers);
  7839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7840. EXPECT_EQ(StatusCode::OK_200, res->status);
  7841. EXPECT_EQ(std::string("123456789"), res->body);
  7842. }
  7843. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7844. Headers headers;
  7845. headers.emplace("Accept-Encoding", "br");
  7846. auto res = cli_.Get("/streamed-chunked2", headers);
  7847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7848. EXPECT_EQ(StatusCode::OK_200, res->status);
  7849. EXPECT_EQ(std::string("123456789"), res->body);
  7850. }
  7851. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7852. cli_.set_compress(true);
  7853. auto res = cli_.Put(
  7854. "/put", 3,
  7855. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7856. sink.os << "PUT";
  7857. return true;
  7858. },
  7859. "text/plain");
  7860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7861. EXPECT_EQ(StatusCode::OK_200, res->status);
  7862. EXPECT_EQ("PUT", res->body);
  7863. }
  7864. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7865. cli_.set_compress(true);
  7866. auto res = cli_.Put(
  7867. "/put",
  7868. [](size_t /*offset*/, DataSink &sink) {
  7869. sink.os << "PUT";
  7870. sink.done();
  7871. return true;
  7872. },
  7873. "text/plain");
  7874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7875. EXPECT_EQ(StatusCode::OK_200, res->status);
  7876. EXPECT_EQ("PUT", res->body);
  7877. }
  7878. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7879. cli_.set_compress(true);
  7880. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7882. EXPECT_EQ(StatusCode::OK_200, res->status);
  7883. EXPECT_EQ(LARGE_DATA, res->body);
  7884. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7885. }
  7886. #endif
  7887. TEST_F(ServerTest, Patch) {
  7888. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7890. EXPECT_EQ(StatusCode::OK_200, res->status);
  7891. EXPECT_EQ("PATCH", res->body);
  7892. }
  7893. TEST_F(ServerTest, Delete) {
  7894. auto res = cli_.Delete("/delete");
  7895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7896. EXPECT_EQ(StatusCode::OK_200, res->status);
  7897. EXPECT_EQ("DELETE", res->body);
  7898. }
  7899. TEST_F(ServerTest, DeleteContentReceiver) {
  7900. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7902. EXPECT_EQ(StatusCode::OK_200, res->status);
  7903. EXPECT_EQ("content", res->body);
  7904. }
  7905. TEST_F(ServerTest, Options) {
  7906. auto res = cli_.Options("*");
  7907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7908. EXPECT_EQ(StatusCode::OK_200, res->status);
  7909. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7910. EXPECT_TRUE(res->body.empty());
  7911. }
  7912. TEST_F(ServerTest, URL) {
  7913. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7915. EXPECT_EQ(StatusCode::OK_200, res->status);
  7916. }
  7917. TEST_F(ServerTest, ArrayParam) {
  7918. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7920. EXPECT_EQ(StatusCode::OK_200, res->status);
  7921. }
  7922. TEST_F(ServerTest, ArrayParamValues) {
  7923. auto res =
  7924. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7926. EXPECT_EQ(StatusCode::OK_200, res->status);
  7927. }
  7928. TEST_F(ServerTest, NoMultipleHeaders) {
  7929. Headers headers = {{"Content-Length", "5"}};
  7930. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7931. "text/plain");
  7932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7933. EXPECT_EQ(StatusCode::OK_200, res->status);
  7934. }
  7935. TEST_F(ServerTest, PostContentReceiver) {
  7936. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7938. ASSERT_EQ(StatusCode::OK_200, res->status);
  7939. ASSERT_EQ("content", res->body);
  7940. }
  7941. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7942. UploadFormDataItems items = {
  7943. {"text1", "text default", "", ""},
  7944. {"text2", "aωb", "", ""},
  7945. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7946. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7947. {"file3", "", "", "application/octet-stream"},
  7948. };
  7949. auto res = cli_.Post("/content_receiver", items);
  7950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7951. EXPECT_EQ(StatusCode::OK_200, res->status);
  7952. }
  7953. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7954. UploadFormDataItems items = {
  7955. {"text1", "text default", "", ""},
  7956. {"text2", "aωb", "", ""},
  7957. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7958. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7959. {"file3", "", "", "application/octet-stream"},
  7960. };
  7961. auto boundary = std::string("+++++");
  7962. std::string body;
  7963. for (const auto &item : items) {
  7964. body += "--" + boundary + "\r\n";
  7965. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7966. if (!item.filename.empty()) {
  7967. body += "; filename=\"" + item.filename + "\"";
  7968. }
  7969. body += "\r\n";
  7970. if (!item.content_type.empty()) {
  7971. body += "Content-Type: " + item.content_type + "\r\n";
  7972. }
  7973. body += "\r\n";
  7974. body += item.content + "\r\n";
  7975. }
  7976. body += "--" + boundary + "--\r\n";
  7977. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7978. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7980. EXPECT_EQ(StatusCode::OK_200, res->status);
  7981. }
  7982. TEST(MultipartFormDataTest, FieldEscaping) {
  7983. Server svr;
  7984. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7985. const ContentReader &content_reader) {
  7986. ASSERT_TRUE(req.is_multipart_form_data());
  7987. std::vector<FormData> received;
  7988. content_reader(
  7989. [&](const FormData &file) {
  7990. received.push_back(file);
  7991. return true;
  7992. },
  7993. [&](const char *data, size_t data_length) {
  7994. received.back().content.append(data, data_length);
  7995. return true;
  7996. });
  7997. // '"', CR and LF in names and filenames are escaped following the
  7998. // WHATWG HTML standard, so each part still parses as a single part
  7999. // with no injected headers. Content types get CR/LF escaped too,
  8000. // while '"' (legal there, e.g. quoted charset) is preserved.
  8001. ASSERT_EQ(4U, received.size());
  8002. EXPECT_EQ("na%22me", received[0].name);
  8003. EXPECT_EQ("quoted name", received[0].content);
  8004. EXPECT_EQ("file", received[1].name);
  8005. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8006. received[1].filename);
  8007. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8008. EXPECT_EQ("injected", received[1].content);
  8009. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8010. EXPECT_EQ("my%22file.txt", received[2].filename);
  8011. EXPECT_EQ("cr lf name", received[2].content);
  8012. EXPECT_EQ("typed", received[3].name);
  8013. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8014. received[3].content_type);
  8015. EXPECT_EQ("typed content", received[3].content);
  8016. });
  8017. auto port = svr.bind_to_any_port("localhost");
  8018. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8019. auto se = detail::scope_exit([&] {
  8020. svr.stop();
  8021. t.join();
  8022. ASSERT_FALSE(svr.is_running());
  8023. });
  8024. svr.wait_until_ready();
  8025. Client cli("localhost", port);
  8026. UploadFormDataItems items = {
  8027. {"na\"me", "quoted name", "", ""},
  8028. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8029. "application/octet-stream"},
  8030. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8031. {"typed", "typed content", "",
  8032. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8033. };
  8034. auto res = cli.Post("/post", items);
  8035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8036. EXPECT_EQ(StatusCode::OK_200, res->status);
  8037. }
  8038. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8039. const UploadFormDataItems items = {
  8040. {"name1", "Content 1", "", ""},
  8041. {"name2", "Content 2", "file2.txt", "text/plain"},
  8042. };
  8043. Server svr;
  8044. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8045. const ContentReader &content_reader) {
  8046. ASSERT_TRUE(req.is_multipart_form_data());
  8047. std::vector<FormData> received;
  8048. content_reader(
  8049. [&](const FormData &file) {
  8050. received.push_back(file);
  8051. return true;
  8052. },
  8053. [&](const char *data, size_t data_length) {
  8054. received.back().content.append(data, data_length);
  8055. return true;
  8056. });
  8057. ASSERT_EQ(2U, received.size());
  8058. EXPECT_EQ("name1", received[0].name);
  8059. EXPECT_EQ("Content 1", received[0].content);
  8060. EXPECT_EQ("name2", received[1].name);
  8061. EXPECT_EQ("Content 2", received[1].content);
  8062. EXPECT_EQ("file2.txt", received[1].filename);
  8063. EXPECT_EQ("text/plain", received[1].content_type);
  8064. });
  8065. auto port = svr.bind_to_any_port("localhost");
  8066. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8067. auto se = detail::scope_exit([&] {
  8068. svr.stop();
  8069. t.join();
  8070. ASSERT_FALSE(svr.is_running());
  8071. });
  8072. svr.wait_until_ready();
  8073. Client cli("localhost", port);
  8074. // Whole-body serialization with a generated boundary
  8075. {
  8076. MultipartFormDataWriter writer;
  8077. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8078. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8079. writer.content_type());
  8080. auto body = writer.serialize(items);
  8081. EXPECT_EQ(body.size(), writer.content_length(items));
  8082. auto res = cli.Post("/post", body, writer.content_type());
  8083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8084. EXPECT_EQ(StatusCode::OK_200, res->status);
  8085. }
  8086. // Per-part framing with a custom boundary via a content provider
  8087. {
  8088. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8089. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8090. MultipartFormDataWriter writer("custom-boundary_123");
  8091. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8092. std::string body;
  8093. for (const auto &item : items) {
  8094. body += writer.item_begin(item);
  8095. body += item.content;
  8096. body += MultipartFormDataWriter::item_end();
  8097. }
  8098. body += writer.finish();
  8099. EXPECT_EQ(body.size(), writer.content_length(items));
  8100. auto res = cli.Post(
  8101. "/post", body.size(),
  8102. [&](size_t offset, size_t length, DataSink &sink) {
  8103. sink.write(body.data() + offset, length);
  8104. return true;
  8105. },
  8106. writer.content_type());
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(StatusCode::OK_200, res->status);
  8109. }
  8110. }
  8111. TEST_F(ServerTest, PostContentReceiverGzip) {
  8112. cli_.set_compress(true);
  8113. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8115. ASSERT_EQ(StatusCode::OK_200, res->status);
  8116. ASSERT_EQ("content", res->body);
  8117. }
  8118. TEST_F(ServerTest, PutContentReceiver) {
  8119. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8121. ASSERT_EQ(StatusCode::OK_200, res->status);
  8122. ASSERT_EQ("content", res->body);
  8123. }
  8124. TEST_F(ServerTest, PatchContentReceiver) {
  8125. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. ASSERT_EQ(StatusCode::OK_200, res->status);
  8128. ASSERT_EQ("content", res->body);
  8129. }
  8130. template <typename ClientType>
  8131. void TestWithHeadersAndContentReceiver(
  8132. ClientType &cli,
  8133. std::function<Result(ClientType &, const std::string &, const Headers &,
  8134. const std::string &, const std::string &,
  8135. ContentReceiver, DownloadProgress)>
  8136. request_func) {
  8137. Headers headers;
  8138. headers.emplace("X-Custom-Header", "test-value");
  8139. std::string received_body;
  8140. auto res = request_func(
  8141. cli, "/content_receiver", headers, "content", "application/json",
  8142. [&](const char *data, size_t data_length) {
  8143. received_body.append(data, data_length);
  8144. return true;
  8145. },
  8146. nullptr);
  8147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8148. EXPECT_EQ(StatusCode::OK_200, res->status);
  8149. EXPECT_EQ("content", received_body);
  8150. }
  8151. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8152. #ifdef CPPHTTPLIB_SSL_ENABLED
  8153. using ClientT = SSLClient;
  8154. #else
  8155. using ClientT = Client;
  8156. #endif
  8157. TestWithHeadersAndContentReceiver<ClientT>(
  8158. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8159. const std::string &body, const std::string &content_type,
  8160. ContentReceiver receiver, DownloadProgress progress) {
  8161. return cli.Post(path, headers, body, content_type, receiver, progress);
  8162. });
  8163. }
  8164. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8165. #ifdef CPPHTTPLIB_SSL_ENABLED
  8166. using ClientT = SSLClient;
  8167. #else
  8168. using ClientT = Client;
  8169. #endif
  8170. TestWithHeadersAndContentReceiver<ClientT>(
  8171. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8172. const std::string &body, const std::string &content_type,
  8173. ContentReceiver receiver, DownloadProgress progress) {
  8174. return cli.Put(path, headers, body, content_type, receiver, progress);
  8175. });
  8176. }
  8177. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8178. #ifdef CPPHTTPLIB_SSL_ENABLED
  8179. using ClientT = SSLClient;
  8180. #else
  8181. using ClientT = Client;
  8182. #endif
  8183. TestWithHeadersAndContentReceiver<ClientT>(
  8184. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8185. const std::string &body, const std::string &content_type,
  8186. ContentReceiver receiver, DownloadProgress progress) {
  8187. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8188. });
  8189. }
  8190. template <typename ClientType>
  8191. void TestWithHeadersAndContentReceiverWithProgress(
  8192. ClientType &cli,
  8193. std::function<Result(ClientType &, const std::string &, const Headers &,
  8194. const std::string &, const std::string &,
  8195. ContentReceiver, DownloadProgress)>
  8196. request_func) {
  8197. Headers headers;
  8198. headers.emplace("X-Test-Header", "progress-test");
  8199. std::string received_body;
  8200. auto progress_called = false;
  8201. auto res = request_func(
  8202. cli, "/content_receiver", headers, "content", "text/plain",
  8203. [&](const char *data, size_t data_length) {
  8204. received_body.append(data, data_length);
  8205. return true;
  8206. },
  8207. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8208. progress_called = true;
  8209. return true;
  8210. });
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. EXPECT_EQ("content", received_body);
  8214. EXPECT_TRUE(progress_called);
  8215. }
  8216. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8217. #ifdef CPPHTTPLIB_SSL_ENABLED
  8218. using ClientT = SSLClient;
  8219. #else
  8220. using ClientT = Client;
  8221. #endif
  8222. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8223. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8224. const std::string &body, const std::string &content_type,
  8225. ContentReceiver receiver, DownloadProgress progress) {
  8226. return cli.Post(path, headers, body, content_type, receiver, progress);
  8227. });
  8228. }
  8229. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8230. #ifdef CPPHTTPLIB_SSL_ENABLED
  8231. using ClientT = SSLClient;
  8232. #else
  8233. using ClientT = Client;
  8234. #endif
  8235. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8236. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8237. const std::string &body, const std::string &content_type,
  8238. ContentReceiver receiver, DownloadProgress progress) {
  8239. return cli.Put(path, headers, body, content_type, receiver, progress);
  8240. });
  8241. }
  8242. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8243. #ifdef CPPHTTPLIB_SSL_ENABLED
  8244. using ClientT = SSLClient;
  8245. #else
  8246. using ClientT = Client;
  8247. #endif
  8248. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8249. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8250. const std::string &body, const std::string &content_type,
  8251. ContentReceiver receiver, DownloadProgress progress) {
  8252. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8253. });
  8254. }
  8255. template <typename ClientType>
  8256. void TestWithHeadersAndContentReceiverError(
  8257. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8258. const Headers &, const std::string &,
  8259. const std::string &, ContentReceiver)>
  8260. request_func) {
  8261. Headers headers;
  8262. headers.emplace("X-Error-Test", "true");
  8263. std::string received_body;
  8264. auto receiver_failed = false;
  8265. auto res =
  8266. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8267. [&](const char *data, size_t data_length) {
  8268. received_body.append(data, data_length);
  8269. receiver_failed = true;
  8270. return false;
  8271. });
  8272. ASSERT_FALSE(res);
  8273. EXPECT_TRUE(receiver_failed);
  8274. }
  8275. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8276. #ifdef CPPHTTPLIB_SSL_ENABLED
  8277. using ClientT = SSLClient;
  8278. #else
  8279. using ClientT = Client;
  8280. #endif
  8281. TestWithHeadersAndContentReceiverError<ClientT>(
  8282. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8283. const std::string &body, const std::string &content_type,
  8284. ContentReceiver receiver) {
  8285. return cli.Post(path, headers, body, content_type, receiver);
  8286. });
  8287. }
  8288. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8289. #ifdef CPPHTTPLIB_SSL_ENABLED
  8290. using ClientT = SSLClient;
  8291. #else
  8292. using ClientT = Client;
  8293. #endif
  8294. TestWithHeadersAndContentReceiverError<ClientT>(
  8295. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8296. const std::string &body, const std::string &content_type,
  8297. ContentReceiver receiver) {
  8298. return cli.Put(path, headers, body, content_type, receiver);
  8299. });
  8300. }
  8301. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8302. #ifdef CPPHTTPLIB_SSL_ENABLED
  8303. using ClientT = SSLClient;
  8304. #else
  8305. using ClientT = Client;
  8306. #endif
  8307. TestWithHeadersAndContentReceiverError<ClientT>(
  8308. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8309. const std::string &body, const std::string &content_type,
  8310. ContentReceiver receiver) {
  8311. return cli.Patch(path, headers, body, content_type, receiver);
  8312. });
  8313. }
  8314. TEST_F(ServerTest, PostQueryStringAndBody) {
  8315. auto res =
  8316. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8318. ASSERT_EQ(StatusCode::OK_200, res->status);
  8319. }
  8320. TEST_F(ServerTest, HTTP2Magic) {
  8321. Request req;
  8322. req.method = "PRI";
  8323. req.path = "*";
  8324. req.body = "SM";
  8325. auto res = std::make_shared<Response>();
  8326. auto error = Error::Success;
  8327. auto ret = cli_.send(req, *res, error);
  8328. ASSERT_TRUE(ret);
  8329. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8330. }
  8331. TEST_F(ServerTest, KeepAlive) {
  8332. auto res = cli_.Get("/hi");
  8333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8334. EXPECT_EQ(StatusCode::OK_200, res->status);
  8335. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8336. EXPECT_EQ("Hello World!", res->body);
  8337. res = cli_.Get("/hi");
  8338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8339. EXPECT_EQ(StatusCode::OK_200, res->status);
  8340. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8341. EXPECT_EQ("Hello World!", res->body);
  8342. res = cli_.Get("/hi");
  8343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8344. EXPECT_EQ(StatusCode::OK_200, res->status);
  8345. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8346. EXPECT_EQ("Hello World!", res->body);
  8347. res = cli_.Get("/not-exist");
  8348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8349. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8350. res = cli_.Post("/empty", "", "text/plain");
  8351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8352. EXPECT_EQ(StatusCode::OK_200, res->status);
  8353. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8354. EXPECT_EQ("empty", res->body);
  8355. EXPECT_EQ("close", res->get_header_value("Connection"));
  8356. res = cli_.Post(
  8357. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8358. "text/plain");
  8359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8360. EXPECT_EQ(StatusCode::OK_200, res->status);
  8361. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8362. EXPECT_EQ("empty", res->body);
  8363. cli_.set_keep_alive(false);
  8364. res = cli_.Get("/last-request");
  8365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8366. EXPECT_EQ(StatusCode::OK_200, res->status);
  8367. EXPECT_EQ("close", res->get_header_value("Connection"));
  8368. }
  8369. TEST_F(ServerTest, TooManyRedirect) {
  8370. cli_.set_follow_location(true);
  8371. auto res = cli_.Get("/redirect/0");
  8372. ASSERT_TRUE(!res);
  8373. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8374. }
  8375. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8376. Request req;
  8377. req.method = "FOOBAR";
  8378. req.path = "/hi";
  8379. cli_.set_keep_alive(true);
  8380. auto res = cli_.send(req);
  8381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8382. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8383. EXPECT_EQ("close", res->get_header_value("Connection"));
  8384. EXPECT_FALSE(cli_.is_socket_open());
  8385. }
  8386. TEST_F(ServerTest, CustomRouteReadsBody) {
  8387. const std::string xml =
  8388. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8389. Request req;
  8390. req.method = "PROPFIND";
  8391. req.path = "/dav/dir";
  8392. req.set_header("Depth", "1");
  8393. req.body = xml;
  8394. auto res = cli_.send(req);
  8395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8396. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8397. EXPECT_EQ(xml, res->body);
  8398. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8399. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8400. }
  8401. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8402. Request req;
  8403. req.method = "PROPFIND";
  8404. req.path = "/dav/42";
  8405. auto res = cli_.send(req);
  8406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8407. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8408. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8409. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8410. }
  8411. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8412. Request req;
  8413. req.method = "PROPFIND";
  8414. req.path = "/dav-re/123";
  8415. auto res = cli_.send(req);
  8416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8417. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8418. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8419. }
  8420. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8421. Request req;
  8422. req.method = "MKCOL";
  8423. req.path = "/dav-mkcol";
  8424. auto res = cli_.send(req);
  8425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8426. EXPECT_EQ(StatusCode::Created_201, res->status);
  8427. }
  8428. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8429. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8430. Request req;
  8431. req.method = "REPORT";
  8432. req.path = "/dav-report";
  8433. req.body = xml;
  8434. auto res = cli_.send(req);
  8435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8436. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8437. EXPECT_EQ(xml, res->body);
  8438. }
  8439. // A content reader route must fire even when the request carries no body,
  8440. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8441. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8442. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8443. Request req;
  8444. req.method = "REPORT";
  8445. req.path = "/dav-report";
  8446. auto res = cli_.send(req);
  8447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8448. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8449. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8450. }
  8451. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8452. Request req;
  8453. req.method = "PROPFIND";
  8454. req.path = "/not-dav";
  8455. auto res = cli_.send(req);
  8456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8457. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8458. }
  8459. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8460. Request req;
  8461. req.method = "UNLOCK";
  8462. req.path = "/dav/dir";
  8463. cli_.set_keep_alive(true);
  8464. auto res = cli_.send(req);
  8465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8466. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8467. EXPECT_EQ("close", res->get_header_value("Connection"));
  8468. EXPECT_FALSE(cli_.is_socket_open());
  8469. }
  8470. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8471. // The mount point serves this path, but only for GET and HEAD.
  8472. auto get_res = cli_.Get("/dir/index.html");
  8473. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8474. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8475. Request req;
  8476. req.method = "PROPFIND";
  8477. req.path = "/dir/index.html";
  8478. auto res = cli_.send(req);
  8479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8480. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8481. }
  8482. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8483. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8484. cli_.set_keep_alive(true);
  8485. for (auto i = 0; i < 2; i++) {
  8486. Request req;
  8487. req.method = "PROPFIND";
  8488. req.path = "/dav/dir";
  8489. req.body = xml;
  8490. auto res = cli_.send(req);
  8491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8492. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8493. EXPECT_EQ(xml, res->body);
  8494. EXPECT_TRUE(cli_.is_socket_open());
  8495. }
  8496. // A built-in method must still be served on the same connection.
  8497. cli_.set_keep_alive(false);
  8498. auto res = cli_.Get("/hi");
  8499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8500. EXPECT_EQ(StatusCode::OK_200, res->status);
  8501. EXPECT_EQ("close", res->get_header_value("Connection"));
  8502. }
  8503. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8504. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8505. Request req;
  8506. req.method = "PROPFIND";
  8507. req.path = "/dav/dir";
  8508. req.set_header("Expect", "100-continue");
  8509. req.body = xml;
  8510. auto res = cli_.send(req);
  8511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8512. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8513. EXPECT_EQ(xml, res->body);
  8514. }
  8515. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8516. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8517. TEST_F(ServerTest, Gzip) {
  8518. Headers headers;
  8519. headers.emplace("Accept-Encoding", "gzip, deflate");
  8520. auto res = cli_.Get("/compress", headers);
  8521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8522. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8523. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8524. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8525. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8526. "7890123456789012345678901234567890",
  8527. res->body);
  8528. EXPECT_EQ(StatusCode::OK_200, res->status);
  8529. }
  8530. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8531. Headers headers;
  8532. headers.emplace("Accept-Encoding", "gzip, deflate");
  8533. auto res = cli_.Get("/compress-with-charset", headers);
  8534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8535. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8536. EXPECT_EQ("application/json; charset=utf-8",
  8537. res->get_header_value("Content-Type"));
  8538. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8539. "7890123456789012345678901234567890",
  8540. res->body);
  8541. EXPECT_EQ(StatusCode::OK_200, res->status);
  8542. }
  8543. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8544. Headers headers;
  8545. headers.emplace("Accept-Encoding", "");
  8546. auto res = cli_.Get("/compress", headers);
  8547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8548. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8549. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8550. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8551. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8552. "7890123456789012345678901234567890",
  8553. res->body);
  8554. EXPECT_EQ(StatusCode::OK_200, res->status);
  8555. }
  8556. TEST_F(ServerTest, GzipWithContentReceiver) {
  8557. Headers headers;
  8558. headers.emplace("Accept-Encoding", "gzip, deflate");
  8559. std::string body;
  8560. auto res =
  8561. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8562. EXPECT_EQ(100U, data_length);
  8563. body.append(data, data_length);
  8564. return true;
  8565. });
  8566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8567. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8569. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8571. "7890123456789012345678901234567890",
  8572. body);
  8573. EXPECT_EQ(StatusCode::OK_200, res->status);
  8574. }
  8575. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8576. Headers headers;
  8577. headers.emplace("Accept-Encoding", "gzip, deflate");
  8578. cli_.set_decompress(false);
  8579. auto res = cli_.Get("/compress", headers);
  8580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8581. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8583. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8584. EXPECT_EQ(33U, res->body.size());
  8585. EXPECT_EQ(StatusCode::OK_200, res->status);
  8586. }
  8587. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8588. Headers headers;
  8589. headers.emplace("Accept-Encoding", "");
  8590. std::string body;
  8591. auto res =
  8592. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8593. EXPECT_EQ(100U, data_length);
  8594. body.append(data, data_length);
  8595. return true;
  8596. });
  8597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8598. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8599. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8600. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8601. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8602. "7890123456789012345678901234567890",
  8603. body);
  8604. EXPECT_EQ(StatusCode::OK_200, res->status);
  8605. }
  8606. TEST_F(ServerTest, NoGzip) {
  8607. Headers headers;
  8608. headers.emplace("Accept-Encoding", "gzip, deflate");
  8609. auto res = cli_.Get("/nocompress", headers);
  8610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8611. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8612. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8613. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8614. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8615. "7890123456789012345678901234567890",
  8616. res->body);
  8617. EXPECT_EQ(StatusCode::OK_200, res->status);
  8618. }
  8619. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8620. Headers headers;
  8621. headers.emplace("Accept-Encoding", "gzip, deflate");
  8622. std::string body;
  8623. auto res = cli_.Get("/nocompress", headers,
  8624. [&](const char *data, size_t data_length) {
  8625. EXPECT_EQ(100U, data_length);
  8626. body.append(data, data_length);
  8627. return true;
  8628. });
  8629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8630. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8631. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8632. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8633. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8634. "7890123456789012345678901234567890",
  8635. body);
  8636. EXPECT_EQ(StatusCode::OK_200, res->status);
  8637. }
  8638. TEST_F(ServerTest, MultipartFormDataGzip) {
  8639. UploadFormDataItems items = {
  8640. {"key1", "test", "", ""},
  8641. {"key2", "--abcdefg123", "", ""},
  8642. };
  8643. cli_.set_compress(true);
  8644. auto res = cli_.Post("/compress-multipart", items);
  8645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8646. EXPECT_EQ(StatusCode::OK_200, res->status);
  8647. }
  8648. #endif
  8649. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8650. // Static file compression is opt-in, so these run their own server rather than
  8651. // flipping it on for the shared ServerTest fixture, which would silently
  8652. // rewrite what every other static file test is asserting.
  8653. class StaticFileCompressionTest : public ::testing::Test {
  8654. protected:
  8655. void TearDown() override {
  8656. if (t_.joinable()) {
  8657. svr_.stop();
  8658. t_.join();
  8659. }
  8660. }
  8661. int start(const std::function<void(Server &)> &configure = nullptr) {
  8662. // Serves the same tree as a directory of build-time compressed assets
  8663. // would be served: the mount point names the coding the files are already
  8664. // stored in. Registered before "/" so it is the one that matches.
  8665. svr_.set_mount_point("/pre-encoded", "./www",
  8666. {{"Content-Encoding", "gzip"}});
  8667. svr_.set_mount_point("/", "./www");
  8668. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8669. res.set_file_content("./www/dir/index.html", "text/html");
  8670. });
  8671. svr_.Get("/pre-encoded-file-content",
  8672. [](const Request & /*req*/, Response &res) {
  8673. res.set_header("Content-Encoding", "gzip");
  8674. res.set_file_content("./www/dir/index.html", "text/html");
  8675. });
  8676. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8677. res.set_content_provider(
  8678. 6, "text/plain",
  8679. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8680. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8681. return true;
  8682. });
  8683. });
  8684. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8685. res.set_content_provider(
  8686. 1000, "text/plain",
  8687. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8688. if (offset < 100) {
  8689. std::string data(100, 'A');
  8690. sink.write(data.data(), data.size());
  8691. return true;
  8692. }
  8693. std::this_thread::sleep_for(std::chrono::seconds(2));
  8694. std::string data(900, 'B');
  8695. sink.write(data.data(), data.size());
  8696. return true;
  8697. });
  8698. });
  8699. if (configure) { configure(svr_); }
  8700. auto port = svr_.bind_to_any_port(HOST);
  8701. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8702. svr_.wait_until_ready();
  8703. return port;
  8704. }
  8705. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8706. // Every file under ./www except 1MB.txt is smaller than the default
  8707. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8708. // it out of the way.
  8709. static void enable_without_floor(Server &svr) {
  8710. svr.set_static_file_compression(true);
  8711. svr.set_static_file_compression_min_length(0);
  8712. }
  8713. Server svr_;
  8714. std::thread t_;
  8715. };
  8716. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8717. auto port = start();
  8718. Client cli(HOST, port);
  8719. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8721. EXPECT_EQ(StatusCode::OK_200, res->status);
  8722. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8723. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8724. EXPECT_EQ(1048576U, res->body.size());
  8725. }
  8726. TEST_F(StaticFileCompressionTest, MountPoint) {
  8727. auto port = start(enable);
  8728. Client cli(HOST, port);
  8729. cli.set_decompress(false);
  8730. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8732. EXPECT_EQ(StatusCode::OK_200, res->status);
  8733. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8734. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8735. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8736. // The response stays self-delimiting: a length, not a chunked body.
  8737. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8738. EXPECT_EQ(std::to_string(res->body.size()),
  8739. res->get_header_value("Content-Length"));
  8740. EXPECT_LT(res->body.size(), 1048576U);
  8741. EXPECT_FALSE(res->body.empty());
  8742. }
  8743. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8744. auto port = start(enable);
  8745. Client cli(HOST, port);
  8746. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8748. EXPECT_EQ(StatusCode::OK_200, res->status);
  8749. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8750. EXPECT_EQ(1048576U, res->body.size());
  8751. }
  8752. TEST_F(StaticFileCompressionTest, FileContent) {
  8753. auto port = start(enable_without_floor);
  8754. Client cli(HOST, port);
  8755. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8757. EXPECT_EQ(StatusCode::OK_200, res->status);
  8758. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8759. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8760. EXPECT_EQ(104U, res->body.size());
  8761. }
  8762. // A handler that serves an already-encoded file names the coding itself. The
  8763. // file-backed path decided its coding from Accept-Encoding and the content
  8764. // type alone, so it compressed the stored bytes a second time and appended a
  8765. // second Content-Encoding field line.
  8766. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8767. auto port = start(enable_without_floor);
  8768. Client cli(HOST, port);
  8769. cli.set_decompress(false);
  8770. auto res = cli.Get("/pre-encoded-file-content",
  8771. Headers{{"Accept-Encoding", "gzip"}});
  8772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8773. EXPECT_EQ(StatusCode::OK_200, res->status);
  8774. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8775. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8776. // Vary belongs to a coding the server chose, and it chose none here.
  8777. EXPECT_FALSE(res->has_header("Vary"));
  8778. // The file travels exactly as it is stored on disk.
  8779. EXPECT_EQ(104U, res->body.size());
  8780. }
  8781. // The 1MB file clears the default floor, so this one runs the configuration a
  8782. // deployment would actually have.
  8783. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8784. auto port = start(enable);
  8785. Client cli(HOST, port);
  8786. cli.set_decompress(false);
  8787. auto res =
  8788. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8790. EXPECT_EQ(StatusCode::OK_200, res->status);
  8791. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8792. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8793. EXPECT_FALSE(res->has_header("Vary"));
  8794. EXPECT_EQ(1048576U, res->body.size());
  8795. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8796. }
  8797. TEST_F(StaticFileCompressionTest, Head) {
  8798. auto port = start(enable);
  8799. Client cli(HOST, port);
  8800. cli.set_decompress(false);
  8801. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8802. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8803. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8805. EXPECT_EQ(StatusCode::OK_200, res->status);
  8806. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8807. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8808. // HEAD still reports the size a GET would return.
  8809. EXPECT_EQ(get->get_header_value("Content-Length"),
  8810. res->get_header_value("Content-Length"));
  8811. EXPECT_TRUE(res->body.empty());
  8812. }
  8813. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8814. auto port = start(enable);
  8815. Client cli(HOST, port);
  8816. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8817. {"Accept-Encoding", "gzip"}});
  8818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8819. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8820. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8821. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8822. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8823. EXPECT_EQ("cd", res->body);
  8824. }
  8825. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8826. auto port = start(enable);
  8827. Client cli(HOST, port);
  8828. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8830. EXPECT_EQ(StatusCode::OK_200, res->status);
  8831. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8832. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8833. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8834. }
  8835. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8836. auto port = start(enable);
  8837. Client cli(HOST, port);
  8838. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8840. EXPECT_EQ(StatusCode::OK_200, res->status);
  8841. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8842. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8843. EXPECT_TRUE(res->body.empty());
  8844. }
  8845. TEST_F(StaticFileCompressionTest, MinLength) {
  8846. auto port = start(enable);
  8847. Client cli(HOST, port);
  8848. // 104 bytes, well under the default floor. Compressing it would add the
  8849. // gzip header and trailer to a body that already fits in one packet.
  8850. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8852. EXPECT_EQ(StatusCode::OK_200, res->status);
  8853. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8854. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8855. }
  8856. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8857. auto port = start([](Server &svr) {
  8858. svr.set_static_file_compression(true);
  8859. svr.set_static_file_compression_min_length(1);
  8860. });
  8861. Client cli(HOST, port);
  8862. cli.set_decompress(false);
  8863. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8865. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8866. // A 9-byte file comes back larger than it went in, because gzip's header and
  8867. // trailer outweigh anything deflate can save. That is the end of the range
  8868. // the floor exists to keep out.
  8869. EXPECT_GT(res->body.size(), 9U);
  8870. }
  8871. TEST_F(StaticFileCompressionTest, MaxLength) {
  8872. auto port = start([](Server &svr) {
  8873. svr.set_static_file_compression(true);
  8874. svr.set_static_file_compression_min_length(0);
  8875. svr.set_static_file_compression_max_length(1024);
  8876. });
  8877. Client cli(HOST, port);
  8878. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8879. // defines `small` as a macro on Windows.
  8880. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8881. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8882. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8883. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8884. // Under it: compressed.
  8885. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8886. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8887. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8888. }
  8889. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8890. auto port = start(enable_without_floor);
  8891. Client cli(HOST, port);
  8892. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8893. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8894. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8895. auto identity_etag = identity->get_header_value("ETag");
  8896. ASSERT_FALSE(identity_etag.empty());
  8897. auto gzipped =
  8898. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8899. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8900. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8901. auto gzip_etag = gzipped->get_header_value("ETag");
  8902. ASSERT_FALSE(gzip_etag.empty());
  8903. // Two representations, two validators.
  8904. EXPECT_NE(identity_etag, gzip_etag);
  8905. // Each one revalidates against the request that would produce it...
  8906. auto fresh =
  8907. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8908. {"If-None-Match", gzip_etag}});
  8909. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8910. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8911. auto fresh_identity =
  8912. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8913. {"If-None-Match", identity_etag}});
  8914. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8915. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8916. // ...and not against the other representation.
  8917. auto crossed =
  8918. cli.Get("/dir/index.html",
  8919. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8920. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8921. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8922. }
  8923. // The opt-in covers responses the server reads off disk itself. A caller's own
  8924. // known-length provider keeps its Content-Length and, more importantly, keeps
  8925. // delivering incrementally: routing it through a compressor would hold every
  8926. // write back until zlib's window filled.
  8927. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8928. auto port = start(enable);
  8929. Client cli(HOST, port);
  8930. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8932. EXPECT_EQ(StatusCode::OK_200, res->status);
  8933. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8934. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8935. EXPECT_EQ("aaabbb", res->body);
  8936. }
  8937. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8938. auto port = start(enable);
  8939. Client cli(HOST, port);
  8940. cli.set_read_timeout(1, 0);
  8941. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8942. Headers{{"Accept-Encoding", "gzip"}});
  8943. ASSERT_TRUE(handle.is_valid());
  8944. // The provider writes 100 bytes and then stalls for longer than the read
  8945. // timeout. Those first bytes have to arrive anyway: run the response through
  8946. // a compressor and zlib holds them until its window fills, so the read would
  8947. // come back empty instead.
  8948. char buf[256];
  8949. auto n = handle.read(buf, sizeof(buf));
  8950. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8951. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8952. }
  8953. #endif
  8954. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8955. TEST_F(ServerTest, Brotli) {
  8956. Headers headers;
  8957. headers.emplace("Accept-Encoding", "br");
  8958. auto res = cli_.Get("/compress", headers);
  8959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8960. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8961. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8962. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8963. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8964. "7890123456789012345678901234567890",
  8965. res->body);
  8966. EXPECT_EQ(StatusCode::OK_200, res->status);
  8967. }
  8968. #endif
  8969. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8970. TEST_F(ServerTest, Zstd) {
  8971. Headers headers;
  8972. headers.emplace("Accept-Encoding", "zstd");
  8973. auto res = cli_.Get("/compress", headers);
  8974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8975. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8976. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8977. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8978. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8979. "7890123456789012345678901234567890",
  8980. res->body);
  8981. EXPECT_EQ(StatusCode::OK_200, res->status);
  8982. }
  8983. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8984. Headers headers;
  8985. headers.emplace("Accept-Encoding", "");
  8986. auto res = cli_.Get("/compress", headers);
  8987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8988. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8989. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8990. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8991. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8992. "7890123456789012345678901234567890",
  8993. res->body);
  8994. EXPECT_EQ(StatusCode::OK_200, res->status);
  8995. }
  8996. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8997. Headers headers;
  8998. headers.emplace("Accept-Encoding", "zstd");
  8999. std::string body;
  9000. auto res =
  9001. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9002. EXPECT_EQ(100U, data_length);
  9003. body.append(data, data_length);
  9004. return true;
  9005. });
  9006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9007. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9008. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9009. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9010. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9011. "7890123456789012345678901234567890",
  9012. body);
  9013. EXPECT_EQ(StatusCode::OK_200, res->status);
  9014. }
  9015. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9016. Headers headers;
  9017. headers.emplace("Accept-Encoding", "zstd");
  9018. cli_.set_decompress(false);
  9019. auto res = cli_.Get("/compress", headers);
  9020. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9021. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9022. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9023. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9025. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9026. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9027. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9028. EXPECT_EQ(StatusCode::OK_200, res->status);
  9029. ASSERT_EQ(26U, res->body.size());
  9030. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9031. 0);
  9032. }
  9033. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9034. Headers headers;
  9035. headers.emplace("Accept-Encoding", "");
  9036. std::string body;
  9037. auto res =
  9038. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9039. EXPECT_EQ(100U, data_length);
  9040. body.append(data, data_length);
  9041. return true;
  9042. });
  9043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9044. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9045. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9046. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9047. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9048. "7890123456789012345678901234567890",
  9049. body);
  9050. EXPECT_EQ(StatusCode::OK_200, res->status);
  9051. }
  9052. TEST_F(ServerTest, NoZstd) {
  9053. Headers headers;
  9054. headers.emplace("Accept-Encoding", "zstd");
  9055. auto res = cli_.Get("/nocompress", headers);
  9056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9057. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9058. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9059. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9060. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9061. "7890123456789012345678901234567890",
  9062. res->body);
  9063. EXPECT_EQ(StatusCode::OK_200, res->status);
  9064. }
  9065. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9066. Headers headers;
  9067. headers.emplace("Accept-Encoding", "zstd");
  9068. std::string body;
  9069. auto res = cli_.Get("/nocompress", headers,
  9070. [&](const char *data, size_t data_length) {
  9071. EXPECT_EQ(100U, data_length);
  9072. body.append(data, data_length);
  9073. return true;
  9074. });
  9075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9076. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9077. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9078. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9079. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9080. "7890123456789012345678901234567890",
  9081. body);
  9082. EXPECT_EQ(StatusCode::OK_200, res->status);
  9083. }
  9084. // TODO: How to enable zstd ??
  9085. TEST_F(ServerTest, MultipartFormDataZstd) {
  9086. UploadFormDataItems items = {
  9087. {"key1", "test", "", ""},
  9088. {"key2", "--abcdefg123", "", ""},
  9089. };
  9090. Headers headers;
  9091. headers.emplace("Accept-Encoding", "zstd");
  9092. cli_.set_compress(true);
  9093. auto res = cli_.Post("/compress-multipart", headers, items);
  9094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9095. EXPECT_EQ(StatusCode::OK_200, res->status);
  9096. }
  9097. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9098. Headers headers;
  9099. headers.emplace("Accept-Encoding", "zstd");
  9100. cli_.set_compress(true);
  9101. auto res = cli_.Put(
  9102. "/put", headers, 3,
  9103. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9104. sink.os << "PUT";
  9105. return true;
  9106. },
  9107. "text/plain");
  9108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9109. EXPECT_EQ(StatusCode::OK_200, res->status);
  9110. EXPECT_EQ("PUT", res->body);
  9111. }
  9112. // Pre-compression logging tests
  9113. TEST_F(ServerTest, PreCompressionLogging) {
  9114. // Test data for compression (matches the actual /compress endpoint content)
  9115. const std::string test_content =
  9116. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9117. "3456789012345678901234567890";
  9118. // Variables to capture logging data
  9119. std::string pre_compression_body;
  9120. std::string pre_compression_content_type;
  9121. std::string pre_compression_content_encoding;
  9122. std::string post_compression_body;
  9123. std::string post_compression_content_type;
  9124. std::string post_compression_content_encoding;
  9125. // Set up pre-compression logger
  9126. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9127. const Response &res) {
  9128. pre_compression_body = res.body;
  9129. pre_compression_content_type = res.get_header_value("Content-Type");
  9130. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9131. });
  9132. // Set up post-compression logger
  9133. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9134. post_compression_body = res.body;
  9135. post_compression_content_type = res.get_header_value("Content-Type");
  9136. post_compression_content_encoding =
  9137. res.get_header_value("Content-Encoding");
  9138. });
  9139. // Test with gzip compression
  9140. Headers headers;
  9141. headers.emplace("Accept-Encoding", "gzip");
  9142. auto res = cli_.Get("/compress", headers);
  9143. // Verify response was compressed
  9144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9145. EXPECT_EQ(StatusCode::OK_200, res->status);
  9146. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9147. // Verify pre-compression logger captured uncompressed content
  9148. EXPECT_EQ(test_content, pre_compression_body);
  9149. EXPECT_EQ("text/plain", pre_compression_content_type);
  9150. EXPECT_TRUE(pre_compression_content_encoding
  9151. .empty()); // No encoding header before compression
  9152. // Verify post-compression logger captured compressed content
  9153. EXPECT_NE(test_content,
  9154. post_compression_body); // Should be different after compression
  9155. EXPECT_EQ("text/plain", post_compression_content_type);
  9156. EXPECT_EQ("gzip", post_compression_content_encoding);
  9157. // Verify compressed content is smaller
  9158. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9159. }
  9160. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9161. const std::string test_content =
  9162. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9163. "3456789012345678901234567890";
  9164. std::string pre_compression_body;
  9165. std::string post_compression_body;
  9166. svr_.set_pre_compression_logger(
  9167. [&](const Request & /*req*/, const Response &res) {
  9168. pre_compression_body = res.body;
  9169. });
  9170. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9171. post_compression_body = res.body;
  9172. });
  9173. Headers headers;
  9174. headers.emplace("Accept-Encoding", "br");
  9175. auto res = cli_.Get("/compress", headers);
  9176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9177. EXPECT_EQ(StatusCode::OK_200, res->status);
  9178. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9179. // Verify pre-compression content is uncompressed
  9180. EXPECT_EQ(test_content, pre_compression_body);
  9181. // Verify post-compression content is compressed
  9182. EXPECT_NE(test_content, post_compression_body);
  9183. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9184. }
  9185. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9186. const std::string test_content =
  9187. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9188. "3456789012345678901234567890";
  9189. std::string pre_compression_body;
  9190. std::string post_compression_body;
  9191. svr_.set_pre_compression_logger(
  9192. [&](const Request & /*req*/, const Response &res) {
  9193. pre_compression_body = res.body;
  9194. });
  9195. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9196. post_compression_body = res.body;
  9197. });
  9198. // Request without compression (use /nocompress endpoint)
  9199. Headers headers;
  9200. auto res = cli_.Get("/nocompress", headers);
  9201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9202. EXPECT_EQ(StatusCode::OK_200, res->status);
  9203. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9204. // Pre-compression logger should not be called when no compression is applied
  9205. EXPECT_TRUE(
  9206. pre_compression_body.empty()); // Pre-compression logger not called
  9207. EXPECT_EQ(
  9208. test_content,
  9209. post_compression_body); // Post-compression logger captures final content
  9210. }
  9211. TEST_F(ServerTest, LoggerSeesContentLength) {
  9212. size_t logged_content_length = 0;
  9213. std::string logged_content_length_header;
  9214. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9215. logged_content_length = res.content_length_;
  9216. logged_content_length_header = res.get_header_value("Content-Length");
  9217. });
  9218. auto res = cli_.Get("/nocompress");
  9219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9220. EXPECT_EQ(StatusCode::OK_200, res->status);
  9221. EXPECT_EQ(res->body.size(), logged_content_length);
  9222. EXPECT_EQ(std::to_string(logged_content_length),
  9223. logged_content_length_header);
  9224. }
  9225. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9226. const std::string test_content =
  9227. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9228. "3456789012345678901234567890";
  9229. std::string pre_compression_body;
  9230. bool pre_logger_called = false;
  9231. // Set only pre-compression logger
  9232. svr_.set_pre_compression_logger(
  9233. [&](const Request & /*req*/, const Response &res) {
  9234. pre_compression_body = res.body;
  9235. pre_logger_called = true;
  9236. });
  9237. Headers headers;
  9238. headers.emplace("Accept-Encoding", "gzip");
  9239. auto res = cli_.Get("/compress", headers);
  9240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9241. EXPECT_EQ(StatusCode::OK_200, res->status);
  9242. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9243. // Verify pre-compression logger was called
  9244. EXPECT_TRUE(pre_logger_called);
  9245. EXPECT_EQ(test_content, pre_compression_body);
  9246. }
  9247. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9248. {
  9249. // Test with Expect: 100-continue header - success case
  9250. // Server returns 100 Continue, client sends body, server returns 200 OK
  9251. Request req;
  9252. req.method = "POST";
  9253. req.path = "/post-large";
  9254. req.set_header("Expect", "100-continue");
  9255. req.body = LARGE_DATA;
  9256. Response res;
  9257. auto error = Error::Success;
  9258. cli_.set_keep_alive(true);
  9259. auto ret = cli_.send(req, res, error);
  9260. EXPECT_TRUE(ret);
  9261. EXPECT_EQ(StatusCode::OK_200, res.status);
  9262. EXPECT_EQ(LARGE_DATA, res.body);
  9263. }
  9264. {
  9265. // Test with Expect: 100-continue header - error case
  9266. // Client should not send the body when server returns an error
  9267. Request req;
  9268. req.method = "POST";
  9269. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9270. req.set_header("Expect", "100-continue");
  9271. req.body = LARGE_DATA;
  9272. Response res;
  9273. auto error = Error::Success;
  9274. auto start = std::chrono::high_resolution_clock::now();
  9275. cli_.set_keep_alive(true);
  9276. auto ret = cli_.send(req, res, error);
  9277. auto end = std::chrono::high_resolution_clock::now();
  9278. auto elapsed =
  9279. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9280. .count();
  9281. // With Expect: 100-continue, request completes successfully but with error
  9282. EXPECT_TRUE(ret);
  9283. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9284. EXPECT_EQ("close", res.get_header_value("Connection"));
  9285. EXPECT_FALSE(cli_.is_socket_open());
  9286. EXPECT_LE(elapsed, 2000);
  9287. }
  9288. {
  9289. // Send an extra GET request to ensure error recovery without hanging
  9290. Request req;
  9291. req.method = "GET";
  9292. req.path = "/hi";
  9293. auto start = std::chrono::high_resolution_clock::now();
  9294. auto res = cli_.send(req);
  9295. auto end = std::chrono::high_resolution_clock::now();
  9296. auto elapsed =
  9297. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9298. .count();
  9299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9300. EXPECT_EQ(StatusCode::OK_200, res->status);
  9301. EXPECT_EQ("Hello World!", res->body);
  9302. EXPECT_LE(elapsed, 500);
  9303. }
  9304. }
  9305. TEST(ZstdDecompressor, ChunkedDecompression) {
  9306. std::string data;
  9307. for (size_t i = 0; i < 32 * 1024; ++i) {
  9308. data.push_back(static_cast<char>('a' + i % 26));
  9309. }
  9310. std::string compressed_data;
  9311. {
  9312. httplib::detail::zstd_compressor compressor;
  9313. bool result = compressor.compress(
  9314. data.data(), data.size(),
  9315. /*last=*/true,
  9316. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9317. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9318. compressed_data_size);
  9319. return true;
  9320. });
  9321. ASSERT_TRUE(result);
  9322. }
  9323. std::string decompressed_data;
  9324. {
  9325. httplib::detail::zstd_decompressor decompressor;
  9326. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9327. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9328. size_t chunk_size = 130;
  9329. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9330. chunk_begin += chunk_size) {
  9331. size_t current_chunk_size =
  9332. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9333. bool result = decompressor.decompress(
  9334. compressed_data.data() + chunk_begin, current_chunk_size,
  9335. [&](const char *decompressed_data_chunk,
  9336. size_t decompressed_data_chunk_size) {
  9337. decompressed_data.insert(decompressed_data.size(),
  9338. decompressed_data_chunk,
  9339. decompressed_data_chunk_size);
  9340. return true;
  9341. });
  9342. ASSERT_TRUE(result);
  9343. }
  9344. }
  9345. ASSERT_EQ(data, decompressed_data);
  9346. }
  9347. TEST(ZstdDecompressor, Decompress) {
  9348. std::string original_text = "Compressed with ZSTD";
  9349. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9350. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9351. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9352. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9353. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9354. std::string decompressed_data;
  9355. {
  9356. httplib::detail::zstd_decompressor decompressor;
  9357. bool result = decompressor.decompress(
  9358. compressed_data.data(), compressed_data.size(),
  9359. [&](const char *decompressed_data_chunk,
  9360. size_t decompressed_data_chunk_size) {
  9361. decompressed_data.insert(decompressed_data.size(),
  9362. decompressed_data_chunk,
  9363. decompressed_data_chunk_size);
  9364. return true;
  9365. });
  9366. ASSERT_TRUE(result);
  9367. }
  9368. ASSERT_EQ(original_text, decompressed_data);
  9369. }
  9370. #endif
  9371. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9372. // separate chunks so that the server sees each part in its own read(). Used to
  9373. // place a read boundary at a specific offset of a request body.
  9374. static bool send_request_in_parts(time_t read_timeout_sec,
  9375. const std::vector<std::string> &parts,
  9376. std::string *resp = nullptr,
  9377. int port = PORT) {
  9378. auto error = Error::Success;
  9379. auto client_sock = detail::create_client_socket(
  9380. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9381. /*connection_timeout_sec=*/5, 0,
  9382. /*read_timeout_sec=*/5, 0,
  9383. /*write_timeout_sec=*/5, 0, std::string(), error);
  9384. if (client_sock == INVALID_SOCKET) { return false; }
  9385. auto ret = detail::process_client_socket(
  9386. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9387. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9388. for (size_t i = 0; i < parts.size(); i++) {
  9389. const auto &part = parts[i];
  9390. if (part.size() !=
  9391. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9392. return false;
  9393. }
  9394. if (i + 1 < parts.size()) {
  9395. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9396. }
  9397. }
  9398. char buf[512];
  9399. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9400. while (line_reader.getline()) {
  9401. if (resp) { *resp += line_reader.ptr(); }
  9402. }
  9403. return true;
  9404. });
  9405. detail::close_socket(client_sock);
  9406. return ret;
  9407. }
  9408. // Sends a raw request to a server listening at HOST:PORT.
  9409. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9410. std::string *resp = nullptr, int port = PORT) {
  9411. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9412. }
  9413. #ifdef CPPHTTPLIB_SSL_ENABLED
  9414. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9416. ASSERT_TRUE(svr.is_valid());
  9417. svr.set_read_timeout(1, 0);
  9418. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9419. auto se = detail::scope_exit([&] {
  9420. svr.stop();
  9421. t.join();
  9422. ASSERT_FALSE(svr.is_running());
  9423. });
  9424. svr.wait_until_ready();
  9425. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9426. // keeps each wait well within the read timeout. The server gives up a
  9427. // second in, so the bytes sent after that fail.
  9428. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9429. parts.resize(26, std::string(1, '\0'));
  9430. EXPECT_FALSE(send_request_in_parts(5, parts));
  9431. }
  9432. #endif
  9433. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9434. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9435. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9436. const std::vector<std::string> &parts,
  9437. std::string *resp = nullptr,
  9438. int port = PORT) {
  9439. auto error = Error::Success;
  9440. auto sock = detail::create_client_socket(
  9441. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9442. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9443. /*write_timeout_sec=*/5, 0, std::string(), error);
  9444. if (sock == INVALID_SOCKET) { return false; }
  9445. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9446. auto ctx = SSL_CTX_new(TLS_client_method());
  9447. auto ssl = SSL_new(ctx);
  9448. auto ssl_se = detail::scope_exit([&] {
  9449. SSL_free(ssl);
  9450. SSL_CTX_free(ctx);
  9451. });
  9452. SSL_set_fd(ssl, static_cast<int>(sock));
  9453. if (SSL_connect(ssl) != 1) { return false; }
  9454. for (size_t i = 0; i < parts.size(); i++) {
  9455. const auto &part = parts[i];
  9456. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9457. static_cast<int>(part.size())) {
  9458. return false;
  9459. }
  9460. if (i + 1 < parts.size()) {
  9461. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9462. }
  9463. }
  9464. char buf[512];
  9465. int n;
  9466. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9467. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9468. }
  9469. return true;
  9470. }
  9471. #endif
  9472. // The request line, then a header value a byte at a time.
  9473. static std::vector<std::string> slow_request_head_parts() {
  9474. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9475. parts.resize(26, "a");
  9476. parts.emplace_back("\r\n\r\n");
  9477. return parts;
  9478. }
  9479. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9480. // within the one-second read timeout. The server gives up a second in, before
  9481. // the head is complete.
  9482. static void
  9483. expect_slow_request_head_dropped(Server &svr,
  9484. const std::function<std::string()> &send) {
  9485. std::atomic<bool> handled(false);
  9486. svr.Get("/", [&](const Request &, Response &res) {
  9487. handled = true;
  9488. res.set_content("ok", "text/plain");
  9489. });
  9490. svr.set_read_timeout(1, 0);
  9491. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9492. auto se = detail::scope_exit([&] {
  9493. svr.stop();
  9494. t.join();
  9495. ASSERT_FALSE(svr.is_running());
  9496. });
  9497. svr.wait_until_ready();
  9498. auto resp = send();
  9499. EXPECT_FALSE(handled);
  9500. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9501. }
  9502. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9503. Server svr;
  9504. expect_slow_request_head_dropped(svr, [] {
  9505. std::string resp;
  9506. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9507. return resp;
  9508. });
  9509. }
  9510. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9511. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9513. ASSERT_TRUE(svr.is_valid());
  9514. expect_slow_request_head_dropped(svr, [] {
  9515. std::string resp;
  9516. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9517. return resp;
  9518. });
  9519. }
  9520. #endif
  9521. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9522. Server svr;
  9523. std::string header_value;
  9524. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9525. header_value = req.get_header_value("foo");
  9526. res.set_content("ok", "text/plain");
  9527. });
  9528. thread t = thread([&] { svr.listen(HOST, PORT); });
  9529. auto se = detail::scope_exit([&] {
  9530. svr.stop();
  9531. t.join();
  9532. ASSERT_FALSE(svr.is_running());
  9533. });
  9534. svr.wait_until_ready();
  9535. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9536. // like characters are not treated the same - use vertical tab and escape.
  9537. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9538. "foo: \t \v bar \x1B\t \r\n"
  9539. "Connection: close\r\n"
  9540. "\r\n";
  9541. std::string res;
  9542. ASSERT_TRUE(send_request(5, req, &res));
  9543. EXPECT_EQ(header_value, "");
  9544. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9545. }
  9546. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9547. Server svr;
  9548. std::string received;
  9549. svr.Get("/order", [&](const Request &req, Response &res) {
  9550. received = entries_to_string(req.headers);
  9551. res.set_content("ok", "text/plain");
  9552. });
  9553. auto port = svr.bind_to_any_port(HOST);
  9554. thread t = thread([&] { svr.listen_after_bind(); });
  9555. auto se = detail::scope_exit([&] {
  9556. svr.stop();
  9557. t.join();
  9558. ASSERT_FALSE(svr.is_running());
  9559. });
  9560. svr.wait_until_ready();
  9561. const std::string req = "GET /order HTTP/1.1\r\n"
  9562. "Host: localhost\r\n"
  9563. "X-First: 1\r\n"
  9564. "X-Dup: a\r\n"
  9565. "X-Second: 2\r\n"
  9566. "X-Dup: b\r\n"
  9567. "Connection: close\r\n"
  9568. "\r\n";
  9569. std::string res;
  9570. ASSERT_TRUE(send_request(5, req, &res, port));
  9571. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9572. EXPECT_EQ(
  9573. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9574. received);
  9575. }
  9576. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9577. Server svr;
  9578. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9579. res.set_header("Set-Cookie", "first=1");
  9580. res.set_header("X-Between", "y");
  9581. res.set_header("Set-Cookie", "second=2");
  9582. res.set_content("ok", "text/plain");
  9583. });
  9584. auto port = svr.bind_to_any_port(HOST);
  9585. thread t = thread([&] { svr.listen_after_bind(); });
  9586. auto se = detail::scope_exit([&] {
  9587. svr.stop();
  9588. t.join();
  9589. ASSERT_FALSE(svr.is_running());
  9590. });
  9591. svr.wait_until_ready();
  9592. Client cli(HOST, port);
  9593. auto res = cli.Get("/cookies");
  9594. ASSERT_TRUE(res);
  9595. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9596. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9597. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9598. }
  9599. // A stream may send a byte at a time with a small extension on each chunk,
  9600. // however long it runs
  9601. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9602. Server svr;
  9603. svr.Post("/count", [](const Request &req, Response &res) {
  9604. res.set_content(std::to_string(req.body.size()), "text/plain");
  9605. });
  9606. auto port = svr.bind_to_any_port(HOST);
  9607. ASSERT_LT(0, port);
  9608. thread t = thread([&] { svr.listen_after_bind(); });
  9609. auto se = detail::scope_exit([&] {
  9610. svr.stop();
  9611. t.join();
  9612. ASSERT_FALSE(svr.is_running());
  9613. });
  9614. svr.wait_until_ready();
  9615. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9616. "\r\nTransfer-Encoding: chunked\r\n"
  9617. "Connection: close\r\n\r\n";
  9618. for (auto i = 0; i < 4096; i++) {
  9619. req += "1;a=b\r\nx\r\n";
  9620. }
  9621. req += "0\r\n\r\n";
  9622. std::string res;
  9623. ASSERT_TRUE(send_request(5, req, &res, port));
  9624. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9625. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9626. }
  9627. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9628. Server svr;
  9629. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9630. auto i = new int(0);
  9631. res.set_header("Trailer", "X-Safe, X-Reflected");
  9632. res.set_chunked_content_provider(
  9633. "text/plain",
  9634. [i](size_t /*offset*/, DataSink &sink) {
  9635. if (*i == 0) {
  9636. sink.os << "body";
  9637. } else {
  9638. Headers trailer;
  9639. // A valid trailer that must survive.
  9640. trailer.emplace("X-Safe", "safe");
  9641. // Attacker-controlled value carrying CR/LF (response splitting).
  9642. trailer.emplace("X-Reflected",
  9643. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9644. // Attacker-controlled name carrying CR/LF.
  9645. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9646. sink.done_with_trailer(trailer);
  9647. }
  9648. (*i)++;
  9649. return true;
  9650. },
  9651. [i](bool /*success*/) { delete i; });
  9652. });
  9653. thread t = thread([&] { svr.listen(HOST, PORT); });
  9654. auto se = detail::scope_exit([&] {
  9655. svr.stop();
  9656. t.join();
  9657. ASSERT_FALSE(svr.is_running());
  9658. });
  9659. svr.wait_until_ready();
  9660. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9661. "Host: " + HOST +
  9662. "\r\n"
  9663. "Connection: close\r\n"
  9664. "\r\n";
  9665. std::string res;
  9666. ASSERT_TRUE(send_request(5, req, &res));
  9667. // The injected fields must not appear anywhere in the raw response.
  9668. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9669. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9670. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9671. // Invalid trailers are dropped entirely, matching set_header().
  9672. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9673. // The valid trailer still passes through.
  9674. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9675. }
  9676. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9677. // A custom header writer gets only the fields the default one writes
  9678. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9679. std::string s;
  9680. for (const auto &h : hdrs) {
  9681. s += h.first + ": " + h.second + "\r\n";
  9682. }
  9683. s += "\r\n";
  9684. return strm.write(s.data(), s.size());
  9685. };
  9686. for (auto custom_writer : {false, true}) {
  9687. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9688. Server svr;
  9689. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9690. svr.set_post_routing_handler([](const Request &, Response &res) {
  9691. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9692. });
  9693. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9694. // res.headers is a public field an application can populate directly,
  9695. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9696. // A valid header that must survive.
  9697. res.headers.emplace("X-Safe", "safe");
  9698. // Attacker-controlled value carrying CR/LF (response splitting).
  9699. res.headers.emplace("X-Reflected",
  9700. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9701. // Attacker-controlled name carrying CR/LF.
  9702. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9703. res.set_content("body", "text/plain");
  9704. });
  9705. thread t = thread([&] { svr.listen(HOST, PORT); });
  9706. auto se = detail::scope_exit([&] {
  9707. svr.stop();
  9708. t.join();
  9709. ASSERT_FALSE(svr.is_running());
  9710. });
  9711. svr.wait_until_ready();
  9712. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9713. "Host: " + HOST +
  9714. "\r\n"
  9715. "Connection: close\r\n"
  9716. "\r\n";
  9717. std::string res;
  9718. ASSERT_TRUE(send_request(5, req, &res));
  9719. // The injected fields must not appear anywhere in the raw response.
  9720. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9721. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9722. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9723. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9724. // Invalid headers are dropped entirely, matching set_header().
  9725. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9726. // The valid header still passes through.
  9727. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9728. }
  9729. }
  9730. // Forward declaration: in split builds split.py strips `inline` and moves the
  9731. // definition into httplib.cc, so detail::write_request_line is not visible from
  9732. // the public httplib.h. Re-declaring it here lets the tests link against the
  9733. // symbol in both header-only and split builds.
  9734. namespace httplib {
  9735. namespace detail {
  9736. ssize_t write_request_line(Stream &strm, const std::string &method,
  9737. const std::string &path);
  9738. } // namespace detail
  9739. } // namespace httplib
  9740. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9741. // A well-formed target is written verbatim.
  9742. {
  9743. detail::BufferStream strm;
  9744. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9745. EXPECT_GT(n, 0);
  9746. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9747. }
  9748. // A target carrying CR/LF, SP or other control octets must be rejected
  9749. // before anything reaches the wire, otherwise it splits the request line and
  9750. // injects a header or a whole request.
  9751. const std::string evil_targets[] = {
  9752. "/a\r\nInjected: pwned",
  9753. "/a\rInjected",
  9754. "/a\nInjected",
  9755. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9756. "/a b",
  9757. "/a\tb",
  9758. "/a\x7f",
  9759. };
  9760. for (const auto &evil : evil_targets) {
  9761. detail::BufferStream strm;
  9762. auto n = detail::write_request_line(strm, "GET", evil);
  9763. EXPECT_LT(n, 0);
  9764. EXPECT_TRUE(strm.get_buffer().empty());
  9765. }
  9766. }
  9767. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9768. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9769. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9770. // target reaches write_request. The client must fail cleanly with
  9771. // Error::Write instead of putting a request-line-less, header-injecting
  9772. // request on the wire.
  9773. Server svr;
  9774. svr.Get("/a", [](const Request &, Response &res) {
  9775. res.set_content("ok", "text/plain");
  9776. });
  9777. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9778. auto se = detail::scope_exit([&] {
  9779. svr.stop();
  9780. thread.join();
  9781. ASSERT_FALSE(svr.is_running());
  9782. });
  9783. svr.wait_until_ready();
  9784. {
  9785. Client cli(HOST, PORT);
  9786. cli.set_path_encode(false);
  9787. // The request is rejected before anything is written, so the connection
  9788. // stays silent and the subsequent response read would otherwise block for
  9789. // the full default read timeout. Shorten it -- the assertion is on the
  9790. // error, not the timeout.
  9791. cli.set_read_timeout(1, 0);
  9792. auto res = cli.Get("/a\r\nInjected: pwned");
  9793. EXPECT_FALSE(res);
  9794. EXPECT_EQ(Error::Write, res.error());
  9795. }
  9796. }
  9797. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9798. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9799. // including extension methods.
  9800. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9801. for (const auto &method : good_methods) {
  9802. detail::BufferStream strm;
  9803. auto n = detail::write_request_line(strm, method, "/");
  9804. EXPECT_GT(n, 0);
  9805. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9806. }
  9807. // A method carrying CR/LF would split the request line and smuggle a whole
  9808. // request ahead of the real one. A space or an empty method corrupts the
  9809. // request line. All must be rejected before anything reaches the wire.
  9810. const std::string evil_methods[] = {
  9811. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9812. "GET\r\nInjected: pwned",
  9813. "GET\r",
  9814. "GET\n",
  9815. "GE T",
  9816. "",
  9817. };
  9818. for (const auto &evil : evil_methods) {
  9819. detail::BufferStream strm;
  9820. auto n = detail::write_request_line(strm, evil, "/");
  9821. EXPECT_LT(n, 0);
  9822. EXPECT_TRUE(strm.get_buffer().empty());
  9823. }
  9824. }
  9825. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9826. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9827. // through Client::send must fail with Error::Write and no request, neither
  9828. // the smuggled one nor the real one, may reach the server.
  9829. Server svr;
  9830. std::atomic<int> request_count(0);
  9831. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9832. request_count++;
  9833. res.status = StatusCode::OK_200;
  9834. return Server::HandlerResponse::Handled;
  9835. });
  9836. auto port = svr.bind_to_any_port(HOST);
  9837. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9838. auto se = detail::scope_exit([&] {
  9839. svr.stop();
  9840. thread.join();
  9841. ASSERT_FALSE(svr.is_running());
  9842. });
  9843. svr.wait_until_ready();
  9844. {
  9845. Client cli(HOST, port);
  9846. const std::string evil_methods[] = {
  9847. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9848. "GE T",
  9849. "",
  9850. };
  9851. for (const auto &evil : evil_methods) {
  9852. Request req;
  9853. req.method = evil;
  9854. req.path = "/";
  9855. auto res = cli.send(req);
  9856. EXPECT_FALSE(res);
  9857. EXPECT_EQ(Error::Write, res.error());
  9858. }
  9859. auto handle =
  9860. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9861. EXPECT_FALSE(handle.is_valid());
  9862. EXPECT_EQ(Error::Write, handle.error);
  9863. // A valid request on the same client still goes through.
  9864. auto res = cli.Get("/");
  9865. ASSERT_TRUE(res);
  9866. EXPECT_EQ(StatusCode::OK_200, res->status);
  9867. }
  9868. EXPECT_EQ(1, request_count.load());
  9869. }
  9870. // Sends a raw request and verifies that there isn't a crash or exception.
  9871. static void test_raw_request(const std::string &req,
  9872. std::string *out = nullptr) {
  9873. Server svr;
  9874. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9875. res.set_content("ok", "text/plain");
  9876. });
  9877. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9878. res.set_content("ok", "text/plain");
  9879. });
  9880. svr.Get("/header_field_value_check",
  9881. [&](const Request & /*req*/, Response &res) {
  9882. res.set_content("ok", "text/plain");
  9883. });
  9884. svr.CustomRoute("PROPFIND", "/dav",
  9885. [&](const Request & /*req*/, Response &res) {
  9886. res.status = StatusCode::MultiStatus_207;
  9887. });
  9888. // Server read timeout must be longer than the client read timeout for the
  9889. // bug to reproduce, probably to force the server to process a request
  9890. // without a trailing blank line.
  9891. const time_t client_read_timeout_sec = 1;
  9892. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9893. bool listen_thread_ok = false;
  9894. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9895. auto se = detail::scope_exit([&] {
  9896. svr.stop();
  9897. t.join();
  9898. ASSERT_FALSE(svr.is_running());
  9899. EXPECT_TRUE(listen_thread_ok);
  9900. });
  9901. svr.wait_until_ready();
  9902. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9903. }
  9904. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9905. // A certain header line causes an exception if the header property is parsed
  9906. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9907. test_raw_request(
  9908. "GET /hi HTTP/1.1\r\n"
  9909. " : "
  9910. " "
  9911. " ");
  9912. }
  9913. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9914. // A certain header line causes an exception if the header property *name* is
  9915. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9916. // greedy matcher and requires backtracking when there are a lot of ":"
  9917. // characters.
  9918. // This occurs with libc++ but not libstdc++.
  9919. test_raw_request(
  9920. "GET /hi HTTP/1.1\r\n"
  9921. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9922. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9923. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9924. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9925. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9926. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9927. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9928. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9929. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9930. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9931. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9932. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9933. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9934. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9935. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9936. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9937. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9938. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9939. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9940. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9941. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9942. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9943. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9944. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9945. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9946. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9947. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9948. "&&&%%%");
  9949. }
  9950. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9951. // Make sure this doesn't crash the server.
  9952. // In a previous version of the header line regex, the "\r" rendered the line
  9953. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9954. // a new position where the leading white space ended and the field value
  9955. // began.
  9956. // The crash occurs with libc++ but not libstdc++.
  9957. test_raw_request("GET /hi HTTP/1.1\r\n"
  9958. "a:" +
  9959. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9960. "\r\n"
  9961. "\r\n");
  9962. }
  9963. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9964. const char *rejected[] = {
  9965. // RFC 9112 §3: one SP between the parts, and nothing else
  9966. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9967. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9968. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9969. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9970. // A request-target has no fragment
  9971. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9972. // An HTTP/1.1 request needs a Host
  9973. "GET /hi HTTP/1.1\r\n\r\n",
  9974. };
  9975. for (auto request : rejected) {
  9976. std::string out;
  9977. test_raw_request(request, &out);
  9978. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9979. }
  9980. std::string out;
  9981. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9982. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9983. }
  9984. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9985. // RFC 9112 §6.1
  9986. const char *requests[] = {
  9987. "PUT /put_hi HTTP/1.1\r\n"
  9988. "Host: localhost\r\n"
  9989. "Content-Length: 0\r\n"
  9990. "Transfer-Encoding: chunked\r\n"
  9991. "\r\n"
  9992. "0\r\n\r\n",
  9993. "PUT /put_hi HTTP/1.0\r\n"
  9994. "Connection: keep-alive\r\n"
  9995. "Transfer-Encoding: chunked\r\n"
  9996. "\r\n"
  9997. "0\r\n\r\n",
  9998. };
  9999. for (auto request : requests) {
  10000. std::string out;
  10001. test_raw_request(request, &out);
  10002. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10003. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10004. }
  10005. }
  10006. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10007. std::string out;
  10008. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10009. "Content-Type: text/plain\r\n"
  10010. "Transfer-Encoding: chunked\r\n"
  10011. "\r\n"
  10012. "nothex\r\n",
  10013. &out);
  10014. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10015. }
  10016. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10017. std::string out;
  10018. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10019. "Content-Type: text/plain\r\n"
  10020. "Transfer-Encoding: chunked\r\n"
  10021. "\r\n"
  10022. "3\r\n"
  10023. "xyz\r\n"
  10024. "NaN\r\n",
  10025. &out);
  10026. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10027. }
  10028. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10029. std::string out;
  10030. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10031. "Content-Type: text/plain\r\n"
  10032. "Transfer-Encoding: chunked\r\n"
  10033. "\r\n"
  10034. // Length is too large for 64 bits.
  10035. "1ffffffffffffffff\r\n"
  10036. "xyz\r\n",
  10037. &out);
  10038. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10039. }
  10040. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10041. test_raw_request("GET /hi HTTP/1.1\r\n"
  10042. "Content-Type: text/plain\r\n\r");
  10043. }
  10044. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10045. std::string out;
  10046. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10047. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10048. }
  10049. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10050. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10051. std::string out;
  10052. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10053. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10054. }
  10055. }
  10056. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10057. std::string out;
  10058. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10059. "Host: localhost\r\n"
  10060. "Connection: close\r\n\r\n",
  10061. &out);
  10062. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10063. }
  10064. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10065. Server svr;
  10066. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10067. EXPECT_TRUE(!req.remote_addr.empty());
  10068. });
  10069. thread t = thread([&] { svr.listen(HOST, PORT); });
  10070. auto se = detail::scope_exit([&] {
  10071. svr.stop();
  10072. t.join();
  10073. ASSERT_FALSE(svr.is_running());
  10074. });
  10075. svr.wait_until_ready();
  10076. // Send an invalid request line to trigger Bad Request
  10077. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10078. std::string out;
  10079. ASSERT_TRUE(send_request(5, bad_req, &out));
  10080. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10081. }
  10082. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10083. // answered right away rather than blocking on a read that waits for EOF.
  10084. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10085. std::string out;
  10086. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10087. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10088. }
  10089. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10090. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10091. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10092. for (const auto *method : methods) {
  10093. Server svr;
  10094. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10095. EXPECT_FALSE(svr.is_valid()) << method;
  10096. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10097. }
  10098. }
  10099. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10100. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10101. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10102. for (const auto *method : methods) {
  10103. Server svr;
  10104. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10105. EXPECT_FALSE(svr.is_valid()) << method;
  10106. }
  10107. }
  10108. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10109. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10110. "COPY", "MOVE", "LOCK",
  10111. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10112. Server svr;
  10113. for (const auto *method : methods) {
  10114. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10115. }
  10116. EXPECT_TRUE(svr.is_valid());
  10117. }
  10118. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10119. Server svr;
  10120. svr.CustomRoute("POST", "/x",
  10121. [](const Request &, Response &, const ContentReader &) {});
  10122. EXPECT_FALSE(svr.is_valid());
  10123. }
  10124. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10125. Server svr;
  10126. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10127. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10128. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10129. EXPECT_FALSE(svr.is_valid());
  10130. }
  10131. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10132. Server svr;
  10133. auto captured = Error::Success;
  10134. svr.set_error_logger(
  10135. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10136. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10137. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10138. }
  10139. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10140. std::string out;
  10141. std::string request(
  10142. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10143. test_raw_request(request, &out);
  10144. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10145. }
  10146. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10147. std::string out;
  10148. std::string request(
  10149. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10150. test_raw_request(request, &out);
  10151. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10152. }
  10153. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10154. std::string out;
  10155. std::string request(
  10156. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10157. test_raw_request(request, &out);
  10158. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10159. }
  10160. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10161. std::string out;
  10162. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10163. "Host: localhost\r\n"
  10164. "Test: \r\n\r\n",
  10165. &out);
  10166. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10167. }
  10168. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10169. Server svr;
  10170. std::string x_custom;
  10171. std::string cookie;
  10172. std::string xff;
  10173. std::string x_unicode;
  10174. std::string x_iis;
  10175. svr.Get("/check", [&](const Request &req, Response &res) {
  10176. x_custom = req.get_header_value("X-Custom");
  10177. cookie = req.get_header_value("Cookie");
  10178. xff = req.get_header_value("X-Forwarded-For");
  10179. x_unicode = req.get_header_value("X-Unicode");
  10180. x_iis = req.get_header_value("X-IIS");
  10181. res.set_content("ok", "text/plain");
  10182. });
  10183. thread t = thread([&] { svr.listen(HOST, PORT); });
  10184. auto se = detail::scope_exit([&] {
  10185. svr.stop();
  10186. t.join();
  10187. ASSERT_FALSE(svr.is_running());
  10188. });
  10189. svr.wait_until_ready();
  10190. const std::string req = "GET /check HTTP/1.1\r\n"
  10191. "Host: localhost\r\n"
  10192. "X-Custom: a%0D%0AInjected: b\r\n"
  10193. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10194. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10195. "X-Unicode: %E3%81%82\r\n"
  10196. "X-IIS: %u00E9\r\n"
  10197. "Connection: close\r\n"
  10198. "\r\n";
  10199. std::string res;
  10200. ASSERT_TRUE(send_request(5, req, &res));
  10201. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10202. // Every value must be returned verbatim (wire form), with no decoding.
  10203. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10204. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10205. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10206. EXPECT_EQ("%E3%81%82", x_unicode);
  10207. EXPECT_EQ("%u00E9", x_iis);
  10208. }
  10209. // Applications that previously relied on automatic percent-decoding can
  10210. // reproduce the old behavior by explicitly calling decode_path_component()
  10211. // or, for RFC 3986 conformance, decode_uri_component().
  10212. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10213. Server svr;
  10214. std::string decoded;
  10215. svr.Get("/check", [&](const Request &req, Response &res) {
  10216. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10217. res.set_content("ok", "text/plain");
  10218. });
  10219. thread t = thread([&] { svr.listen(HOST, PORT); });
  10220. auto se = detail::scope_exit([&] {
  10221. svr.stop();
  10222. t.join();
  10223. ASSERT_FALSE(svr.is_running());
  10224. });
  10225. svr.wait_until_ready();
  10226. const std::string req = "GET /check HTTP/1.1\r\n"
  10227. "Host: localhost\r\n"
  10228. "X-Custom: hello%20world\r\n"
  10229. "Connection: close\r\n"
  10230. "\r\n";
  10231. std::string res;
  10232. ASSERT_TRUE(send_request(5, req, &res));
  10233. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10234. EXPECT_EQ("hello world", decoded);
  10235. }
  10236. // Regression test for #2033. Browsers send Referer values that include
  10237. // percent-encoded characters such as %0A inside the URL. Decoding the
  10238. // header value would either trip the post-decode CR/LF/NUL guard (the
  10239. // original bug, returning 400) or, after that guard was relaxed, silently
  10240. // store a literal LF — both unacceptable. The wire form must round-trip.
  10241. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10242. Server svr;
  10243. std::string referer;
  10244. svr.Get("/check", [&](const Request &req, Response &res) {
  10245. referer = req.get_header_value("Referer");
  10246. res.set_content("ok", "text/plain");
  10247. });
  10248. thread t = thread([&] { svr.listen(HOST, PORT); });
  10249. auto se = detail::scope_exit([&] {
  10250. svr.stop();
  10251. t.join();
  10252. ASSERT_FALSE(svr.is_running());
  10253. });
  10254. svr.wait_until_ready();
  10255. const std::string req = "GET /check HTTP/1.1\r\n"
  10256. "Host: localhost\r\n"
  10257. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10258. "Connection: close\r\n"
  10259. "\r\n";
  10260. std::string res;
  10261. ASSERT_TRUE(send_request(5, req, &res));
  10262. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10263. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10264. }
  10265. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10266. Server svr;
  10267. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10268. res.set_header("Cache-Control", "no-cache");
  10269. res.set_chunked_content_provider(
  10270. "text/event-stream", [](size_t offset, DataSink &sink) {
  10271. std::string s = "data:";
  10272. s += std::to_string(offset);
  10273. s += "\n\n";
  10274. auto ret = sink.write(s.data(), s.size());
  10275. EXPECT_TRUE(ret);
  10276. std::this_thread::sleep_for(std::chrono::seconds(1));
  10277. return true;
  10278. });
  10279. });
  10280. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10281. svr.wait_until_ready();
  10282. Client client(HOST, PORT);
  10283. const Headers headers = {{"Accept", "text/event-stream"}};
  10284. auto get_thread = std::thread([&client, &headers]() {
  10285. auto res = client.Get(
  10286. "/events", headers,
  10287. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10288. });
  10289. auto se = detail::scope_exit([&] {
  10290. svr.stop();
  10291. get_thread.join();
  10292. listen_thread.join();
  10293. ASSERT_FALSE(svr.is_running());
  10294. });
  10295. // Give GET time to get a few messages.
  10296. std::this_thread::sleep_for(std::chrono::seconds(2));
  10297. }
  10298. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10299. httplib::Server svr;
  10300. svr.Post("/hi",
  10301. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10302. res.status = StatusCode::OK_200;
  10303. });
  10304. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10305. svr.wait_until_ready();
  10306. Client cli(HOST, PORT);
  10307. auto res = cli.Post("/hi", "data", "text/plain");
  10308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10309. EXPECT_EQ(StatusCode::OK_200, res->status);
  10310. svr.stop();
  10311. thread.join();
  10312. ASSERT_FALSE(svr.is_running());
  10313. res = cli.Post("/hi", "data", "text/plain");
  10314. ASSERT_FALSE(res);
  10315. }
  10316. TEST(ServerStopTest, ListenFailure) {
  10317. Server svr;
  10318. auto t = thread([&]() {
  10319. auto ret = svr.listen("????", PORT);
  10320. EXPECT_FALSE(ret);
  10321. });
  10322. svr.wait_until_ready();
  10323. svr.stop();
  10324. t.join();
  10325. }
  10326. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10327. TEST(ServerStopTest, Decommision) {
  10328. Server svr;
  10329. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10330. for (int i = 0; i < 4; i++) {
  10331. auto is_even = !(i % 2);
  10332. std::thread t{[&] {
  10333. try {
  10334. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10335. if (is_even) {
  10336. throw std::runtime_error("Some thing that happens to go wrong.");
  10337. }
  10338. svr.listen(HOST, PORT);
  10339. } catch (...) { svr.decommission(); }
  10340. }};
  10341. svr.wait_until_ready();
  10342. // Server is up
  10343. {
  10344. Client cli(HOST, PORT);
  10345. auto res = cli.Get("/hi");
  10346. if (is_even) {
  10347. EXPECT_FALSE(res);
  10348. } else {
  10349. EXPECT_TRUE(res);
  10350. EXPECT_EQ("hi...", res->body);
  10351. }
  10352. }
  10353. svr.stop();
  10354. t.join();
  10355. // Server is down...
  10356. {
  10357. Client cli(HOST, PORT);
  10358. auto res = cli.Get("/hi");
  10359. EXPECT_FALSE(res);
  10360. }
  10361. }
  10362. }
  10363. #endif
  10364. // Helper function for string body upload progress tests
  10365. template <typename SetupHandler, typename ClientCall>
  10366. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10367. ClientCall &&client_call,
  10368. const string &body) {
  10369. Server svr;
  10370. setup_handler(svr);
  10371. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10372. auto se = detail::scope_exit([&] {
  10373. svr.stop();
  10374. t.join();
  10375. });
  10376. svr.wait_until_ready();
  10377. Client cli(HOST, PORT);
  10378. vector<uint64_t> progress_values;
  10379. bool progress_called = false;
  10380. auto res =
  10381. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10382. progress_values.push_back(current);
  10383. progress_called = true;
  10384. return true;
  10385. });
  10386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10387. EXPECT_EQ(200, res->status);
  10388. EXPECT_TRUE(progress_called);
  10389. }
  10390. TEST(UploadProgressTest, PostStringBodyBasic) {
  10391. TestStringBodyUploadProgress(
  10392. [](Server &svr) {
  10393. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10394. res.set_content("received", "text/plain");
  10395. });
  10396. },
  10397. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10398. return cli.Post("/test", body, "text/plain", progress_callback);
  10399. },
  10400. "test data for upload progress");
  10401. }
  10402. TEST(UploadProgressTest, PutStringBodyBasic) {
  10403. TestStringBodyUploadProgress(
  10404. [](Server &svr) {
  10405. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10406. res.set_content("put received", "text/plain");
  10407. });
  10408. },
  10409. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10410. return cli.Put("/test", body, "text/plain", progress_callback);
  10411. },
  10412. "put test data for upload progress");
  10413. }
  10414. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10415. TestStringBodyUploadProgress(
  10416. [](Server &svr) {
  10417. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10418. res.set_content("patch received", "text/plain");
  10419. });
  10420. },
  10421. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10422. return cli.Patch("/test", body, "text/plain", progress_callback);
  10423. },
  10424. "patch test data for upload progress");
  10425. }
  10426. // Helper function for content provider upload progress tests
  10427. template <typename SetupHandler, typename ClientCall>
  10428. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10429. ClientCall &&client_call) {
  10430. Server svr;
  10431. setup_handler(svr);
  10432. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10433. auto se = detail::scope_exit([&] {
  10434. svr.stop();
  10435. t.join();
  10436. });
  10437. svr.wait_until_ready();
  10438. Client cli(HOST, PORT);
  10439. vector<uint64_t> progress_values;
  10440. auto res =
  10441. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10442. progress_values.push_back(current);
  10443. return true;
  10444. });
  10445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10446. EXPECT_EQ(200, res->status);
  10447. EXPECT_FALSE(progress_values.empty());
  10448. }
  10449. TEST(UploadProgressTest, PostContentProviderProgress) {
  10450. TestContentProviderUploadProgress(
  10451. [](Server &svr) {
  10452. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10453. res.set_content("provider received", "text/plain");
  10454. });
  10455. },
  10456. [](Client &cli, UploadProgress progress_callback) {
  10457. return cli.Post(
  10458. "/test", 9,
  10459. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10460. sink.os << "test data";
  10461. return true;
  10462. },
  10463. "text/plain", progress_callback);
  10464. });
  10465. }
  10466. // Helper function for multipart upload progress tests
  10467. template <typename SetupHandler, typename ClientCall>
  10468. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10469. ClientCall &&client_call,
  10470. const string &endpoint) {
  10471. Server svr;
  10472. setup_handler(svr);
  10473. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10474. auto se = detail::scope_exit([&] {
  10475. svr.stop();
  10476. t.join();
  10477. });
  10478. svr.wait_until_ready();
  10479. Client cli(HOST, PORT);
  10480. vector<uint64_t> progress_values;
  10481. UploadFormDataItems items = {
  10482. {"field1", "value1", "", ""},
  10483. {"field2", "longer value for progress tracking test", "", ""},
  10484. {"file1", "file content data for upload progress", "test.txt",
  10485. "text/plain"}};
  10486. auto res = client_call(cli, endpoint, items,
  10487. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10488. progress_values.push_back(current);
  10489. return true;
  10490. });
  10491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10492. EXPECT_EQ(200, res->status);
  10493. EXPECT_FALSE(progress_values.empty());
  10494. }
  10495. TEST(UploadProgressTest, PostMultipartProgress) {
  10496. TestMultipartUploadProgress(
  10497. [](Server &svr) {
  10498. svr.Post("/multipart", [](const Request &req, Response &res) {
  10499. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10500. res.set_content("multipart received", "text/plain");
  10501. });
  10502. },
  10503. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10504. UploadProgress progress_callback) {
  10505. return cli.Post(endpoint, items, progress_callback);
  10506. },
  10507. "/multipart");
  10508. }
  10509. // Helper function for basic download progress tests
  10510. template <typename SetupHandler, typename ClientCall>
  10511. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10512. ClientCall &&client_call, const string &endpoint,
  10513. size_t expected_content_size) {
  10514. Server svr;
  10515. setup_handler(svr);
  10516. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10517. auto se = detail::scope_exit([&] {
  10518. svr.stop();
  10519. t.join();
  10520. });
  10521. svr.wait_until_ready();
  10522. Client cli(HOST, PORT);
  10523. vector<uint64_t> progress_values;
  10524. auto res = client_call(cli, endpoint,
  10525. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10526. progress_values.push_back(current);
  10527. return true;
  10528. });
  10529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10530. EXPECT_EQ(200, res->status);
  10531. EXPECT_FALSE(progress_values.empty());
  10532. EXPECT_EQ(expected_content_size, res->body.size());
  10533. }
  10534. TEST(DownloadProgressTest, GetBasic) {
  10535. TestBasicDownloadProgress(
  10536. [](Server &svr) {
  10537. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10538. string content(1000, 'D');
  10539. res.set_content(content, "text/plain");
  10540. });
  10541. },
  10542. [](Client &cli, const string &endpoint,
  10543. DownloadProgress progress_callback) {
  10544. return cli.Get(endpoint, progress_callback);
  10545. },
  10546. "/download", 1000u);
  10547. }
  10548. // Helper function for content receiver download progress tests
  10549. template <typename SetupHandler, typename ClientCall>
  10550. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10551. ClientCall &&client_call,
  10552. const string &endpoint,
  10553. size_t expected_content_size) {
  10554. Server svr;
  10555. setup_handler(svr);
  10556. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10557. auto se = detail::scope_exit([&] {
  10558. svr.stop();
  10559. t.join();
  10560. });
  10561. svr.wait_until_ready();
  10562. Client cli(HOST, PORT);
  10563. vector<uint64_t> progress_values;
  10564. string received_body;
  10565. auto res = client_call(
  10566. cli, endpoint,
  10567. [&](const char *data, size_t data_length) -> bool {
  10568. received_body.append(data, data_length);
  10569. return true;
  10570. },
  10571. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10572. progress_values.push_back(current);
  10573. return true;
  10574. });
  10575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10576. EXPECT_EQ(200, res->status);
  10577. EXPECT_FALSE(progress_values.empty());
  10578. EXPECT_EQ(expected_content_size, received_body.size());
  10579. EXPECT_TRUE(res->body.empty());
  10580. }
  10581. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10582. TestContentReceiverDownloadProgress(
  10583. [](Server &svr) {
  10584. svr.Get("/download-receiver",
  10585. [](const Request & /*req*/, Response &res) {
  10586. string content(2000, 'R');
  10587. res.set_content(content, "text/plain");
  10588. });
  10589. },
  10590. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10591. DownloadProgress progress_callback) {
  10592. return cli.Get(endpoint, content_receiver, progress_callback);
  10593. },
  10594. "/download-receiver", 2000u);
  10595. }
  10596. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10597. // A provider reaching a pass with nothing to hand over - an empty buffer
  10598. // popped off a queue, say - must not be taken to mean the body is finished.
  10599. // It used to end the loop with the terminating chunk unwritten while the
  10600. // server still considered the response complete, so the peer waited for an
  10601. // end that never arrived.
  10602. Server svr;
  10603. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10604. auto step = std::make_shared<int>(0);
  10605. res.set_chunked_content_provider("text/plain",
  10606. [step](size_t /*offset*/, DataSink &sink) {
  10607. switch ((*step)++) {
  10608. case 0: sink.write("", 0); break;
  10609. case 1: sink.write("hello", 5); break;
  10610. default: sink.done(); break;
  10611. }
  10612. return true;
  10613. });
  10614. });
  10615. auto port = svr.bind_to_any_port(HOST);
  10616. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10617. auto listen_se = detail::scope_exit([&] {
  10618. svr.stop();
  10619. listen_thread.join();
  10620. ASSERT_FALSE(svr.is_running());
  10621. });
  10622. svr.wait_until_ready();
  10623. Client cli(HOST, port);
  10624. // Without the fix the body is never terminated, so bound the wait rather
  10625. // than letting the test hang on the default read timeout.
  10626. cli.set_read_timeout(5, 0);
  10627. auto res = cli.Get("/stream");
  10628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10629. EXPECT_EQ(StatusCode::OK_200, res->status);
  10630. EXPECT_EQ("hello", res->body);
  10631. }
  10632. TEST(StreamingTest, NoContentLengthStreaming) {
  10633. Server svr;
  10634. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10635. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10636. if (offset < 6) {
  10637. sink.os << (offset < 3 ? "a" : "b");
  10638. } else {
  10639. sink.done();
  10640. }
  10641. return true;
  10642. });
  10643. });
  10644. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10645. auto listen_se = detail::scope_exit([&] {
  10646. svr.stop();
  10647. listen_thread.join();
  10648. ASSERT_FALSE(svr.is_running());
  10649. });
  10650. svr.wait_until_ready();
  10651. Client client(HOST, PORT);
  10652. auto get_thread = std::thread([&client]() {
  10653. std::string s;
  10654. auto res =
  10655. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10656. s += std::string(data, len);
  10657. return true;
  10658. });
  10659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10660. EXPECT_EQ(StatusCode::OK_200, res->status);
  10661. EXPECT_EQ("aaabbb", s);
  10662. });
  10663. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10664. // Give GET time to get a few messages.
  10665. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10666. }
  10667. TEST(MountTest, Unmount) {
  10668. Server svr;
  10669. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10670. auto se = detail::scope_exit([&] {
  10671. svr.stop();
  10672. listen_thread.join();
  10673. ASSERT_FALSE(svr.is_running());
  10674. });
  10675. svr.wait_until_ready();
  10676. Client cli("localhost", PORT);
  10677. svr.set_mount_point("/mount2", "./www2");
  10678. auto res = cli.Get("/");
  10679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10680. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10681. res = cli.Get("/mount2/dir/test.html");
  10682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10683. EXPECT_EQ(StatusCode::OK_200, res->status);
  10684. svr.set_mount_point("/", "./www");
  10685. res = cli.Get("/dir/");
  10686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10687. EXPECT_EQ(StatusCode::OK_200, res->status);
  10688. svr.remove_mount_point("/");
  10689. res = cli.Get("/dir/");
  10690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10691. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10692. svr.remove_mount_point("/mount2");
  10693. res = cli.Get("/mount2/dir/test.html");
  10694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10696. }
  10697. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10698. Server svr;
  10699. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10700. svr.Get("/api/hello", [](const Request &, Response &res) {
  10701. res.set_content("api", "text/plain");
  10702. });
  10703. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10704. auto se = detail::scope_exit([&] {
  10705. svr.stop();
  10706. listen_thread.join();
  10707. ASSERT_FALSE(svr.is_running());
  10708. });
  10709. svr.wait_until_ready();
  10710. Client cli(HOST, PORT);
  10711. auto res = cli.Get("/dir/test.html");
  10712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10713. EXPECT_EQ(StatusCode::OK_200, res->status);
  10714. res = cli.Get("/api/hello");
  10715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10716. EXPECT_EQ(StatusCode::OK_200, res->status);
  10717. EXPECT_EQ("api", res->body);
  10718. }
  10719. TEST(MountTest, PathSegmentBoundary) {
  10720. Server svr;
  10721. svr.set_mount_point("/mount2", "./www2");
  10722. svr.set_mount_point("/", "./www");
  10723. auto port = svr.bind_to_any_port(HOST);
  10724. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10725. auto se = detail::scope_exit([&] {
  10726. svr.stop();
  10727. listen_thread.join();
  10728. ASSERT_FALSE(svr.is_running());
  10729. });
  10730. svr.wait_until_ready();
  10731. Client cli(HOST, port);
  10732. auto res = cli.Get("/mount2/dir/test.html");
  10733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10734. EXPECT_EQ(StatusCode::OK_200, res->status);
  10735. // "/mount2" must not match part-way through a path segment.
  10736. res = cli.Get("/mount2dir/test.html");
  10737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10738. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10739. // A mount point ending in '/' keeps matching every path below it.
  10740. res = cli.Get("/dir/test.html");
  10741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10742. EXPECT_EQ(StatusCode::OK_200, res->status);
  10743. }
  10744. TEST(MountTest, Redicect) {
  10745. Server svr;
  10746. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10747. auto se = detail::scope_exit([&] {
  10748. svr.stop();
  10749. listen_thread.join();
  10750. ASSERT_FALSE(svr.is_running());
  10751. });
  10752. svr.set_mount_point("/", "./www");
  10753. svr.wait_until_ready();
  10754. Client cli("localhost", PORT);
  10755. auto res = cli.Get("/dir/");
  10756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10757. EXPECT_EQ(StatusCode::OK_200, res->status);
  10758. res = cli.Get("/dir");
  10759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10760. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10761. res = cli.Get("/file");
  10762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10763. EXPECT_EQ(StatusCode::OK_200, res->status);
  10764. res = cli.Get("/file/");
  10765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10766. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10767. cli.set_follow_location(true);
  10768. res = cli.Get("/dir");
  10769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10770. EXPECT_EQ(StatusCode::OK_200, res->status);
  10771. }
  10772. TEST(MountTest, MultibytesPathName) {
  10773. Server svr;
  10774. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10775. auto se = detail::scope_exit([&] {
  10776. svr.stop();
  10777. listen_thread.join();
  10778. ASSERT_FALSE(svr.is_running());
  10779. });
  10780. svr.set_mount_point("/", "./www");
  10781. svr.wait_until_ready();
  10782. Client cli("localhost", PORT);
  10783. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10785. EXPECT_EQ(StatusCode::OK_200, res->status);
  10786. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10787. }
  10788. // A mount point serves no path with an empty segment or one ending in '.' or
  10789. // a space, so a guard in the pre-routing handler sees the path of every file
  10790. // that is served
  10791. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10792. Server svr;
  10793. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10794. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10795. if (req.path == "/dir/test.html") {
  10796. res.status = StatusCode::Unauthorized_401;
  10797. return Server::HandlerResponse::Handled;
  10798. }
  10799. return Server::HandlerResponse::Unhandled;
  10800. });
  10801. auto port = svr.bind_to_any_port(HOST);
  10802. ASSERT_LT(0, port);
  10803. thread t = thread([&] { svr.listen_after_bind(); });
  10804. auto se = detail::scope_exit([&] {
  10805. svr.stop();
  10806. t.join();
  10807. ASSERT_FALSE(svr.is_running());
  10808. });
  10809. svr.wait_until_ready();
  10810. Client cli(HOST, port);
  10811. for (auto path :
  10812. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10813. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10814. "/dir/test.html.", "/dir/test.html%20"}) {
  10815. SCOPED_TRACE(path);
  10816. auto res = cli.Get(path);
  10817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10818. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10819. }
  10820. }
  10821. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10822. Server svr;
  10823. svr.set_mount_point("/", "./www");
  10824. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10825. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10826. auto port = svr.bind_to_any_port(HOST);
  10827. ASSERT_GT(port, 0);
  10828. thread t = thread([&] { svr.listen_after_bind(); });
  10829. auto se = detail::scope_exit([&] {
  10830. svr.stop();
  10831. t.join();
  10832. ASSERT_FALSE(svr.is_running());
  10833. });
  10834. svr.wait_until_ready();
  10835. Client cli(HOST, port);
  10836. auto res = cli.Get("/dir/test.abcde");
  10837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10838. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10839. res = cli.Get("/dir/test.html");
  10840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10841. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10842. }
  10843. #ifdef _WIN32
  10844. // Issue #2435: mmap::open() must succeed even when another handle holds
  10845. // the file open for writing (e.g. an active log file).
  10846. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10847. const char *path = "mmap_concurrent_writer_test.txt";
  10848. const char *content = "hello";
  10849. {
  10850. std::ofstream f(path, std::ios::binary);
  10851. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10852. }
  10853. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10854. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10855. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10856. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10857. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10858. detail::mmap m(path);
  10859. ASSERT_TRUE(m.is_open());
  10860. EXPECT_EQ(strlen(content), m.size());
  10861. char buf[8];
  10862. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10863. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10864. }
  10865. #endif
  10866. #ifndef _WIN32
  10867. // A directory or a device has no size to serve.
  10868. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10869. const char *path = "./mmap_not_regular_test_dir";
  10870. ASSERT_EQ(0, ::mkdir(path, 0755));
  10871. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10872. for (auto p : {path, "/dev/null"}) {
  10873. detail::mmap m(p);
  10874. EXPECT_FALSE(m.is_open()) << p;
  10875. EXPECT_EQ(0U, m.size()) << p;
  10876. }
  10877. Server svr;
  10878. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10879. res.set_file_content("/dev/null");
  10880. });
  10881. auto port = svr.bind_to_any_port(HOST);
  10882. thread t = thread([&] { svr.listen_after_bind(); });
  10883. auto se = detail::scope_exit([&] {
  10884. svr.stop();
  10885. t.join();
  10886. });
  10887. svr.wait_until_ready();
  10888. auto res = Client(HOST, port).Get("/null");
  10889. ASSERT_TRUE(res);
  10890. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10891. }
  10892. #endif
  10893. #ifdef __linux__
  10894. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10895. TEST(MmapTest, FileIsNotMapped) {
  10896. const char *path = "mmap_not_mapped_test.txt";
  10897. {
  10898. std::ofstream f(path, std::ios::binary);
  10899. f << "hello";
  10900. }
  10901. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10902. detail::mmap m(path);
  10903. ASSERT_TRUE(m.is_open());
  10904. std::ifstream maps("/proc/self/maps");
  10905. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10906. std::istreambuf_iterator<char>());
  10907. EXPECT_EQ(std::string::npos, mappings.find(path));
  10908. }
  10909. #endif
  10910. TEST(KeepAliveTest, ReadTimeout) {
  10911. Server svr;
  10912. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10913. std::this_thread::sleep_for(std::chrono::seconds(2));
  10914. res.set_content("a", "text/plain");
  10915. });
  10916. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10917. res.set_content("b", "text/plain");
  10918. });
  10919. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10920. auto se = detail::scope_exit([&] {
  10921. svr.stop();
  10922. listen_thread.join();
  10923. ASSERT_FALSE(svr.is_running());
  10924. });
  10925. svr.wait_until_ready();
  10926. Client cli("localhost", PORT);
  10927. cli.set_keep_alive(true);
  10928. cli.set_read_timeout(std::chrono::seconds(1));
  10929. auto resa = cli.Get("/a");
  10930. ASSERT_FALSE(resa);
  10931. EXPECT_EQ(Error::Read, resa.error());
  10932. auto resb = cli.Get("/b");
  10933. ASSERT_TRUE(resb);
  10934. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10935. EXPECT_EQ("b", resb->body);
  10936. }
  10937. TEST(KeepAliveTest, MaxCount) {
  10938. size_t keep_alive_max_count = 3;
  10939. Server svr;
  10940. svr.set_keep_alive_max_count(keep_alive_max_count);
  10941. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10942. res.set_content("Hello World!", "text/plain");
  10943. });
  10944. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10945. auto se = detail::scope_exit([&] {
  10946. svr.stop();
  10947. listen_thread.join();
  10948. ASSERT_FALSE(svr.is_running());
  10949. });
  10950. svr.wait_until_ready();
  10951. Client cli(HOST, PORT);
  10952. cli.set_keep_alive(true);
  10953. for (size_t i = 0; i < 5; i++) {
  10954. auto result = cli.Get("/hi");
  10955. ASSERT_TRUE(result);
  10956. EXPECT_EQ(StatusCode::OK_200, result->status);
  10957. if (i == keep_alive_max_count - 1) {
  10958. EXPECT_EQ("close", result->get_header_value("Connection"));
  10959. } else {
  10960. EXPECT_FALSE(result->has_header("Connection"));
  10961. }
  10962. }
  10963. }
  10964. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10965. // can pull the next one into the server's buffer. The server must serve it
  10966. // without waiting for the socket to become readable again. The keep-alive
  10967. // timeout outlasts the client's read timeout, so a request left waiting for it
  10968. // shows up as a missing response.
  10969. static void serve_pipelining_routes(Server &svr,
  10970. const std::function<void(int)> &client) {
  10971. svr.set_keep_alive_timeout(5);
  10972. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10973. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10974. });
  10975. svr.Post("/echo", [](const Request &req, Response &res) {
  10976. res.set_content("echo " + req.body, "text/plain");
  10977. });
  10978. auto port = svr.bind_to_any_port(HOST);
  10979. thread t = thread([&] { svr.listen_after_bind(); });
  10980. auto se = detail::scope_exit([&] {
  10981. svr.stop();
  10982. t.join();
  10983. });
  10984. svr.wait_until_ready();
  10985. client(port);
  10986. }
  10987. static std::string
  10988. send_pipelined_requests(const std::vector<std::string> &parts) {
  10989. Server svr;
  10990. std::string res;
  10991. serve_pipelining_routes(svr, [&](int port) {
  10992. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10993. });
  10994. return res;
  10995. }
  10996. static void expect_in_order(const std::string &res,
  10997. const std::vector<std::string> &bodies) {
  10998. size_t pos = 0;
  10999. for (const auto &body : bodies) {
  11000. pos = res.find(body, pos);
  11001. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11002. pos += body.size();
  11003. }
  11004. }
  11005. TEST(KeepAliveTest, PipelinedRequests) {
  11006. auto res = send_pipelined_requests(
  11007. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11008. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11009. "Content-Length: 4\r\n\r\nbody"
  11010. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11011. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11012. }
  11013. // The second request starts in the server's buffer and ends on the socket.
  11014. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11015. auto res =
  11016. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11017. "GET /hi/2 HTTP/1.1\r\nHo",
  11018. "st: localhost\r\nConnection: close\r\n\r\n"});
  11019. expect_in_order(res, {"hi 1", "hi 2"});
  11020. }
  11021. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11022. // CRLF after a body does not turn into a 400 for the next request.
  11023. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11024. auto res = send_pipelined_requests(
  11025. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11026. "Content-Length: 4\r\n\r\nbody\r\n"
  11027. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11028. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11029. expect_in_order(res, {"echo body", "hi 2"});
  11030. }
  11031. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11032. // must not be served as the next request.
  11033. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11034. auto res = send_pipelined_requests(
  11035. {"INVALID REQUEST LINE\r\n\r\n"
  11036. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11037. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11038. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11039. }
  11040. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11041. // Over TLS, the next request is held by the TLS library as already decrypted
  11042. // data rather than on the socket.
  11043. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11045. std::string res;
  11046. serve_pipelining_routes(svr, [&](int port) {
  11047. // One part, so all three requests arrive in one TLS record
  11048. EXPECT_TRUE(send_ssl_request_in_parts(
  11049. 2,
  11050. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11051. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11052. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11053. &res, port));
  11054. });
  11055. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11056. }
  11057. #endif
  11058. TEST(KeepAliveTest, Issue1041) {
  11059. Server svr;
  11060. svr.set_keep_alive_timeout(3);
  11061. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11062. res.set_content("Hello World!", "text/plain");
  11063. });
  11064. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11065. auto se = detail::scope_exit([&] {
  11066. svr.stop();
  11067. listen_thread.join();
  11068. ASSERT_FALSE(svr.is_running());
  11069. });
  11070. svr.wait_until_ready();
  11071. Client cli(HOST, PORT);
  11072. cli.set_keep_alive(true);
  11073. auto result = cli.Get("/hi");
  11074. ASSERT_TRUE(result);
  11075. EXPECT_EQ(StatusCode::OK_200, result->status);
  11076. std::this_thread::sleep_for(std::chrono::seconds(5));
  11077. result = cli.Get("/hi");
  11078. ASSERT_TRUE(result);
  11079. EXPECT_EQ(StatusCode::OK_200, result->status);
  11080. }
  11081. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11082. Server svr;
  11083. svr.set_keep_alive_max_count(0);
  11084. std::set<int> remote_ports;
  11085. svr.Get("/hi", [&](const Request &req, Response &res) {
  11086. remote_ports.insert(req.remote_port);
  11087. res.set_content("hi", "text/plain");
  11088. });
  11089. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11090. auto se = detail::scope_exit([&] {
  11091. svr.stop();
  11092. listen_thread.join();
  11093. ASSERT_FALSE(svr.is_running());
  11094. });
  11095. svr.wait_until_ready();
  11096. Client cli(HOST, PORT);
  11097. cli.set_keep_alive(true);
  11098. for (int i = 0; i < 3; i++) {
  11099. auto res = cli.Get("/hi");
  11100. ASSERT_TRUE(res);
  11101. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11102. }
  11103. // All three over one connection
  11104. EXPECT_EQ(1u, remote_ports.size());
  11105. }
  11106. TEST(KeepAliveTest, Issue1959) {
  11107. Server svr;
  11108. svr.set_keep_alive_timeout(5);
  11109. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11110. res.set_content("a", "text/plain");
  11111. });
  11112. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11113. auto se = detail::scope_exit([&] {
  11114. if (!svr.is_running()) return;
  11115. svr.stop();
  11116. listen_thread.join();
  11117. ASSERT_FALSE(svr.is_running());
  11118. });
  11119. svr.wait_until_ready();
  11120. Client cli("localhost", PORT);
  11121. cli.set_keep_alive(true);
  11122. using namespace std::chrono;
  11123. auto start = steady_clock::now();
  11124. cli.Get("/a");
  11125. svr.stop();
  11126. listen_thread.join();
  11127. auto end = steady_clock::now();
  11128. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11129. EXPECT_LT(elapsed, 5000);
  11130. }
  11131. #ifdef CPPHTTPLIB_SSL_ENABLED
  11132. TEST(KeepAliveTest, SSLClientReconnection) {
  11133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11134. ASSERT_TRUE(svr.is_valid());
  11135. svr.set_keep_alive_timeout(1);
  11136. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11137. res.set_content("Hello World!", "text/plain");
  11138. });
  11139. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11140. auto se = detail::scope_exit([&] {
  11141. svr.stop();
  11142. listen_thread.join();
  11143. ASSERT_FALSE(svr.is_running());
  11144. });
  11145. svr.wait_until_ready();
  11146. SSLClient cli(HOST, PORT);
  11147. cli.enable_server_certificate_verification(false);
  11148. cli.set_keep_alive(true);
  11149. auto result = cli.Get("/hi");
  11150. ASSERT_TRUE(result);
  11151. EXPECT_EQ(StatusCode::OK_200, result->status);
  11152. result = cli.Get("/hi");
  11153. ASSERT_TRUE(result);
  11154. EXPECT_EQ(StatusCode::OK_200, result->status);
  11155. std::this_thread::sleep_for(std::chrono::seconds(2));
  11156. // Recoonect
  11157. result = cli.Get("/hi");
  11158. ASSERT_TRUE(result);
  11159. EXPECT_EQ(StatusCode::OK_200, result->status);
  11160. result = cli.Get("/hi");
  11161. ASSERT_TRUE(result);
  11162. EXPECT_EQ(StatusCode::OK_200, result->status);
  11163. }
  11164. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11165. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11166. ASSERT_TRUE(svr.is_valid());
  11167. svr.set_keep_alive_timeout(1);
  11168. std::string content = "reconnect";
  11169. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11170. res.set_content("Hello World!", "text/plain");
  11171. });
  11172. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11173. auto se = detail::scope_exit([&] {
  11174. svr.stop();
  11175. listen_thread.join();
  11176. ASSERT_FALSE(svr.is_running());
  11177. });
  11178. svr.wait_until_ready();
  11179. SSLClient cli(HOST, PORT);
  11180. cli.enable_server_certificate_verification(false);
  11181. cli.set_keep_alive(true);
  11182. auto result = cli.Post(
  11183. "/hi", content.size(),
  11184. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11185. sink.write(content.c_str(), content.size());
  11186. return true;
  11187. },
  11188. "text/plain");
  11189. ASSERT_TRUE(result);
  11190. EXPECT_EQ(200, result->status);
  11191. std::this_thread::sleep_for(std::chrono::seconds(2));
  11192. // Recoonect
  11193. result = cli.Post(
  11194. "/hi", content.size(),
  11195. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11196. sink.write(content.c_str(), content.size());
  11197. return true;
  11198. },
  11199. "text/plain");
  11200. ASSERT_TRUE(result);
  11201. EXPECT_EQ(200, result->status);
  11202. result = cli.Post(
  11203. "/hi", content.size(),
  11204. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11205. sink.write(content.c_str(), content.size());
  11206. return true;
  11207. },
  11208. "text/plain");
  11209. ASSERT_TRUE(result);
  11210. EXPECT_EQ(200, result->status);
  11211. }
  11212. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11213. using namespace httplib::tls;
  11214. {
  11215. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11216. ASSERT_TRUE(svr.is_valid());
  11217. svr.Get("/sni", [&](const Request &req, Response &res) {
  11218. std::string expected = req.sni();
  11219. EXPECT_EQ(expected, req.get_param_value("expected"));
  11220. res.set_content("ok", "text/plain");
  11221. });
  11222. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11223. auto se = detail::scope_exit([&] {
  11224. svr.stop();
  11225. listen_thread.join();
  11226. ASSERT_FALSE(svr.is_running());
  11227. });
  11228. svr.wait_until_ready();
  11229. {
  11230. SSLClient cli("localhost", PORT);
  11231. cli.enable_server_certificate_verification(false);
  11232. auto res = cli.Get("/sni?expected=localhost");
  11233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11234. }
  11235. {
  11236. SSLClient cli("::1", PORT);
  11237. cli.enable_server_certificate_verification(false);
  11238. auto res = cli.Get("/sni?expected=");
  11239. // NOTE: This may fail if the server is listening on IPv4 only
  11240. // (e.g., when localhost resolves to 127.0.0.1 only)
  11241. if (res) {
  11242. EXPECT_EQ(StatusCode::OK_200, res->status);
  11243. } else {
  11244. EXPECT_EQ(Error::Connection, res.error());
  11245. }
  11246. }
  11247. }
  11248. }
  11249. // The SNI of a failed handshake does not reach the next connection that the
  11250. // same worker thread serves
  11251. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11252. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11253. ASSERT_TRUE(svr.is_valid());
  11254. svr.new_task_queue = [] { return new ThreadPool(1); };
  11255. svr.Get("/sni", [](const Request &req, Response &res) {
  11256. res.set_content(req.sni(), "text/plain");
  11257. });
  11258. auto port = svr.bind_to_any_port("127.0.0.1");
  11259. ASSERT_LT(0, port);
  11260. thread t = thread([&] { svr.listen_after_bind(); });
  11261. auto se = detail::scope_exit([&] {
  11262. svr.stop();
  11263. t.join();
  11264. ASSERT_FALSE(svr.is_running());
  11265. });
  11266. svr.wait_until_ready();
  11267. {
  11268. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11269. SSLClient cli("localhost", port);
  11270. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11271. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11272. auto res = cli.Get("/sni");
  11273. ASSERT_FALSE(res);
  11274. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11275. }
  11276. // An IP host sends no SNI (RFC 6066)
  11277. SSLClient cli("127.0.0.1", port);
  11278. cli.enable_server_certificate_verification(false);
  11279. auto res = cli.Get("/sni");
  11280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11281. EXPECT_EQ("", res->body);
  11282. }
  11283. #endif
  11284. TEST(ClientProblemDetectionTest, ContentProvider) {
  11285. Server svr;
  11286. size_t content_length = 1024 * 1024;
  11287. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11288. res.set_content_provider(
  11289. content_length, "text/plain",
  11290. [&](size_t offset, size_t length, DataSink &sink) {
  11291. auto out_len = std::min(length, static_cast<size_t>(1024));
  11292. std::string out(out_len, '@');
  11293. sink.write(out.data(), out_len);
  11294. return offset < 4096;
  11295. },
  11296. [](bool success) { ASSERT_FALSE(success); });
  11297. });
  11298. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11299. res.set_content_provider(
  11300. 0, "text/plain",
  11301. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11302. EXPECT_TRUE(false);
  11303. return true;
  11304. },
  11305. [](bool success) { ASSERT_FALSE(success); });
  11306. });
  11307. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11308. auto se = detail::scope_exit([&] {
  11309. svr.stop();
  11310. listen_thread.join();
  11311. ASSERT_FALSE(svr.is_running());
  11312. });
  11313. svr.wait_until_ready();
  11314. Client cli("localhost", PORT);
  11315. {
  11316. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11317. size_t /*data_length*/) { return false; });
  11318. ASSERT_FALSE(res);
  11319. }
  11320. {
  11321. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11322. size_t /*data_length*/) { return false; });
  11323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11324. }
  11325. }
  11326. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11327. // A provider that reports success without writing anything and without
  11328. // calling done() used to be handed the same offset and length again on every
  11329. // pass, so it spun for as long as the peer stayed connected.
  11330. Server svr;
  11331. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11332. res.set_content("ok", "text/plain");
  11333. });
  11334. auto port = svr.bind_to_any_port(HOST);
  11335. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11336. auto se = detail::scope_exit([&] {
  11337. svr.stop();
  11338. listen_thread.join();
  11339. ASSERT_FALSE(svr.is_running());
  11340. });
  11341. svr.wait_until_ready();
  11342. std::atomic<int> call_count{0};
  11343. Client cli(HOST, port);
  11344. auto res = cli.Post(
  11345. "/", 1024,
  11346. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11347. // Give up after enough passes to show the spin, so that losing the
  11348. // check below fails this test instead of hanging it.
  11349. return ++call_count < 100;
  11350. },
  11351. "text/plain");
  11352. ASSERT_FALSE(res);
  11353. EXPECT_EQ(Error::Write, res.error());
  11354. EXPECT_EQ(1, call_count.load());
  11355. }
  11356. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11357. // A writer only has to assign `write`. The other three used to be left as
  11358. // empty std::functions, so a provider calling one threw
  11359. // std::bad_function_call out of the thread running it and took the whole
  11360. // process down.
  11361. DataSink sink;
  11362. std::string written;
  11363. sink.write = [&](const char *data, size_t data_len) {
  11364. written.append(data, data_len);
  11365. return true;
  11366. };
  11367. EXPECT_TRUE(sink.is_writable());
  11368. sink.done();
  11369. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11370. EXPECT_TRUE(written.empty());
  11371. }
  11372. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11373. // A sink that cannot carry trailers still has to finish.
  11374. DataSink sink;
  11375. auto done_count = 0;
  11376. sink.done = [&]() { done_count++; };
  11377. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11378. EXPECT_EQ(1, done_count);
  11379. }
  11380. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11381. Server svr;
  11382. const std::string body(4096, 'x');
  11383. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11384. res.set_content_provider(body.size(), "text/plain",
  11385. [&](size_t offset, size_t length, DataSink &sink) {
  11386. sink.write(body.data() + offset, length);
  11387. sink.done();
  11388. return true;
  11389. });
  11390. });
  11391. auto port = svr.bind_to_any_port(HOST);
  11392. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11393. auto se = detail::scope_exit([&] {
  11394. svr.stop();
  11395. listen_thread.join();
  11396. ASSERT_FALSE(svr.is_running());
  11397. });
  11398. svr.wait_until_ready();
  11399. Client cli(HOST, port);
  11400. auto res = cli.Get("/");
  11401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11402. EXPECT_EQ(StatusCode::OK_200, res->status);
  11403. EXPECT_EQ(body, res->body);
  11404. }
  11405. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11406. Server svr;
  11407. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11408. res.set_content_provider(
  11409. 1024, "text/plain",
  11410. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11411. sink.write("hello", 5);
  11412. sink.done(); // short of the 1024 bytes the response promised
  11413. return true;
  11414. });
  11415. });
  11416. auto port = svr.bind_to_any_port(HOST);
  11417. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11418. auto se = detail::scope_exit([&] {
  11419. svr.stop();
  11420. listen_thread.join();
  11421. ASSERT_FALSE(svr.is_running());
  11422. });
  11423. svr.wait_until_ready();
  11424. Client cli(HOST, port);
  11425. cli.set_read_timeout(5, 0);
  11426. // The response is short of its Content-Length, so the client cannot read a
  11427. // complete body. What matters is that this returns at all: a no-op done()
  11428. // would leave the writer looping over a provider that never makes progress.
  11429. auto res = cli.Get("/");
  11430. EXPECT_FALSE(res);
  11431. }
  11432. // Read as the next response by a peer that sees it after a framed body.
  11433. static const std::string smuggled_response =
  11434. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11435. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11436. Server svr;
  11437. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11438. res.set_content_provider(
  11439. 5, "text/plain",
  11440. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11441. auto data = "AAAAA" + smuggled_response;
  11442. sink.write(data.data(), data.size());
  11443. return true;
  11444. });
  11445. });
  11446. thread t = thread([&] { svr.listen(HOST, PORT); });
  11447. auto se = detail::scope_exit([&] {
  11448. svr.stop();
  11449. t.join();
  11450. ASSERT_FALSE(svr.is_running());
  11451. });
  11452. svr.wait_until_ready();
  11453. std::string resp;
  11454. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11455. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11456. resp.clear();
  11457. ASSERT_TRUE(send_request(
  11458. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11459. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11460. }
  11461. TEST(NoContentTest, BodyIsNotSent) {
  11462. Server svr;
  11463. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11464. res.status = StatusCode::NoContent_204;
  11465. res.set_content(smuggled_response, "text/plain");
  11466. });
  11467. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11468. res.status = StatusCode::NotModified_304;
  11469. res.set_chunked_content_provider(
  11470. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11471. sink.write(smuggled_response.data(), smuggled_response.size());
  11472. sink.done();
  11473. return true;
  11474. });
  11475. });
  11476. thread t = thread([&] { svr.listen(HOST, PORT); });
  11477. auto se = detail::scope_exit([&] {
  11478. svr.stop();
  11479. t.join();
  11480. ASSERT_FALSE(svr.is_running());
  11481. });
  11482. svr.wait_until_ready();
  11483. for (auto path : {"/204", "/304"}) {
  11484. std::string resp;
  11485. ASSERT_TRUE(send_request(
  11486. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11487. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11488. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11489. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11490. }
  11491. }
  11492. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11493. Server svr;
  11494. std::atomic<bool> smuggled(false);
  11495. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11496. res.set_content("ok", "text/plain");
  11497. });
  11498. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11499. smuggled = true;
  11500. });
  11501. auto port = svr.bind_to_any_port(HOST);
  11502. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11503. auto se = detail::scope_exit([&] {
  11504. svr.stop();
  11505. listen_thread.join();
  11506. ASSERT_FALSE(svr.is_running());
  11507. });
  11508. svr.wait_until_ready();
  11509. // What follows the body would be read as the next request.
  11510. Client cli(HOST, port);
  11511. auto res = cli.Post(
  11512. "/", 5,
  11513. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11514. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11515. sink.write(data.data(), data.size());
  11516. return true;
  11517. },
  11518. "text/plain");
  11519. ASSERT_FALSE(res);
  11520. EXPECT_EQ(Error::Write, res.error());
  11521. EXPECT_FALSE(smuggled);
  11522. }
  11523. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11524. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11525. // The compressed path builds the whole body before connecting, so this
  11526. // fails client-side and never reaches a server.
  11527. Client cli(HOST, PORT);
  11528. cli.set_compress(true);
  11529. auto res = cli.Post(
  11530. "/", 1024,
  11531. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11532. sink.write("hello", 5);
  11533. sink.done(); // short of the 1024 bytes the request announced
  11534. return true;
  11535. },
  11536. "text/plain");
  11537. ASSERT_FALSE(res);
  11538. EXPECT_EQ(Error::Write, res.error());
  11539. }
  11540. #endif
  11541. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11542. Server svr;
  11543. svr.set_error_handler([](Request const &, Response &res) -> void {
  11544. res.set_chunked_content_provider(
  11545. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11546. sink.os << "hello";
  11547. sink.os << "world";
  11548. sink.done();
  11549. return true;
  11550. });
  11551. });
  11552. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11553. auto se = detail::scope_exit([&] {
  11554. svr.stop();
  11555. listen_thread.join();
  11556. ASSERT_FALSE(svr.is_running());
  11557. });
  11558. svr.wait_until_ready();
  11559. Client cli("localhost", PORT);
  11560. auto res = cli.Get("/");
  11561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11562. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11563. EXPECT_EQ("helloworld", res->body);
  11564. }
  11565. // A body set after a content provider must replace it, not be sent through it.
  11566. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11567. Server svr;
  11568. svr.set_mount_point("/", "./www");
  11569. svr.set_file_request_handler([](const Request &req, Response &res) {
  11570. if (req.path == "/dir/test.html") {
  11571. res.status = StatusCode::Forbidden_403;
  11572. res.set_content(std::string(5000, 'D'), "text/plain");
  11573. } else if (req.path == "/file") {
  11574. res.status = StatusCode::Forbidden_403;
  11575. res.body = "Denied";
  11576. }
  11577. });
  11578. auto port = svr.bind_to_any_port(HOST);
  11579. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11580. auto se = detail::scope_exit([&] {
  11581. svr.stop();
  11582. t.join();
  11583. ASSERT_FALSE(svr.is_running());
  11584. });
  11585. svr.wait_until_ready();
  11586. Client cli(HOST, port);
  11587. {
  11588. auto res = cli.Get("/dir/test.html");
  11589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11590. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11591. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11592. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11593. }
  11594. {
  11595. auto res = cli.Get("/file");
  11596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11597. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11598. EXPECT_EQ("Denied", res->body);
  11599. }
  11600. {
  11601. auto res = cli.Get("/dir/index.html");
  11602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11603. EXPECT_EQ(StatusCode::OK_200, res->status);
  11604. EXPECT_EQ(0U, res->body.find("<html>"));
  11605. }
  11606. }
  11607. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11608. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11609. Server svr;
  11610. std::vector<bool> released;
  11611. std::mutex released_mutex;
  11612. auto releaser = [&](bool success) {
  11613. std::lock_guard<std::mutex> guard(released_mutex);
  11614. released.push_back(success);
  11615. };
  11616. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11617. return sink.write(&"hello"[offset], length);
  11618. };
  11619. svr.Get("/sized", [&](const Request &, Response &res) {
  11620. res.status = StatusCode::NotFound_404;
  11621. res.set_content_provider(5, "text/plain", provider, releaser);
  11622. });
  11623. svr.Get("/chunked", [&](const Request &, Response &res) {
  11624. res.status = StatusCode::ServiceUnavailable_503;
  11625. res.set_chunked_content_provider(
  11626. "text/plain",
  11627. [](size_t, DataSink &sink) {
  11628. sink.os << "chunk";
  11629. sink.done();
  11630. return true;
  11631. },
  11632. releaser);
  11633. });
  11634. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11635. res.set_content_provider(5, "text/plain", provider, releaser);
  11636. throw std::runtime_error("after the provider");
  11637. });
  11638. svr.set_error_handler([](const Request &req, Response &res) {
  11639. // Leave the exception handler's content to it.
  11640. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11641. res.set_content(std::string(1000, 'E'), "text/html");
  11642. return Server::HandlerResponse::Handled;
  11643. });
  11644. svr.set_exception_handler(
  11645. [](const Request &, Response &res, std::exception_ptr) {
  11646. res.status = StatusCode::InternalServerError_500;
  11647. res.set_content(std::string(1000, 'X'), "text/html");
  11648. });
  11649. auto port = svr.bind_to_any_port(HOST);
  11650. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11651. auto se = detail::scope_exit([&] {
  11652. svr.stop();
  11653. t.join();
  11654. ASSERT_FALSE(svr.is_running());
  11655. });
  11656. svr.wait_until_ready();
  11657. Client cli(HOST, port);
  11658. {
  11659. auto res = cli.Get("/sized");
  11660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11661. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11662. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11663. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11664. }
  11665. {
  11666. auto res = cli.Get("/chunked");
  11667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11668. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11669. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11670. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11671. }
  11672. {
  11673. auto res = cli.Get("/throw");
  11674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11675. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11676. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11677. }
  11678. std::lock_guard<std::mutex> guard(released_mutex);
  11679. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11680. }
  11681. #endif
  11682. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11683. Server svr;
  11684. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11685. return sink.write(&"abc"[offset], length);
  11686. };
  11687. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11688. res.set_file_content("./www/dir/test.html");
  11689. res.set_content("body", "text/plain");
  11690. });
  11691. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11692. res.set_content(std::string(100, 'B'), "text/plain");
  11693. res.set_file_content("./www/dir/test.html");
  11694. });
  11695. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11696. res.set_content(std::string(100, 'B'), "text/plain");
  11697. res.set_content_provider(3, "text/x-provider", abc);
  11698. });
  11699. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11700. res.set_content_provider(3, "text/x-provider", abc);
  11701. res.set_content(std::string(100, 'B'), "text/plain");
  11702. });
  11703. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11704. res.set_content_provider(3, "text/x-provider", abc);
  11705. res.set_file_content("./www/dir/test.html", "text/x-file");
  11706. });
  11707. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11708. res.set_file_content("./www/dir/test.html");
  11709. res.set_header("Content-Type", "text/x-handler");
  11710. });
  11711. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11712. res.set_content_provider(3, "text/plain", abc);
  11713. res.body = "direct";
  11714. });
  11715. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11716. res.set_file_content("./www/dir/test.html");
  11717. res.body = "direct";
  11718. });
  11719. auto port = svr.bind_to_any_port(HOST);
  11720. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11721. auto se = detail::scope_exit([&] {
  11722. svr.stop();
  11723. t.join();
  11724. ASSERT_FALSE(svr.is_running());
  11725. });
  11726. svr.wait_until_ready();
  11727. Client cli(HOST, port);
  11728. auto expect_body = [&](const char *path, const std::string &body,
  11729. const std::string &type) {
  11730. // Uncompressed, so Content-Length can be compared with the body.
  11731. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11732. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11733. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11734. EXPECT_EQ(body, res->body) << path;
  11735. EXPECT_EQ(std::to_string(body.size()),
  11736. res->get_header_value("Content-Length"))
  11737. << path;
  11738. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11739. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11740. };
  11741. expect_body("/file-then-body", "body", "text/plain");
  11742. expect_body("/body-then-file", "test.html", "text/html");
  11743. expect_body("/body-then-provider", "abc", "text/x-provider");
  11744. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11745. expect_body("/provider-then-file", "test.html", "text/x-file");
  11746. expect_body("/file-then-header", "test.html", "text/x-handler");
  11747. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11748. expect_body("/file-then-direct-body", "direct", "text/plain");
  11749. // Ranges are checked against the body, not the dropped provider.
  11750. {
  11751. auto res = cli.Get("/provider-then-direct-body",
  11752. Headers{{make_range_header({{1, 2}})}});
  11753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11754. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11755. EXPECT_EQ("ir", res->body);
  11756. }
  11757. {
  11758. auto res = cli.Get("/file-then-direct-body",
  11759. Headers{{make_range_header({{7, 8}})}});
  11760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11761. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11762. }
  11763. }
  11764. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11765. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11766. const char *path = "./truncated_while_served.txt";
  11767. const size_t size = 32 * 1024 * 1024;
  11768. {
  11769. std::ofstream f(path, std::ios::binary);
  11770. f << std::string(size, 'x');
  11771. }
  11772. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11773. // Over TLS, where the bytes are encrypted in this process rather than
  11774. // copied by send().
  11775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11776. svr.Get("/file", [&](const Request &, Response &res) {
  11777. res.set_file_content(path, "text/plain");
  11778. });
  11779. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11780. auto se = detail::scope_exit([&] {
  11781. svr.stop();
  11782. thread.join();
  11783. ASSERT_FALSE(svr.is_running());
  11784. });
  11785. svr.wait_until_ready();
  11786. // The file shrinks once the first bytes are in, as a rewrite in place
  11787. // would, and reading the mapping past its new end used to raise SIGBUS.
  11788. SSLClient cli(HOST, PORT);
  11789. cli.enable_server_certificate_verification(false);
  11790. size_t received = 0;
  11791. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11792. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11793. received += len;
  11794. return true;
  11795. });
  11796. EXPECT_FALSE(res);
  11797. EXPECT_LT(received, size);
  11798. }
  11799. #endif
  11800. // Forward declaration (see the base64_encode note).
  11801. namespace httplib {
  11802. namespace detail {
  11803. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11804. const std::string &content_type,
  11805. EncodingType encoding);
  11806. } // namespace detail
  11807. } // namespace httplib
  11808. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11809. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11810. ASSERT_TRUE(mm->is_open());
  11811. Response res;
  11812. detail::set_file_content_provider(res, mm, "text/html",
  11813. detail::EncodingType::None);
  11814. std::string out;
  11815. DataSink sink;
  11816. sink.write = [&](const char *d, size_t l) {
  11817. out.append(d, l);
  11818. return true;
  11819. };
  11820. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11821. EXPECT_EQ("test.html", out);
  11822. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11823. EXPECT_EQ("test.html", out);
  11824. }
  11825. TEST(LongPollingTest, ClientCloseDetection) {
  11826. Server svr;
  11827. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11828. res.set_chunked_content_provider(
  11829. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11830. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11831. sink.os << "hello";
  11832. auto count = 10;
  11833. while (count > 0 && sink.is_writable()) {
  11834. this_thread::sleep_for(chrono::milliseconds(10));
  11835. count--;
  11836. }
  11837. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11838. return true;
  11839. });
  11840. });
  11841. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11842. auto se = detail::scope_exit([&] {
  11843. svr.stop();
  11844. listen_thread.join();
  11845. ASSERT_FALSE(svr.is_running());
  11846. });
  11847. svr.wait_until_ready();
  11848. Client cli("localhost", PORT);
  11849. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11850. EXPECT_EQ("hello", string(data, data_length));
  11851. return false; // close the socket immediately.
  11852. });
  11853. ASSERT_FALSE(res);
  11854. }
  11855. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11856. Server svr;
  11857. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11858. res.set_chunked_content_provider(
  11859. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11860. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11861. sink.os << "hello";
  11862. EXPECT_TRUE(sink.os.good());
  11863. // Wait for the client to close the connection
  11864. auto count = 10;
  11865. while (count > 0 && sink.is_writable()) {
  11866. this_thread::sleep_for(chrono::milliseconds(10));
  11867. count--;
  11868. }
  11869. // After client disconnect, write repeatedly until the socket
  11870. // write actually fails (small writes may be absorbed by the
  11871. // kernel buffer)
  11872. std::string chunk(1024, 'x');
  11873. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11874. sink.os << chunk;
  11875. }
  11876. EXPECT_TRUE(sink.os.fail());
  11877. return true;
  11878. });
  11879. });
  11880. auto port = svr.bind_to_any_port("localhost");
  11881. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11882. auto se = detail::scope_exit([&] {
  11883. svr.stop();
  11884. listen_thread.join();
  11885. ASSERT_FALSE(svr.is_running());
  11886. });
  11887. svr.wait_until_ready();
  11888. Client cli("localhost", port);
  11889. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11890. EXPECT_EQ("hello", string(data, data_length));
  11891. return false; // close the socket immediately.
  11892. });
  11893. ASSERT_FALSE(res);
  11894. }
  11895. TEST(GetWithParametersTest, GetWithParameters) {
  11896. Server svr;
  11897. svr.Get("/", [&](const Request &req, Response &) {
  11898. EXPECT_EQ("world", req.get_param_value("hello"));
  11899. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11900. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11901. });
  11902. svr.Get("/params", [&](const Request &req, Response &) {
  11903. EXPECT_EQ("world", req.get_param_value("hello"));
  11904. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11905. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11906. });
  11907. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11908. EXPECT_EQ("resource-id", req.matches[1]);
  11909. EXPECT_EQ("foo", req.get_param_value("param1"));
  11910. EXPECT_EQ("bar", req.get_param_value("param2"));
  11911. });
  11912. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11913. EXPECT_EQ("user-id", req.path_params.at("id"));
  11914. EXPECT_EQ("foo", req.get_param_value("param1"));
  11915. EXPECT_EQ("bar", req.get_param_value("param2"));
  11916. });
  11917. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11918. auto se = detail::scope_exit([&] {
  11919. svr.stop();
  11920. listen_thread.join();
  11921. ASSERT_FALSE(svr.is_running());
  11922. });
  11923. svr.wait_until_ready();
  11924. {
  11925. Client cli(HOST, PORT);
  11926. Params params;
  11927. params.emplace("hello", "world");
  11928. params.emplace("hello2", "world2");
  11929. params.emplace("hello3", "world3");
  11930. auto res = cli.Get("/", params, Headers{});
  11931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11932. EXPECT_EQ(StatusCode::OK_200, res->status);
  11933. }
  11934. {
  11935. Client cli(HOST, PORT);
  11936. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11938. EXPECT_EQ(StatusCode::OK_200, res->status);
  11939. }
  11940. {
  11941. Client cli(HOST, PORT);
  11942. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11944. EXPECT_EQ(StatusCode::OK_200, res->status);
  11945. }
  11946. {
  11947. Client cli(HOST, PORT);
  11948. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11950. EXPECT_EQ(StatusCode::OK_200, res->status);
  11951. }
  11952. }
  11953. TEST(GetWithParametersTest, GetWithParameters2) {
  11954. Server svr;
  11955. svr.Get("/", [&](const Request &req, Response &res) {
  11956. auto text = req.get_param_value("hello");
  11957. res.set_content(text, "text/plain");
  11958. });
  11959. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11960. auto se = detail::scope_exit([&] {
  11961. svr.stop();
  11962. listen_thread.join();
  11963. ASSERT_FALSE(svr.is_running());
  11964. });
  11965. svr.wait_until_ready();
  11966. Client cli("localhost", PORT);
  11967. Params params;
  11968. params.emplace("hello", "world");
  11969. std::string body;
  11970. auto res = cli.Get("/", params, Headers{},
  11971. [&](const char *data, size_t data_length) {
  11972. body.append(data, data_length);
  11973. return true;
  11974. });
  11975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11976. EXPECT_EQ(StatusCode::OK_200, res->status);
  11977. EXPECT_EQ("world", body);
  11978. }
  11979. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11980. Server svr;
  11981. svr.Get("/search", [&](const Request &req, Response &res) {
  11982. auto q = req.get_param_value("q");
  11983. res.set_content(q, "text/plain");
  11984. });
  11985. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11986. auto se = detail::scope_exit([&] {
  11987. svr.stop();
  11988. listen_thread.join();
  11989. ASSERT_FALSE(svr.is_running());
  11990. });
  11991. svr.wait_until_ready();
  11992. Client cli("localhost", PORT);
  11993. // Verify that Get(path, params) works without requiring Headers argument
  11994. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11996. EXPECT_EQ(StatusCode::OK_200, res->status);
  11997. EXPECT_EQ("cpp-httplib", res->body);
  11998. }
  11999. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12000. auto host = "httpbingo.org";
  12001. auto path = std::string{"/range/32"};
  12002. #ifdef CPPHTTPLIB_SSL_ENABLED
  12003. SSLClient cli(host);
  12004. #else
  12005. Client cli(host);
  12006. #endif
  12007. cli.set_default_headers({make_range_header({{1, 10}})});
  12008. cli.set_connection_timeout(5);
  12009. {
  12010. auto res = cli.Get(path);
  12011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12012. EXPECT_EQ("bcdefghijk", res->body);
  12013. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12014. }
  12015. {
  12016. auto res = cli.Get(path);
  12017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12018. EXPECT_EQ("bcdefghijk", res->body);
  12019. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12020. }
  12021. }
  12022. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12023. Server svr;
  12024. svr.set_default_headers({{"Hello", "World"}});
  12025. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12026. res.set_content("ok", "text/plain");
  12027. });
  12028. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12029. auto se = detail::scope_exit([&] {
  12030. svr.stop();
  12031. listen_thread.join();
  12032. ASSERT_FALSE(svr.is_running());
  12033. });
  12034. svr.wait_until_ready();
  12035. Client cli("localhost", PORT);
  12036. auto res = cli.Get("/");
  12037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12038. EXPECT_EQ(StatusCode::OK_200, res->status);
  12039. EXPECT_EQ("ok", res->body);
  12040. EXPECT_EQ("World", res->get_header_value("Hello"));
  12041. }
  12042. #ifdef CPPHTTPLIB_SSL_ENABLED
  12043. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12045. ASSERT_TRUE(svr.is_valid());
  12046. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12047. std::this_thread::sleep_for(std::chrono::seconds(2));
  12048. res.set_content("a", "text/plain");
  12049. });
  12050. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12051. res.set_content("b", "text/plain");
  12052. });
  12053. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12054. auto se = detail::scope_exit([&] {
  12055. svr.stop();
  12056. listen_thread.join();
  12057. ASSERT_FALSE(svr.is_running());
  12058. });
  12059. svr.wait_until_ready();
  12060. SSLClient cli("localhost", PORT);
  12061. cli.enable_server_certificate_verification(false);
  12062. cli.set_keep_alive(true);
  12063. cli.set_read_timeout(std::chrono::seconds(1));
  12064. auto resa = cli.Get("/a");
  12065. ASSERT_TRUE(!resa);
  12066. EXPECT_EQ(Error::Read, resa.error());
  12067. auto resb = cli.Get("/b");
  12068. ASSERT_TRUE(resb);
  12069. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12070. EXPECT_EQ("b", resb->body);
  12071. }
  12072. // Closing an idle keep-alive connection sends close_notify and returns. The
  12073. // server must not wait for the client's close_notify: an idle client never
  12074. // sends one, so the worker would be held until the read timeout expires, and
  12075. // stop() would wait for it.
  12076. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12078. ASSERT_TRUE(svr.is_valid());
  12079. svr.set_keep_alive_timeout(1);
  12080. svr.set_read_timeout(10, 0);
  12081. svr.Get("/", [](const Request &, Response &res) {
  12082. res.set_content("ok", "text/plain");
  12083. });
  12084. auto port = svr.bind_to_any_port(HOST);
  12085. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12086. auto se = detail::scope_exit([&] {
  12087. if (listen_thread.joinable()) {
  12088. svr.stop();
  12089. listen_thread.join();
  12090. }
  12091. });
  12092. svr.wait_until_ready();
  12093. SSLClient cli(HOST, port);
  12094. cli.enable_server_certificate_verification(false);
  12095. cli.set_keep_alive(true);
  12096. auto res = cli.Get("/");
  12097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12098. EXPECT_EQ(StatusCode::OK_200, res->status);
  12099. // Stay idle past the keep-alive timeout so the server closes the connection.
  12100. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12101. auto start = std::chrono::steady_clock::now();
  12102. svr.stop();
  12103. listen_thread.join();
  12104. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12105. std::chrono::steady_clock::now() - start)
  12106. .count();
  12107. EXPECT_LT(elapsed, 3000);
  12108. }
  12109. #endif
  12110. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12111. protected:
  12112. ServerTestWithAI_PASSIVE()
  12113. : cli_(HOST, PORT)
  12114. #ifdef CPPHTTPLIB_SSL_ENABLED
  12115. ,
  12116. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12117. #endif
  12118. {
  12119. #ifdef CPPHTTPLIB_SSL_ENABLED
  12120. cli_.enable_server_certificate_verification(false);
  12121. #endif
  12122. }
  12123. virtual void SetUp() {
  12124. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12125. res.set_content("Hello World!", "text/plain");
  12126. });
  12127. t_ = thread(
  12128. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12129. svr_.wait_until_ready();
  12130. }
  12131. virtual void TearDown() {
  12132. svr_.stop();
  12133. t_.join();
  12134. }
  12135. #ifdef CPPHTTPLIB_SSL_ENABLED
  12136. SSLClient cli_;
  12137. SSLServer svr_;
  12138. #else
  12139. Client cli_;
  12140. Server svr_;
  12141. #endif
  12142. thread t_;
  12143. };
  12144. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12145. auto res = cli_.Get("/hi");
  12146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12147. EXPECT_EQ(StatusCode::OK_200, res->status);
  12148. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12149. EXPECT_EQ("Hello World!", res->body);
  12150. }
  12151. class ServerUpDownTest : public ::testing::Test {
  12152. protected:
  12153. ServerUpDownTest() : cli_(HOST, PORT) {}
  12154. virtual void SetUp() {
  12155. t_ = thread([&]() {
  12156. svr_.bind_to_any_port(HOST);
  12157. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12158. ASSERT_TRUE(svr_.listen_after_bind());
  12159. });
  12160. svr_.wait_until_ready();
  12161. }
  12162. virtual void TearDown() {
  12163. svr_.stop();
  12164. t_.join();
  12165. }
  12166. Client cli_;
  12167. Server svr_;
  12168. thread t_;
  12169. };
  12170. TEST_F(ServerUpDownTest, QuickStartStop) {
  12171. // Should not crash, especially when run with
  12172. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12173. }
  12174. class PayloadMaxLengthTest : public ::testing::Test {
  12175. protected:
  12176. PayloadMaxLengthTest()
  12177. : cli_(HOST, PORT)
  12178. #ifdef CPPHTTPLIB_SSL_ENABLED
  12179. ,
  12180. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12181. #endif
  12182. {
  12183. #ifdef CPPHTTPLIB_SSL_ENABLED
  12184. cli_.enable_server_certificate_verification(false);
  12185. #endif
  12186. }
  12187. virtual void SetUp() {
  12188. svr_.set_payload_max_length(8);
  12189. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12190. res.set_content("test", "text/plain");
  12191. });
  12192. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12193. svr_.wait_until_ready();
  12194. }
  12195. virtual void TearDown() {
  12196. svr_.stop();
  12197. t_.join();
  12198. }
  12199. #ifdef CPPHTTPLIB_SSL_ENABLED
  12200. SSLClient cli_;
  12201. SSLServer svr_;
  12202. #else
  12203. Client cli_;
  12204. Server svr_;
  12205. #endif
  12206. thread t_;
  12207. };
  12208. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12209. auto res = cli_.Post("/test", "123456789", "text/plain");
  12210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12211. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12212. res = cli_.Post("/test", "12345678", "text/plain");
  12213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12214. EXPECT_EQ(StatusCode::OK_200, res->status);
  12215. }
  12216. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12217. // Test chunked encoding with payload exceeding the 8-byte limit
  12218. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12219. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12221. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12222. }
  12223. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12224. // Test chunked encoding with payload within the 8-byte limit
  12225. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12226. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12228. EXPECT_EQ(StatusCode::OK_200, res->status);
  12229. }
  12230. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12231. // Test using send_request to send chunked data exceeding payload limit
  12232. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12233. "Host: " +
  12234. std::string(HOST) + ":" + std::to_string(PORT) +
  12235. "\r\n"
  12236. "Transfer-Encoding: chunked\r\n"
  12237. "Connection: close\r\n"
  12238. "\r\n"
  12239. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12240. "0123456789\r\n"
  12241. "0\r\n" // End chunk
  12242. "\r\n";
  12243. std::string response;
  12244. bool result = send_request(1, chunked_request, &response);
  12245. if (!result) {
  12246. // If send_request fails, it might be because the server closed the
  12247. // connection due to payload limit enforcement, which is acceptable
  12248. SUCCEED()
  12249. << "Server rejected oversized chunked request (connection closed)";
  12250. } else {
  12251. // If we got a response, check if it's an error response or connection was
  12252. // closed early Short response length indicates connection was closed due to
  12253. // payload limit
  12254. if (response.length() <= 10) {
  12255. SUCCEED() << "Server closed connection for oversized chunked request";
  12256. } else {
  12257. // Check for error status codes
  12258. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12259. response.find("Payload Too Large") != std::string::npos ||
  12260. response.find("400") != std::string::npos);
  12261. }
  12262. }
  12263. }
  12264. class LargePayloadMaxLengthTest : public ::testing::Test {
  12265. protected:
  12266. LargePayloadMaxLengthTest()
  12267. : cli_(HOST, PORT)
  12268. #ifdef CPPHTTPLIB_SSL_ENABLED
  12269. ,
  12270. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12271. #endif
  12272. {
  12273. #ifdef CPPHTTPLIB_SSL_ENABLED
  12274. cli_.enable_server_certificate_verification(false);
  12275. #endif
  12276. }
  12277. virtual void SetUp() {
  12278. // Set 10MB payload limit
  12279. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12280. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12281. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12282. res.set_content("Large payload test", "text/plain");
  12283. });
  12284. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12285. svr_.wait_until_ready();
  12286. }
  12287. virtual void TearDown() {
  12288. svr_.stop();
  12289. t_.join();
  12290. }
  12291. #ifdef CPPHTTPLIB_SSL_ENABLED
  12292. SSLClient cli_;
  12293. SSLServer svr_;
  12294. #else
  12295. Client cli_;
  12296. Server svr_;
  12297. #endif
  12298. thread t_;
  12299. };
  12300. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12301. // Test chunked encoding with payload within 10MB limit
  12302. std::string medium_payload(5 * 1024 * 1024,
  12303. 'A'); // 5MB payload, within 10MB limit
  12304. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12306. EXPECT_EQ(StatusCode::OK_200, res->status);
  12307. }
  12308. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12309. // Test chunked encoding with payload exceeding 10MB limit
  12310. std::string large_payload(12 * 1024 * 1024,
  12311. 'B'); // 12MB payload, exceeds 10MB limit
  12312. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12313. // Server may either return 413 or close the connection
  12314. if (res) {
  12315. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12316. } else {
  12317. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12318. }
  12319. }
  12320. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12321. Server svr;
  12322. svr.Get("/", [](const Request &, Response &res) {
  12323. // Claims the most the client accepts, far more than it sends, then drops
  12324. // the connection.
  12325. res.set_content_provider(std::string().max_size(), "text/plain",
  12326. [](size_t, size_t, DataSink &sink) {
  12327. sink.write("abc", 3);
  12328. return false;
  12329. });
  12330. });
  12331. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12332. auto se = detail::scope_exit([&] {
  12333. svr.stop();
  12334. thread.join();
  12335. ASSERT_FALSE(svr.is_running());
  12336. });
  12337. svr.wait_until_ready();
  12338. Client cli(HOST, PORT);
  12339. cli.set_payload_max_length(0);
  12340. EXPECT_FALSE(cli.Get("/"));
  12341. }
  12342. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12343. // Stream API does, not as a plain read failure
  12344. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12345. Server svr;
  12346. svr.Get("/big", [](const Request &, Response &res) {
  12347. res.set_content(std::string(100000, 'b'), "text/plain");
  12348. });
  12349. auto port = svr.bind_to_any_port(HOST);
  12350. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12351. auto se = detail::scope_exit([&] {
  12352. svr.stop();
  12353. thread.join();
  12354. });
  12355. svr.wait_until_ready();
  12356. Client cli(HOST, port);
  12357. cli.set_payload_max_length(1000);
  12358. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12359. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12360. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12361. [](const char *, size_t) { return true; });
  12362. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12363. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12364. // Small on the wire, over the limit once decompressed
  12365. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12366. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12367. #endif
  12368. }
  12369. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12370. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12371. // path.
  12372. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12373. Server svr;
  12374. const size_t LIMIT = 64 * 1024; // 64KB
  12375. svr.set_payload_max_length(LIMIT);
  12376. size_t total = 0;
  12377. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12378. const ContentReader &content_reader) {
  12379. content_reader([&](const char * /*data*/, size_t len) {
  12380. total += len;
  12381. return true;
  12382. });
  12383. res.status = 200;
  12384. res.set_content("stream_ok", "text/plain");
  12385. });
  12386. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12387. auto se = detail::scope_exit([&] {
  12388. svr.stop();
  12389. thread.join();
  12390. ASSERT_FALSE(svr.is_running());
  12391. });
  12392. svr.wait_until_ready();
  12393. // Prepare 256KB raw data and gzip-compress it
  12394. std::string raw(256 * 1024, 'A');
  12395. std::string gz;
  12396. {
  12397. z_stream zs{};
  12398. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12399. Z_DEFAULT_STRATEGY);
  12400. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12401. zs.avail_in = static_cast<uInt>(raw.size());
  12402. char outbuf[4096];
  12403. int ret;
  12404. do {
  12405. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12406. zs.avail_out = sizeof(outbuf);
  12407. ret = deflate(&zs, Z_FINISH);
  12408. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12409. } while (ret != Z_STREAM_END);
  12410. deflateEnd(&zs);
  12411. }
  12412. Client cli(HOST, PORT);
  12413. cli.set_connection_timeout(std::chrono::seconds(5));
  12414. Headers headers = {{"Content-Encoding", "gzip"}};
  12415. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12416. "application/octet-stream");
  12417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12418. // Server must reject oversized decompressed payloads with 413.
  12419. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12420. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12421. EXPECT_LE(total, LIMIT);
  12422. }
  12423. #endif
  12424. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12425. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12426. // the payload must be passed through untouched instead of being rejected.
  12427. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12428. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12429. Server svr;
  12430. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12431. res.set_content(body, "image/jpeg");
  12432. res.set_header("Content-Encoding", "UTF-8");
  12433. });
  12434. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12435. res.set_content(body, "image/jpeg");
  12436. res.set_header("Content-Encoding", "identity");
  12437. });
  12438. svr.Post("/echo", [](const Request &req, Response &res) {
  12439. res.set_content(req.body, "image/jpeg");
  12440. });
  12441. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12442. auto se = detail::scope_exit([&] {
  12443. svr.stop();
  12444. t.join();
  12445. ASSERT_FALSE(svr.is_running());
  12446. });
  12447. svr.wait_until_ready();
  12448. Client cli(HOST, PORT);
  12449. {
  12450. auto res = cli.Get("/image");
  12451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12452. EXPECT_EQ(StatusCode::OK_200, res->status);
  12453. EXPECT_EQ(body, res->body);
  12454. }
  12455. {
  12456. auto res = cli.Get("/identity");
  12457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12458. EXPECT_EQ(StatusCode::OK_200, res->status);
  12459. EXPECT_EQ(body, res->body);
  12460. }
  12461. {
  12462. // The same applies to a request body reaching the server.
  12463. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12464. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12466. EXPECT_EQ(StatusCode::OK_200, res->status);
  12467. EXPECT_EQ(body, res->body);
  12468. }
  12469. }
  12470. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12471. // gzip-encoded response even when the build has no zlib support.
  12472. static const char GZIPPED_HELLO_WORLD[] = {
  12473. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12474. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12475. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12476. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12477. // A content coding is a whole token, not something the field value merely
  12478. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12479. // as "fibre" look like Brotli, and turned a multi-coding value like
  12480. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12481. // it was never meant to see.
  12482. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12483. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12484. Server svr;
  12485. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12486. res.set_content(body, "image/jpeg");
  12487. res.set_header("Content-Encoding", "fibre");
  12488. });
  12489. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12490. res.set_content(body, "image/jpeg");
  12491. res.set_header("Content-Encoding", "gzip, br");
  12492. });
  12493. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12494. res.set_content(body, "image/jpeg");
  12495. res.set_header("Content-Encoding", "x-zstd-ish");
  12496. });
  12497. auto port = svr.bind_to_any_port(HOST);
  12498. thread t = thread([&]() { svr.listen_after_bind(); });
  12499. auto se = detail::scope_exit([&] {
  12500. svr.stop();
  12501. t.join();
  12502. ASSERT_FALSE(svr.is_running());
  12503. });
  12504. svr.wait_until_ready();
  12505. Client cli(HOST, port);
  12506. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12507. auto res = cli.Get(path);
  12508. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12509. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12510. // Not a coding we recognize, so the payload comes back untouched
  12511. EXPECT_EQ(body, res->body) << path;
  12512. }
  12513. }
  12514. // A content coding cpp-httplib recognizes but was not built with must be
  12515. // reported as such. Handing the still-compressed payload back to the caller
  12516. // would silently corrupt it.
  12517. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12518. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12519. Server svr;
  12520. // "image/jpeg" keeps the server from applying a content coding of its own,
  12521. // so the hand-crafted Content-Encoding below survives.
  12522. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12523. res.set_content(gzipped, "image/jpeg");
  12524. res.set_header("Content-Encoding", "gzip");
  12525. });
  12526. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12527. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12528. res.set_content(gzipped, "image/jpeg");
  12529. res.set_header("Content-Encoding", "GZIP");
  12530. });
  12531. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12532. auto se = detail::scope_exit([&] {
  12533. svr.stop();
  12534. t.join();
  12535. ASSERT_FALSE(svr.is_running());
  12536. });
  12537. svr.wait_until_ready();
  12538. Client cli(HOST, PORT);
  12539. {
  12540. auto res = cli.Get("/gzipped");
  12541. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12543. EXPECT_EQ("Hello World!", res->body);
  12544. #else
  12545. ASSERT_FALSE(res);
  12546. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12547. #endif
  12548. }
  12549. {
  12550. // open_stream() must behave the same way.
  12551. auto handle = cli.open_stream("GET", "/gzipped");
  12552. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12553. ASSERT_TRUE(handle.is_valid());
  12554. std::string received;
  12555. char buf[256];
  12556. ssize_t n;
  12557. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12558. received.append(buf, static_cast<size_t>(n));
  12559. }
  12560. EXPECT_EQ("Hello World!", received);
  12561. #else
  12562. EXPECT_FALSE(handle.is_valid());
  12563. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12564. #endif
  12565. }
  12566. {
  12567. // A differently-cased coding must not be mistaken for an unknown one, or
  12568. // the body would be handed back still compressed.
  12569. auto res = cli.Get("/gzipped-uppercase");
  12570. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12572. EXPECT_EQ("Hello World!", res->body);
  12573. #else
  12574. ASSERT_FALSE(res);
  12575. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12576. #endif
  12577. }
  12578. }
  12579. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12580. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12581. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12582. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12583. // body a second time and appending a second Content-Encoding field line, so
  12584. // clients that decode one coding per listed value handed back raw gzip bytes.
  12585. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12586. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12587. Server svr;
  12588. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12589. // keeps the server from applying a coding of its own.
  12590. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12591. res.set_content(gzipped, "text/plain");
  12592. res.set_header("Content-Encoding", "gzip");
  12593. });
  12594. auto port = svr.bind_to_any_port(HOST);
  12595. thread t = thread([&]() { svr.listen_after_bind(); });
  12596. auto se = detail::scope_exit([&] {
  12597. svr.stop();
  12598. t.join();
  12599. ASSERT_FALSE(svr.is_running());
  12600. });
  12601. svr.wait_until_ready();
  12602. Client cli(HOST, port);
  12603. Headers headers = {{"Accept-Encoding", "gzip"}};
  12604. auto res = cli.Get("/pre-gzipped", headers);
  12605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12606. EXPECT_EQ(StatusCode::OK_200, res->status);
  12607. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12608. EXPECT_EQ("Hello World!", res->body);
  12609. }
  12610. // set_compress(false) sends every handler response as it is, buffered or
  12611. // streamed
  12612. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12613. const std::string text(1000, 'a');
  12614. Server svr;
  12615. svr.set_compress(false);
  12616. svr.Get("/buffered", [&](const Request &, Response &res) {
  12617. res.set_content(text, "text/plain");
  12618. });
  12619. svr.Get("/streamed", [&](const Request &, Response &res) {
  12620. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12621. sink.write(text.data(), text.size());
  12622. sink.done();
  12623. return true;
  12624. });
  12625. });
  12626. auto port = svr.bind_to_any_port(HOST);
  12627. ASSERT_LT(0, port);
  12628. thread t = thread([&] { svr.listen_after_bind(); });
  12629. auto se = detail::scope_exit([&] {
  12630. svr.stop();
  12631. t.join();
  12632. ASSERT_FALSE(svr.is_running());
  12633. });
  12634. svr.wait_until_ready();
  12635. Client cli(HOST, port);
  12636. cli.set_decompress(false);
  12637. for (auto path : {"/buffered", "/streamed"}) {
  12638. SCOPED_TRACE(path);
  12639. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12641. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12642. EXPECT_EQ(text, res->body);
  12643. }
  12644. }
  12645. // A chunked provider settles its coding where the headers are written and
  12646. // reuses it at write time. Both ends of that have to hold: a handler's own
  12647. // Content-Encoding suppresses the coding, and a response without one is still
  12648. // compressed as it always was.
  12649. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12650. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12651. const std::string plain = "Hello World! Hello World! Hello World!";
  12652. Server svr;
  12653. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12654. res.set_header("Content-Encoding", "gzip");
  12655. res.set_chunked_content_provider(
  12656. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12657. sink.write(gzipped.data(), gzipped.size());
  12658. sink.done();
  12659. return true;
  12660. });
  12661. });
  12662. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12663. res.set_chunked_content_provider(
  12664. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12665. sink.write(plain.data(), plain.size());
  12666. sink.done();
  12667. return true;
  12668. });
  12669. });
  12670. auto port = svr.bind_to_any_port(HOST);
  12671. thread t = thread([&]() { svr.listen_after_bind(); });
  12672. auto se = detail::scope_exit([&] {
  12673. svr.stop();
  12674. t.join();
  12675. ASSERT_FALSE(svr.is_running());
  12676. });
  12677. svr.wait_until_ready();
  12678. Client cli(HOST, port);
  12679. Headers headers = {{"Accept-Encoding", "gzip"}};
  12680. {
  12681. auto res = cli.Get("/pre-gzipped", headers);
  12682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12683. EXPECT_EQ(StatusCode::OK_200, res->status);
  12684. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12685. EXPECT_EQ("Hello World!", res->body);
  12686. }
  12687. {
  12688. auto res = cli.Get("/negotiated", headers);
  12689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12690. EXPECT_EQ(StatusCode::OK_200, res->status);
  12691. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12692. EXPECT_EQ(plain, res->body);
  12693. }
  12694. }
  12695. #endif
  12696. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12697. // the same message as the comma-joined one, so both have to be read the same
  12698. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12699. // single gzip coding, and a body the sender says was encoded twice was handed
  12700. // back after one pass, still compressed but presented as decoded.
  12701. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12702. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12703. Server svr;
  12704. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12705. res.set_content(body, "image/jpeg");
  12706. res.headers.emplace("Content-Encoding", "gzip");
  12707. res.headers.emplace("Content-Encoding", "gzip");
  12708. });
  12709. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12710. res.set_content(body, "image/jpeg");
  12711. res.set_header("Content-Encoding", "gzip, gzip");
  12712. });
  12713. auto port = svr.bind_to_any_port(HOST);
  12714. thread t = thread([&]() { svr.listen_after_bind(); });
  12715. auto se = detail::scope_exit([&] {
  12716. svr.stop();
  12717. t.join();
  12718. ASSERT_FALSE(svr.is_running());
  12719. });
  12720. svr.wait_until_ready();
  12721. Client cli(HOST, port);
  12722. // Two codings is not something cpp-httplib decodes, so both representations
  12723. // take the pass-through path rather than one of them being gunzipped once.
  12724. for (const char *path : {"/split", "/joined"}) {
  12725. auto res = cli.Get(path);
  12726. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12727. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12728. EXPECT_EQ(body, res->body) << path;
  12729. }
  12730. }
  12731. // Regression test for DoS vulnerability: a malicious server sending a response
  12732. // without Content-Length header must not cause unbounded memory consumption on
  12733. // the client side. The client should stop reading after a reasonable limit,
  12734. // similar to the server-side set_payload_max_length protection.
  12735. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12736. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12737. #ifndef _WIN32
  12738. signal(SIGPIPE, SIG_IGN);
  12739. #endif
  12740. auto server_thread = std::thread([] {
  12741. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12742. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12743. default_socket_options(srv);
  12744. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12745. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12746. sockaddr_in addr{};
  12747. addr.sin_family = AF_INET;
  12748. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12749. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12750. int opt = 1;
  12751. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12752. #ifdef _WIN32
  12753. reinterpret_cast<const char *>(&opt),
  12754. #else
  12755. &opt,
  12756. #endif
  12757. sizeof(opt));
  12758. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12759. ::listen(srv, 1);
  12760. sockaddr_in cli_addr{};
  12761. socklen_t cli_len = sizeof(cli_addr);
  12762. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12763. if (cli != INVALID_SOCKET) {
  12764. char buf[4096];
  12765. ::recv(cli, buf, sizeof(buf), 0);
  12766. // Malicious response: no Content-Length, no chunked encoding
  12767. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12768. "Connection: close\r\n"
  12769. "\r\n";
  12770. ::send(cli,
  12771. #ifdef _WIN32
  12772. static_cast<const char *>(response_header.c_str()),
  12773. static_cast<int>(response_header.size()),
  12774. #else
  12775. response_header.c_str(), response_header.size(),
  12776. #endif
  12777. 0);
  12778. // Send 10MB of data
  12779. std::string chunk(64 * 1024, 'A');
  12780. size_t total_sent = 0;
  12781. while (total_sent < MALICIOUS_DATA_SIZE) {
  12782. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12783. auto sent = ::send(cli,
  12784. #ifdef _WIN32
  12785. static_cast<const char *>(chunk.c_str()),
  12786. static_cast<int>(to_send),
  12787. #else
  12788. chunk.c_str(), to_send,
  12789. #endif
  12790. 0);
  12791. if (sent <= 0) break;
  12792. total_sent += static_cast<size_t>(sent);
  12793. }
  12794. detail::close_socket(cli);
  12795. }
  12796. detail::close_socket(srv);
  12797. });
  12798. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12799. size_t total_read = 0;
  12800. {
  12801. Client cli("127.0.0.1", PORT + 2);
  12802. cli.set_read_timeout(5, 0);
  12803. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12804. auto stream = cli.open_stream("GET", "/malicious");
  12805. ASSERT_TRUE(stream.is_valid());
  12806. char buffer[64 * 1024];
  12807. ssize_t n;
  12808. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12809. total_read += static_cast<size_t>(n);
  12810. }
  12811. } // StreamHandle and Client destroyed here, closing the socket
  12812. server_thread.join();
  12813. // With set_payload_max_length, the client must stop reading before consuming
  12814. // all 10MB. The read loop should be cut off at or near the configured limit.
  12815. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12816. << "Client read " << total_read << " bytes, exceeding the configured "
  12817. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12818. }
  12819. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12820. // the entire response body without truncation.
  12821. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12822. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12823. #ifndef _WIN32
  12824. signal(SIGPIPE, SIG_IGN);
  12825. #endif
  12826. auto server_thread = std::thread([] {
  12827. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12828. default_socket_options(srv);
  12829. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12830. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12831. sockaddr_in addr{};
  12832. addr.sin_family = AF_INET;
  12833. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12834. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12835. int opt = 1;
  12836. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12837. #ifdef _WIN32
  12838. reinterpret_cast<const char *>(&opt),
  12839. #else
  12840. &opt,
  12841. #endif
  12842. sizeof(opt));
  12843. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12844. ::listen(srv, 1);
  12845. sockaddr_in cli_addr{};
  12846. socklen_t cli_len = sizeof(cli_addr);
  12847. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12848. if (cli != INVALID_SOCKET) {
  12849. char buf[4096];
  12850. ::recv(cli, buf, sizeof(buf), 0);
  12851. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12852. "Connection: close\r\n"
  12853. "\r\n";
  12854. ::send(cli,
  12855. #ifdef _WIN32
  12856. static_cast<const char *>(response_header.c_str()),
  12857. static_cast<int>(response_header.size()),
  12858. #else
  12859. response_header.c_str(), response_header.size(),
  12860. #endif
  12861. 0);
  12862. std::string chunk(64 * 1024, 'A');
  12863. size_t total_sent = 0;
  12864. while (total_sent < DATA_SIZE) {
  12865. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12866. auto sent = ::send(cli,
  12867. #ifdef _WIN32
  12868. static_cast<const char *>(chunk.c_str()),
  12869. static_cast<int>(to_send),
  12870. #else
  12871. chunk.c_str(), to_send,
  12872. #endif
  12873. 0);
  12874. if (sent <= 0) break;
  12875. total_sent += static_cast<size_t>(sent);
  12876. }
  12877. #ifdef _WIN32
  12878. ::shutdown(cli, SD_SEND);
  12879. #else
  12880. ::shutdown(cli, SHUT_WR);
  12881. #endif
  12882. // Drain until the client closes its end, ensuring all data is delivered
  12883. char drain[1024];
  12884. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12885. detail::close_socket(cli);
  12886. }
  12887. detail::close_socket(srv);
  12888. });
  12889. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12890. size_t total_read = 0;
  12891. {
  12892. Client cli("127.0.0.1", PORT + 2);
  12893. cli.set_read_timeout(5, 0);
  12894. cli.set_payload_max_length(0); // 0 means no limit
  12895. auto stream = cli.open_stream("GET", "/data");
  12896. ASSERT_TRUE(stream.is_valid());
  12897. char buffer[64 * 1024];
  12898. ssize_t n;
  12899. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12900. total_read += static_cast<size_t>(n);
  12901. }
  12902. }
  12903. server_thread.join();
  12904. EXPECT_EQ(total_read, DATA_SIZE)
  12905. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12906. << " bytes without truncation, but only read " << total_read << " bytes.";
  12907. }
  12908. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12909. // enormous Content-Length must not cause the client to pre-allocate a huge
  12910. // response body buffer. The reservation is capped at payload_max_length_, and
  12911. // the read itself fails when the body exceeds the limit.
  12912. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12913. #ifndef _WIN32
  12914. signal(SIGPIPE, SIG_IGN);
  12915. #endif
  12916. auto server_thread = std::thread([] {
  12917. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12918. default_socket_options(srv);
  12919. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12920. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12921. sockaddr_in addr{};
  12922. addr.sin_family = AF_INET;
  12923. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12924. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12925. int opt = 1;
  12926. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12927. #ifdef _WIN32
  12928. reinterpret_cast<const char *>(&opt),
  12929. #else
  12930. &opt,
  12931. #endif
  12932. sizeof(opt));
  12933. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12934. ::listen(srv, 1);
  12935. sockaddr_in cli_addr{};
  12936. socklen_t cli_len = sizeof(cli_addr);
  12937. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12938. if (cli != INVALID_SOCKET) {
  12939. char buf[4096];
  12940. ::recv(cli, buf, sizeof(buf), 0);
  12941. // Malicious response: claim a 20GB body but send only a tiny payload.
  12942. std::string response = "HTTP/1.1 200 OK\r\n"
  12943. "Content-Length: 20000000000\r\n"
  12944. "\r\n"
  12945. "abc";
  12946. ::send(cli,
  12947. #ifdef _WIN32
  12948. static_cast<const char *>(response.c_str()),
  12949. static_cast<int>(response.size()),
  12950. #else
  12951. response.c_str(), response.size(),
  12952. #endif
  12953. 0);
  12954. detail::close_socket(cli);
  12955. }
  12956. detail::close_socket(srv);
  12957. });
  12958. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12959. {
  12960. Client cli("127.0.0.1", PORT + 2);
  12961. cli.set_read_timeout(5, 0);
  12962. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12963. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12964. // (server claims more bytes than payload_max_length permits), but it must
  12965. // not exhaust memory before getting there.
  12966. auto res = cli.Get("/malicious");
  12967. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12968. }
  12969. server_thread.join();
  12970. }
  12971. // Verify that content_receiver bypasses the default payload_max_length,
  12972. // allowing streaming downloads larger than 100MB without requiring an explicit
  12973. // set_payload_max_length call.
  12974. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12975. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12976. #ifndef _WIN32
  12977. signal(SIGPIPE, SIG_IGN);
  12978. #endif
  12979. auto server_thread = std::thread([] {
  12980. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12981. default_socket_options(srv);
  12982. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12983. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12984. sockaddr_in addr{};
  12985. addr.sin_family = AF_INET;
  12986. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12987. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12988. int opt = 1;
  12989. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12990. #ifdef _WIN32
  12991. reinterpret_cast<const char *>(&opt),
  12992. #else
  12993. &opt,
  12994. #endif
  12995. sizeof(opt));
  12996. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12997. ::listen(srv, 1);
  12998. sockaddr_in cli_addr{};
  12999. socklen_t cli_len = sizeof(cli_addr);
  13000. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13001. if (cli != INVALID_SOCKET) {
  13002. char buf[4096];
  13003. ::recv(cli, buf, sizeof(buf), 0);
  13004. // Response with Content-Length larger than default 100MB limit
  13005. auto content_length = std::to_string(DATA_SIZE);
  13006. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13007. "Content-Length: " +
  13008. content_length +
  13009. "\r\n"
  13010. "Connection: close\r\n"
  13011. "\r\n";
  13012. ::send(cli,
  13013. #ifdef _WIN32
  13014. static_cast<const char *>(response_header.c_str()),
  13015. static_cast<int>(response_header.size()),
  13016. #else
  13017. response_header.c_str(), response_header.size(),
  13018. #endif
  13019. 0);
  13020. std::string chunk(64 * 1024, 'A');
  13021. size_t total_sent = 0;
  13022. while (total_sent < DATA_SIZE) {
  13023. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13024. auto sent = ::send(cli,
  13025. #ifdef _WIN32
  13026. static_cast<const char *>(chunk.c_str()),
  13027. static_cast<int>(to_send),
  13028. #else
  13029. chunk.c_str(), to_send,
  13030. #endif
  13031. 0);
  13032. if (sent <= 0) break;
  13033. total_sent += static_cast<size_t>(sent);
  13034. }
  13035. detail::close_socket(cli);
  13036. }
  13037. detail::close_socket(srv);
  13038. });
  13039. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13040. size_t total_received = 0;
  13041. {
  13042. Client cli("127.0.0.1", PORT + 2);
  13043. cli.set_read_timeout(10, 0);
  13044. // Do NOT call set_payload_max_length — use the default 100MB limit
  13045. auto res =
  13046. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13047. total_received += data_length;
  13048. return true;
  13049. });
  13050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13051. EXPECT_EQ(StatusCode::OK_200, res->status);
  13052. }
  13053. server_thread.join();
  13054. EXPECT_EQ(total_received, DATA_SIZE)
  13055. << "With content_receiver, the client should read all " << DATA_SIZE
  13056. << " bytes despite the default 100MB payload_max_length, but only read "
  13057. << total_received << " bytes.";
  13058. }
  13059. // Verify that an explicit set_payload_max_length smaller than the response is
  13060. // enforced even when a content_receiver is used.
  13061. TEST(ClientVulnerabilityTest,
  13062. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13063. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13064. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13065. #ifndef _WIN32
  13066. signal(SIGPIPE, SIG_IGN);
  13067. #endif
  13068. auto server_thread = std::thread([] {
  13069. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13070. default_socket_options(srv);
  13071. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13072. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13073. sockaddr_in addr{};
  13074. addr.sin_family = AF_INET;
  13075. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13076. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13077. int opt = 1;
  13078. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13079. #ifdef _WIN32
  13080. reinterpret_cast<const char *>(&opt),
  13081. #else
  13082. &opt,
  13083. #endif
  13084. sizeof(opt));
  13085. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13086. ::listen(srv, 1);
  13087. sockaddr_in cli_addr{};
  13088. socklen_t cli_len = sizeof(cli_addr);
  13089. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13090. if (cli != INVALID_SOCKET) {
  13091. char buf[4096];
  13092. ::recv(cli, buf, sizeof(buf), 0);
  13093. auto content_length = std::to_string(DATA_SIZE);
  13094. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13095. "Content-Length: " +
  13096. content_length +
  13097. "\r\n"
  13098. "Connection: close\r\n"
  13099. "\r\n";
  13100. ::send(cli,
  13101. #ifdef _WIN32
  13102. static_cast<const char *>(response_header.c_str()),
  13103. static_cast<int>(response_header.size()),
  13104. #else
  13105. response_header.c_str(), response_header.size(),
  13106. #endif
  13107. 0);
  13108. std::string chunk(64 * 1024, 'A');
  13109. size_t total_sent = 0;
  13110. while (total_sent < DATA_SIZE) {
  13111. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13112. auto sent = ::send(cli,
  13113. #ifdef _WIN32
  13114. static_cast<const char *>(chunk.c_str()),
  13115. static_cast<int>(to_send),
  13116. #else
  13117. chunk.c_str(), to_send,
  13118. #endif
  13119. 0);
  13120. if (sent <= 0) break;
  13121. total_sent += static_cast<size_t>(sent);
  13122. }
  13123. detail::close_socket(cli);
  13124. }
  13125. detail::close_socket(srv);
  13126. });
  13127. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13128. size_t total_received = 0;
  13129. {
  13130. Client cli("127.0.0.1", PORT + 2);
  13131. cli.set_read_timeout(10, 0);
  13132. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13133. auto res =
  13134. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13135. total_received += data_length;
  13136. return true;
  13137. });
  13138. // Should fail because 200MB exceeds the explicit 150MB limit
  13139. EXPECT_FALSE(res);
  13140. }
  13141. server_thread.join();
  13142. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13143. << "Client with content_receiver should respect the explicit "
  13144. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13145. << total_received << " bytes.";
  13146. }
  13147. // Verify that an explicit set_payload_max_length larger than the response
  13148. // allows the content_receiver to read all data successfully.
  13149. TEST(ClientVulnerabilityTest,
  13150. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13151. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13152. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13153. #ifndef _WIN32
  13154. signal(SIGPIPE, SIG_IGN);
  13155. #endif
  13156. auto server_thread = std::thread([] {
  13157. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13158. default_socket_options(srv);
  13159. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13160. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13161. sockaddr_in addr{};
  13162. addr.sin_family = AF_INET;
  13163. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13164. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13165. int opt = 1;
  13166. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13167. #ifdef _WIN32
  13168. reinterpret_cast<const char *>(&opt),
  13169. #else
  13170. &opt,
  13171. #endif
  13172. sizeof(opt));
  13173. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13174. ::listen(srv, 1);
  13175. sockaddr_in cli_addr{};
  13176. socklen_t cli_len = sizeof(cli_addr);
  13177. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13178. if (cli != INVALID_SOCKET) {
  13179. char buf[4096];
  13180. ::recv(cli, buf, sizeof(buf), 0);
  13181. auto content_length = std::to_string(DATA_SIZE);
  13182. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13183. "Content-Length: " +
  13184. content_length +
  13185. "\r\n"
  13186. "Connection: close\r\n"
  13187. "\r\n";
  13188. ::send(cli,
  13189. #ifdef _WIN32
  13190. static_cast<const char *>(response_header.c_str()),
  13191. static_cast<int>(response_header.size()),
  13192. #else
  13193. response_header.c_str(), response_header.size(),
  13194. #endif
  13195. 0);
  13196. std::string chunk(64 * 1024, 'A');
  13197. size_t total_sent = 0;
  13198. while (total_sent < DATA_SIZE) {
  13199. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13200. auto sent = ::send(cli,
  13201. #ifdef _WIN32
  13202. static_cast<const char *>(chunk.c_str()),
  13203. static_cast<int>(to_send),
  13204. #else
  13205. chunk.c_str(), to_send,
  13206. #endif
  13207. 0);
  13208. if (sent <= 0) break;
  13209. total_sent += static_cast<size_t>(sent);
  13210. }
  13211. #ifdef _WIN32
  13212. ::shutdown(cli, SD_SEND);
  13213. #else
  13214. ::shutdown(cli, SHUT_WR);
  13215. #endif
  13216. char drain[1024];
  13217. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13218. detail::close_socket(cli);
  13219. }
  13220. detail::close_socket(srv);
  13221. });
  13222. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13223. size_t total_received = 0;
  13224. {
  13225. Client cli("127.0.0.1", PORT + 2);
  13226. cli.set_read_timeout(10, 0);
  13227. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13228. auto res =
  13229. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13230. total_received += data_length;
  13231. return true;
  13232. });
  13233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13234. EXPECT_EQ(StatusCode::OK_200, res->status);
  13235. }
  13236. server_thread.join();
  13237. EXPECT_EQ(total_received, DATA_SIZE)
  13238. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13239. << " bytes (larger than " << DATA_SIZE
  13240. << " bytes response), content_receiver should read all data, but only "
  13241. "read "
  13242. << total_received << " bytes.";
  13243. }
  13244. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13245. // Regression test for "zip bomb" attack on the client side: a malicious server
  13246. // sends a small gzip-compressed response that decompresses to a huge payload.
  13247. // The client must enforce payload_max_length on the decompressed size.
  13248. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13249. constexpr size_t DECOMPRESSED_SIZE =
  13250. 10 * 1024 * 1024; // 10MB after decompression
  13251. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13252. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13253. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13254. std::string compressed;
  13255. {
  13256. httplib::detail::gzip_compressor compressor;
  13257. bool ok =
  13258. compressor.compress(uncompressed.data(), uncompressed.size(),
  13259. /*last=*/true, [&](const char *buf, size_t len) {
  13260. compressed.append(buf, len);
  13261. return true;
  13262. });
  13263. ASSERT_TRUE(ok);
  13264. }
  13265. // Sanity: compressed data should be much smaller than the decompressed size
  13266. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13267. #ifndef _WIN32
  13268. signal(SIGPIPE, SIG_IGN);
  13269. #endif
  13270. // Set up the listening socket in the main thread so the server is guaranteed
  13271. // to be ready before the client connects (eliminates race condition).
  13272. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13273. default_socket_options(srv);
  13274. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13275. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13276. sockaddr_in addr{};
  13277. addr.sin_family = AF_INET;
  13278. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13279. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13280. int opt = 1;
  13281. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13282. #ifdef _WIN32
  13283. reinterpret_cast<const char *>(&opt),
  13284. #else
  13285. &opt,
  13286. #endif
  13287. sizeof(opt));
  13288. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13289. ASSERT_EQ(0, ::listen(srv, 1));
  13290. auto server_thread = std::thread([&compressed, srv] {
  13291. sockaddr_in cli_addr{};
  13292. socklen_t cli_len = sizeof(cli_addr);
  13293. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13294. if (cli != INVALID_SOCKET) {
  13295. // Read the full HTTP request (until \r\n\r\n)
  13296. char buf[4096];
  13297. size_t total = 0;
  13298. while (total < sizeof(buf)) {
  13299. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13300. if (n <= 0) break;
  13301. total += static_cast<size_t>(n);
  13302. // Check for end of headers
  13303. if (total >= 4) {
  13304. std::string req(buf, total);
  13305. if (req.find("\r\n\r\n") != std::string::npos) break;
  13306. }
  13307. }
  13308. // Malicious response: gzip-compressed body, no Content-Length
  13309. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13310. "Content-Encoding: gzip\r\n"
  13311. "Connection: close\r\n"
  13312. "\r\n";
  13313. ::send(cli,
  13314. #ifdef _WIN32
  13315. static_cast<const char *>(response_header.c_str()),
  13316. static_cast<int>(response_header.size()),
  13317. #else
  13318. response_header.c_str(), response_header.size(),
  13319. #endif
  13320. 0);
  13321. // Send the compressed payload (small on the wire, huge when decompressed)
  13322. size_t total_sent = 0;
  13323. while (total_sent < compressed.size()) {
  13324. auto to_send = std::min(compressed.size() - total_sent,
  13325. static_cast<size_t>(64 * 1024));
  13326. auto sent =
  13327. ::send(cli,
  13328. #ifdef _WIN32
  13329. static_cast<const char *>(compressed.c_str() + total_sent),
  13330. static_cast<int>(to_send),
  13331. #else
  13332. compressed.c_str() + total_sent, to_send,
  13333. #endif
  13334. 0);
  13335. if (sent <= 0) break;
  13336. total_sent += static_cast<size_t>(sent);
  13337. }
  13338. detail::close_socket(cli);
  13339. }
  13340. });
  13341. auto se = detail::scope_exit([&] {
  13342. detail::close_socket(srv);
  13343. server_thread.join();
  13344. });
  13345. size_t total_decompressed = 0;
  13346. {
  13347. Client cli("127.0.0.1", PORT + 3);
  13348. cli.set_read_timeout(5, 0);
  13349. cli.set_decompress(true);
  13350. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13351. auto stream = cli.open_stream("GET", "/zipbomb");
  13352. ASSERT_TRUE(stream.is_valid());
  13353. char buffer[64 * 1024];
  13354. ssize_t n;
  13355. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13356. total_decompressed += static_cast<size_t>(n);
  13357. }
  13358. }
  13359. // The decompressed size must be capped by payload_max_length. Without
  13360. // protection, the client would decompress the full 10MB from a tiny
  13361. // compressed payload, enabling a zip bomb DoS attack.
  13362. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13363. << "Client decompressed " << total_decompressed
  13364. << " bytes from a gzip response. The decompressed size should be "
  13365. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13366. }
  13367. #endif
  13368. TEST(HostAndPortPropertiesTest, NoSSL) {
  13369. httplib::Client cli("www.google.com", 1234);
  13370. ASSERT_EQ("www.google.com", cli.host());
  13371. ASSERT_EQ(1234, cli.port());
  13372. }
  13373. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13374. httplib::Client cli("www.google.com:1234");
  13375. ASSERT_EQ("www.google.com", cli.host());
  13376. ASSERT_EQ(1234, cli.port());
  13377. }
  13378. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13379. // Port number that overflows int — should not crash, client becomes invalid
  13380. httplib::Client cli("http://www.google.com:99999999999999999999");
  13381. ASSERT_FALSE(cli.is_valid());
  13382. }
  13383. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13384. // Port 99999 exceeds valid range (1-65535) — should not crash
  13385. httplib::Client cli("http://www.google.com:99999");
  13386. ASSERT_FALSE(cli.is_valid());
  13387. auto res = cli.Get("/");
  13388. EXPECT_FALSE(res);
  13389. EXPECT_EQ(Error::Connection, res.error());
  13390. }
  13391. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13392. httplib::Client cli("http://user:pass@localhost:1234");
  13393. ASSERT_FALSE(cli.is_valid());
  13394. EXPECT_FALSE(cli.Get("/"));
  13395. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13396. }
  13397. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13398. httplib::Client cli("http://www.google.com:80abc");
  13399. ASSERT_FALSE(cli.is_valid());
  13400. }
  13401. #ifdef CPPHTTPLIB_SSL_ENABLED
  13402. TEST(HostAndPortPropertiesTest, SSL) {
  13403. httplib::SSLClient cli("www.google.com");
  13404. ASSERT_EQ("www.google.com", cli.host());
  13405. ASSERT_EQ(443, cli.port());
  13406. }
  13407. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13408. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13409. std::string cert;
  13410. read_file(CA_CERT_FILE, cert);
  13411. httplib::SSLClient httplib_client("www.google.com");
  13412. // Load CA store first time
  13413. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13414. // Load CA store second time (update)
  13415. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13416. // Verify client is still valid and can make connections
  13417. httplib_client.enable_server_certificate_verification(true);
  13418. auto res = httplib_client.Get("/");
  13419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13420. // Google may return 200 or 301 depending on various factors
  13421. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13422. res->status == StatusCode::MovedPermanently_301);
  13423. }
  13424. TEST(SSLClientTest, ServerNameIndication_Online) {
  13425. auto host = "httpbingo.org";
  13426. auto path = std::string{"/get"};
  13427. SSLClient cli(host, 443);
  13428. auto res = cli.Get(path);
  13429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13430. ASSERT_EQ(StatusCode::OK_200, res->status);
  13431. }
  13432. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13433. // Use a site that will cause SSL verification failure due to self-signed cert
  13434. SSLClient cli("self-signed.badssl.com", 443);
  13435. cli.enable_server_certificate_verification(true);
  13436. auto res = cli.Get("/");
  13437. ASSERT_TRUE(!res);
  13438. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13439. // Verify backend error is captured for SSLServerVerification
  13440. // This occurs when certificate verification fails
  13441. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13442. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13443. EXPECT_NE(0UL, res.ssl_backend_error());
  13444. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13445. res.ssl_error());
  13446. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13447. #if !defined(_WIN32) || \
  13448. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13449. // On non-Windows or when Windows Schannel is disabled, the error comes
  13450. // from OpenSSL's verification
  13451. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13452. res.ssl_backend_error());
  13453. #endif
  13454. #endif
  13455. }
  13456. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13457. // Use a site where hostname doesn't match the certificate
  13458. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13459. SSLClient cli("wrong.host.badssl.com", 443);
  13460. cli.enable_server_certificate_verification(true);
  13461. cli.enable_server_hostname_verification(true);
  13462. auto res = cli.Get("/");
  13463. ASSERT_TRUE(!res);
  13464. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13465. // Verify backend error is captured for hostname verification failure
  13466. EXPECT_NE(0UL, res.ssl_backend_error());
  13467. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13468. res.ssl_error());
  13469. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13470. #if !defined(_WIN32) || \
  13471. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13472. // On non-Windows or when Windows Schannel is disabled, the error comes
  13473. // from OpenSSL's hostname verification
  13474. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13475. res.ssl_backend_error());
  13476. #endif
  13477. #endif
  13478. }
  13479. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13480. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13481. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13482. SSLClient cli("www.google.com", 443);
  13483. cli.enable_server_certificate_verification(true);
  13484. auto res = cli.Get("/");
  13485. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13486. }
  13487. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13488. SSLClient cli("www.google.com", 443);
  13489. cli.enable_server_certificate_verification(true);
  13490. cli.enable_windows_certificate_verification(false);
  13491. auto res = cli.Get("/");
  13492. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13493. }
  13494. // The server sends an intermediate cross-signed by a root Windows trusts,
  13495. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13496. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13497. SSLClient cli("accounts.spotify.com", 443);
  13498. auto res = cli.Get("/");
  13499. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13500. << " ssl_backend_error=" << res.ssl_backend_error();
  13501. }
  13502. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13503. // policy status, which no backend reports for a self-signed certificate.
  13504. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13505. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13506. ASSERT_TRUE(svr.is_valid());
  13507. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13508. auto se = detail::scope_exit([&] {
  13509. svr.stop();
  13510. t.join();
  13511. ASSERT_FALSE(svr.is_running());
  13512. });
  13513. svr.wait_until_ready();
  13514. SSLClient cli("127.0.0.1", PORT);
  13515. cli.set_connection_timeout(30);
  13516. auto res = cli.Get("/");
  13517. ASSERT_FALSE(res);
  13518. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13519. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13520. }
  13521. #endif
  13522. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13523. Client cli("https://google.com");
  13524. auto res = cli.Get("/");
  13525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13526. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13527. }
  13528. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13529. SSLClient cli("google.com");
  13530. cli.set_ca_cert_path(CA_CERT_FILE);
  13531. auto res = cli.Get("/");
  13532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13533. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13534. }
  13535. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13536. SSLClient cli("google.com");
  13537. cli.enable_server_certificate_verification(true);
  13538. cli.set_ca_cert_path("hello");
  13539. auto res = cli.Get("/");
  13540. ASSERT_TRUE(!res);
  13541. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13542. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13543. // should be set
  13544. EXPECT_EQ(0, res.ssl_error());
  13545. // Verify backend error is captured for SSLLoadingCerts
  13546. // This error occurs when loading CA certificates fails
  13547. EXPECT_NE(0UL, res.ssl_backend_error());
  13548. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13549. // OpenSSL specific error codes:
  13550. // > openssl errstr 0x80000002
  13551. // error:80000002:system library::No such file or directory
  13552. // > openssl errstr 0xA000126
  13553. // error:0A000126:SSL routines::unexpected eof while reading
  13554. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13555. res.ssl_backend_error() == 0xA000126);
  13556. #endif
  13557. }
  13558. TEST(SSLClientTest, ServerCertificateVerification4) {
  13559. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13560. ASSERT_TRUE(svr.is_valid());
  13561. svr.Get("/test", [&](const Request &, Response &res) {
  13562. res.set_content("test", "text/plain");
  13563. svr.stop();
  13564. ASSERT_TRUE(true);
  13565. });
  13566. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13567. auto se = detail::scope_exit([&] {
  13568. t.join();
  13569. ASSERT_FALSE(svr.is_running());
  13570. });
  13571. svr.wait_until_ready();
  13572. SSLClient cli("127.0.0.1", PORT);
  13573. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13574. cli.enable_server_certificate_verification(true);
  13575. cli.set_connection_timeout(30);
  13576. auto res = cli.Get("/test");
  13577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13578. ASSERT_EQ(StatusCode::OK_200, res->status);
  13579. }
  13580. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13581. std::string cert;
  13582. read_file(CA_CERT_FILE, cert);
  13583. SSLClient cli("google.com");
  13584. cli.load_ca_cert_store(cert.data(), cert.size());
  13585. const auto res = cli.Get("/");
  13586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13587. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13588. }
  13589. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13590. // clang-format off
  13591. static constexpr char cert[] =
  13592. "GlobalSign Root CA\n"
  13593. "==================\n"
  13594. "-----BEGIN CERTIFICATE-----\n"
  13595. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13596. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13597. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13598. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13599. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13600. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13601. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13602. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13603. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13604. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13605. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13606. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13607. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13608. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13609. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13610. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13611. "-----END CERTIFICATE-----\n";
  13612. // clang-format on
  13613. SSLClient cli("google.com");
  13614. cli.load_ca_cert_store(cert, sizeof(cert));
  13615. const auto res = cli.Get("/");
  13616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13617. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13618. }
  13619. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13620. SSLClient cli("www.youtube.com");
  13621. cli.set_ca_cert_path(CA_CERT_FILE);
  13622. cli.enable_server_certificate_verification(true);
  13623. cli.set_follow_location(true);
  13624. auto res = cli.Get("/");
  13625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13626. ASSERT_EQ(StatusCode::OK_200, res->status);
  13627. }
  13628. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13629. SSLClient cli("wWw.YouTube.Com");
  13630. cli.set_ca_cert_path(CA_CERT_FILE);
  13631. cli.enable_server_certificate_verification(true);
  13632. cli.enable_server_hostname_verification(true);
  13633. cli.set_follow_location(true);
  13634. auto res = cli.Get("/");
  13635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13636. ASSERT_EQ(StatusCode::OK_200, res->status);
  13637. }
  13638. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13639. SSLClient cli("gOoGlE.COm");
  13640. cli.enable_server_certificate_verification(true);
  13641. cli.enable_server_hostname_verification(true);
  13642. cli.set_follow_location(true);
  13643. auto res = cli.Get("/");
  13644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13645. ASSERT_EQ(StatusCode::OK_200, res->status);
  13646. }
  13647. TEST(SSLClientTest, Issue2004_Online) {
  13648. Client client("https://google.com");
  13649. client.set_follow_location(true);
  13650. auto res = client.Get("/");
  13651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13652. ASSERT_EQ(StatusCode::OK_200, res->status);
  13653. auto body = res->body;
  13654. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13655. }
  13656. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13657. // Create SSLClient with invalid cert/key to make is_valid() return false
  13658. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13659. "nonexistent_key.pem");
  13660. // is_valid() should be false due to cert loading failure
  13661. ASSERT_FALSE(cli.is_valid());
  13662. auto res = cli.Get("/");
  13663. ASSERT_FALSE(res);
  13664. EXPECT_EQ(Error::SSLConnection, res.error());
  13665. }
  13666. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13667. // Test for Issue #2251: SSL error not properly reported when client cert
  13668. // and key paths are swapped or mismatched
  13669. // This simulates the scenario where user accidentally swaps the cert and key
  13670. // files
  13671. // Using client cert file as private key and vice versa (completely wrong)
  13672. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13673. // Should fail validation due to cert/key mismatch
  13674. ASSERT_FALSE(cli.is_valid());
  13675. // Attempt to make a request should fail with proper error
  13676. auto res = cli.Get("/");
  13677. ASSERT_FALSE(res);
  13678. EXPECT_EQ(Error::SSLConnection, res.error());
  13679. // SSL error should be recorded in the Result object (this is the key fix for
  13680. // Issue #2251)
  13681. auto backend_error = res.ssl_backend_error();
  13682. EXPECT_NE(0u, backend_error);
  13683. }
  13684. // Tests cert/key mismatch detection at the TLS context level
  13685. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13686. // Test that using mismatched cert/key causes connection failure.
  13687. // We verify this at the SSLClient level rather than through internal
  13688. // TLS API functions.
  13689. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13690. cli.enable_server_certificate_verification(false);
  13691. cli.set_connection_timeout(2);
  13692. // The mismatch should cause a connection or handshake error
  13693. auto res = cli.Get("/test");
  13694. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13695. // Either way, the request should fail
  13696. EXPECT_FALSE(res);
  13697. }
  13698. #endif
  13699. #if 0
  13700. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13701. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13702. ASSERT_TRUE(cli != nullptr);
  13703. cli->set_address_family(AF_INET6);
  13704. cli->set_interface("en0");
  13705. auto res = cli->Get("/get");
  13706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13707. ASSERT_EQ(StatusCode::OK_200, res->status);
  13708. }
  13709. #endif
  13710. // Client certificate tests - work with all TLS backends
  13711. #ifdef CPPHTTPLIB_SSL_ENABLED
  13712. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13713. void ClientCertPresent(
  13714. const std::string &client_cert_file,
  13715. const std::string &client_private_key_file,
  13716. const std::string &client_encrypted_private_key_pass = std::string(),
  13717. const ClientCertServerSetup &setup = nullptr) {
  13718. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13719. ASSERT_TRUE(svr.is_valid());
  13720. if (setup) { setup(svr); }
  13721. svr.Get("/test", [&](const Request &req, Response &res) {
  13722. res.set_content("test", "text/plain");
  13723. auto cert = req.peer_cert();
  13724. ASSERT_TRUE(static_cast<bool>(cert));
  13725. std::string common_name = cert.subject_cn();
  13726. EXPECT_EQ("Common Name", common_name);
  13727. });
  13728. auto port = svr.bind_to_any_port(HOST);
  13729. ASSERT_LT(0, port);
  13730. thread t = thread([&]() { svr.listen_after_bind(); });
  13731. auto se = detail::scope_exit([&] {
  13732. svr.stop();
  13733. t.join();
  13734. ASSERT_FALSE(svr.is_running());
  13735. });
  13736. svr.wait_until_ready();
  13737. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13738. client_encrypted_private_key_pass);
  13739. cli.enable_server_certificate_verification(false);
  13740. cli.set_connection_timeout(30);
  13741. auto res = cli.Get("/test");
  13742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13743. ASSERT_EQ(StatusCode::OK_200, res->status);
  13744. }
  13745. TEST(SSLClientServerTest, ClientCertPresent) {
  13746. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13747. }
  13748. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13749. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13750. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13751. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13752. }
  13753. // Expects svr, which must require client certificates, to reject a client
  13754. // that has none
  13755. void RejectsClientWithoutCert(SSLServer &svr) {
  13756. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13757. auto port = svr.bind_to_any_port(HOST);
  13758. ASSERT_LT(0, port);
  13759. thread t = thread([&]() { svr.listen_after_bind(); });
  13760. auto se = detail::scope_exit([&] {
  13761. svr.stop();
  13762. t.join();
  13763. ASSERT_FALSE(svr.is_running());
  13764. });
  13765. svr.wait_until_ready();
  13766. SSLClient cli(HOST, port);
  13767. cli.set_connection_timeout(30);
  13768. // Skip the server certificate check, so that the request fails because the
  13769. // client certificate is missing rather than because cert.pem is not trusted
  13770. cli.enable_server_certificate_verification(false);
  13771. auto res = cli.Get("/test");
  13772. ASSERT_FALSE(res);
  13773. // The server rejects the client during the handshake, or on TLS 1.3 right
  13774. // after it, which the client notices on its first write or read
  13775. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13776. res.error() == Error::Write || res.error() == Error::Read)
  13777. << to_string(res.error());
  13778. if (res.error() == Error::SSLConnection) {
  13779. EXPECT_NE(0UL, res.ssl_backend_error());
  13780. }
  13781. // A rejection noticed on the write keeps the TLS error the write hit
  13782. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13783. }
  13784. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13786. ASSERT_TRUE(svr.is_valid());
  13787. if (setup) { setup(svr); }
  13788. RejectsClientWithoutCert(svr);
  13789. }
  13790. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13791. // A server that requires client certificates must keep requiring them after
  13792. // setup changes it, and keep accepting a client that has one
  13793. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13794. ClientCertMissing(setup);
  13795. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13796. setup);
  13797. }
  13798. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13799. ClientCertStillRequired([](SSLServer &svr) {
  13800. ASSERT_TRUE(tls::set_verify_callback(
  13801. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13802. });
  13803. }
  13804. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13805. ClientCertStillRequired([](SSLServer &svr) {
  13806. ASSERT_TRUE(tls::set_verify_callback(
  13807. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13808. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13809. });
  13810. }
  13811. // The client verifies the server certificate during the handshake, so a
  13812. // server that fails the check never gets the client certificate, even when a
  13813. // verifier of the client's own accepts it
  13814. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13815. struct Case {
  13816. const char *trusted_ca;
  13817. const char *host;
  13818. Error error;
  13819. };
  13820. // cert2.pem names localhost: the first client does not trust it, and the
  13821. // second trusts it but asks for another name
  13822. for (const auto &c :
  13823. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13824. Case{SERVER_CERT2_FILE, "example.com",
  13825. Error::SSLServerHostnameVerification}}) {
  13826. for (auto with_verifier : {false, true}) {
  13827. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13828. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13829. CLIENT_CA_CERT_FILE);
  13830. ASSERT_TRUE(svr.is_valid());
  13831. std::atomic<bool> got_client_cert{false};
  13832. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13833. [&](const tls::VerifyContext &) {
  13834. got_client_cert = true;
  13835. return true;
  13836. }));
  13837. auto port = svr.bind_to_any_port("127.0.0.1");
  13838. ASSERT_LT(0, port);
  13839. thread t = thread([&] { svr.listen_after_bind(); });
  13840. svr.wait_until_ready();
  13841. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13842. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13843. cli.set_ca_cert_path(c.trusted_ca);
  13844. if (with_verifier) {
  13845. cli.set_server_certificate_verifier(
  13846. [](const tls::VerifyContext &) { return true; });
  13847. }
  13848. auto res = cli.Get("/");
  13849. EXPECT_FALSE(res);
  13850. EXPECT_EQ(c.error, res.error());
  13851. svr.stop();
  13852. t.join();
  13853. EXPECT_FALSE(got_client_cert);
  13854. }
  13855. }
  13856. }
  13857. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13858. std::string cert_pem, key_pem, ca_pem;
  13859. read_file(SERVER_CERT_FILE, cert_pem);
  13860. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13861. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13862. ASSERT_TRUE(
  13863. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13864. }
  13865. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13866. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13867. ASSERT_TRUE(svr.is_valid());
  13868. UpdateCertsPemWithClientCA(svr);
  13869. RejectsClientWithoutCert(svr);
  13870. }
  13871. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13872. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13873. }
  13874. // A TLS error from one request must not show up in a later request's Result
  13875. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13876. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13877. ASSERT_TRUE(svr.is_valid());
  13878. svr.Get("/test", [](const Request &, Response &res) {
  13879. res.set_content("test", "text/plain");
  13880. });
  13881. auto port = svr.bind_to_any_port(HOST);
  13882. ASSERT_LT(0, port);
  13883. thread t = thread([&]() { svr.listen_after_bind(); });
  13884. auto se = detail::scope_exit([&] {
  13885. svr.stop();
  13886. t.join();
  13887. ASSERT_FALSE(svr.is_running());
  13888. });
  13889. svr.wait_until_ready();
  13890. SSLClient cli(HOST, port);
  13891. cli.set_connection_timeout(30);
  13892. cli.enable_server_hostname_verification(false);
  13893. // cert.pem is not trusted, so the handshake fails
  13894. ASSERT_FALSE(cli.Get("/test"));
  13895. cli.enable_server_certificate_verification(false);
  13896. auto res = cli.Get("/test");
  13897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13898. EXPECT_EQ(0, res.ssl_error());
  13899. EXPECT_EQ(0UL, res.ssl_backend_error());
  13900. }
  13901. // PEM memory-based constructor tests (works with all TLS backends).
  13902. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13903. // terminator after it.
  13904. void PemMemoryClientCertPresent(
  13905. const std::string &client_cert_file,
  13906. const std::string &client_private_key_file,
  13907. const std::string &client_encrypted_private_key_pass = std::string(),
  13908. bool exact_size = false) {
  13909. // Read PEM files into memory
  13910. std::string server_cert_pem, server_key_pem;
  13911. std::string client_ca_pem;
  13912. std::string client_cert_pem, client_key_pem;
  13913. read_file(SERVER_CERT_FILE, server_cert_pem);
  13914. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13915. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13916. read_file(client_cert_file, client_cert_pem);
  13917. read_file(client_private_key_file, client_key_pem);
  13918. std::list<std::vector<char>> exact_copies;
  13919. auto data = [&](const std::string &pem) -> const char * {
  13920. if (!exact_size) { return pem.c_str(); }
  13921. exact_copies.emplace_back(pem.begin(), pem.end());
  13922. return exact_copies.back().data();
  13923. };
  13924. // Create server with PEM memory
  13925. SSLServer::PemMemory server_pem = {
  13926. data(server_cert_pem),
  13927. server_cert_pem.size(),
  13928. data(server_key_pem),
  13929. server_key_pem.size(),
  13930. data(client_ca_pem),
  13931. client_ca_pem.size(),
  13932. nullptr // no password for server key
  13933. };
  13934. SSLServer svr(server_pem);
  13935. ASSERT_TRUE(svr.is_valid());
  13936. svr.Get("/test", [&](const Request &req, Response &res) {
  13937. res.set_content("test", "text/plain");
  13938. auto cert = req.peer_cert();
  13939. ASSERT_TRUE(static_cast<bool>(cert));
  13940. EXPECT_EQ("Common Name", cert.subject_cn());
  13941. });
  13942. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13943. auto se = detail::scope_exit([&] {
  13944. svr.stop();
  13945. t.join();
  13946. ASSERT_FALSE(svr.is_running());
  13947. });
  13948. svr.wait_until_ready();
  13949. // Create client with PEM memory
  13950. const char *password = client_encrypted_private_key_pass.empty()
  13951. ? nullptr
  13952. : client_encrypted_private_key_pass.c_str();
  13953. SSLClient::PemMemory client_pem = {
  13954. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13955. client_key_pem.size(), password};
  13956. SSLClient cli(HOST, PORT, client_pem);
  13957. cli.enable_server_certificate_verification(false);
  13958. cli.set_connection_timeout(30);
  13959. auto res = cli.Get("/test");
  13960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13961. ASSERT_EQ(StatusCode::OK_200, res->status);
  13962. }
  13963. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13964. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13965. }
  13966. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13967. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13968. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13969. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13970. }
  13971. // A server built from PEM memory with a client CA requires client certificates,
  13972. // also when the CA is a NUL-terminated string passed with a length of 0
  13973. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13974. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13975. read_file(SERVER_CERT_FILE, server_cert_pem);
  13976. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13977. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13978. SSLServer::PemMemory server_pem = {
  13979. server_cert_pem.c_str(),
  13980. server_cert_pem.size(),
  13981. server_key_pem.c_str(),
  13982. server_key_pem.size(),
  13983. client_ca_pem.c_str(),
  13984. client_ca_pem.size(),
  13985. nullptr // no password for server key
  13986. };
  13987. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13988. SCOPED_TRACE(client_ca_pem_len);
  13989. server_pem.client_ca_pem_len = client_ca_pem_len;
  13990. SSLServer svr(server_pem);
  13991. ASSERT_TRUE(svr.is_valid());
  13992. RejectsClientWithoutCert(svr);
  13993. }
  13994. // An empty CA fails to load instead of turning the check off
  13995. server_pem.client_ca_pem = "";
  13996. server_pem.client_ca_pem_len = 0;
  13997. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13998. }
  13999. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14000. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14001. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14002. true);
  14003. }
  14004. // A length shorter than the PEM cuts it short, so it no longer loads
  14005. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14006. std::string cert, key;
  14007. read_file(SERVER_CERT_FILE, cert);
  14008. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14009. for (auto cut_cert : {true, false}) {
  14010. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14011. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14012. SSLServer::PemMemory server_pem = {
  14013. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14014. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14015. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14016. key_len, nullptr};
  14017. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14018. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14019. key.c_str(), key_len, nullptr};
  14020. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14021. }
  14022. }
  14023. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14024. class NoListenSSLServer : public SSLServer {
  14025. public:
  14026. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14027. const char *client_ca_cert_file_path,
  14028. const char *client_ca_cert_dir_path = nullptr)
  14029. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14030. client_ca_cert_dir_path),
  14031. stop_(false) {}
  14032. std::atomic_bool stop_;
  14033. private:
  14034. bool process_and_close_socket(socket_t /*sock*/) override {
  14035. // Don't create SSL context
  14036. while (!stop_.load()) {
  14037. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14038. }
  14039. return true;
  14040. }
  14041. };
  14042. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14043. CLIENT_CA_CERT_FILE);
  14044. ASSERT_TRUE(svr.is_valid());
  14045. svr.Get("/test", [&](const Request &, Response &res) {
  14046. res.set_content("test", "text/plain");
  14047. });
  14048. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14049. auto se = detail::scope_exit([&] {
  14050. svr.stop_ = true;
  14051. svr.stop();
  14052. t.join();
  14053. ASSERT_FALSE(svr.is_running());
  14054. });
  14055. svr.wait_until_ready();
  14056. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14057. cli.enable_server_certificate_verification(false);
  14058. cli.set_connection_timeout(1);
  14059. auto res = cli.Get("/test");
  14060. ASSERT_TRUE(!res);
  14061. EXPECT_EQ(Error::SSLConnection, res.error());
  14062. // Timeout results in WantRead error code (maps to backend-specific value)
  14063. EXPECT_NE(0, res.ssl_error());
  14064. }
  14065. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14066. // Test SSLServer with client certificate verification using the standard
  14067. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14068. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14069. CLIENT_CA_CERT_DIR);
  14070. ASSERT_TRUE(svr.is_valid());
  14071. svr.Get("/test", [&](const Request &req, Response &res) {
  14072. res.set_content("test", "text/plain");
  14073. auto cert = req.peer_cert();
  14074. ASSERT_TRUE(static_cast<bool>(cert));
  14075. auto common_name = cert.subject_cn();
  14076. EXPECT_EQ("Common Name", common_name);
  14077. });
  14078. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14079. auto se = detail::scope_exit([&] {
  14080. svr.stop();
  14081. t.join();
  14082. ASSERT_FALSE(svr.is_running());
  14083. });
  14084. svr.wait_until_ready();
  14085. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14086. cli.enable_server_certificate_verification(false);
  14087. cli.set_connection_timeout(30);
  14088. auto res = cli.Get("/test");
  14089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14090. ASSERT_EQ(StatusCode::OK_200, res->status);
  14091. }
  14092. // Test verify_hostname on every backend: a host is named by a SAN only
  14093. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14094. using namespace httplib::tls;
  14095. // We need a running server to test against
  14096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14097. ASSERT_TRUE(svr.is_valid());
  14098. svr.Get("/test", [](const Request &, Response &res) {
  14099. res.set_content("ok", "text/plain");
  14100. });
  14101. thread t([&]() { svr.listen(HOST, PORT); });
  14102. auto se = detail::scope_exit([&] {
  14103. svr.stop();
  14104. t.join();
  14105. });
  14106. svr.wait_until_ready();
  14107. bool verify_callback_called = false;
  14108. bool verify_result_wrong = false;
  14109. SSLClient cli(HOST, PORT);
  14110. cli.enable_server_certificate_verification(true);
  14111. cli.set_ca_cert_path(CA_CERT_FILE);
  14112. cli.set_connection_timeout(5);
  14113. // Note: Test certificate has CN="Common Name", not "localhost"
  14114. bool verify_result_cn = false;
  14115. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14116. verify_callback_called = true;
  14117. if (!ctx.cert) return false;
  14118. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14119. verify_result_cn = ctx.check_hostname("Common Name");
  14120. // Test 2: wrong hostname should not match
  14121. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14122. return true; // Accept for the purpose of this test
  14123. });
  14124. auto res = cli.Get("/test");
  14125. // The request may succeed or fail depending on cert configuration
  14126. // but the callback should have been called
  14127. ASSERT_TRUE(verify_callback_called)
  14128. << "Verify callback should have been called";
  14129. EXPECT_FALSE(verify_result_cn)
  14130. << "verify_hostname must not match the certificate CN (no SAN)";
  14131. // Wrong hostname should not match
  14132. EXPECT_FALSE(verify_result_wrong)
  14133. << "verify_hostname should not match 'wronghost.example.com'";
  14134. }
  14135. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14136. // backend verifies it.
  14137. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14138. // Certificate CN is "localhost" and it carries no SAN.
  14139. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14140. ASSERT_TRUE(svr.is_valid());
  14141. svr.Get("/test", [](const Request &, Response &res) {
  14142. res.set_content("ok", "text/plain");
  14143. });
  14144. auto port = svr.bind_to_any_port(HOST);
  14145. thread t([&]() { svr.listen_after_bind(); });
  14146. auto se = detail::scope_exit([&] {
  14147. svr.stop();
  14148. t.join();
  14149. });
  14150. svr.wait_until_ready();
  14151. SSLClient cli("localhost", port);
  14152. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14153. cli.enable_server_certificate_verification(true);
  14154. cli.set_connection_timeout(5);
  14155. auto res = cli.Get("/test");
  14156. ASSERT_FALSE(res);
  14157. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14158. // The same certificate is accepted once host name verification is off, so the
  14159. // failure above is the host name and not the chain.
  14160. cli.enable_server_hostname_verification(false);
  14161. res = cli.Get("/test");
  14162. ASSERT_TRUE(res) << to_string(res.error());
  14163. EXPECT_EQ(StatusCode::OK_200, res->status);
  14164. }
  14165. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14166. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14167. // X509_check_ip behavior and must hold for every backend.
  14168. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14169. using namespace httplib::tls;
  14170. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14171. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14172. ASSERT_TRUE(svr.is_valid());
  14173. svr.Get("/test", [](const Request &, Response &res) {
  14174. res.set_content("ok", "text/plain");
  14175. });
  14176. thread t([&]() { svr.listen(HOST, PORT); });
  14177. auto se = detail::scope_exit([&] {
  14178. svr.stop();
  14179. t.join();
  14180. });
  14181. svr.wait_until_ready();
  14182. bool verify_callback_called = false;
  14183. bool ip_matched_via_cn = true;
  14184. SSLClient cli(HOST, PORT);
  14185. cli.enable_server_certificate_verification(true);
  14186. cli.set_ca_cert_path(CA_CERT_FILE);
  14187. cli.set_connection_timeout(5);
  14188. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14189. verify_callback_called = true;
  14190. if (!ctx.cert) return false;
  14191. // The IP appears only in the CN, so it must NOT be accepted.
  14192. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14193. return true; // Accept for the purpose of this test
  14194. });
  14195. cli.Get("/test");
  14196. ASSERT_TRUE(verify_callback_called)
  14197. << "Verify callback should have been called";
  14198. EXPECT_FALSE(ip_matched_via_cn)
  14199. << "An IP host must not be authenticated via the certificate CN";
  14200. }
  14201. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14202. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14203. using namespace httplib::tls;
  14204. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14205. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14206. ASSERT_TRUE(svr.is_valid());
  14207. svr.Get("/test", [](const Request &, Response &res) {
  14208. res.set_content("ok", "text/plain");
  14209. });
  14210. thread t([&]() { svr.listen(HOST, PORT); });
  14211. auto se = detail::scope_exit([&] {
  14212. svr.stop();
  14213. t.join();
  14214. });
  14215. svr.wait_until_ready();
  14216. bool verify_callback_called = false;
  14217. bool san_matched = false;
  14218. bool wrong_ipv6_matched = true;
  14219. bool cn_ipv6_matched = true;
  14220. SSLClient cli(HOST, PORT);
  14221. cli.enable_server_certificate_verification(true);
  14222. cli.set_ca_cert_path(CA_CERT_FILE);
  14223. cli.set_connection_timeout(5);
  14224. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14225. verify_callback_called = true;
  14226. if (!ctx.cert) return false;
  14227. // Matches the IPv6 iPAddress SAN.
  14228. san_matched = ctx.check_hostname("2001:db8::1");
  14229. // A different IPv6 address must not match.
  14230. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14231. // "::1" lives only in the CN, so it must not be accepted.
  14232. cn_ipv6_matched = ctx.check_hostname("::1");
  14233. return true; // Accept for the purpose of this test
  14234. });
  14235. cli.Get("/test");
  14236. ASSERT_TRUE(verify_callback_called)
  14237. << "Verify callback should have been called";
  14238. EXPECT_TRUE(san_matched)
  14239. << "verify_hostname should match an IPv6 iPAddress SAN";
  14240. EXPECT_FALSE(wrong_ipv6_matched)
  14241. << "verify_hostname should not match a non-matching IPv6 address";
  14242. EXPECT_FALSE(cn_ipv6_matched)
  14243. << "An IPv6 host must not be authenticated via the certificate CN";
  14244. }
  14245. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14246. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14247. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14248. using namespace httplib::tls;
  14249. // SANs: DNS:a.zz, IP:42.46.122.122
  14250. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14251. ASSERT_TRUE(svr.is_valid());
  14252. svr.Get("/test", [](const Request &, Response &res) {
  14253. res.set_content("ok", "text/plain");
  14254. });
  14255. auto port = svr.bind_to_any_port(HOST);
  14256. thread t([&]() { svr.listen_after_bind(); });
  14257. auto se = detail::scope_exit([&] {
  14258. svr.stop();
  14259. t.join();
  14260. });
  14261. svr.wait_until_ready();
  14262. bool verify_callback_called = false;
  14263. bool dns_san_matched = false;
  14264. bool ip_san_matched = false;
  14265. bool ip_matched_via_dns_san = true;
  14266. bool dns_matched_via_ip_san = true;
  14267. bool cn_matched_next_to_dns_san = true;
  14268. SSLClient cli(HOST, port);
  14269. cli.enable_server_certificate_verification(true);
  14270. cli.set_ca_cert_path(CA_CERT_FILE);
  14271. cli.set_connection_timeout(5);
  14272. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14273. verify_callback_called = true;
  14274. if (!ctx.cert) return false;
  14275. dns_san_matched = ctx.check_hostname("a.zz");
  14276. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14277. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14278. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14279. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14280. return true; // Accept for the purpose of this test
  14281. });
  14282. cli.Get("/test");
  14283. ASSERT_TRUE(verify_callback_called)
  14284. << "Verify callback should have been called";
  14285. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14286. EXPECT_TRUE(ip_san_matched)
  14287. << "verify_hostname should match an iPAddress SAN";
  14288. EXPECT_FALSE(ip_matched_via_dns_san)
  14289. << "An IP host must not be authenticated via a dNSName SAN";
  14290. EXPECT_FALSE(dns_matched_via_ip_san)
  14291. << "A DNS host must not be authenticated via an iPAddress SAN";
  14292. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14293. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14294. }
  14295. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14296. // "www.*.example.test" names one host and not every host under example.test.
  14297. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14298. using namespace httplib::tls;
  14299. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14300. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14301. ASSERT_TRUE(svr.is_valid());
  14302. svr.Get("/test", [](const Request &, Response &res) {
  14303. res.set_content("ok", "text/plain");
  14304. });
  14305. auto port = svr.bind_to_any_port(HOST);
  14306. thread t([&]() { svr.listen_after_bind(); });
  14307. auto se = detail::scope_exit([&] {
  14308. svr.stop();
  14309. t.join();
  14310. });
  14311. svr.wait_until_ready();
  14312. bool verify_callback_called = false;
  14313. bool leftmost_wildcard_matched = false;
  14314. bool wildcard_spanned_labels = true;
  14315. bool inner_wildcard_matched = true;
  14316. SSLClient cli(HOST, port);
  14317. cli.enable_server_certificate_verification(true);
  14318. cli.set_ca_cert_path(CA_CERT_FILE);
  14319. cli.set_connection_timeout(5);
  14320. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14321. verify_callback_called = true;
  14322. if (!ctx.cert) return false;
  14323. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14324. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14325. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14326. return true; // Accept for the purpose of this test
  14327. });
  14328. cli.Get("/test");
  14329. ASSERT_TRUE(verify_callback_called)
  14330. << "Verify callback should have been called";
  14331. EXPECT_TRUE(leftmost_wildcard_matched)
  14332. << "A leftmost wildcard should match a single label";
  14333. EXPECT_FALSE(wildcard_spanned_labels)
  14334. << "A wildcard label must not match more than one label";
  14335. EXPECT_FALSE(inner_wildcard_matched)
  14336. << "A wildcard outside the leftmost label must not be honoured";
  14337. }
  14338. // sans() must report each SAN entry under its own type.
  14339. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14340. using namespace httplib::tls;
  14341. // SANs: DNS:a.zz, IP:42.46.122.122
  14342. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14343. ASSERT_TRUE(svr.is_valid());
  14344. svr.Get("/test", [](const Request &, Response &res) {
  14345. res.set_content("ok", "text/plain");
  14346. });
  14347. auto port = svr.bind_to_any_port(HOST);
  14348. thread t([&]() { svr.listen_after_bind(); });
  14349. auto se = detail::scope_exit([&] {
  14350. svr.stop();
  14351. t.join();
  14352. });
  14353. svr.wait_until_ready();
  14354. bool verify_callback_called = false;
  14355. std::vector<SanEntry> sans;
  14356. SSLClient cli(HOST, port);
  14357. cli.enable_server_certificate_verification(true);
  14358. cli.set_ca_cert_path(CA_CERT_FILE);
  14359. cli.set_connection_timeout(5);
  14360. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14361. verify_callback_called = true;
  14362. if (!ctx.cert) return false;
  14363. sans = ctx.sans();
  14364. return true; // Accept for the purpose of this test
  14365. });
  14366. cli.Get("/test");
  14367. ASSERT_TRUE(verify_callback_called)
  14368. << "Verify callback should have been called";
  14369. auto has_san = [&](SanType type, const std::string &value) {
  14370. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14371. return san.type == type && san.value == value;
  14372. });
  14373. };
  14374. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14375. << "sans() should report the dNSName SAN";
  14376. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14377. << "sans() should report the iPAddress SAN";
  14378. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14379. << "sans() must not report the dNSName SAN as an address";
  14380. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14381. << "sans() must not report the iPAddress SAN as a DNS name";
  14382. }
  14383. #endif
  14384. // mbedTLS-specific callback constructor test
  14385. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14386. #ifdef CPPHTTPLIB_SSL_ENABLED
  14387. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14389. ASSERT_TRUE(svr.is_valid());
  14390. // Set up a handler to verify client certificate is present
  14391. bool client_cert_verified = false;
  14392. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14393. // Verify that client certificate was provided
  14394. client_cert_verified = true;
  14395. res.set_content("success", "text/plain");
  14396. });
  14397. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14398. auto se = detail::scope_exit([&] {
  14399. svr.stop();
  14400. t.join();
  14401. ASSERT_FALSE(svr.is_running());
  14402. });
  14403. svr.wait_until_ready();
  14404. // Client with certificate
  14405. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14406. cli.enable_server_certificate_verification(false);
  14407. cli.set_connection_timeout(30);
  14408. auto res = cli.Get("/test");
  14409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14410. ASSERT_EQ(StatusCode::OK_200, res->status);
  14411. ASSERT_TRUE(client_cert_verified);
  14412. EXPECT_EQ("success", res->body);
  14413. }
  14414. #endif
  14415. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14416. // backends
  14417. #ifdef CPPHTTPLIB_SSL_ENABLED
  14418. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14419. using namespace httplib::tls;
  14420. // Test that when client CA cert file is provided,
  14421. // the server properly requests and validates client certificates
  14422. // Create a server with client authentication
  14423. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14424. ASSERT_TRUE(svr.is_valid());
  14425. bool handler_called = false;
  14426. svr.Get("/test", [&](const Request &req, Response &res) {
  14427. handler_called = true;
  14428. // Verify that a client certificate was provided
  14429. auto cert = req.peer_cert();
  14430. ASSERT_TRUE(static_cast<bool>(cert));
  14431. // Get the issuer name
  14432. std::string issuer_str = cert.issuer_name();
  14433. ASSERT_FALSE(issuer_str.empty());
  14434. // The client certificate should be issued by our test CA
  14435. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14436. res.set_content("authenticated", "text/plain");
  14437. });
  14438. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14439. auto se = detail::scope_exit([&] {
  14440. svr.stop();
  14441. t.join();
  14442. ASSERT_FALSE(svr.is_running());
  14443. });
  14444. svr.wait_until_ready();
  14445. // Connect with a client certificate issued by the CA
  14446. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14447. cli.enable_server_certificate_verification(false);
  14448. cli.set_connection_timeout(30);
  14449. auto res = cli.Get("/test");
  14450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14451. ASSERT_EQ(StatusCode::OK_200, res->status);
  14452. ASSERT_TRUE(handler_called);
  14453. EXPECT_EQ("authenticated", res->body);
  14454. }
  14455. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14456. using namespace httplib::tls;
  14457. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14458. ASSERT_TRUE(svr.is_valid());
  14459. svr.Get("/test", [](const Request &, Response &res) {
  14460. res.set_content("ok", "text/plain");
  14461. });
  14462. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14463. auto se = detail::scope_exit([&] {
  14464. svr.stop();
  14465. t.join();
  14466. });
  14467. svr.wait_until_ready();
  14468. SSLClient cli(HOST, PORT);
  14469. cli.enable_server_certificate_verification(false);
  14470. cli.set_connection_timeout(30);
  14471. bool cert_checked = false;
  14472. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14473. if (ctx.cert) {
  14474. auto sans = ctx.sans();
  14475. // Test certificate may or may not have SANs - just verify the API
  14476. // works If SANs exist, verify the types are valid
  14477. for (const auto &san : sans) {
  14478. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14479. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14480. san.type == SanType::OTHER);
  14481. EXPECT_FALSE(san.value.empty());
  14482. }
  14483. cert_checked = true;
  14484. }
  14485. return true;
  14486. });
  14487. auto res = cli.Get("/test");
  14488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14489. EXPECT_TRUE(cert_checked);
  14490. }
  14491. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14492. using namespace httplib::tls;
  14493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14494. ASSERT_TRUE(svr.is_valid());
  14495. svr.Get("/test", [](const Request &, Response &res) {
  14496. res.set_content("ok", "text/plain");
  14497. });
  14498. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14499. auto se = detail::scope_exit([&] {
  14500. svr.stop();
  14501. t.join();
  14502. });
  14503. svr.wait_until_ready();
  14504. SSLClient cli(HOST, PORT);
  14505. cli.enable_server_certificate_verification(false);
  14506. cli.set_connection_timeout(30);
  14507. bool validity_checked = false;
  14508. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14509. if (ctx.cert) {
  14510. time_t not_before = 0, not_after = 0;
  14511. bool result = ctx.validity(not_before, not_after);
  14512. EXPECT_TRUE(result);
  14513. // Verify that not_before < now < not_after for a valid cert
  14514. time_t now = time(nullptr);
  14515. EXPECT_LT(not_before, now);
  14516. EXPECT_GT(not_after, now);
  14517. validity_checked = true;
  14518. }
  14519. return true;
  14520. });
  14521. auto res = cli.Get("/test");
  14522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14523. EXPECT_TRUE(validity_checked);
  14524. }
  14525. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14526. using namespace httplib::tls;
  14527. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14528. ASSERT_TRUE(svr.is_valid());
  14529. svr.Get("/test", [](const Request &, Response &res) {
  14530. res.set_content("ok", "text/plain");
  14531. });
  14532. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14533. auto se = detail::scope_exit([&] {
  14534. svr.stop();
  14535. t.join();
  14536. });
  14537. svr.wait_until_ready();
  14538. SSLClient cli(HOST, PORT);
  14539. cli.enable_server_certificate_verification(false);
  14540. cli.set_connection_timeout(30);
  14541. bool serial_checked = false;
  14542. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14543. if (ctx.cert) {
  14544. std::string serial = ctx.serial();
  14545. EXPECT_FALSE(serial.empty());
  14546. // Serial should be a hex string
  14547. for (char c : serial) {
  14548. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14549. (c >= 'a' && c <= 'f'));
  14550. }
  14551. serial_checked = true;
  14552. }
  14553. return true;
  14554. });
  14555. auto res = cli.Get("/test");
  14556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14557. EXPECT_TRUE(serial_checked);
  14558. }
  14559. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14560. // Test 1: Valid CA file - no error should be recorded
  14561. {
  14562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14563. CLIENT_CA_CERT_FILE);
  14564. ASSERT_TRUE(svr.is_valid());
  14565. // With valid setup, last_ssl_error should be 0
  14566. EXPECT_EQ(0, svr.ssl_last_error());
  14567. }
  14568. // Test 2: Invalid CA file content
  14569. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14570. {
  14571. // Create a temporary file with completely invalid content
  14572. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14573. {
  14574. std::ofstream ofs(temp_invalid_ca);
  14575. ofs << "This is not a certificate file at all\n";
  14576. ofs << "Just plain text content\n";
  14577. }
  14578. // Create server with invalid CA file
  14579. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14580. // Clean up temporary file
  14581. std::remove(temp_invalid_ca);
  14582. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14583. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14584. // Note: SSL_CTX_load_verify_locations typically fails first,
  14585. // but our error handling code path is still exercised
  14586. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14587. }
  14588. }
  14589. TEST(VerifyCallbackTest, VerifyContextFields) {
  14590. using namespace httplib::tls;
  14591. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14592. ASSERT_TRUE(svr.is_valid());
  14593. svr.Get("/test", [](const Request &, Response &res) {
  14594. res.set_content("ok", "text/plain");
  14595. });
  14596. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14597. auto se = detail::scope_exit([&] {
  14598. svr.stop();
  14599. t.join();
  14600. });
  14601. svr.wait_until_ready();
  14602. SSLClient cli(HOST, PORT);
  14603. cli.enable_server_certificate_verification(false);
  14604. cli.set_connection_timeout(30);
  14605. int callback_count = 0;
  14606. bool saw_leaf_cert = false;
  14607. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14608. if (ctx.cert) {
  14609. callback_count++;
  14610. // We should see at least one certificate (the leaf)
  14611. std::string cn = ctx.subject_cn();
  14612. if (!cn.empty()) { saw_leaf_cert = true; }
  14613. // Verify context fields are populated
  14614. EXPECT_NE(ctx.session, nullptr);
  14615. EXPECT_GE(ctx.depth, 0);
  14616. }
  14617. return true;
  14618. });
  14619. auto res = cli.Get("/test");
  14620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14621. EXPECT_GT(callback_count, 0);
  14622. EXPECT_TRUE(saw_leaf_cert);
  14623. }
  14624. // A verifier that accepts runs alongside the built-in verification, and is the
  14625. // only check once that is turned off.
  14626. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14627. using namespace httplib::tls;
  14628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14629. ASSERT_TRUE(svr.is_valid());
  14630. svr.Get("/test", [](const Request &, Response &res) {
  14631. res.set_content("ok", "text/plain");
  14632. });
  14633. auto port = svr.bind_to_any_port(HOST);
  14634. thread t([&]() { svr.listen_after_bind(); });
  14635. auto se = detail::scope_exit([&] {
  14636. svr.stop();
  14637. t.join();
  14638. });
  14639. svr.wait_until_ready();
  14640. SSLClient cli(HOST, port);
  14641. cli.enable_server_hostname_verification(false);
  14642. auto calls = 0;
  14643. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14644. calls++;
  14645. return true;
  14646. });
  14647. // cert.pem is not trusted
  14648. auto res = cli.Get("/test");
  14649. ASSERT_FALSE(res);
  14650. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14651. EXPECT_GT(calls, 0);
  14652. cli.enable_server_certificate_verification(false);
  14653. res = cli.Get("/test");
  14654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14655. EXPECT_EQ("ok", res->body);
  14656. }
  14657. // A verifier belongs to the client that set it, not to the thread that set it.
  14658. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14659. using namespace httplib::tls;
  14660. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14661. ASSERT_TRUE(svr.is_valid());
  14662. svr.Get("/test", [](const Request &, Response &res) {
  14663. res.set_content("ok", "text/plain");
  14664. });
  14665. auto port = svr.bind_to_any_port(HOST);
  14666. thread t([&]() { svr.listen_after_bind(); });
  14667. auto se = detail::scope_exit([&] {
  14668. svr.stop();
  14669. t.join();
  14670. });
  14671. svr.wait_until_ready();
  14672. auto rejecting_calls = 0;
  14673. SSLClient rejecting(HOST, port);
  14674. rejecting.enable_server_certificate_verification(false);
  14675. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14676. rejecting_calls++;
  14677. return false;
  14678. });
  14679. auto accepting_calls = 0;
  14680. SSLClient accepting(HOST, port);
  14681. accepting.enable_server_certificate_verification(false);
  14682. // Set on another thread than the requests below.
  14683. thread([&]() {
  14684. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14685. accepting_calls++;
  14686. return true;
  14687. });
  14688. }).join();
  14689. // Requested on another thread than the verifier was set on.
  14690. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14691. EXPECT_GT(rejecting_calls, 0);
  14692. auto res = accepting.Get("/test");
  14693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14694. EXPECT_GT(accepting_calls, 0);
  14695. }
  14696. // A verifier replaced while a handshake runs it lives until it returns.
  14697. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14698. using namespace httplib::tls;
  14699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14700. ASSERT_TRUE(svr.is_valid());
  14701. svr.Get("/test", [](const Request &, Response &res) {
  14702. res.set_content("ok", "text/plain");
  14703. });
  14704. auto port = svr.bind_to_any_port(HOST);
  14705. thread t([&]() { svr.listen_after_bind(); });
  14706. auto se = detail::scope_exit([&] {
  14707. svr.stop();
  14708. t.join();
  14709. });
  14710. svr.wait_until_ready();
  14711. SSLClient cli(HOST, port);
  14712. cli.enable_server_certificate_verification(false);
  14713. std::promise<void> entered;
  14714. std::promise<void> replaced;
  14715. auto replaced_future = replaced.get_future();
  14716. auto first_call = true;
  14717. // Long enough to live on the heap
  14718. std::string expected(64, 'v');
  14719. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14720. if (first_call) {
  14721. first_call = false;
  14722. entered.set_value();
  14723. replaced_future.wait();
  14724. }
  14725. return expected == std::string(64, 'v');
  14726. });
  14727. thread request([&]() {
  14728. auto res = cli.Get("/test");
  14729. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14730. });
  14731. entered.get_future().wait();
  14732. cli.set_server_certificate_verifier(
  14733. [](const VerifyContext &) { return true; });
  14734. replaced.set_value();
  14735. request.join();
  14736. }
  14737. // VerifyContext::session is the same handle the other tls:: functions take.
  14738. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14739. using namespace httplib::tls;
  14740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14741. ASSERT_TRUE(svr.is_valid());
  14742. svr.Get("/test", [](const Request &, Response &res) {
  14743. res.set_content("ok", "text/plain");
  14744. });
  14745. auto port = svr.bind_to_any_port(HOST);
  14746. thread t([&]() { svr.listen_after_bind(); });
  14747. auto se = detail::scope_exit([&] {
  14748. svr.stop();
  14749. t.join();
  14750. });
  14751. svr.wait_until_ready();
  14752. SSLClient cli(HOST, port);
  14753. cli.enable_server_certificate_verification(false);
  14754. session_t verifier_session = nullptr;
  14755. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14756. verifier_session = ctx.session;
  14757. return true;
  14758. });
  14759. session_t session_verifier_session = nullptr;
  14760. cli.set_session_verifier([&](session_t session) {
  14761. session_verifier_session = session;
  14762. return SSLVerifierResponse::NoDecisionMade;
  14763. });
  14764. auto res = cli.Get("/test");
  14765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14766. EXPECT_NE(nullptr, verifier_session);
  14767. EXPECT_EQ(session_verifier_session, verifier_session);
  14768. }
  14769. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14770. using httplib::tls::TlsError;
  14771. // Test that verify_error_to_string returns empty for success
  14772. std::string success_str = TlsError::verify_error_to_string(0);
  14773. EXPECT_TRUE(success_str.empty());
  14774. // Test that verify_error_to_string returns non-empty for error codes
  14775. // Using a common error code (certificate expired)
  14776. std::string error_str =
  14777. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14778. EXPECT_FALSE(error_str.empty());
  14779. }
  14780. TEST(SessionVerifierTest, CertificateAccepted) {
  14781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14782. ASSERT_TRUE(svr.is_valid());
  14783. svr.Get("/test", [](const Request &, Response &res) {
  14784. res.set_content("ok", "text/plain");
  14785. });
  14786. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14787. auto se = detail::scope_exit([&] {
  14788. svr.stop();
  14789. t.join();
  14790. });
  14791. svr.wait_until_ready();
  14792. SSLClient cli(HOST, PORT);
  14793. cli.enable_server_certificate_verification(false);
  14794. cli.set_connection_timeout(30);
  14795. bool callback_called = false;
  14796. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14797. EXPECT_NE(session, nullptr);
  14798. callback_called = true;
  14799. return SSLVerifierResponse::CertificateAccepted;
  14800. });
  14801. auto res = cli.Get("/test");
  14802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14803. EXPECT_EQ(200, res->status);
  14804. EXPECT_TRUE(callback_called);
  14805. }
  14806. TEST(SessionVerifierTest, CertificateRejected) {
  14807. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14808. ASSERT_TRUE(svr.is_valid());
  14809. svr.Get("/test", [](const Request &, Response &res) {
  14810. res.set_content("ok", "text/plain");
  14811. });
  14812. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14813. auto se = detail::scope_exit([&] {
  14814. svr.stop();
  14815. t.join();
  14816. });
  14817. svr.wait_until_ready();
  14818. SSLClient cli(HOST, PORT);
  14819. cli.enable_server_certificate_verification(false);
  14820. cli.set_connection_timeout(30);
  14821. bool callback_called = false;
  14822. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14823. EXPECT_NE(session, nullptr);
  14824. callback_called = true;
  14825. return SSLVerifierResponse::CertificateRejected;
  14826. });
  14827. auto res = cli.Get("/test");
  14828. EXPECT_FALSE(res);
  14829. EXPECT_TRUE(callback_called);
  14830. }
  14831. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14832. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14833. ASSERT_TRUE(svr.is_valid());
  14834. svr.Get("/test", [](const Request &, Response &res) {
  14835. res.set_content("ok", "text/plain");
  14836. });
  14837. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14838. auto se = detail::scope_exit([&] {
  14839. svr.stop();
  14840. t.join();
  14841. });
  14842. svr.wait_until_ready();
  14843. // NoDecisionMade with verification disabled should succeed (no default check)
  14844. SSLClient cli(HOST, PORT);
  14845. cli.enable_server_certificate_verification(false);
  14846. cli.set_connection_timeout(30);
  14847. bool callback_called = false;
  14848. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14849. EXPECT_NE(session, nullptr);
  14850. callback_called = true;
  14851. return SSLVerifierResponse::NoDecisionMade;
  14852. });
  14853. auto res = cli.Get("/test");
  14854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14855. EXPECT_EQ(200, res->status);
  14856. EXPECT_TRUE(callback_called);
  14857. }
  14858. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14859. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14860. ASSERT_TRUE(svr.is_valid());
  14861. svr.Get("/test", [](const Request &, Response &res) {
  14862. res.set_content("ok", "text/plain");
  14863. });
  14864. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14865. auto se = detail::scope_exit([&] {
  14866. svr.stop();
  14867. t.join();
  14868. });
  14869. svr.wait_until_ready();
  14870. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14871. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14872. // so we only check that the request fails, not whether the callback was
  14873. // called.
  14874. SSLClient cli(HOST, PORT);
  14875. cli.enable_server_certificate_verification(true);
  14876. cli.set_connection_timeout(30);
  14877. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14878. EXPECT_NE(session, nullptr);
  14879. return SSLVerifierResponse::NoDecisionMade;
  14880. });
  14881. auto res = cli.Get("/test");
  14882. EXPECT_FALSE(res);
  14883. }
  14884. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14885. // Test SSL server using PemMemory constructor with client CA certificates
  14886. // Read PEM files
  14887. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14888. read_file(SERVER_CERT_FILE, server_cert_pem);
  14889. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14890. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14891. // Create SSLServer with PemMemory constructor including client CA
  14892. SSLServer::PemMemory server_pem = {
  14893. server_cert_pem.c_str(),
  14894. server_cert_pem.size(),
  14895. server_key_pem.c_str(),
  14896. server_key_pem.size(),
  14897. client_ca_pem.c_str(),
  14898. client_ca_pem.size(),
  14899. nullptr // no password for server key
  14900. };
  14901. SSLServer svr(server_pem);
  14902. ASSERT_TRUE(svr.is_valid());
  14903. // No SSL error should be recorded for valid setup
  14904. EXPECT_EQ(0, svr.ssl_last_error());
  14905. // Set up server endpoints
  14906. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14907. res.set_content("ok", "text/plain");
  14908. });
  14909. // Start server in a thread
  14910. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14911. svr.wait_until_ready();
  14912. // Connect with client certificate (using constructor with paths)
  14913. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14914. cli.enable_server_certificate_verification(false);
  14915. auto res = cli.Get("/test-pem-ca");
  14916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14917. EXPECT_EQ(200, res->status);
  14918. EXPECT_EQ("ok", res->body);
  14919. svr.stop();
  14920. server_thread.join();
  14921. }
  14922. #endif
  14923. #ifdef _WIN32
  14924. TEST(CleanupTest, WSACleanup) {
  14925. int ret = WSACleanup();
  14926. ASSERT_EQ(0, ret);
  14927. }
  14928. #endif
  14929. #ifndef CPPHTTPLIB_SSL_ENABLED
  14930. TEST(NoSSLSupport, SimpleInterface) {
  14931. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14932. }
  14933. #endif
  14934. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14935. TEST(InvalidScheme, SimpleInterface) {
  14936. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14937. }
  14938. #endif
  14939. TEST(NoScheme, SimpleInterface) {
  14940. Client cli("yahoo.com:80");
  14941. ASSERT_TRUE(cli.is_valid());
  14942. }
  14943. TEST(SendAPI, SimpleInterface_Online) {
  14944. Client cli("http://yahoo.com");
  14945. Request req;
  14946. req.method = "GET";
  14947. req.path = "/";
  14948. auto res = cli.send(req);
  14949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14950. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14951. }
  14952. TEST(SendAPI, WithParamsInRequest) {
  14953. Server svr;
  14954. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14955. EXPECT_TRUE(req.has_param("test"));
  14956. EXPECT_EQ("test_value", req.get_param_value("test"));
  14957. });
  14958. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14959. auto se = detail::scope_exit([&] {
  14960. svr.stop();
  14961. t.join();
  14962. ASSERT_FALSE(svr.is_running());
  14963. });
  14964. svr.wait_until_ready();
  14965. Client cli(HOST, PORT);
  14966. {
  14967. Request req;
  14968. req.method = "GET";
  14969. req.path = "/";
  14970. req.params.emplace("test", "test_value");
  14971. auto res = cli.send(req);
  14972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14973. }
  14974. {
  14975. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14977. }
  14978. }
  14979. TEST(ClientImplMethods, GetSocketTest) {
  14980. httplib::Server svr;
  14981. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14982. res.status = StatusCode::OK_200;
  14983. });
  14984. auto port = svr.bind_to_any_port("127.0.0.1");
  14985. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14986. auto se = detail::scope_exit([&] {
  14987. svr.stop();
  14988. thread.join();
  14989. ASSERT_FALSE(svr.is_running());
  14990. });
  14991. svr.wait_until_ready();
  14992. {
  14993. httplib::Client cli("127.0.0.1", port);
  14994. cli.set_keep_alive(true);
  14995. // Use the behavior of cpp-httplib of opening the connection
  14996. // only when the first request happens. If that changes,
  14997. // this test would be obsolete.
  14998. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14999. // This also implicitly tests the server. But other tests would fail much
  15000. // earlier than this one to be considered.
  15001. auto res = cli.Get("/");
  15002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15003. EXPECT_EQ(StatusCode::OK_200, res->status);
  15004. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15005. }
  15006. }
  15007. #ifdef CPPHTTPLIB_SSL_ENABLED
  15008. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15009. Client cli("http://yahoo.com");
  15010. auto res = cli.Get("/");
  15011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15012. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15013. cli.set_follow_location(true);
  15014. res = cli.Get("/");
  15015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15016. EXPECT_EQ(StatusCode::OK_200, res->status);
  15017. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15018. }
  15019. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15020. Client cli("https://yahoo.com");
  15021. auto res = cli.Get("/");
  15022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15023. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15024. cli.set_follow_location(true);
  15025. res = cli.Get("/");
  15026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15027. EXPECT_EQ(StatusCode::OK_200, res->status);
  15028. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15029. }
  15030. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15031. Client cli("https://yahoo.com");
  15032. auto res = cli.Get("/");
  15033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15034. ASSERT_FALSE(!res);
  15035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15036. ASSERT_FALSE(res == nullptr);
  15037. ASSERT_TRUE(res != nullptr);
  15038. EXPECT_EQ(Error::Success, res.error());
  15039. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15040. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15041. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15042. cli.set_follow_location(true);
  15043. res = cli.Get("/");
  15044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15045. EXPECT_EQ(Error::Success, res.error());
  15046. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15047. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15048. EXPECT_EQ(StatusCode::OK_200, res->status);
  15049. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15050. }
  15051. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15052. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15053. Client cli("https://cdnjs.cloudflare.com");
  15054. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15055. Headers{{"Accept-Encoding", "br"}});
  15056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15057. EXPECT_EQ(StatusCode::OK_200, res->status);
  15058. EXPECT_EQ(287630U, res->body.size());
  15059. EXPECT_EQ("application/javascript; charset=utf-8",
  15060. res->get_header_value("Content-Type"));
  15061. }
  15062. #endif
  15063. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15064. #undef REDIR_HOST // Silence compiler warning
  15065. #define REDIR_HOST "https://httpbingo.org"
  15066. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15067. Client cli(REDIR_HOST);
  15068. cli.set_follow_location(true);
  15069. auto res =
  15070. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15072. EXPECT_EQ(StatusCode::OK_200, res->status);
  15073. }
  15074. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15075. Client cli(REDIR_HOST);
  15076. cli.set_follow_location(true);
  15077. Params params;
  15078. params.emplace("url", "http://example.com");
  15079. params.emplace("status_code", "302");
  15080. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15082. EXPECT_EQ(StatusCode::OK_200, res->status);
  15083. }
  15084. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15085. Client cli(REDIR_HOST);
  15086. cli.set_follow_location(true);
  15087. Params params;
  15088. params.emplace("url", "http://example.com");
  15089. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15091. EXPECT_EQ(StatusCode::OK_200, res->status);
  15092. }
  15093. TEST(HttpToHttpsRedirectTest, CertFile) {
  15094. auto ssl_port = PORT + 1;
  15095. Server svr;
  15096. ASSERT_TRUE(svr.is_valid());
  15097. svr.Get("/index", [&](const Request &, Response &res) {
  15098. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15099. "/index");
  15100. svr.stop();
  15101. });
  15102. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15103. ASSERT_TRUE(ssl_svr.is_valid());
  15104. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15105. res.set_content("test", "text/plain");
  15106. ssl_svr.stop();
  15107. });
  15108. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15109. thread t2 =
  15110. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15111. auto se = detail::scope_exit([&] {
  15112. t2.join();
  15113. t.join();
  15114. ASSERT_FALSE(svr.is_running());
  15115. });
  15116. svr.wait_until_ready();
  15117. ssl_svr.wait_until_ready();
  15118. Client cli("127.0.0.1", PORT);
  15119. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15120. cli.enable_server_certificate_verification(true);
  15121. cli.set_follow_location(true);
  15122. cli.set_connection_timeout(30);
  15123. auto res = cli.Get("/index");
  15124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15125. ASSERT_EQ(StatusCode::OK_200, res->status);
  15126. }
  15127. TEST(SSLClientRedirectTest, CertFile) {
  15128. auto ssl_port = PORT + 1;
  15129. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15130. ASSERT_TRUE(ssl_svr1.is_valid());
  15131. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15132. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15133. "/index");
  15134. ssl_svr1.stop();
  15135. });
  15136. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15137. ASSERT_TRUE(ssl_svr2.is_valid());
  15138. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15139. res.set_content("test", "text/plain");
  15140. ssl_svr2.stop();
  15141. });
  15142. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15143. thread t2 =
  15144. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15145. auto se = detail::scope_exit([&] {
  15146. t2.join();
  15147. t.join();
  15148. ASSERT_FALSE(ssl_svr1.is_running());
  15149. });
  15150. ssl_svr1.wait_until_ready();
  15151. ssl_svr2.wait_until_ready();
  15152. SSLClient cli("127.0.0.1", PORT);
  15153. std::string cert;
  15154. read_file(SERVER_CERT2_FILE, cert);
  15155. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15156. cli.enable_server_certificate_verification(true);
  15157. cli.set_follow_location(true);
  15158. cli.set_connection_timeout(30);
  15159. auto res = cli.Get("/index");
  15160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15161. ASSERT_EQ(StatusCode::OK_200, res->status);
  15162. }
  15163. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15164. // another port, so the client follows it with a new client.
  15165. static Result GetThroughTlsRedirectToDifferentPort(
  15166. const std::function<void(SSLClient &)> &setup,
  15167. const char *target_cert = SERVER_CERT2_FILE,
  15168. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15169. auto ssl_port = PORT + 1;
  15170. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15171. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15172. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15173. "/index");
  15174. });
  15175. SSLServer ssl_svr2(target_cert, target_key);
  15176. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15177. res.set_content("test", "text/plain");
  15178. });
  15179. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15180. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15181. auto se = detail::scope_exit([&] {
  15182. ssl_svr2.stop();
  15183. ssl_svr1.stop();
  15184. t2.join();
  15185. t.join();
  15186. });
  15187. ssl_svr1.wait_until_ready();
  15188. ssl_svr2.wait_until_ready();
  15189. SSLClient cli("127.0.0.1", PORT);
  15190. cli.set_follow_location(true);
  15191. cli.set_connection_timeout(30);
  15192. setup(cli);
  15193. return cli.Get("/index");
  15194. }
  15195. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15196. auto calls = 0;
  15197. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15198. cli.enable_server_certificate_verification(false);
  15199. // Accept the first server only.
  15200. cli.set_session_verifier([&](tls::session_t) {
  15201. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15202. : SSLVerifierResponse::CertificateRejected;
  15203. });
  15204. });
  15205. ASSERT_FALSE(res);
  15206. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15207. EXPECT_EQ(2, calls);
  15208. }
  15209. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15210. std::string pinned;
  15211. auto res = GetThroughTlsRedirectToDifferentPort(
  15212. [&](SSLClient &cli) {
  15213. cli.enable_server_certificate_verification(false);
  15214. // Pin the first certificate seen.
  15215. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15216. if (pinned.empty()) { pinned = ctx.serial(); }
  15217. return ctx.serial() == pinned;
  15218. });
  15219. },
  15220. // A certificate other than the first server's.
  15221. SERVER_CERT_FILE);
  15222. EXPECT_FALSE(res);
  15223. EXPECT_FALSE(pinned.empty());
  15224. }
  15225. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15226. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15227. std::string cert;
  15228. read_file(SERVER_CERT2_FILE, cert);
  15229. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15230. });
  15231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15232. EXPECT_EQ(StatusCode::OK_200, res->status);
  15233. }
  15234. // The target's certificate is signed by the root CA, which the first server's
  15235. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15236. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15237. auto res = GetThroughTlsRedirectToDifferentPort(
  15238. [](SSLClient &cli) {
  15239. std::string root_ca, cert;
  15240. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15241. read_file(SERVER_CERT2_FILE, cert);
  15242. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15243. cli.load_ca_cert_store(cert.data(), cert.size());
  15244. cli.enable_server_hostname_verification(false);
  15245. },
  15246. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15248. EXPECT_EQ(StatusCode::OK_200, res->status);
  15249. }
  15250. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15251. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15252. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15253. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15254. auto res = GetThroughTlsRedirectToDifferentPort(
  15255. [](SSLClient &cli) {
  15256. std::string root_ca, cert;
  15257. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15258. read_file(SERVER_CERT2_FILE, cert);
  15259. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15260. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15261. cli.enable_server_hostname_verification(false);
  15262. },
  15263. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15264. ASSERT_FALSE(res);
  15265. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15266. }
  15267. #endif
  15268. #endif
  15269. #ifdef CPPHTTPLIB_SSL_ENABLED
  15270. // Test that set_ca_cert_store() skips system certs (consistent with
  15271. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15272. // should be trusted - system certs should NOT be loaded.
  15273. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15274. // Load a specific cert that is NOT a system CA cert
  15275. std::string cert;
  15276. read_file(SERVER_CERT2_FILE, cert);
  15277. SSLClient cli("google.com");
  15278. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15279. cli.enable_server_certificate_verification(true);
  15280. // This should FAIL because:
  15281. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15282. // 2. System certs should NOT be loaded when custom store is set
  15283. // If system certs WERE loaded, this would succeed
  15284. auto res = cli.Get("/");
  15285. ASSERT_FALSE(res);
  15286. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15287. }
  15288. // Same as above, but through the native store handle path. Regression test:
  15289. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15290. // merged system certs into the user-provided store.
  15291. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15292. std::string cert;
  15293. read_file(SERVER_CERT2_FILE, cert);
  15294. SSLClient cli("google.com");
  15295. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15296. cli.enable_server_certificate_verification(true);
  15297. auto res = cli.Get("/");
  15298. ASSERT_FALSE(res);
  15299. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15300. }
  15301. // A custom store set via the native handle must still verify a server whose
  15302. // cert it does contain.
  15303. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15304. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15305. ASSERT_TRUE(svr.is_valid());
  15306. svr.Get("/test", [&](const Request &, Response &res) {
  15307. res.set_content("test", "text/plain");
  15308. });
  15309. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15310. auto se = detail::scope_exit([&] {
  15311. svr.stop();
  15312. t.join();
  15313. ASSERT_FALSE(svr.is_running());
  15314. });
  15315. svr.wait_until_ready();
  15316. SSLClient cli("127.0.0.1", PORT);
  15317. std::string cert;
  15318. read_file(SERVER_CERT2_FILE, cert);
  15319. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15320. cli.enable_server_certificate_verification(true);
  15321. cli.set_connection_timeout(30);
  15322. auto res = cli.Get("/test");
  15323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15324. ASSERT_EQ(StatusCode::OK_200, res->status);
  15325. }
  15326. // CA certs loaded through the universal Client must be transferred to the
  15327. // client created internally for following an HTTPS redirect. Regression test:
  15328. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15329. // the CA data for redirect transfer.
  15330. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15331. auto ssl_port = PORT + 1;
  15332. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15333. ASSERT_TRUE(ssl_svr1.is_valid());
  15334. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15335. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15336. "/index");
  15337. });
  15338. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15339. ASSERT_TRUE(ssl_svr2.is_valid());
  15340. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15341. res.set_content("test", "text/plain");
  15342. });
  15343. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15344. thread t2 =
  15345. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15346. auto se = detail::scope_exit([&] {
  15347. ssl_svr2.stop();
  15348. ssl_svr1.stop();
  15349. t2.join();
  15350. t.join();
  15351. ASSERT_FALSE(ssl_svr1.is_running());
  15352. });
  15353. ssl_svr1.wait_until_ready();
  15354. ssl_svr2.wait_until_ready();
  15355. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15356. std::string cert;
  15357. read_file(SERVER_CERT2_FILE, cert);
  15358. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15359. cli.enable_server_certificate_verification(true);
  15360. cli.set_follow_location(true);
  15361. cli.set_connection_timeout(30);
  15362. auto res = cli.Get("/index");
  15363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15364. ASSERT_EQ(StatusCode::OK_200, res->status);
  15365. }
  15366. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15367. // so a host signed by a system CA verifies even though a custom CA is set
  15368. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15369. std::string cert;
  15370. read_file(SERVER_CERT2_FILE, cert);
  15371. SSLClient cli("google.com");
  15372. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15373. cli.enable_system_ca(true);
  15374. cli.enable_server_certificate_verification(true);
  15375. auto res = cli.Get("/");
  15376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15377. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15378. }
  15379. // The custom CA remains effective when combined with the system CA
  15380. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15381. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15382. ASSERT_TRUE(svr.is_valid());
  15383. svr.Get("/test", [&](const Request &, Response &res) {
  15384. res.set_content("test", "text/plain");
  15385. });
  15386. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15387. auto se = detail::scope_exit([&] {
  15388. svr.stop();
  15389. t.join();
  15390. ASSERT_FALSE(svr.is_running());
  15391. });
  15392. svr.wait_until_ready();
  15393. SSLClient cli("127.0.0.1", PORT);
  15394. std::string cert;
  15395. read_file(SERVER_CERT2_FILE, cert);
  15396. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15397. cli.enable_system_ca(true);
  15398. cli.enable_server_certificate_verification(true);
  15399. cli.set_connection_timeout(30);
  15400. auto res = cli.Get("/test");
  15401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15402. ASSERT_EQ(StatusCode::OK_200, res->status);
  15403. }
  15404. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15405. // skip chain verification entirely (only the certificate identity was
  15406. // checked), so a server presenting an untrusted certificate with a matching
  15407. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15408. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15409. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15410. ASSERT_TRUE(svr.is_valid());
  15411. svr.Get("/test", [&](const Request &, Response &res) {
  15412. res.set_content("test", "text/plain");
  15413. });
  15414. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15415. auto se = detail::scope_exit([&] {
  15416. svr.stop();
  15417. t.join();
  15418. ASSERT_FALSE(svr.is_running());
  15419. });
  15420. svr.wait_until_ready();
  15421. SSLClient cli("127.0.0.1", PORT);
  15422. std::string cert;
  15423. // A trusted CA that did not sign the server certificate. The server cert
  15424. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15425. // this connection.
  15426. read_file(CLIENT_CA_CERT_FILE, cert);
  15427. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15428. cli.enable_server_certificate_verification(true);
  15429. cli.set_connection_timeout(30);
  15430. auto res = cli.Get("/test");
  15431. ASSERT_FALSE(res);
  15432. }
  15433. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15434. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15435. // CA that failed to come through fails verification instead of trusting them.
  15436. // (wolfSSL does not list the system CAs it loaded.)
  15437. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15438. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15439. ASSERT_TRUE(svr.is_valid());
  15440. auto port = svr.bind_to_any_port("127.0.0.1");
  15441. ASSERT_LT(0, port);
  15442. thread t = thread([&] { svr.listen_after_bind(); });
  15443. auto se = detail::scope_exit([&] {
  15444. svr.stop();
  15445. t.join();
  15446. ASSERT_FALSE(svr.is_running());
  15447. });
  15448. svr.wait_until_ready();
  15449. // The CAs a client trusts once its first request has loaded them
  15450. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15451. Client cli("https://127.0.0.1:" + std::to_string(port));
  15452. setup(cli);
  15453. cli.Get("/");
  15454. return tls::get_ca_names(cli.tls_context()).size();
  15455. };
  15456. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15457. EXPECT_EQ(0u,
  15458. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15459. }
  15460. #endif
  15461. // A TLS setting changed between requests applies to the next one, not just to
  15462. // the next connection
  15463. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15464. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15465. ASSERT_TRUE(svr.is_valid());
  15466. svr.Get("/", [](const Request &req, Response &res) {
  15467. res.set_content(std::to_string(req.remote_port), "text/plain");
  15468. });
  15469. auto port = svr.bind_to_any_port("127.0.0.1");
  15470. ASSERT_LT(0, port);
  15471. thread t = thread([&] { svr.listen_after_bind(); });
  15472. auto se = detail::scope_exit([&] {
  15473. svr.stop();
  15474. t.join();
  15475. ASSERT_FALSE(svr.is_running());
  15476. });
  15477. svr.wait_until_ready();
  15478. SSLClient cli("127.0.0.1", port);
  15479. cli.set_keep_alive(true);
  15480. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15481. cli.enable_server_certificate_verification(false);
  15482. // The port the request went out from, so a new one means a new connection
  15483. auto client_port = [&] {
  15484. auto res = cli.Get("/");
  15485. return res ? res->body : std::string();
  15486. };
  15487. auto last = client_port();
  15488. ASSERT_FALSE(last.empty());
  15489. // Setting a value it already has keeps the connection
  15490. cli.enable_server_certificate_verification(false);
  15491. cli.enable_server_hostname_verification(true);
  15492. EXPECT_EQ(last, client_port());
  15493. cli.enable_server_certificate_verification(true);
  15494. auto res = cli.Get("/");
  15495. EXPECT_FALSE(res);
  15496. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15497. std::string ca;
  15498. read_file(SERVER_CERT2_FILE, ca);
  15499. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15500. last = client_port();
  15501. ASSERT_FALSE(last.empty());
  15502. std::vector<std::function<void()>> setters = {
  15503. [&] { cli.enable_server_hostname_verification(false); },
  15504. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15505. [&] {
  15506. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15507. },
  15508. [&] {
  15509. cli.set_server_certificate_verifier(
  15510. [](const tls::VerifyContext &) { return true; });
  15511. },
  15512. [&] {
  15513. cli.set_session_verifier(
  15514. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15515. },
  15516. };
  15517. for (const auto &setter : setters) {
  15518. setter();
  15519. auto next = client_port();
  15520. ASSERT_FALSE(next.empty());
  15521. EXPECT_NE(last, next);
  15522. last = next;
  15523. }
  15524. cli.set_session_verifier(
  15525. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15526. auto handle = cli.open_stream("GET", "/");
  15527. EXPECT_FALSE(handle.is_valid());
  15528. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15529. }
  15530. // A PEM given to create_ca_store() needs no NUL after it
  15531. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15532. std::string pem;
  15533. read_file(SERVER_CERT2_FILE, pem);
  15534. auto buf = pem + "X";
  15535. auto store = tls::create_ca_store(buf.data(), pem.size());
  15536. EXPECT_TRUE(store != nullptr);
  15537. SSLClient cli("localhost");
  15538. cli.set_ca_cert_store(store);
  15539. }
  15540. // enable_system_ca(false) prevents system CA loading entirely
  15541. TEST(SSLClientTest, DisableSystemCa_Online) {
  15542. SSLClient cli("google.com");
  15543. cli.enable_system_ca(false);
  15544. cli.enable_server_certificate_verification(true);
  15545. auto res = cli.Get("/");
  15546. ASSERT_FALSE(res);
  15547. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15548. // itself when the CA chain is empty
  15549. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15550. res.error() == Error::SSLConnection);
  15551. }
  15552. // The universal Client forwards enable_system_ca()
  15553. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15554. std::string cert;
  15555. read_file(SERVER_CERT2_FILE, cert);
  15556. Client cli("https://google.com");
  15557. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15558. cli.enable_system_ca(true);
  15559. cli.enable_server_certificate_verification(true);
  15560. auto res = cli.Get("/");
  15561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15562. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15563. }
  15564. // The system CA policy must carry over to the client created internally for
  15565. // following a cross-host HTTPS redirect
  15566. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15567. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15568. ASSERT_TRUE(svr.is_valid());
  15569. svr.Get("/index", [&](const Request &, Response &res) {
  15570. res.set_redirect("https://www.google.com/");
  15571. });
  15572. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15573. auto se = detail::scope_exit([&] {
  15574. svr.stop();
  15575. t.join();
  15576. ASSERT_FALSE(svr.is_running());
  15577. });
  15578. svr.wait_until_ready();
  15579. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15580. std::string cert;
  15581. read_file(SERVER_CERT2_FILE, cert);
  15582. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15583. cli.enable_system_ca(true);
  15584. cli.enable_server_certificate_verification(true);
  15585. cli.set_follow_location(true);
  15586. cli.set_connection_timeout(30);
  15587. // Receiving any response proves the redirect client completed the TLS
  15588. // handshake with a system-CA-signed host
  15589. auto res = cli.Get("/index");
  15590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15591. }
  15592. TEST(MultipartFormDataTest, LargeData) {
  15593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15594. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15595. const ContentReader &content_reader) {
  15596. if (req.is_multipart_form_data()) {
  15597. std::vector<FormData> items;
  15598. content_reader(
  15599. [&](const FormData &file) {
  15600. items.push_back(file);
  15601. return true;
  15602. },
  15603. [&](const char *data, size_t data_length) {
  15604. items.back().content.append(data, data_length);
  15605. return true;
  15606. });
  15607. EXPECT_TRUE(std::string(items[0].name) == "document");
  15608. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15609. EXPECT_TRUE(items[0].filename == "2MB_data");
  15610. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15611. EXPECT_TRUE(items[1].name == "hello");
  15612. EXPECT_TRUE(items[1].content == "world");
  15613. EXPECT_TRUE(items[1].filename == "");
  15614. EXPECT_TRUE(items[1].content_type == "");
  15615. } else {
  15616. std::string body;
  15617. content_reader([&](const char *data, size_t data_length) {
  15618. body.append(data, data_length);
  15619. return true;
  15620. });
  15621. }
  15622. });
  15623. auto port = svr.bind_to_any_port(HOST);
  15624. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15625. auto se = detail::scope_exit([&] {
  15626. svr.stop();
  15627. t.join();
  15628. ASSERT_FALSE(svr.is_running());
  15629. });
  15630. svr.wait_until_ready();
  15631. {
  15632. std::string data(1024 * 1024 * 2, '.');
  15633. std::stringstream buffer;
  15634. buffer << data;
  15635. SSLClient cli(HOST, port);
  15636. cli.enable_server_certificate_verification(false);
  15637. UploadFormDataItems items{
  15638. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15639. {"hello", "world", "", ""},
  15640. };
  15641. auto res = cli.Post("/post", items);
  15642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15643. ASSERT_EQ(StatusCode::OK_200, res->status);
  15644. }
  15645. }
  15646. TEST(MultipartFormDataTest, DataProviderItems) {
  15647. std::random_device seed_gen;
  15648. std::mt19937 random(seed_gen());
  15649. std::string rand1;
  15650. rand1.resize(1000);
  15651. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15652. std::string rand2;
  15653. rand2.resize(3000);
  15654. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15655. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15656. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15657. const ContentReader &content_reader) {
  15658. ASSERT_FALSE(req.is_multipart_form_data());
  15659. std::string body;
  15660. content_reader([&](const char *data, size_t data_length) {
  15661. body.append(data, data_length);
  15662. return true;
  15663. });
  15664. EXPECT_EQ(body, "");
  15665. });
  15666. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15667. const ContentReader &content_reader) {
  15668. ASSERT_TRUE(req.is_multipart_form_data());
  15669. std::vector<FormData> items;
  15670. content_reader(
  15671. [&](const FormData &file) {
  15672. items.push_back(file);
  15673. return true;
  15674. },
  15675. [&](const char *data, size_t data_length) {
  15676. items.back().content.append(data, data_length);
  15677. return true;
  15678. });
  15679. ASSERT_TRUE(items.size() == 2);
  15680. EXPECT_EQ(std::string(items[0].name), "name1");
  15681. EXPECT_EQ(items[0].content, "Testing123");
  15682. EXPECT_EQ(items[0].filename, "filename1");
  15683. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15684. EXPECT_EQ(items[1].name, "name2");
  15685. EXPECT_EQ(items[1].content, "Testing456");
  15686. EXPECT_EQ(items[1].filename, "");
  15687. EXPECT_EQ(items[1].content_type, "");
  15688. });
  15689. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15690. const ContentReader &content_reader) {
  15691. ASSERT_TRUE(req.is_multipart_form_data());
  15692. std::vector<FormData> items;
  15693. content_reader(
  15694. [&](const FormData &file) {
  15695. items.push_back(file);
  15696. return true;
  15697. },
  15698. [&](const char *data, size_t data_length) {
  15699. items.back().content.append(data, data_length);
  15700. return true;
  15701. });
  15702. ASSERT_TRUE(items.size() == 2);
  15703. EXPECT_EQ(items[0].name, "name3");
  15704. EXPECT_EQ(items[0].content, rand1);
  15705. EXPECT_EQ(items[0].filename, "filename3");
  15706. EXPECT_EQ(items[0].content_type, "");
  15707. EXPECT_EQ(items[1].name, "name4");
  15708. EXPECT_EQ(items[1].content, rand2);
  15709. EXPECT_EQ(items[1].filename, "filename4");
  15710. EXPECT_EQ(items[1].content_type, "");
  15711. });
  15712. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15713. const ContentReader &content_reader) {
  15714. ASSERT_TRUE(req.is_multipart_form_data());
  15715. std::vector<FormData> items;
  15716. content_reader(
  15717. [&](const FormData &file) {
  15718. items.push_back(file);
  15719. return true;
  15720. },
  15721. [&](const char *data, size_t data_length) {
  15722. items.back().content.append(data, data_length);
  15723. return true;
  15724. });
  15725. ASSERT_TRUE(items.size() == 4);
  15726. EXPECT_EQ(std::string(items[0].name), "name1");
  15727. EXPECT_EQ(items[0].content, "Testing123");
  15728. EXPECT_EQ(items[0].filename, "filename1");
  15729. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15730. EXPECT_EQ(items[1].name, "name2");
  15731. EXPECT_EQ(items[1].content, "Testing456");
  15732. EXPECT_EQ(items[1].filename, "");
  15733. EXPECT_EQ(items[1].content_type, "");
  15734. EXPECT_EQ(items[2].name, "name3");
  15735. EXPECT_EQ(items[2].content, rand1);
  15736. EXPECT_EQ(items[2].filename, "filename3");
  15737. EXPECT_EQ(items[2].content_type, "");
  15738. EXPECT_EQ(items[3].name, "name4");
  15739. EXPECT_EQ(items[3].content, rand2);
  15740. EXPECT_EQ(items[3].filename, "filename4");
  15741. EXPECT_EQ(items[3].content_type, "");
  15742. });
  15743. auto port = svr.bind_to_any_port("localhost");
  15744. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15745. auto se = detail::scope_exit([&] {
  15746. svr.stop();
  15747. t.join();
  15748. ASSERT_FALSE(svr.is_running());
  15749. });
  15750. svr.wait_until_ready();
  15751. {
  15752. SSLClient cli("localhost", port);
  15753. cli.enable_server_certificate_verification(false);
  15754. UploadFormDataItems items{
  15755. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15756. {"name2", "Testing456", "", ""}, // not a file
  15757. };
  15758. {
  15759. auto res = cli.Post("/post-none", {}, {}, {});
  15760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15761. ASSERT_EQ(StatusCode::OK_200, res->status);
  15762. }
  15763. FormDataProviderItems providers;
  15764. {
  15765. auto res =
  15766. cli.Post("/post-items", {}, items, providers); // empty providers
  15767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15768. ASSERT_EQ(StatusCode::OK_200, res->status);
  15769. }
  15770. providers.push_back({"name3",
  15771. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15772. // test the offset is given correctly at each step
  15773. if (!offset)
  15774. sink.os.write(rand1.data(), 30);
  15775. else if (offset == 30)
  15776. sink.os.write(rand1.data() + 30, 300);
  15777. else if (offset == 330)
  15778. sink.os.write(rand1.data() + 330, 670);
  15779. else if (offset == rand1.size())
  15780. sink.done();
  15781. return true;
  15782. },
  15783. "filename3",
  15784. {}});
  15785. providers.push_back({"name4",
  15786. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15787. // test the offset is given correctly at each step
  15788. if (!offset)
  15789. sink.os.write(rand2.data(), 2000);
  15790. else if (offset == 2000)
  15791. sink.os.write(rand2.data() + 2000, 1);
  15792. else if (offset == 2001)
  15793. sink.os.write(rand2.data() + 2001, 999);
  15794. else if (offset == rand2.size())
  15795. sink.done();
  15796. return true;
  15797. },
  15798. "filename4",
  15799. {}});
  15800. {
  15801. auto res = cli.Post("/post-providers", {}, {}, providers);
  15802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15803. ASSERT_EQ(StatusCode::OK_200, res->status);
  15804. }
  15805. {
  15806. auto res = cli.Post("/post-both", {}, items, providers);
  15807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15808. ASSERT_EQ(StatusCode::OK_200, res->status);
  15809. }
  15810. }
  15811. }
  15812. TEST(MultipartFormDataTest, BadHeader) {
  15813. Server svr;
  15814. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15815. res.set_content("ok", "text/plain");
  15816. });
  15817. thread t = thread([&] { svr.listen(HOST, PORT); });
  15818. auto se = detail::scope_exit([&] {
  15819. svr.stop();
  15820. t.join();
  15821. ASSERT_FALSE(svr.is_running());
  15822. });
  15823. svr.wait_until_ready();
  15824. const std::string body =
  15825. "This is the preamble. It is to be ignored, though it\r\n"
  15826. "is a handy place for composition agents to include an\r\n"
  15827. "explanatory note to non-MIME conformant readers.\r\n"
  15828. "\r\n"
  15829. "\r\n"
  15830. "--simple boundary\r\n"
  15831. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15832. ": BAD...\r\n"
  15833. "\r\n"
  15834. "value1\r\n"
  15835. "--simple boundary\r\n"
  15836. "Content-Disposition: form-data; name=\"field2\"; "
  15837. "filename=\"example.txt\"\r\n"
  15838. "\r\n"
  15839. "value2\r\n"
  15840. "--simple boundary--\r\n"
  15841. "This is the epilogue. It is also to be ignored.\r\n";
  15842. std::string content_type =
  15843. R"(multipart/form-data; boundary="simple boundary")";
  15844. Client cli(HOST, PORT);
  15845. auto res = cli.Post("/post", body, content_type.c_str());
  15846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15847. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15848. }
  15849. TEST(MultipartFormDataTest, WithPreamble) {
  15850. Server svr;
  15851. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15852. res.set_content("ok", "text/plain");
  15853. });
  15854. thread t = thread([&] { svr.listen(HOST, PORT); });
  15855. auto se = detail::scope_exit([&] {
  15856. svr.stop();
  15857. t.join();
  15858. ASSERT_FALSE(svr.is_running());
  15859. });
  15860. svr.wait_until_ready();
  15861. const std::string body =
  15862. "This is the preamble. It is to be ignored, though it\r\n"
  15863. "is a handy place for composition agents to include an\r\n"
  15864. "explanatory note to non-MIME conformant readers.\r\n"
  15865. "\r\n"
  15866. "\r\n"
  15867. "--simple boundary\r\n"
  15868. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15869. "\r\n"
  15870. "value1\r\n"
  15871. "--simple boundary\r\n"
  15872. "Content-Disposition: form-data; name=\"field2\"; "
  15873. "filename=\"example.txt\"\r\n"
  15874. "\r\n"
  15875. "value2\r\n"
  15876. "--simple boundary--\r\n"
  15877. "This is the epilogue. It is also to be ignored.\r\n";
  15878. std::string content_type =
  15879. R"(multipart/form-data; boundary="simple boundary")";
  15880. Client cli(HOST, PORT);
  15881. auto res = cli.Post("/post", body, content_type.c_str());
  15882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15883. EXPECT_EQ(StatusCode::OK_200, res->status);
  15884. }
  15885. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15886. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15887. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15888. const ContentReader &content_reader) {
  15889. if (req.is_multipart_form_data()) {
  15890. std::vector<FormData> items;
  15891. content_reader(
  15892. [&](const FormData &file) {
  15893. items.push_back(file);
  15894. return true;
  15895. },
  15896. [&](const char *data, size_t data_length) {
  15897. items.back().content.append(data, data_length);
  15898. return true;
  15899. });
  15900. EXPECT_TRUE(std::string(items[0].name) == "document");
  15901. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15902. EXPECT_TRUE(items[0].filename == "2MB_data");
  15903. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15904. EXPECT_TRUE(items[1].name == "hello");
  15905. EXPECT_TRUE(items[1].content == "world");
  15906. EXPECT_TRUE(items[1].filename == "");
  15907. EXPECT_TRUE(items[1].content_type == "");
  15908. } else {
  15909. std::string body;
  15910. content_reader([&](const char *data, size_t data_length) {
  15911. body.append(data, data_length);
  15912. return true;
  15913. });
  15914. }
  15915. });
  15916. auto port = svr.bind_to_any_port("localhost");
  15917. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15918. auto se = detail::scope_exit([&] {
  15919. svr.stop();
  15920. t.join();
  15921. ASSERT_FALSE(svr.is_running());
  15922. });
  15923. svr.wait_until_ready();
  15924. {
  15925. std::string data(1024 * 1024 * 2, '.');
  15926. std::stringstream buffer;
  15927. buffer << data;
  15928. SSLClient cli("localhost", port);
  15929. cli.enable_server_certificate_verification(false);
  15930. UploadFormDataItems items{
  15931. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15932. {"hello", "world", "", ""},
  15933. };
  15934. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15936. ASSERT_EQ(StatusCode::OK_200, res->status);
  15937. }
  15938. }
  15939. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15940. std::string data(1024 * 1024 * 2, '&');
  15941. std::stringstream buffer;
  15942. buffer << data;
  15943. Client cli("https://localhost:8080");
  15944. UploadFormDataItems items{
  15945. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15946. {"hello", "world", "", ""},
  15947. };
  15948. for (const char &c : " \t\r\n") {
  15949. auto res =
  15950. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15951. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15952. ASSERT_FALSE(res);
  15953. }
  15954. }
  15955. TEST(MultipartFormDataTest, PutFormData) {
  15956. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15957. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15958. const ContentReader &content_reader) {
  15959. if (req.is_multipart_form_data()) {
  15960. std::vector<FormData> items;
  15961. content_reader(
  15962. [&](const FormData &file) {
  15963. items.push_back(file);
  15964. return true;
  15965. },
  15966. [&](const char *data, size_t data_length) {
  15967. items.back().content.append(data, data_length);
  15968. return true;
  15969. });
  15970. EXPECT_TRUE(std::string(items[0].name) == "document");
  15971. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15972. EXPECT_TRUE(items[0].filename == "2MB_data");
  15973. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15974. EXPECT_TRUE(items[1].name == "hello");
  15975. EXPECT_TRUE(items[1].content == "world");
  15976. EXPECT_TRUE(items[1].filename == "");
  15977. EXPECT_TRUE(items[1].content_type == "");
  15978. } else {
  15979. std::string body;
  15980. content_reader([&](const char *data, size_t data_length) {
  15981. body.append(data, data_length);
  15982. return true;
  15983. });
  15984. }
  15985. });
  15986. auto port = svr.bind_to_any_port("localhost");
  15987. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15988. auto se = detail::scope_exit([&] {
  15989. svr.stop();
  15990. t.join();
  15991. ASSERT_FALSE(svr.is_running());
  15992. });
  15993. svr.wait_until_ready();
  15994. {
  15995. std::string data(1024 * 1024 * 2, '&');
  15996. std::stringstream buffer;
  15997. buffer << data;
  15998. SSLClient cli("localhost", port);
  15999. cli.enable_server_certificate_verification(false);
  16000. UploadFormDataItems items{
  16001. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16002. {"hello", "world", "", ""},
  16003. };
  16004. auto res = cli.Put("/put", items);
  16005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16006. ASSERT_EQ(StatusCode::OK_200, res->status);
  16007. }
  16008. }
  16009. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16011. svr.Put("/put_customboundary",
  16012. [&](const Request &req, const Response & /*res*/,
  16013. const ContentReader &content_reader) {
  16014. if (req.is_multipart_form_data()) {
  16015. std::vector<FormData> items;
  16016. content_reader(
  16017. [&](const FormData &file) {
  16018. items.push_back(file);
  16019. return true;
  16020. },
  16021. [&](const char *data, size_t data_length) {
  16022. items.back().content.append(data, data_length);
  16023. return true;
  16024. });
  16025. EXPECT_TRUE(std::string(items[0].name) == "document");
  16026. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16027. EXPECT_TRUE(items[0].filename == "2MB_data");
  16028. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16029. EXPECT_TRUE(items[1].name == "hello");
  16030. EXPECT_TRUE(items[1].content == "world");
  16031. EXPECT_TRUE(items[1].filename == "");
  16032. EXPECT_TRUE(items[1].content_type == "");
  16033. } else {
  16034. std::string body;
  16035. content_reader([&](const char *data, size_t data_length) {
  16036. body.append(data, data_length);
  16037. return true;
  16038. });
  16039. }
  16040. });
  16041. auto port = svr.bind_to_any_port("localhost");
  16042. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16043. auto se = detail::scope_exit([&] {
  16044. svr.stop();
  16045. t.join();
  16046. ASSERT_FALSE(svr.is_running());
  16047. });
  16048. svr.wait_until_ready();
  16049. {
  16050. std::string data(1024 * 1024 * 2, '&');
  16051. std::stringstream buffer;
  16052. buffer << data;
  16053. SSLClient cli("localhost", port);
  16054. cli.enable_server_certificate_verification(false);
  16055. UploadFormDataItems items{
  16056. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16057. {"hello", "world", "", ""},
  16058. };
  16059. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16061. ASSERT_EQ(StatusCode::OK_200, res->status);
  16062. }
  16063. }
  16064. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16065. std::string data(1024 * 1024 * 2, '&');
  16066. std::stringstream buffer;
  16067. buffer << data;
  16068. Client cli("https://localhost:8080");
  16069. cli.enable_server_certificate_verification(false);
  16070. UploadFormDataItems items{
  16071. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16072. {"hello", "world", "", ""},
  16073. };
  16074. for (const char &c : " \t\r\n") {
  16075. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16076. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16077. ASSERT_FALSE(res);
  16078. }
  16079. }
  16080. TEST(MultipartFormDataTest, AlternateFilename) {
  16081. auto handled = false;
  16082. Server svr;
  16083. svr.Post("/test", [&](const Request &req, Response &res) {
  16084. ASSERT_EQ(2u, req.form.files.size());
  16085. ASSERT_EQ(1u, req.form.fields.size());
  16086. // Test files
  16087. const auto &file1 = req.form.get_file("file1");
  16088. ASSERT_EQ("file1", file1.name);
  16089. ASSERT_EQ("A.txt", file1.filename);
  16090. ASSERT_EQ("text/plain", file1.content_type);
  16091. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16092. const auto &file2 = req.form.get_file("file2");
  16093. ASSERT_EQ("file2", file2.name);
  16094. ASSERT_EQ("a.html", file2.filename);
  16095. ASSERT_EQ("text/html", file2.content_type);
  16096. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16097. file2.content);
  16098. // Test text field
  16099. const auto &text = req.form.get_field("text");
  16100. ASSERT_EQ("text default", text);
  16101. res.set_content("ok", "text/plain");
  16102. handled = true;
  16103. });
  16104. thread t = thread([&] { svr.listen(HOST, PORT); });
  16105. auto se = detail::scope_exit([&] {
  16106. svr.stop();
  16107. t.join();
  16108. ASSERT_FALSE(svr.is_running());
  16109. ASSERT_TRUE(handled);
  16110. });
  16111. svr.wait_until_ready();
  16112. auto req = "POST /test HTTP/1.1\r\n"
  16113. "Host: localhost\r\n"
  16114. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16115. "Content-Length: 399\r\n"
  16116. "\r\n"
  16117. "----------\r\n"
  16118. "Content-Disposition: form-data; name=\"text\"\r\n"
  16119. "\r\n"
  16120. "text default\r\n"
  16121. "----------\r\n"
  16122. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16123. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16124. "Content-Type: text/plain\r\n"
  16125. "\r\n"
  16126. "Content of a.txt.\r\n"
  16127. "\r\n"
  16128. "----------\r\n"
  16129. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16130. "\"a.html\"\r\n"
  16131. "Content-Type: text/html\r\n"
  16132. "\r\n"
  16133. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16134. "\r\n"
  16135. "------------\r\n";
  16136. ASSERT_TRUE(send_request(1, req));
  16137. }
  16138. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16139. auto handled = false;
  16140. Server svr;
  16141. svr.Post("/test", [&](const Request &req, Response &res) {
  16142. // Case-insensitive "utf-8''" prefix with a long value
  16143. const auto &file = req.form.get_file("file1");
  16144. ASSERT_EQ("file1", file.name);
  16145. // 8000 chars exercises both the Content-Disposition parser and the
  16146. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16147. // Prior to the fix, std::regex_match on this header would cause O(N)
  16148. // stack recursion in libstdc++, leading to SIGSEGV.
  16149. std::string expected_filename(8000, 'A');
  16150. ASSERT_EQ(expected_filename, file.filename);
  16151. res.set_content("ok", "text/plain");
  16152. handled = true;
  16153. });
  16154. thread t = thread([&] { svr.listen(HOST, PORT); });
  16155. auto se = detail::scope_exit([&] {
  16156. svr.stop();
  16157. t.join();
  16158. ASSERT_FALSE(svr.is_running());
  16159. ASSERT_TRUE(handled);
  16160. });
  16161. svr.wait_until_ready();
  16162. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16163. // Regression test for GHSA-qq6v-r583-3h69
  16164. std::string long_filename(8000, 'A');
  16165. std::string body = "----------\r\n"
  16166. "Content-Disposition: form-data; name=\"file1\"; "
  16167. "filename*=\"Utf-8''" +
  16168. long_filename +
  16169. "\"\r\n"
  16170. "\r\n"
  16171. "hello\r\n"
  16172. "------------\r\n";
  16173. auto req = "POST /test HTTP/1.1\r\n"
  16174. "Host: localhost\r\n"
  16175. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16176. "Content-Length: " +
  16177. std::to_string(body.size()) + "\r\n\r\n" + body;
  16178. ASSERT_TRUE(send_request(1, req));
  16179. }
  16180. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16181. auto handled = false;
  16182. Server svr;
  16183. svr.Post("/test", [&](const Request &req, Response &) {
  16184. ASSERT_EQ(2u, req.form.fields.size());
  16185. const auto &text1 = req.form.get_field("text1");
  16186. ASSERT_EQ("text1", text1);
  16187. const auto &text2 = req.form.get_field("text2");
  16188. ASSERT_EQ("text2", text2);
  16189. handled = true;
  16190. });
  16191. thread t = thread([&] { svr.listen(HOST, PORT); });
  16192. auto se = detail::scope_exit([&] {
  16193. svr.stop();
  16194. t.join();
  16195. ASSERT_FALSE(svr.is_running());
  16196. ASSERT_TRUE(handled);
  16197. });
  16198. svr.wait_until_ready();
  16199. auto req = "POST /test HTTP/1.1\r\n"
  16200. "Host: localhost\r\n"
  16201. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16202. "Content-Length: 146\r\n"
  16203. "\r\n----------\r\n"
  16204. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16205. "\r\n"
  16206. "text1"
  16207. "\r\n----------\r\n"
  16208. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16209. "\r\n"
  16210. "text2"
  16211. "\r\n------------";
  16212. std::string response;
  16213. ASSERT_TRUE(send_request(1, req, &response));
  16214. ASSERT_EQ("200", response.substr(9, 3));
  16215. }
  16216. TEST(MultipartFormDataTest, ContentLength) {
  16217. auto handled = false;
  16218. Server svr;
  16219. svr.Post("/test", [&](const Request &req, Response &) {
  16220. ASSERT_EQ(2u, req.form.fields.size());
  16221. const auto &text1 = req.form.get_field("text1");
  16222. ASSERT_EQ("text1", text1);
  16223. const auto &text2 = req.form.get_field("text2");
  16224. ASSERT_EQ("text2", text2);
  16225. handled = true;
  16226. });
  16227. thread t = thread([&] { svr.listen(HOST, PORT); });
  16228. auto se = detail::scope_exit([&] {
  16229. svr.stop();
  16230. t.join();
  16231. ASSERT_FALSE(svr.is_running());
  16232. ASSERT_TRUE(handled);
  16233. });
  16234. svr.wait_until_ready();
  16235. auto req = "POST /test HTTP/1.1\r\n"
  16236. "Host: localhost\r\n"
  16237. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16238. "Content-Length: 167\r\n"
  16239. "\r\n----------\r\n"
  16240. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16241. "Content-Length: 5\r\n"
  16242. "\r\n"
  16243. "text1"
  16244. "\r\n----------\r\n"
  16245. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16246. "\r\n"
  16247. "text2"
  16248. "\r\n------------\r\n";
  16249. std::string response;
  16250. ASSERT_TRUE(send_request(1, req, &response));
  16251. ASSERT_EQ("200", response.substr(9, 3));
  16252. }
  16253. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16254. auto handled = false;
  16255. Server svr;
  16256. svr.Post("/test", [&](const Request &req, Response &) {
  16257. ASSERT_EQ(2u, req.form.fields.size());
  16258. const auto &text1 = req.form.get_field("text1");
  16259. ASSERT_EQ("text1", text1);
  16260. // TODO: Add header access for text fields if needed
  16261. const auto &text2 = req.form.get_field("text2");
  16262. ASSERT_EQ("text2", text2);
  16263. // TODO: Header access for text fields needs to be implemented
  16264. // auto &headers = it->second.headers;
  16265. // ASSERT_EQ(3U, headers.size());
  16266. // auto custom_header = headers.find("x-whatever");
  16267. // ASSERT_TRUE(custom_header != headers.end());
  16268. // ASSERT_NE("customvalue", custom_header->second);
  16269. // ASSERT_EQ("CustomValue", custom_header->second);
  16270. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16271. handled = true;
  16272. });
  16273. thread t = thread([&] { svr.listen(HOST, PORT); });
  16274. auto se = detail::scope_exit([&] {
  16275. svr.stop();
  16276. t.join();
  16277. ASSERT_FALSE(svr.is_running());
  16278. ASSERT_TRUE(handled);
  16279. });
  16280. svr.wait_until_ready();
  16281. auto req = "POST /test HTTP/1.1\r\n"
  16282. "Host: localhost\r\n"
  16283. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16284. "Content-Length: 232\r\n"
  16285. "\r\n----------\r\n"
  16286. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16287. "Content-Length: 5\r\n"
  16288. "X-Test: 1\r\n"
  16289. "\r\n"
  16290. "text1"
  16291. "\r\n----------\r\n"
  16292. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16293. "Content-Type: text/plain\r\n"
  16294. "X-Whatever: CustomValue\r\n"
  16295. "\r\n"
  16296. "text2"
  16297. "\r\n------------\r\n"
  16298. "That should be disregarded. Not even read";
  16299. std::string response;
  16300. ASSERT_TRUE(send_request(1, req, &response));
  16301. ASSERT_EQ("200", response.substr(9, 3));
  16302. }
  16303. TEST(MultipartFormDataTest, LargeHeader) {
  16304. auto handled = false;
  16305. Server svr;
  16306. svr.Post("/test", [&](const Request &req, Response &) {
  16307. ASSERT_EQ(1u, req.form.fields.size());
  16308. const auto &text = req.form.get_field("name1");
  16309. ASSERT_EQ("text1", text);
  16310. handled = true;
  16311. });
  16312. thread t = thread([&] { svr.listen(HOST, PORT); });
  16313. auto se = detail::scope_exit([&] {
  16314. svr.stop();
  16315. t.join();
  16316. ASSERT_FALSE(svr.is_running());
  16317. ASSERT_TRUE(handled);
  16318. });
  16319. svr.wait_until_ready();
  16320. auto boundary = std::string("cpp-httplib-multipart-data");
  16321. std::string content = "--" + boundary +
  16322. "\r\n"
  16323. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16324. "\r\n"
  16325. "text1\r\n"
  16326. "--" +
  16327. boundary + "--\r\n";
  16328. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16329. "Host: localhost\r\n"
  16330. "Content-Type: multipart/form-data;boundary=" +
  16331. boundary +
  16332. "\r\n"
  16333. "Content-Length: " +
  16334. std::to_string(content.size()) +
  16335. "\r\n"
  16336. "Dummy-Header: ";
  16337. std::string header_suffix = "\r\n"
  16338. "\r\n";
  16339. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16340. size_t header_dummy_size =
  16341. read_buff_size -
  16342. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16343. auto header_dummy = std::string(header_dummy_size, '@');
  16344. auto req = header_prefix + header_dummy + header_suffix + content;
  16345. std::string response;
  16346. ASSERT_TRUE(send_request(1, req, &response));
  16347. ASSERT_EQ("200", response.substr(9, 3));
  16348. }
  16349. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16350. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16351. // (not chunked Transfer-Encoding) after the streaming refactor.
  16352. auto handled = false;
  16353. Server svr;
  16354. svr.Post("/upload", [&](const Request &req, Response &res) {
  16355. auto cl_it = req.headers.find("Content-Length");
  16356. EXPECT_TRUE(cl_it != req.headers.end());
  16357. auto te_it = req.headers.find("Transfer-Encoding");
  16358. EXPECT_TRUE(te_it == req.headers.end());
  16359. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16360. res.set_content("ok", "text/plain");
  16361. handled = true;
  16362. });
  16363. auto port = svr.bind_to_any_port(HOST);
  16364. auto t = thread([&] { svr.listen_after_bind(); });
  16365. auto se = detail::scope_exit([&] {
  16366. svr.stop();
  16367. t.join();
  16368. ASSERT_FALSE(svr.is_running());
  16369. ASSERT_TRUE(handled);
  16370. });
  16371. svr.wait_until_ready();
  16372. UploadFormDataItems items = {
  16373. {"field1", "hello", "", "text/plain"},
  16374. {"file1", "world", "test.txt", "application/octet-stream"},
  16375. };
  16376. Client cli(HOST, port);
  16377. auto res = cli.Post("/upload", {}, items);
  16378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16379. EXPECT_EQ(StatusCode::OK_200, res->status);
  16380. }
  16381. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16382. // Verify that make_multipart_content_provider coalesces many small segments
  16383. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16384. constexpr size_t kItemCount = 1000;
  16385. UploadFormDataItems items;
  16386. items.reserve(kItemCount);
  16387. for (size_t i = 0; i < kItemCount; i++) {
  16388. items.push_back(
  16389. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16390. }
  16391. const std::string boundary = "----test-boundary";
  16392. auto content_length = detail::get_multipart_content_length(items, boundary);
  16393. auto provider = detail::make_multipart_content_provider(items, boundary);
  16394. // Drive the provider the same way write_content_with_progress does
  16395. size_t write_count = 0;
  16396. size_t total_bytes = 0;
  16397. DataSink sink;
  16398. size_t offset = 0;
  16399. sink.write = [&](const char *d, size_t l) -> bool {
  16400. (void)d;
  16401. write_count++;
  16402. total_bytes += l;
  16403. offset += l;
  16404. return true;
  16405. };
  16406. sink.is_writable = []() -> bool { return true; };
  16407. while (offset < content_length) {
  16408. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16409. }
  16410. EXPECT_EQ(content_length, total_bytes);
  16411. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16412. // With buffering into 64KB blocks, write_count should be much smaller.
  16413. auto segment_count = 3 * kItemCount + 1;
  16414. EXPECT_LT(write_count, segment_count / 10);
  16415. }
  16416. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16417. // Integration test: send many UploadFormDataItems and verify the server
  16418. // receives all of them correctly (#2410).
  16419. constexpr size_t kItemCount = 500;
  16420. auto handled = false;
  16421. Server svr;
  16422. svr.Post("/upload", [&](const Request &req, Response &res) {
  16423. EXPECT_EQ(kItemCount, req.form.fields.size());
  16424. for (size_t i = 0; i < kItemCount; i++) {
  16425. auto key = "field" + std::to_string(i);
  16426. auto val = "value" + std::to_string(i);
  16427. auto it = req.form.fields.find(key);
  16428. if (it != req.form.fields.end()) {
  16429. EXPECT_EQ(val, it->second.content);
  16430. } else {
  16431. ADD_FAILURE() << "Missing field: " << key;
  16432. }
  16433. }
  16434. res.set_content("ok", "text/plain");
  16435. handled = true;
  16436. });
  16437. auto port = svr.bind_to_any_port(HOST);
  16438. auto t = thread([&] { svr.listen_after_bind(); });
  16439. auto se = detail::scope_exit([&] {
  16440. svr.stop();
  16441. t.join();
  16442. ASSERT_FALSE(svr.is_running());
  16443. ASSERT_TRUE(handled);
  16444. });
  16445. svr.wait_until_ready();
  16446. UploadFormDataItems items;
  16447. items.reserve(kItemCount);
  16448. for (size_t i = 0; i < kItemCount; i++) {
  16449. items.push_back(
  16450. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16451. }
  16452. Client cli(HOST, port);
  16453. auto res = cli.Post("/upload", items);
  16454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16455. EXPECT_EQ(StatusCode::OK_200, res->status);
  16456. }
  16457. TEST(MultipartFormDataTest, MakeFileProvider) {
  16458. // Verify make_file_provider sends a file's contents correctly.
  16459. const std::string file_content(4096, 'Z');
  16460. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16461. {
  16462. std::ofstream ofs(tmp_path, std::ios::binary);
  16463. ofs.write(file_content.data(),
  16464. static_cast<std::streamsize>(file_content.size()));
  16465. }
  16466. auto handled = false;
  16467. Server svr;
  16468. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16469. const ContentReader &content_reader) {
  16470. ASSERT_TRUE(req.is_multipart_form_data());
  16471. std::vector<FormData> items;
  16472. content_reader(
  16473. [&](const FormData &file) {
  16474. items.push_back(file);
  16475. return true;
  16476. },
  16477. [&](const char *data, size_t data_length) {
  16478. items.back().content.append(data, data_length);
  16479. return true;
  16480. });
  16481. ASSERT_EQ(1u, items.size());
  16482. EXPECT_EQ("myfile", items[0].name);
  16483. EXPECT_EQ("data.bin", items[0].filename);
  16484. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16485. EXPECT_EQ(file_content, items[0].content);
  16486. handled = true;
  16487. });
  16488. auto port = svr.bind_to_any_port(HOST);
  16489. auto t = thread([&] { svr.listen_after_bind(); });
  16490. auto se = detail::scope_exit([&] {
  16491. svr.stop();
  16492. t.join();
  16493. ASSERT_FALSE(svr.is_running());
  16494. ASSERT_TRUE(handled);
  16495. std::remove(tmp_path.c_str());
  16496. });
  16497. svr.wait_until_ready();
  16498. FormDataProviderItems providers;
  16499. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16500. "application/octet-stream"));
  16501. Client cli(HOST, port);
  16502. auto res = cli.Post("/upload", {}, {}, providers);
  16503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16504. EXPECT_EQ(StatusCode::OK_200, res->status);
  16505. }
  16506. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16507. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16508. // (100) headers is rejected with a 400 Bad Request response.
  16509. Server svr;
  16510. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16511. res.set_content("ok", "text/plain");
  16512. });
  16513. thread t = thread([&] { svr.listen(HOST, PORT); });
  16514. auto se = detail::scope_exit([&] {
  16515. svr.stop();
  16516. t.join();
  16517. ASSERT_FALSE(svr.is_running());
  16518. });
  16519. svr.wait_until_ready();
  16520. // Build a multipart part with 101 custom headers (exceeding
  16521. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16522. std::stringstream body;
  16523. body << "--simpleboundary\r\n"
  16524. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16525. for (int i = 0; i < 101; i++) {
  16526. body << "X-Custom-Header-" << i << ": value\r\n";
  16527. }
  16528. body << "\r\n"
  16529. << "value1\r\n"
  16530. << "--simpleboundary--\r\n";
  16531. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16532. Client cli(HOST, PORT);
  16533. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16535. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16536. }
  16537. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16538. // A body that never contains the declared boundary must not be accumulated
  16539. // while the parser waits for it. Buffering it would also make every read
  16540. // rescan everything seen so far, which is quadratic in the body size.
  16541. Server svr;
  16542. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16543. res.set_content("ok", "text/plain");
  16544. });
  16545. auto port = svr.bind_to_any_port(HOST);
  16546. thread t = thread([&] { svr.listen_after_bind(); });
  16547. auto se = detail::scope_exit([&] {
  16548. svr.stop();
  16549. t.join();
  16550. ASSERT_FALSE(svr.is_running());
  16551. });
  16552. svr.wait_until_ready();
  16553. Client cli(HOST, port);
  16554. cli.set_read_timeout(60, 0);
  16555. cli.set_write_timeout(60, 0);
  16556. // '-' is the worst case: it matches the first character of the boundary, so
  16557. // every position has to be checked against it.
  16558. auto post_dashes = [&](size_t size) {
  16559. const std::string body(size, '-');
  16560. auto start = std::chrono::steady_clock::now();
  16561. auto res =
  16562. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16563. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16564. std::chrono::steady_clock::now() - start)
  16565. .count();
  16566. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16567. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16568. return ms;
  16569. };
  16570. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16571. // Windows.
  16572. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16573. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16574. // Comparing the two sizes rather than checking an absolute duration keeps
  16575. // this meaningful across build types and CI load, both of which move the
  16576. // absolute numbers by more than an order of magnitude. Four times the bytes
  16577. // costs about four times the time when parsing is linear, and about sixteen
  16578. // times when the body is buffered and rescanned.
  16579. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16580. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16581. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16582. << "ms, which suggests the body is being buffered and rescanned";
  16583. }
  16584. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16585. // A boundary can only be followed by CRLF or by "--", so anything else is
  16586. // malformed no matter what comes next. The parser must say so right away
  16587. // instead of buffering the rest of the declared body.
  16588. Server svr;
  16589. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16590. res.set_content("ok", "text/plain");
  16591. });
  16592. auto port = svr.bind_to_any_port(HOST);
  16593. thread t = thread([&] { svr.listen_after_bind(); });
  16594. auto se = detail::scope_exit([&] {
  16595. svr.stop();
  16596. t.join();
  16597. ASSERT_FALSE(svr.is_running());
  16598. });
  16599. svr.wait_until_ready();
  16600. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16601. // buffers instead of failing would still be waiting for the remaining bytes.
  16602. const std::string body = "--zzzz\r\n"
  16603. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16604. "\r\n"
  16605. "text1"
  16606. "\r\n--zzzzXX";
  16607. const std::string req = "POST /post HTTP/1.1\r\n"
  16608. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16609. "Content-Length: 1048576\r\n"
  16610. "\r\n" +
  16611. body;
  16612. std::string response;
  16613. ASSERT_TRUE(send_request(3, req, &response, port));
  16614. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16615. EXPECT_EQ("400", response.substr(9, 3));
  16616. }
  16617. // Posts a multipart body split into two writes, so that the server sees the
  16618. // split at whatever offset the caller chose, and expects the single "text1"
  16619. // field to come through.
  16620. static void expect_split_multipart_ok(const std::string &body1,
  16621. const std::string &body2) {
  16622. auto handled = false;
  16623. Server svr;
  16624. svr.Post("/post", [&](const Request &req, Response &) {
  16625. EXPECT_EQ(1u, req.form.fields.size());
  16626. EXPECT_EQ("text1", req.form.get_field("text1"));
  16627. handled = true;
  16628. });
  16629. auto port = svr.bind_to_any_port(HOST);
  16630. thread t = thread([&] { svr.listen_after_bind(); });
  16631. auto se = detail::scope_exit([&] {
  16632. svr.stop();
  16633. t.join();
  16634. ASSERT_FALSE(svr.is_running());
  16635. ASSERT_TRUE(handled);
  16636. });
  16637. svr.wait_until_ready();
  16638. // "Connection: close" makes the server close once it has answered, so the
  16639. // response drain ends immediately instead of idling until the read timeout.
  16640. const std::string head =
  16641. "POST /post HTTP/1.1\r\n"
  16642. "Host: localhost\r\n"
  16643. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16644. "Connection: close\r\n"
  16645. "Content-Length: " +
  16646. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16647. std::string response;
  16648. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16649. ASSERT_GE(response.size(), 12u) << "no response";
  16650. EXPECT_EQ("200", response.substr(9, 3));
  16651. }
  16652. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16653. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16654. // ignored, including when it does not arrive in the same read as the
  16655. // close-delimiter itself.
  16656. expect_split_multipart_ok("--zzzz\r\n"
  16657. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16658. "\r\n"
  16659. "text1"
  16660. "\r\n--zzzz--",
  16661. "\r\nthis epilogue must be ignored\r\n");
  16662. }
  16663. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16664. // The initial boundary may be preceded by a preamble of any length and may
  16665. // straddle a read boundary. Discarding data while waiting for it must not
  16666. // throw away a partial boundary sitting at the end of the buffer.
  16667. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16668. "zz\r\n"
  16669. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16670. "\r\n"
  16671. "text1"
  16672. "\r\n--zzzz--\r\n");
  16673. }
  16674. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16675. // The received boundary was only checked for being non-empty, so it could be
  16676. // as long as a header is allowed to be. The parser scans the body for
  16677. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16678. // costs a nearly full comparison at nearly every position, making the
  16679. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16680. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16681. Server svr;
  16682. svr.Post("/post", [](const Request &req, Response &res) {
  16683. EXPECT_EQ(1u, req.form.fields.size());
  16684. EXPECT_EQ("text1", req.form.get_field("text1"));
  16685. res.set_content("ok", "text/plain");
  16686. });
  16687. auto port = svr.bind_to_any_port(HOST);
  16688. thread t = thread([&] { svr.listen_after_bind(); });
  16689. auto se = detail::scope_exit([&] {
  16690. svr.stop();
  16691. t.join();
  16692. ASSERT_FALSE(svr.is_running());
  16693. });
  16694. svr.wait_until_ready();
  16695. Client cli(HOST, port);
  16696. auto post_with_boundary_of_length = [&](size_t len) {
  16697. const std::string boundary(len, 'a');
  16698. const std::string body =
  16699. "--" + boundary +
  16700. "\r\n"
  16701. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16702. "\r\n"
  16703. "text1"
  16704. "\r\n--" +
  16705. boundary + "--\r\n";
  16706. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16707. };
  16708. auto res = post_with_boundary_of_length(70);
  16709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16710. EXPECT_EQ(StatusCode::OK_200, res->status);
  16711. res = post_with_boundary_of_length(71);
  16712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16713. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16714. }
  16715. TEST(MakeFileBodyTest, Basic) {
  16716. const std::string file_content(4096, 'Z');
  16717. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16718. {
  16719. std::ofstream ofs(tmp_path, std::ios::binary);
  16720. ofs.write(file_content.data(),
  16721. static_cast<std::streamsize>(file_content.size()));
  16722. }
  16723. auto handled = false;
  16724. Server svr;
  16725. svr.Post("/upload", [&](const Request &req, Response &res) {
  16726. EXPECT_EQ(file_content, req.body);
  16727. handled = true;
  16728. res.status = StatusCode::OK_200;
  16729. });
  16730. auto port = svr.bind_to_any_port(HOST);
  16731. auto t = thread([&] { svr.listen_after_bind(); });
  16732. auto se = detail::scope_exit([&] {
  16733. svr.stop();
  16734. t.join();
  16735. ASSERT_FALSE(svr.is_running());
  16736. ASSERT_TRUE(handled);
  16737. std::remove(tmp_path.c_str());
  16738. });
  16739. svr.wait_until_ready();
  16740. auto fb = make_file_body(tmp_path);
  16741. ASSERT_GT(fb.first, 0u);
  16742. Client cli(HOST, port);
  16743. auto res =
  16744. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16746. EXPECT_EQ(StatusCode::OK_200, res->status);
  16747. }
  16748. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16749. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16750. {
  16751. std::ofstream ofs(path, std::ios::binary);
  16752. const std::string content(100, 'A');
  16753. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16754. }
  16755. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16756. auto body = make_file_body(path);
  16757. ASSERT_EQ(100u, body.first);
  16758. ASSERT_TRUE(static_cast<bool>(body.second));
  16759. // Rewritten shorter after its length was measured - and, on a server, after
  16760. // that length has already gone out as Content-Length.
  16761. {
  16762. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16763. const std::string content(10, 'A');
  16764. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16765. }
  16766. std::string written;
  16767. DataSink sink;
  16768. sink.write = [&](const char *d, size_t l) {
  16769. written.append(d, l);
  16770. return true;
  16771. };
  16772. // The provider has to report failure. write_content_with_progress() advances
  16773. // its offset only by what was written, so a provider that returns true
  16774. // without completing the length it promised is called again straight away,
  16775. // and again.
  16776. EXPECT_FALSE(body.second(0, body.first, sink));
  16777. EXPECT_EQ(std::string(10, 'A'), written);
  16778. }
  16779. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16780. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16781. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16782. {
  16783. std::ofstream ofs(path, std::ios::binary);
  16784. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16785. }
  16786. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16787. auto body = make_file_body(path);
  16788. ASSERT_EQ(content.size(), body.first);
  16789. ASSERT_TRUE(static_cast<bool>(body.second));
  16790. std::string written;
  16791. DataSink sink;
  16792. sink.write = [&](const char *d, size_t l) {
  16793. written.append(d, l);
  16794. return true;
  16795. };
  16796. EXPECT_TRUE(body.second(0, body.first, sink));
  16797. EXPECT_EQ(content, written);
  16798. }
  16799. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16800. static constexpr unsigned int number_of_tasks{1000000};
  16801. std::atomic_uint count{0};
  16802. std::unique_ptr<TaskQueue> task_queue{
  16803. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16804. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16805. auto queued = task_queue->enqueue(
  16806. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16807. EXPECT_TRUE(queued);
  16808. }
  16809. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16810. task_queue->shutdown();
  16811. #else
  16812. EXPECT_NO_THROW(task_queue->shutdown());
  16813. #endif
  16814. EXPECT_EQ(number_of_tasks, count.load());
  16815. }
  16816. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16817. static constexpr unsigned int number_of_tasks{1000000};
  16818. static constexpr unsigned int qlimit{2};
  16819. unsigned int queued_count{0};
  16820. std::atomic_uint count{0};
  16821. std::unique_ptr<TaskQueue> task_queue{
  16822. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16823. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16824. if (task_queue->enqueue(
  16825. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16826. queued_count++;
  16827. }
  16828. }
  16829. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16830. task_queue->shutdown();
  16831. #else
  16832. EXPECT_NO_THROW(task_queue->shutdown());
  16833. #endif
  16834. EXPECT_EQ(queued_count, count.load());
  16835. EXPECT_TRUE(queued_count <= number_of_tasks);
  16836. EXPECT_TRUE(queued_count >= qlimit);
  16837. }
  16838. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16839. // Use a short idle timeout so a dynamic thread spawns, times out and
  16840. // exits during the test, and the pool keeps working afterwards.
  16841. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16842. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16843. /*idle_timeout_sec=*/1}};
  16844. std::atomic_uint count{0};
  16845. std::condition_variable cv;
  16846. std::mutex mtx;
  16847. bool release = false;
  16848. // Block the base thread so the second task spawns a dynamic thread.
  16849. EXPECT_TRUE(task_queue->enqueue([&] {
  16850. std::unique_lock<std::mutex> lock(mtx);
  16851. while (!release) {
  16852. cv.wait(lock);
  16853. }
  16854. count++;
  16855. }));
  16856. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16857. // Let the dynamic thread finish its task and exceed the idle timeout.
  16858. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16859. {
  16860. std::unique_lock<std::mutex> lock(mtx);
  16861. release = true;
  16862. }
  16863. cv.notify_all();
  16864. // The pool must still accept and run tasks after the dynamic thread exited.
  16865. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16866. task_queue->shutdown();
  16867. EXPECT_EQ(3u, count.load());
  16868. }
  16869. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16870. static constexpr size_t number_of_tasks{32};
  16871. std::unique_ptr<TaskQueue> task_queue{
  16872. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16873. // Let the base threads go idle so the burst below finds them waiting.
  16874. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16875. std::mutex mtx;
  16876. std::condition_variable cv;
  16877. size_t running = 0;
  16878. bool release = false;
  16879. for (size_t i = 0; i < number_of_tasks; i++) {
  16880. EXPECT_TRUE(task_queue->enqueue([&] {
  16881. std::unique_lock<std::mutex> lock(mtx);
  16882. running++;
  16883. cv.notify_all();
  16884. cv.wait(lock, [&] { return release; });
  16885. }));
  16886. }
  16887. {
  16888. std::unique_lock<std::mutex> lock(mtx);
  16889. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16890. [&] { return running == number_of_tasks; }));
  16891. release = true;
  16892. }
  16893. cv.notify_all();
  16894. task_queue->shutdown();
  16895. }
  16896. TEST(TaskQueueTest, MaxQueuedRequests) {
  16897. static constexpr unsigned int qlimit{3};
  16898. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16899. std::condition_variable sem_cv;
  16900. std::mutex sem_mtx;
  16901. int credits = 0;
  16902. bool queued;
  16903. /* Fill up the queue with tasks that will block until we give them credits to
  16904. * complete. */
  16905. for (unsigned int n = 0; n <= qlimit;) {
  16906. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16907. std::unique_lock<std::mutex> lock(sem_mtx);
  16908. while (credits <= 0) {
  16909. sem_cv.wait(lock);
  16910. }
  16911. /* Consume the credit and signal the test code if they are all gone. */
  16912. if (--credits == 0) { sem_cv.notify_one(); }
  16913. });
  16914. if (n < qlimit) {
  16915. /* The first qlimit enqueues must succeed. */
  16916. EXPECT_TRUE(queued);
  16917. } else {
  16918. /* The last one will succeed only when the worker thread
  16919. * starts and dequeues the first blocking task. Although
  16920. * not necessary for the correctness of this test, we sleep for
  16921. * a short while to avoid busy waiting. */
  16922. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16923. }
  16924. if (queued) { n++; }
  16925. }
  16926. /* Further enqueues must fail since the queue is full. */
  16927. for (auto i = 0; i < 4; i++) {
  16928. queued = task_queue->enqueue([] {});
  16929. EXPECT_FALSE(queued);
  16930. }
  16931. /* Give the credits to allow the previous tasks to complete. */
  16932. {
  16933. std::unique_lock<std::mutex> lock(sem_mtx);
  16934. credits += qlimit + 1;
  16935. }
  16936. sem_cv.notify_all();
  16937. /* Wait for all the credits to be consumed. */
  16938. {
  16939. std::unique_lock<std::mutex> lock(sem_mtx);
  16940. while (credits > 0) {
  16941. sem_cv.wait(lock);
  16942. }
  16943. }
  16944. /* Check that we are able again to enqueue at least qlimit tasks. */
  16945. for (unsigned int i = 0; i < qlimit; i++) {
  16946. queued = task_queue->enqueue([] {});
  16947. EXPECT_TRUE(queued);
  16948. }
  16949. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16950. task_queue->shutdown();
  16951. #else
  16952. EXPECT_NO_THROW(task_queue->shutdown());
  16953. #endif
  16954. }
  16955. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16956. Server svr;
  16957. std::string method;
  16958. std::string body;
  16959. auto has_content_length = false;
  16960. auto has_transfer_encoding = false;
  16961. std::atomic<int> bad_requests{0};
  16962. // Leftover body bytes get parsed as a malformed request and answered with
  16963. // 400
  16964. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16965. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16966. });
  16967. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16968. res.set_redirect("/down", StatusCode::SeeOther_303);
  16969. });
  16970. svr.Get("/down", [&](const Request &req, Response &res) {
  16971. method = req.method;
  16972. body = req.body;
  16973. has_content_length = req.has_header("Content-Length");
  16974. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16975. res.set_content("ok", "text/plain");
  16976. });
  16977. auto port = svr.bind_to_any_port(HOST);
  16978. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16979. auto se = detail::scope_exit([&] {
  16980. svr.stop();
  16981. thread.join();
  16982. ASSERT_FALSE(svr.is_running());
  16983. });
  16984. svr.wait_until_ready();
  16985. const std::string payload = "SECRET-BODY";
  16986. auto check = [&](Client &cli, const Result &res) {
  16987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16988. EXPECT_EQ(StatusCode::OK_200, res->status);
  16989. EXPECT_EQ("ok", res->body);
  16990. EXPECT_EQ("GET", method);
  16991. EXPECT_TRUE(body.empty());
  16992. EXPECT_FALSE(has_content_length);
  16993. EXPECT_FALSE(has_transfer_encoding);
  16994. // Nothing of the original body may be left on the connection
  16995. auto res2 = cli.Get("/down");
  16996. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16997. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16998. EXPECT_EQ("ok", res2->body);
  16999. EXPECT_EQ(0, bad_requests);
  17000. };
  17001. // With content length
  17002. {
  17003. Client cli(HOST, port);
  17004. cli.set_keep_alive(true);
  17005. cli.set_follow_location(true);
  17006. auto res = cli.Post(
  17007. "/up", payload.size(),
  17008. [&](size_t offset, size_t length, DataSink &sink) {
  17009. return sink.write(payload.data() + offset, length);
  17010. },
  17011. "text/plain");
  17012. check(cli, res);
  17013. }
  17014. // Without content length (chunked)
  17015. {
  17016. Client cli(HOST, port);
  17017. cli.set_keep_alive(true);
  17018. cli.set_follow_location(true);
  17019. auto res = cli.Post(
  17020. "/up",
  17021. [&](size_t /*offset*/, DataSink &sink) {
  17022. sink.write(payload.data(), payload.size());
  17023. sink.done();
  17024. return true;
  17025. },
  17026. "text/plain");
  17027. check(cli, res);
  17028. }
  17029. }
  17030. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17031. Server svr;
  17032. std::string target;
  17033. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17034. // Echo the still-encoded name back in the Location
  17035. const std::string prefix = "/start/";
  17036. res.status = StatusCode::Found_302;
  17037. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17038. });
  17039. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17040. target = req.target;
  17041. res.set_content("ok", "text/plain");
  17042. });
  17043. auto port = svr.bind_to_any_port(HOST);
  17044. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17045. auto se = detail::scope_exit([&] {
  17046. svr.stop();
  17047. thread.join();
  17048. ASSERT_FALSE(svr.is_running());
  17049. });
  17050. svr.wait_until_ready();
  17051. // Decoding the Location path would turn the first four into a path
  17052. // separator, a query delimiter, a fragment delimiter and a different
  17053. // percent-encoded octet. The rest must keep reaching the server as they are.
  17054. const std::vector<std::string> names = {
  17055. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17056. };
  17057. for (auto path_encode : {true, false}) {
  17058. Client cli(HOST, port);
  17059. cli.set_follow_location(true);
  17060. cli.set_path_encode(path_encode);
  17061. for (const auto &name : names) {
  17062. target.clear();
  17063. auto res = cli.Get("/start/" + name);
  17064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17065. EXPECT_EQ(StatusCode::OK_200, res->status);
  17066. EXPECT_EQ("/dest/" + name, target);
  17067. }
  17068. }
  17069. }
  17070. TEST(RedirectTest, NotModifiedIsReturned) {
  17071. Server svr;
  17072. svr.Get("/cached", [](const Request &, Response &res) {
  17073. res.status = StatusCode::NotModified_304;
  17074. });
  17075. auto port = svr.bind_to_any_port(HOST);
  17076. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17077. auto se = detail::scope_exit([&] {
  17078. svr.stop();
  17079. thread.join();
  17080. ASSERT_FALSE(svr.is_running());
  17081. });
  17082. svr.wait_until_ready();
  17083. Client cli(HOST, port);
  17084. cli.set_follow_location(true);
  17085. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17087. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17088. }
  17089. TEST(RedirectTest, NoLocationIsReturned) {
  17090. Server svr;
  17091. svr.Get("/no-location", [](const Request &, Response &res) {
  17092. res.status = StatusCode::Found_302;
  17093. res.set_content("no location", "text/plain");
  17094. });
  17095. auto port = svr.bind_to_any_port(HOST);
  17096. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17097. auto se = detail::scope_exit([&] {
  17098. svr.stop();
  17099. thread.join();
  17100. ASSERT_FALSE(svr.is_running());
  17101. });
  17102. svr.wait_until_ready();
  17103. Client cli(HOST, port);
  17104. cli.set_follow_location(true);
  17105. auto res = cli.Get("/no-location");
  17106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17107. EXPECT_EQ(StatusCode::Found_302, res->status);
  17108. EXPECT_EQ("no location", res->body);
  17109. // The callbacks see the body of the response that is returned
  17110. auto handler_called = false;
  17111. auto progress_called = false;
  17112. std::string body;
  17113. auto res2 = cli.Get(
  17114. "/no-location",
  17115. [&](const Response &) {
  17116. handler_called = true;
  17117. return true;
  17118. },
  17119. [&](const char *data, size_t data_length) {
  17120. body.append(data, data_length);
  17121. return true;
  17122. },
  17123. [&](size_t, size_t) {
  17124. progress_called = true;
  17125. return true;
  17126. });
  17127. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17128. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17129. EXPECT_TRUE(handler_called);
  17130. EXPECT_TRUE(progress_called);
  17131. EXPECT_EQ("no location", body);
  17132. }
  17133. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17134. Server svr;
  17135. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17136. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17137. });
  17138. svr.Get("/hello", [](const Request &req, Response &res) {
  17139. res.set_content(req.get_param_value("key"), "text/plain");
  17140. });
  17141. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17142. auto se = detail::scope_exit([&] {
  17143. svr.stop();
  17144. thread.join();
  17145. ASSERT_FALSE(svr.is_running());
  17146. });
  17147. svr.wait_until_ready();
  17148. {
  17149. Client cli(HOST, PORT);
  17150. cli.set_follow_location(true);
  17151. auto res = cli.Get("/");
  17152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17153. EXPECT_EQ(StatusCode::OK_200, res->status);
  17154. EXPECT_EQ("val&key2=val2", res->body);
  17155. }
  17156. }
  17157. #endif
  17158. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17159. Server svr;
  17160. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17161. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17162. });
  17163. svr.Get("/hello", [](const Request &req, Response &res) {
  17164. res.set_content(req.get_param_value("key"), "text/plain");
  17165. });
  17166. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17167. auto se = detail::scope_exit([&] {
  17168. svr.stop();
  17169. thread.join();
  17170. ASSERT_FALSE(svr.is_running());
  17171. });
  17172. svr.wait_until_ready();
  17173. {
  17174. Client cli(HOST, PORT);
  17175. cli.set_follow_location(true);
  17176. auto res = cli.Get("/");
  17177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17178. EXPECT_EQ(StatusCode::OK_200, res->status);
  17179. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17180. }
  17181. }
  17182. TEST(RedirectTest, RedirectWithPlusInPath) {
  17183. Server svr;
  17184. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17185. res.set_redirect("/a+b");
  17186. });
  17187. // Route pattern uses regex; escape + as \\+
  17188. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17189. res.set_content(req.path, "text/plain");
  17190. });
  17191. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17192. auto se = detail::scope_exit([&] {
  17193. svr.stop();
  17194. thread.join();
  17195. ASSERT_FALSE(svr.is_running());
  17196. });
  17197. svr.wait_until_ready();
  17198. {
  17199. Client cli(HOST, PORT);
  17200. cli.set_follow_location(true);
  17201. auto res = cli.Get("/");
  17202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17203. EXPECT_EQ(StatusCode::OK_200, res->status);
  17204. EXPECT_EQ("/a+b", res->body);
  17205. }
  17206. }
  17207. TEST(RedirectTest, ResolveRelativeLocation) {
  17208. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17209. const std::vector<std::pair<std::string, std::string>> cases = {
  17210. {"g", "/b/c/g"},
  17211. {"./g", "/b/c/g"},
  17212. {"g/", "/b/c/g/"},
  17213. {"?y", "/b/c/d;p?y"},
  17214. {"g?y", "/b/c/g?y"},
  17215. {"#s", "/b/c/d;p?q#s"},
  17216. {"g#s", "/b/c/g#s"},
  17217. {"g?y#s", "/b/c/g?y#s"},
  17218. {";x", "/b/c/;x"},
  17219. {"g;x", "/b/c/g;x"},
  17220. {".", "/b/c/"},
  17221. {"./", "/b/c/"},
  17222. {"..", "/b/"},
  17223. {"../", "/b/"},
  17224. {"../g", "/b/g"},
  17225. {"../..", "/"},
  17226. {"../../", "/"},
  17227. {"../../g", "/g"},
  17228. {"../../../g", "/g"},
  17229. {"g.", "/b/c/g."},
  17230. {".g", "/b/c/.g"},
  17231. {"g..", "/b/c/g.."},
  17232. {"..g", "/b/c/..g"},
  17233. {"./../g", "/b/g"},
  17234. {"./g/.", "/b/c/g/"},
  17235. {"g/./h", "/b/c/g/h"},
  17236. {"g/../h", "/b/c/h"},
  17237. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17238. {"g;x=1/../y", "/b/c/y"},
  17239. {"g?y/./x", "/b/c/g?y/./x"},
  17240. {"g#s/../x", "/b/c/g#s/../x"},
  17241. // Not relative-path references, so left for parse_url.
  17242. {"/g", "/g"},
  17243. {"//g", "//g"},
  17244. {"http://g/x", "http://g/x"},
  17245. {"g:h", "g:h"},
  17246. };
  17247. for (const auto &c : cases) {
  17248. EXPECT_EQ(c.second,
  17249. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17250. << c.first;
  17251. }
  17252. }
  17253. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17254. Server svr;
  17255. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17256. res.set_redirect(req.get_param_value("to"));
  17257. });
  17258. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17259. res.set_content(req.target, "text/plain");
  17260. });
  17261. svr.Get("/other", [](const Request &req, Response &res) {
  17262. res.set_content(req.target, "text/plain");
  17263. });
  17264. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17265. auto se = detail::scope_exit([&] {
  17266. svr.stop();
  17267. thread.join();
  17268. ASSERT_FALSE(svr.is_running());
  17269. });
  17270. svr.wait_until_ready();
  17271. const std::vector<std::pair<std::string, std::string>> cases = {
  17272. {"next", "/dir/next"},
  17273. {"./next?x=1", "/dir/next?x=1"},
  17274. {"../other", "/other"},
  17275. };
  17276. for (const auto &c : cases) {
  17277. Client cli(HOST, PORT);
  17278. cli.set_follow_location(true);
  17279. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17280. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17281. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17282. EXPECT_EQ(c.second, res->body) << c.first;
  17283. }
  17284. }
  17285. #ifdef CPPHTTPLIB_SSL_ENABLED
  17286. TEST(RedirectTest, Issue2185_Online) {
  17287. SSLClient client("github.com");
  17288. client.set_follow_location(true);
  17289. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17290. "Coollab-Windows.zip");
  17291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17292. EXPECT_EQ(StatusCode::OK_200, res->status);
  17293. EXPECT_EQ(9920427U, res->body.size());
  17294. }
  17295. #endif
  17296. TEST(VulnerabilityTest, CRLFInjection) {
  17297. Server svr;
  17298. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17299. res.set_content("Hello 1", "text/plain");
  17300. });
  17301. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17302. res.set_content("Hello 2", "text/plain");
  17303. });
  17304. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17305. res.set_content("Hello 3", "text/plain");
  17306. });
  17307. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17308. res.set_content("Hello 4", "text/plain");
  17309. });
  17310. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17311. for (const auto &x : req.headers) {
  17312. auto key = x.first;
  17313. EXPECT_STRNE("evil", key.c_str());
  17314. }
  17315. });
  17316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17317. auto se = detail::scope_exit([&] {
  17318. svr.stop();
  17319. thread.join();
  17320. ASSERT_FALSE(svr.is_running());
  17321. });
  17322. svr.wait_until_ready();
  17323. {
  17324. Client cli(HOST, PORT);
  17325. cli.Post("/test1", "A=B",
  17326. "application/x-www-form-urlencoded\r\nevil: hello1");
  17327. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17328. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17329. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17330. }
  17331. }
  17332. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17333. auto server_thread = std::thread([] {
  17334. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17335. default_socket_options(srv);
  17336. sockaddr_in addr{};
  17337. addr.sin_family = AF_INET;
  17338. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17339. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17340. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17341. ::listen(srv, 1);
  17342. sockaddr_in cli_addr{};
  17343. socklen_t cli_len = sizeof(cli_addr);
  17344. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17345. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17346. std::string buf_all;
  17347. char buf[2048];
  17348. ssize_t n;
  17349. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17350. buf_all.append(buf, static_cast<size_t>(n));
  17351. size_t pos;
  17352. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17353. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17354. auto e = request_block.find("\r\n");
  17355. if (e != std::string::npos) {
  17356. auto request_line = request_block.substr(0, e);
  17357. std::string msg =
  17358. "CRLF injection detected in request line: '" + request_line + "'";
  17359. EXPECT_FALSE(true) << msg;
  17360. }
  17361. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17362. ::send(cli,
  17363. #ifdef _WIN32
  17364. static_cast<const char *>(resp.c_str()),
  17365. static_cast<int>(resp.size()),
  17366. #else
  17367. resp.c_str(), resp.size(),
  17368. #endif
  17369. 0);
  17370. buf_all.erase(0, pos + 4);
  17371. }
  17372. }
  17373. detail::close_socket(cli);
  17374. detail::close_socket(srv);
  17375. });
  17376. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17377. auto cli = Client("127.0.0.1", PORT + 1);
  17378. auto headers = Headers{
  17379. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17380. {"Connection", "keep-alive"}};
  17381. auto res = cli.Get("/hi", headers);
  17382. EXPECT_FALSE(res);
  17383. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17384. server_thread.join();
  17385. }
  17386. // A request rejected before any byte reaches the socket must fail right away
  17387. // instead of waiting for a response the server will never send.
  17388. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17389. // The kernel completes the TCP handshake from the listen backlog, so the
  17390. // client connects, but nothing ever reads, responds or closes.
  17391. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17392. default_socket_options(srv);
  17393. sockaddr_in addr{};
  17394. addr.sin_family = AF_INET;
  17395. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17396. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17397. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17398. ASSERT_EQ(0, ::listen(srv, 8));
  17399. auto cli = Client("127.0.0.1", PORT + 1);
  17400. cli.set_read_timeout(10, 0);
  17401. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17402. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17403. std::chrono::steady_clock::now() - start)
  17404. .count();
  17405. };
  17406. {
  17407. Request req;
  17408. req.method = "GE T";
  17409. req.path = "/";
  17410. auto start = std::chrono::steady_clock::now();
  17411. auto res = cli.send(req);
  17412. EXPECT_FALSE(res);
  17413. EXPECT_EQ(Error::Write, res.error());
  17414. EXPECT_LT(elapsed_ms(start), 1000);
  17415. }
  17416. {
  17417. auto start = std::chrono::steady_clock::now();
  17418. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17419. EXPECT_FALSE(res);
  17420. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17421. EXPECT_LT(elapsed_ms(start), 1000);
  17422. }
  17423. EXPECT_FALSE(cli.is_socket_open());
  17424. detail::close_socket(srv);
  17425. }
  17426. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17427. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17428. default_socket_options(srv);
  17429. sockaddr_in addr{};
  17430. addr.sin_family = AF_INET;
  17431. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17432. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17433. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17434. ASSERT_EQ(0, ::listen(srv, 1));
  17435. std::string received;
  17436. auto server_thread = std::thread([&] {
  17437. auto sock = ::accept(srv, nullptr, nullptr);
  17438. if (sock == INVALID_SOCKET) { return; }
  17439. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17440. char buf[2048];
  17441. ssize_t n;
  17442. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17443. received.append(buf, static_cast<size_t>(n));
  17444. }
  17445. detail::close_socket(sock);
  17446. });
  17447. {
  17448. auto cli = Client("127.0.0.1", PORT + 1);
  17449. // "Z" sorts after the default headers, so writing straight to the socket
  17450. // would have sent the request line and those headers before the rejection.
  17451. auto handle =
  17452. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17453. EXPECT_FALSE(handle.is_valid());
  17454. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17455. }
  17456. server_thread.join();
  17457. detail::close_socket(srv);
  17458. EXPECT_TRUE(received.empty()) << received;
  17459. }
  17460. TEST(PathParamsTest, StaticMatch) {
  17461. const auto pattern = "/users/all";
  17462. detail::PathParamsMatcher matcher(pattern);
  17463. Request request;
  17464. request.path = "/users/all";
  17465. ASSERT_TRUE(matcher.match(request));
  17466. std::unordered_map<std::string, std::string> expected_params = {};
  17467. EXPECT_EQ(request.path_params, expected_params);
  17468. }
  17469. TEST(PathParamsTest, StaticMismatch) {
  17470. const auto pattern = "/users/all";
  17471. detail::PathParamsMatcher matcher(pattern);
  17472. Request request;
  17473. request.path = "/users/1";
  17474. ASSERT_FALSE(matcher.match(request));
  17475. }
  17476. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17477. const auto pattern = "/users/:id/subscriptions";
  17478. detail::PathParamsMatcher matcher(pattern);
  17479. Request request;
  17480. request.path = "/users/42/subscriptions";
  17481. ASSERT_TRUE(matcher.match(request));
  17482. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17483. EXPECT_EQ(request.path_params, expected_params);
  17484. }
  17485. TEST(PathParamsTest, SingleParamInTheEnd) {
  17486. const auto pattern = "/users/:id";
  17487. detail::PathParamsMatcher matcher(pattern);
  17488. Request request;
  17489. request.path = "/users/24";
  17490. ASSERT_TRUE(matcher.match(request));
  17491. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17492. EXPECT_EQ(request.path_params, expected_params);
  17493. }
  17494. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17495. const auto pattern = "/users/:id/";
  17496. detail::PathParamsMatcher matcher(pattern);
  17497. Request request;
  17498. request.path = "/users/42/";
  17499. ASSERT_TRUE(matcher.match(request));
  17500. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17501. EXPECT_EQ(request.path_params, expected_params);
  17502. }
  17503. TEST(PathParamsTest, EmptyParam) {
  17504. const auto pattern = "/users/:id/";
  17505. detail::PathParamsMatcher matcher(pattern);
  17506. Request request;
  17507. request.path = "/users//";
  17508. ASSERT_TRUE(matcher.match(request));
  17509. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17510. EXPECT_EQ(request.path_params, expected_params);
  17511. }
  17512. TEST(PathParamsTest, FragmentMismatch) {
  17513. const auto pattern = "/users/:id/";
  17514. detail::PathParamsMatcher matcher(pattern);
  17515. Request request;
  17516. request.path = "/admins/24/";
  17517. ASSERT_FALSE(matcher.match(request));
  17518. }
  17519. TEST(PathParamsTest, ExtraFragments) {
  17520. const auto pattern = "/users/:id";
  17521. detail::PathParamsMatcher matcher(pattern);
  17522. Request request;
  17523. request.path = "/users/42/subscriptions";
  17524. ASSERT_FALSE(matcher.match(request));
  17525. }
  17526. TEST(PathParamsTest, MissingTrailingParam) {
  17527. const auto pattern = "/users/:id";
  17528. detail::PathParamsMatcher matcher(pattern);
  17529. Request request;
  17530. request.path = "/users";
  17531. ASSERT_FALSE(matcher.match(request));
  17532. }
  17533. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17534. const auto pattern = "/users/:id/subscriptions";
  17535. detail::PathParamsMatcher matcher(pattern);
  17536. Request request;
  17537. request.path = "/users/subscriptions";
  17538. ASSERT_FALSE(matcher.match(request));
  17539. }
  17540. TEST(PathParamsTest, MultipleParams) {
  17541. const auto pattern = "/users/:userid/subscriptions/:subid";
  17542. detail::PathParamsMatcher matcher(pattern);
  17543. Request request;
  17544. request.path = "/users/42/subscriptions/2";
  17545. ASSERT_TRUE(matcher.match(request));
  17546. std::unordered_map<std::string, std::string> expected_params = {
  17547. {"userid", "42"}, {"subid", "2"}};
  17548. EXPECT_EQ(request.path_params, expected_params);
  17549. }
  17550. TEST(PathParamsTest, SequenceOfParams) {
  17551. const auto pattern = "/values/:x/:y/:z";
  17552. detail::PathParamsMatcher matcher(pattern);
  17553. Request request;
  17554. request.path = "/values/1/2/3";
  17555. ASSERT_TRUE(matcher.match(request));
  17556. std::unordered_map<std::string, std::string> expected_params = {
  17557. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17558. EXPECT_EQ(request.path_params, expected_params);
  17559. }
  17560. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17561. const auto pattern = "/prefix:suffix";
  17562. detail::PathParamsMatcher matcher(pattern);
  17563. Request request;
  17564. request.path = "/prefix:suffix";
  17565. ASSERT_TRUE(matcher.match(request));
  17566. const std::unordered_map<std::string, std::string> expected_params = {};
  17567. EXPECT_EQ(request.path_params, expected_params);
  17568. }
  17569. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17570. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17571. // calling thread's stack on a long enough path for a quantified pattern;
  17572. // RegexMatcher must refuse to run regex matching on paths beyond
  17573. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17574. detail::RegexMatcher matcher("/files/(.*)");
  17575. Request within_limit;
  17576. within_limit.path = "/files/" + std::string(10, 'A');
  17577. EXPECT_TRUE(matcher.match(within_limit));
  17578. Request over_limit;
  17579. over_limit.path =
  17580. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17581. EXPECT_FALSE(matcher.match(over_limit));
  17582. }
  17583. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17584. Server svr;
  17585. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17586. res.set_content("ok", "text/plain");
  17587. });
  17588. auto port = svr.bind_to_any_port(HOST);
  17589. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17590. auto se = detail::scope_exit([&] {
  17591. svr.stop();
  17592. thread.join();
  17593. ASSERT_FALSE(svr.is_running());
  17594. });
  17595. svr.wait_until_ready();
  17596. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17597. // request URI limit; this used to be able to crash the process.
  17598. std::string path =
  17599. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17600. std::string req = "GET " + path +
  17601. " HTTP/1.1\r\n"
  17602. "Host: " +
  17603. std::string(HOST) + ":" + std::to_string(port) +
  17604. "\r\n"
  17605. "Connection: close\r\n"
  17606. "\r\n";
  17607. std::string response;
  17608. ASSERT_TRUE(send_request(5, req, &response, port));
  17609. EXPECT_NE(std::string::npos, response.find("404"));
  17610. }
  17611. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17612. Server svr;
  17613. auto handler = [](const Request & /*req*/, Response &res) {
  17614. res.set_content("hit", "text/plain");
  17615. };
  17616. // No regex metacharacter, so this one is compared literally
  17617. svr.Get("/literal/route", handler);
  17618. // '.' is a regex metacharacter, so this one must keep regex semantics
  17619. svr.Get("/a.c", handler);
  17620. auto port = svr.bind_to_any_port(HOST);
  17621. std::thread t([&]() { svr.listen_after_bind(); });
  17622. auto se = detail::scope_exit([&] {
  17623. svr.stop();
  17624. t.join();
  17625. ASSERT_FALSE(svr.is_running());
  17626. });
  17627. svr.wait_until_ready();
  17628. Client cli(HOST, port);
  17629. struct {
  17630. const char *path;
  17631. int status;
  17632. } cases[] = {
  17633. {"/literal/route", StatusCode::OK_200},
  17634. {"/literal/routes", StatusCode::NotFound_404},
  17635. {"/literal/rout", StatusCode::NotFound_404},
  17636. {"/abc", StatusCode::OK_200},
  17637. {"/a.c", StatusCode::OK_200},
  17638. };
  17639. for (const auto &x : cases) {
  17640. auto res = cli.Get(x.path);
  17641. ASSERT_TRUE(res) << x.path;
  17642. EXPECT_EQ(x.status, res->status) << x.path;
  17643. }
  17644. }
  17645. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17646. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17647. // from exhausting the stack, so it must only constrain routes that actually
  17648. // run a regular expression. A literal route is matched by comparison and
  17649. // stays usable at any length.
  17650. Server svr;
  17651. const std::string pattern =
  17652. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17653. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17654. res.set_content("hit", "text/plain");
  17655. });
  17656. auto port = svr.bind_to_any_port(HOST);
  17657. std::thread t([&]() { svr.listen_after_bind(); });
  17658. auto se = detail::scope_exit([&] {
  17659. svr.stop();
  17660. t.join();
  17661. ASSERT_FALSE(svr.is_running());
  17662. });
  17663. svr.wait_until_ready();
  17664. Client cli(HOST, port);
  17665. auto res = cli.Get(pattern);
  17666. ASSERT_TRUE(res);
  17667. EXPECT_EQ(StatusCode::OK_200, res->status);
  17668. }
  17669. TEST(ParseUrlTest, VariousPatterns) {
  17670. {
  17671. detail::UrlComponents uc;
  17672. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17673. EXPECT_EQ("http", uc.scheme);
  17674. EXPECT_EQ("example.com", uc.host);
  17675. EXPECT_EQ("8080", uc.port);
  17676. EXPECT_EQ("/path", uc.path);
  17677. EXPECT_EQ("?q=1", uc.query);
  17678. }
  17679. {
  17680. detail::UrlComponents uc;
  17681. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17682. EXPECT_EQ("https", uc.scheme);
  17683. EXPECT_EQ("example.com", uc.host);
  17684. EXPECT_TRUE(uc.port.empty());
  17685. EXPECT_EQ("/path", uc.path);
  17686. }
  17687. {
  17688. detail::UrlComponents uc;
  17689. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17690. EXPECT_EQ("::1", uc.host);
  17691. EXPECT_EQ("8080", uc.port);
  17692. EXPECT_EQ("/path", uc.path);
  17693. }
  17694. {
  17695. detail::UrlComponents uc;
  17696. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17697. }
  17698. {
  17699. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17700. // the path while the connection still targets the bracketed host.
  17701. detail::UrlComponents uc;
  17702. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17703. }
  17704. {
  17705. detail::UrlComponents uc;
  17706. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17707. }
  17708. {
  17709. detail::UrlComponents uc;
  17710. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17711. EXPECT_EQ("::1", uc.host);
  17712. EXPECT_TRUE(uc.port.empty());
  17713. EXPECT_EQ("/path", uc.path);
  17714. }
  17715. {
  17716. detail::UrlComponents uc;
  17717. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17718. EXPECT_TRUE(uc.scheme.empty());
  17719. EXPECT_EQ("example.com", uc.host);
  17720. EXPECT_EQ("/path", uc.path);
  17721. EXPECT_EQ("?q=1", uc.query);
  17722. }
  17723. {
  17724. detail::UrlComponents uc;
  17725. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17726. EXPECT_TRUE(uc.host.empty());
  17727. EXPECT_EQ("/path", uc.path);
  17728. EXPECT_EQ("?q=1", uc.query);
  17729. }
  17730. {
  17731. detail::UrlComponents uc;
  17732. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17733. EXPECT_EQ("example.com", uc.host);
  17734. EXPECT_EQ("8080", uc.port);
  17735. }
  17736. {
  17737. // Unix socket path — must not be parsed as host
  17738. detail::UrlComponents uc;
  17739. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17740. EXPECT_TRUE(uc.host.empty());
  17741. }
  17742. {
  17743. detail::UrlComponents uc;
  17744. ASSERT_TRUE(detail::parse_url("", uc));
  17745. EXPECT_TRUE(uc.host.empty());
  17746. EXPECT_TRUE(uc.path.empty());
  17747. }
  17748. {
  17749. detail::UrlComponents uc;
  17750. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17751. }
  17752. {
  17753. detail::UrlComponents uc;
  17754. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17755. }
  17756. {
  17757. // Accepted by parse_url; callers restrict to http/https
  17758. detail::UrlComponents uc;
  17759. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17760. EXPECT_EQ("ftp", uc.scheme);
  17761. }
  17762. {
  17763. detail::UrlComponents uc;
  17764. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17765. }
  17766. {
  17767. detail::UrlComponents uc;
  17768. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17769. }
  17770. }
  17771. TEST(ParseUrlTest, FragmentHandling) {
  17772. {
  17773. detail::UrlComponents uc;
  17774. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17775. EXPECT_EQ("/path", uc.path);
  17776. EXPECT_TRUE(uc.query.empty());
  17777. }
  17778. {
  17779. detail::UrlComponents uc;
  17780. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17781. EXPECT_TRUE(uc.path.empty());
  17782. EXPECT_TRUE(uc.query.empty());
  17783. }
  17784. }
  17785. TEST(ParseUrlTest, UserinfoHandling) {
  17786. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17787. // parsers would see evil.com as the host.
  17788. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17789. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17790. for (auto url : urls) {
  17791. detail::UrlComponents uc;
  17792. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17793. }
  17794. }
  17795. TEST(ParseUrlTest, IPv6EdgeCases) {
  17796. {
  17797. detail::UrlComponents uc;
  17798. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17799. EXPECT_TRUE(uc.scheme.empty());
  17800. EXPECT_EQ("::1", uc.host);
  17801. EXPECT_EQ("8080", uc.port);
  17802. }
  17803. {
  17804. // Zone ID '%25' is not in [a-fA-F0-9:]
  17805. detail::UrlComponents uc;
  17806. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17807. }
  17808. }
  17809. TEST(ParseUrlTest, SchemeEdgeCases) {
  17810. {
  17811. detail::UrlComponents uc;
  17812. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17813. }
  17814. {
  17815. detail::UrlComponents uc;
  17816. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17817. }
  17818. {
  17819. detail::UrlComponents uc;
  17820. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17821. }
  17822. }
  17823. TEST(ParseUrlTest, PortEdgeCases) {
  17824. {
  17825. detail::UrlComponents uc;
  17826. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17827. EXPECT_TRUE(uc.port.empty());
  17828. EXPECT_EQ("/path", uc.path);
  17829. }
  17830. {
  17831. // parse_url accepts any port string; validation is done by parse_port
  17832. detail::UrlComponents uc;
  17833. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17834. EXPECT_EQ("abc", uc.port);
  17835. }
  17836. }
  17837. TEST(ParseUrlTest, WebSocketPatterns) {
  17838. {
  17839. detail::UrlComponents uc;
  17840. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17841. EXPECT_EQ("ws", uc.scheme);
  17842. EXPECT_EQ("echo.example.com", uc.host);
  17843. EXPECT_EQ("8080", uc.port);
  17844. EXPECT_EQ("/ws", uc.path);
  17845. }
  17846. {
  17847. detail::UrlComponents uc;
  17848. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17849. EXPECT_EQ("wss", uc.scheme);
  17850. EXPECT_EQ("echo.example.com", uc.host);
  17851. EXPECT_TRUE(uc.port.empty());
  17852. EXPECT_EQ("/ws", uc.path);
  17853. }
  17854. }
  17855. TEST(ParseUrlTest, QueryOnly) {
  17856. detail::UrlComponents uc;
  17857. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17858. EXPECT_TRUE(uc.host.empty());
  17859. EXPECT_TRUE(uc.path.empty());
  17860. EXPECT_EQ("?q=1&r=2", uc.query);
  17861. }
  17862. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17863. detail::UrlComponents uc;
  17864. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17865. EXPECT_TRUE(uc.scheme.empty());
  17866. EXPECT_EQ("example.com", uc.host);
  17867. EXPECT_EQ("443", uc.port);
  17868. EXPECT_EQ("/path", uc.path);
  17869. }
  17870. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17871. // If ipv6 regex working, regex match codepath is taken.
  17872. // else port will default to 80 in Client impl
  17873. int clientImplMagicPort = 80;
  17874. int port = 4321;
  17875. // above ports must be different to avoid false negative
  17876. EXPECT_NE(clientImplMagicPort, port);
  17877. std::string ipV6TestURL = "http://[ff06::c3]";
  17878. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17879. CLIENT_PRIVATE_KEY_FILE);
  17880. EXPECT_EQ(cli.port(), port);
  17881. }
  17882. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17883. auto file_path = "./www/dir/index.html";
  17884. auto dir_path = "./www/dir";
  17885. detail::FileStat stat_file(file_path);
  17886. EXPECT_TRUE(stat_file.is_file());
  17887. EXPECT_FALSE(stat_file.is_dir());
  17888. detail::FileStat stat_dir(dir_path);
  17889. EXPECT_FALSE(stat_dir.is_file());
  17890. EXPECT_TRUE(stat_dir.is_dir());
  17891. }
  17892. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17893. // IPv4 with default HTTP port (80)
  17894. EXPECT_EQ("example.com",
  17895. detail::make_host_and_port_string("example.com", 80, false));
  17896. // IPv4 with default HTTPS port (443)
  17897. EXPECT_EQ("example.com",
  17898. detail::make_host_and_port_string("example.com", 443, true));
  17899. // IPv4 with non-default HTTP port
  17900. EXPECT_EQ("example.com:8080",
  17901. detail::make_host_and_port_string("example.com", 8080, false));
  17902. // IPv4 with non-default HTTPS port
  17903. EXPECT_EQ("example.com:8443",
  17904. detail::make_host_and_port_string("example.com", 8443, true));
  17905. // IPv6 with default HTTP port (80)
  17906. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17907. // IPv6 with default HTTPS port (443)
  17908. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17909. // IPv6 with non-default HTTP port
  17910. EXPECT_EQ("[::1]:8080",
  17911. detail::make_host_and_port_string("::1", 8080, false));
  17912. // IPv6 with non-default HTTPS port
  17913. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17914. // IPv6 full address with default port
  17915. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17916. detail::make_host_and_port_string(
  17917. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17918. // IPv6 full address with non-default port
  17919. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17920. detail::make_host_and_port_string(
  17921. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17922. // IPv6 localhost with non-default port
  17923. EXPECT_EQ("[::1]:3000",
  17924. detail::make_host_and_port_string("::1", 3000, false));
  17925. // IPv6 with zone ID (link-local address) with default port
  17926. EXPECT_EQ("[fe80::1%eth0]",
  17927. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17928. // IPv6 with zone ID (link-local address) with non-default port
  17929. EXPECT_EQ("[fe80::1%eth0]:8080",
  17930. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17931. // Edge case: Port 443 with is_ssl=false (should add port)
  17932. EXPECT_EQ("example.com:443",
  17933. detail::make_host_and_port_string("example.com", 443, false));
  17934. // Edge case: Port 80 with is_ssl=true (should add port)
  17935. EXPECT_EQ("example.com:80",
  17936. detail::make_host_and_port_string("example.com", 80, true));
  17937. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17938. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17939. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17940. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17941. // Security fix: Already bracketed IPv6 should not get double brackets
  17942. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17943. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17944. EXPECT_EQ("[::1]:8080",
  17945. detail::make_host_and_port_string("[::1]", 8080, false));
  17946. EXPECT_EQ("[2001:db8::1]:8080",
  17947. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17948. EXPECT_EQ("[fe80::1%eth0]",
  17949. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17950. EXPECT_EQ("[fe80::1%eth0]:8080",
  17951. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17952. // Edge case: Empty host (should return as-is)
  17953. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17954. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17955. // This is a known limitation but shouldn't crash
  17956. EXPECT_EQ("[host:name]",
  17957. detail::make_host_and_port_string("host:name", 80, false));
  17958. // Port number edge cases (no validation, but should not crash)
  17959. EXPECT_EQ("example.com:0",
  17960. detail::make_host_and_port_string("example.com", 0, false));
  17961. EXPECT_EQ("example.com:-1",
  17962. detail::make_host_and_port_string("example.com", -1, false));
  17963. EXPECT_EQ("example.com:65535",
  17964. detail::make_host_and_port_string("example.com", 65535, false));
  17965. EXPECT_EQ("example.com:65536",
  17966. detail::make_host_and_port_string("example.com", 65536, false));
  17967. }
  17968. #ifdef CPPHTTPLIB_SSL_ENABLED
  17969. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17970. httplib::SSLClient cli("roblox.com", 443);
  17971. cli.set_follow_location(true);
  17972. auto res = cli.Get("/");
  17973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17974. EXPECT_EQ(StatusCode::OK_200, res->status);
  17975. }
  17976. #endif
  17977. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17978. Server svr;
  17979. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17980. EXPECT_EQ(res.status, 400);
  17981. });
  17982. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17983. auto se = detail::scope_exit([&] {
  17984. svr.stop();
  17985. thread.join();
  17986. ASSERT_FALSE(svr.is_running());
  17987. });
  17988. svr.wait_until_ready();
  17989. Client cli(HOST, PORT);
  17990. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17991. }
  17992. TEST(InvalidHeaderCharsTest, is_field_name) {
  17993. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17994. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17995. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17996. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17997. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17998. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17999. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18000. EXPECT_FALSE(detail::fields::is_field_name(""));
  18001. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18002. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18003. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18004. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18005. }
  18006. TEST(InvalidHeaderCharsTest, is_field_value) {
  18007. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18008. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18009. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18010. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18011. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18012. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18013. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18014. EXPECT_TRUE(detail::fields::is_field_value(""));
  18015. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18016. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18017. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18018. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18019. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18020. }
  18021. TEST(InvalidHeaderCharsTest, OnServer) {
  18022. Server svr;
  18023. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18024. std::string header = "Not Set";
  18025. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18026. res.set_header(header, "value");
  18027. res.set_content("Page Content Page Content", "text/plain");
  18028. });
  18029. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18030. std::string header = "Not Set";
  18031. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18032. res.set_header("X-Test", header);
  18033. res.set_content("Page Content Page Content", "text/plain");
  18034. });
  18035. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18036. auto se = detail::scope_exit([&] {
  18037. svr.stop();
  18038. thread.join();
  18039. ASSERT_FALSE(svr.is_running());
  18040. });
  18041. svr.wait_until_ready();
  18042. Client cli(HOST, PORT);
  18043. {
  18044. auto res = cli.Get(
  18045. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18047. EXPECT_EQ("Page Content Page Content", res->body);
  18048. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18049. }
  18050. {
  18051. auto res = cli.Get(
  18052. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18054. EXPECT_EQ("Page Content Page Content", res->body);
  18055. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18056. }
  18057. }
  18058. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18059. auto handled = false;
  18060. Server svr;
  18061. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18062. thread t = thread([&] { svr.listen(HOST, PORT); });
  18063. auto se = detail::scope_exit([&] {
  18064. svr.stop();
  18065. t.join();
  18066. ASSERT_FALSE(svr.is_running());
  18067. ASSERT_FALSE(handled);
  18068. });
  18069. svr.wait_until_ready();
  18070. auto req = "POST /test HTTP/1.1\r\n"
  18071. "Content-Length: x\r\n"
  18072. "\r\n";
  18073. std::string response;
  18074. ASSERT_TRUE(send_request(1, req, &response));
  18075. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18076. response.substr(0, response.find("\r\n")));
  18077. }
  18078. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18079. // case-insensitive, and a server that receives a 100-continue expectation in
  18080. // an HTTP/1.0 request MUST ignore it.
  18081. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18082. std::string response;
  18083. ASSERT_TRUE(send_request(1, req, &response, port));
  18084. *got_100 = response.find("100 Continue") != std::string::npos;
  18085. }
  18086. class ExpectTokenTest : public ::testing::Test {
  18087. protected:
  18088. void SetUp() override {
  18089. svr_.Post("/p", [](const Request &, Response &res) {
  18090. res.set_content("ok", "text/plain");
  18091. });
  18092. port_ = svr_.bind_to_any_port(HOST);
  18093. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18094. svr_.wait_until_ready();
  18095. }
  18096. void TearDown() override {
  18097. svr_.stop();
  18098. if (thread_.joinable()) { thread_.join(); }
  18099. }
  18100. std::string request(const char *version, const char *expect_value) const {
  18101. return std::string("POST /p ") + version +
  18102. "\r\n"
  18103. "Host: localhost\r\n"
  18104. "Content-Length: 2\r\n"
  18105. "Connection: close\r\n"
  18106. "Expect: " +
  18107. expect_value +
  18108. "\r\n"
  18109. "\r\n"
  18110. "hi";
  18111. }
  18112. Server svr_;
  18113. int port_ = 0;
  18114. thread thread_;
  18115. };
  18116. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18117. bool got_100 = false;
  18118. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18119. EXPECT_TRUE(got_100);
  18120. }
  18121. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18122. bool got_100 = true;
  18123. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18124. EXPECT_FALSE(got_100);
  18125. }
  18126. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18127. bool got_100 = false;
  18128. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18129. EXPECT_TRUE(got_100);
  18130. }
  18131. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18132. bool got_100 = false;
  18133. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18134. EXPECT_TRUE(got_100);
  18135. }
  18136. // `100 Continue` is sent only when the server starts reading the body, so a
  18137. // request rejected before that never invites the client to send it. The
  18138. // requests below carry the expectation but withhold the body, as a client
  18139. // waiting for `100 Continue` would.
  18140. // A POST that expects `100 Continue` and withholds its two-byte body.
  18141. static std::string expect_headers_only(const std::string &path) {
  18142. return "POST " + path +
  18143. " HTTP/1.1\r\n"
  18144. "Host: localhost\r\n"
  18145. "Content-Length: 2\r\n"
  18146. "Expect: 100-continue\r\n"
  18147. "\r\n";
  18148. }
  18149. class ExpectLazyContinueTest : public ::testing::Test {
  18150. protected:
  18151. void SetUp() override {
  18152. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18153. if (req.path == "/pre-routing") {
  18154. res.status = StatusCode::Unauthorized_401;
  18155. return Server::HandlerResponse::Handled;
  18156. }
  18157. return Server::HandlerResponse::Unhandled;
  18158. });
  18159. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18160. if (req.matched_route == "/pre-request") {
  18161. res.status = StatusCode::Forbidden_403;
  18162. return Server::HandlerResponse::Handled;
  18163. }
  18164. return Server::HandlerResponse::Unhandled;
  18165. });
  18166. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18167. res.set_content("ok", "text/plain");
  18168. });
  18169. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18170. res.set_content("ok", "text/plain");
  18171. });
  18172. svr_.Post("/reader-used", [](const Request &, Response &res,
  18173. const ContentReader &content_reader) {
  18174. std::string body;
  18175. content_reader([&](const char *data, size_t len) {
  18176. body.append(data, len);
  18177. return true;
  18178. });
  18179. res.set_content(body, "text/plain");
  18180. });
  18181. svr_.Post("/reader-unused",
  18182. [](const Request &, Response &res, const ContentReader &) {
  18183. res.set_content("ignored", "text/plain");
  18184. });
  18185. port_ = svr_.bind_to_any_port(HOST);
  18186. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18187. svr_.wait_until_ready();
  18188. }
  18189. void TearDown() override {
  18190. svr_.stop();
  18191. if (thread_.joinable()) { thread_.join(); }
  18192. }
  18193. // Sends `req` and reads until the server closes the connection. Returns
  18194. // false if the read had to wait for the client-side timeout instead.
  18195. bool send_until_closed(const std::string &req, std::string *resp) const {
  18196. auto start = std::chrono::steady_clock::now();
  18197. if (!send_request(3, req, resp, port_)) { return false; }
  18198. auto elapsed = std::chrono::steady_clock::now() - start;
  18199. return elapsed < std::chrono::seconds(2);
  18200. }
  18201. // The final response comes without `100 Continue`, and the server closes
  18202. // the connection since the body may or may not follow.
  18203. void expect_final_without_interim(const std::string &path,
  18204. const char *status_line) const {
  18205. std::string resp;
  18206. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18207. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18208. EXPECT_EQ(0u, resp.find(status_line));
  18209. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18210. }
  18211. Server svr_;
  18212. int port_ = 0;
  18213. thread thread_;
  18214. };
  18215. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18216. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18217. }
  18218. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18219. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18220. }
  18221. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18222. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18223. }
  18224. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18225. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18226. }
  18227. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18228. // The body follows once `100 Continue` has had time to arrive.
  18229. auto req = expect_headers_only("/reader-used");
  18230. req.insert(req.size() - 2, "Connection: close\r\n");
  18231. std::string resp;
  18232. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18233. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18234. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18235. EXPECT_NE(std::string::npos, resp.find("hi"));
  18236. }
  18237. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18238. // Large enough for the client to add `Expect: 100-continue` itself.
  18239. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18240. std::atomic<bool> body_sent{false};
  18241. Client cli(HOST, port_);
  18242. auto res = cli.Post(
  18243. "/pre-request", length,
  18244. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18245. body_sent = true;
  18246. std::string chunk(len, 'x');
  18247. sink.write(chunk.data(), chunk.size());
  18248. return true;
  18249. },
  18250. "application/octet-stream");
  18251. ASSERT_TRUE(res);
  18252. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18253. EXPECT_FALSE(body_sent);
  18254. }
  18255. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18256. Server svr;
  18257. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18258. return StatusCode::ExpectationFailed_417;
  18259. });
  18260. svr.Post("/p", [](const Request &, Response &res) {
  18261. res.set_content("ok", "text/plain");
  18262. });
  18263. auto port = svr.bind_to_any_port(HOST);
  18264. thread t = thread([&] { svr.listen_after_bind(); });
  18265. auto se = detail::scope_exit([&] {
  18266. svr.stop();
  18267. t.join();
  18268. });
  18269. svr.wait_until_ready();
  18270. std::string resp;
  18271. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18272. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18273. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18274. // Exactly one response: the route handler must not run after the 417.
  18275. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18276. }
  18277. #ifndef _WIN32
  18278. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18279. static constexpr char reject[] = "Unauthorized";
  18280. static constexpr char accept[] = "Upload accepted";
  18281. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18282. Server svr;
  18283. svr.set_expect_100_continue_handler(
  18284. [](const Request & /*req*/, Response &res) {
  18285. res.status = StatusCode::Unauthorized_401;
  18286. res.set_content(reject, "text/plain");
  18287. return res.status;
  18288. });
  18289. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18290. res.set_content(accept, "text/plain");
  18291. });
  18292. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18293. auto se = detail::scope_exit([&] {
  18294. svr.stop();
  18295. thread.join();
  18296. ASSERT_FALSE(svr.is_running());
  18297. });
  18298. svr.wait_until_ready();
  18299. {
  18300. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18301. curl_easy_init(), &curl_easy_cleanup};
  18302. ASSERT_NE(curl, nullptr);
  18303. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18304. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18305. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18306. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18307. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18308. &curl_slist_free_all};
  18309. ASSERT_NE(list, nullptr);
  18310. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18311. struct read_data {
  18312. uint64_t read_size;
  18313. uint64_t total_size;
  18314. } data = {0, total_size};
  18315. using read_callback_t =
  18316. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18317. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18318. void *userdata) -> size_t {
  18319. read_data *d = (read_data *)userdata;
  18320. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18321. std::fill_n(ptr, size * nmemb, 'A');
  18322. d->read_size += size * nmemb;
  18323. return size * nmemb;
  18324. };
  18325. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18326. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18327. std::vector<char> buffer;
  18328. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18329. using write_callback_t =
  18330. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18331. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18332. void *userdata) -> size_t {
  18333. std::vector<char> *buf = (std::vector<char> *)userdata;
  18334. buf->reserve(buf->size() + size * nmemb + 1);
  18335. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18336. return size * nmemb;
  18337. };
  18338. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18339. {
  18340. const auto res = curl_easy_perform(curl.get());
  18341. ASSERT_EQ(res, CURLE_OK);
  18342. }
  18343. {
  18344. auto response_code = long{};
  18345. const auto res =
  18346. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18347. ASSERT_EQ(res, CURLE_OK);
  18348. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18349. }
  18350. {
  18351. auto dl = curl_off_t{};
  18352. const auto res =
  18353. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18354. ASSERT_EQ(res, CURLE_OK);
  18355. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18356. }
  18357. {
  18358. buffer.push_back('\0');
  18359. ASSERT_STRCASEEQ(buffer.data(), reject);
  18360. }
  18361. }
  18362. }
  18363. #endif
  18364. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18365. // Regression test for #2458.
  18366. //
  18367. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18368. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18369. // ticket can make the client socket spuriously readable during the
  18370. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18371. // the client withholds the body and then blocks reading a response that never
  18372. // comes, failing with `Failed to read connection`.
  18373. //
  18374. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18375. // within the timeout. This raw OpenSSL server deliberately never sends
  18376. // `100 Continue`; the client must still deliver the body and receive 200.
  18377. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18378. signal(SIGPIPE, SIG_IGN);
  18379. const auto port = PORT + 4;
  18380. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18381. ASSERT_NE(srv, INVALID_SOCKET);
  18382. int opt = 1;
  18383. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18384. sockaddr_in addr{};
  18385. addr.sin_family = AF_INET;
  18386. addr.sin_port = htons(static_cast<uint16_t>(port));
  18387. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18388. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18389. ASSERT_EQ(0, ::listen(srv, 1));
  18390. std::atomic<size_t> server_body_bytes{0};
  18391. auto server_thread = std::thread([&] {
  18392. sockaddr_in cli_addr{};
  18393. socklen_t cli_len = sizeof(cli_addr);
  18394. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18395. if (cli == INVALID_SOCKET) { return; }
  18396. // Bound the lifetime of the server side so a buggy client (which never
  18397. // sends the body) cannot make this thread block forever on join.
  18398. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18399. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18400. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18401. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18402. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18403. SSL *ssl = SSL_new(ctx);
  18404. SSL_set_fd(ssl, static_cast<int>(cli));
  18405. if (SSL_accept(ssl) > 0) {
  18406. // Read the request headers. Reading here also flushes the TLS 1.3
  18407. // session tickets to the client. Deliberately do NOT send
  18408. // `100 Continue`.
  18409. std::string buf;
  18410. char tmp[1024];
  18411. while (buf.find("\r\n\r\n") == std::string::npos) {
  18412. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18413. if (n <= 0) { break; }
  18414. buf.append(tmp, static_cast<size_t>(n));
  18415. }
  18416. // A correct client sends the body now; count what arrives.
  18417. auto pos = buf.find("\r\n\r\n");
  18418. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18419. while (body < 4096) {
  18420. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18421. if (n <= 0) { break; }
  18422. body += static_cast<size_t>(n);
  18423. }
  18424. server_body_bytes = body;
  18425. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18426. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18427. SSL_shutdown(ssl);
  18428. }
  18429. SSL_free(ssl);
  18430. detail::close_socket(cli);
  18431. SSL_CTX_free(ctx);
  18432. });
  18433. auto se = detail::scope_exit([&] {
  18434. server_thread.join();
  18435. detail::close_socket(srv);
  18436. });
  18437. SSLClient cli("127.0.0.1", port);
  18438. cli.enable_server_certificate_verification(false);
  18439. cli.set_connection_timeout(5, 0);
  18440. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18441. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18442. std::string body(4096, 'A');
  18443. auto res = cli.Put("/api/test", body, "application/json");
  18444. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18445. EXPECT_EQ(StatusCode::OK_200, res->status);
  18446. EXPECT_EQ(body.size(), server_body_bytes.load());
  18447. }
  18448. #endif
  18449. template <typename S, typename C>
  18450. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18451. svr.Get("/stream", [&](const Request &, Response &res) {
  18452. auto data = new std::string("01234567890123456789");
  18453. res.set_content_provider(
  18454. data->size(), "text/plain",
  18455. [&, data](size_t offset, size_t length, DataSink &sink) {
  18456. const size_t DATA_CHUNK_SIZE = 4;
  18457. const auto &d = *data;
  18458. std::this_thread::sleep_for(std::chrono::seconds(1));
  18459. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18460. return true;
  18461. },
  18462. [data](bool success) {
  18463. EXPECT_FALSE(success);
  18464. delete data;
  18465. });
  18466. });
  18467. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18468. auto i = new size_t(0);
  18469. res.set_content_provider(
  18470. "text/plain",
  18471. [i](size_t, DataSink &sink) {
  18472. if (*i < 5) {
  18473. std::this_thread::sleep_for(std::chrono::seconds(1));
  18474. sink.write("abcd", 4);
  18475. (*i)++;
  18476. } else {
  18477. sink.done();
  18478. }
  18479. return true;
  18480. },
  18481. [i](bool success) {
  18482. EXPECT_FALSE(success);
  18483. delete i;
  18484. });
  18485. });
  18486. svr.Get("/chunked", [&](const Request &, Response &res) {
  18487. auto i = new size_t(0);
  18488. res.set_chunked_content_provider(
  18489. "text/plain",
  18490. [i](size_t, DataSink &sink) {
  18491. if (*i < 5) {
  18492. std::this_thread::sleep_for(std::chrono::seconds(1));
  18493. sink.os << "abcd";
  18494. (*i)++;
  18495. } else {
  18496. sink.done();
  18497. }
  18498. return true;
  18499. },
  18500. [i](bool success) {
  18501. EXPECT_FALSE(success);
  18502. delete i;
  18503. });
  18504. });
  18505. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18506. auto se = detail::scope_exit([&] {
  18507. svr.stop();
  18508. listen_thread.join();
  18509. ASSERT_FALSE(svr.is_running());
  18510. });
  18511. svr.wait_until_ready();
  18512. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18513. {
  18514. auto start = std::chrono::steady_clock::now();
  18515. auto res = cli.Get("/stream");
  18516. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18517. std::chrono::steady_clock::now() - start)
  18518. .count();
  18519. ASSERT_FALSE(res);
  18520. EXPECT_EQ(Error::Read, res.error());
  18521. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18522. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18523. }
  18524. {
  18525. auto start = std::chrono::steady_clock::now();
  18526. auto res = cli.Get("/stream_without_length");
  18527. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18528. std::chrono::steady_clock::now() - start)
  18529. .count();
  18530. ASSERT_FALSE(res);
  18531. EXPECT_EQ(Error::Read, res.error());
  18532. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18533. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18534. }
  18535. {
  18536. auto start = std::chrono::steady_clock::now();
  18537. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18538. EXPECT_EQ("abcd", string(data, data_length));
  18539. return true;
  18540. });
  18541. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18542. std::chrono::steady_clock::now() - start)
  18543. .count();
  18544. ASSERT_FALSE(res);
  18545. EXPECT_EQ(Error::Read, res.error());
  18546. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18547. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18548. }
  18549. }
  18550. TEST(MaxTimeoutTest, ContentStream) {
  18551. time_t timeout = 2000;
  18552. time_t threshold = 200;
  18553. Server svr;
  18554. Client cli("localhost", PORT);
  18555. max_timeout_test(svr, cli, timeout, threshold);
  18556. }
  18557. #ifdef CPPHTTPLIB_SSL_ENABLED
  18558. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18559. time_t timeout = 2000;
  18560. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18561. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18562. SSLClient cli("localhost", PORT);
  18563. cli.enable_server_certificate_verification(false);
  18564. max_timeout_test(svr, cli, timeout, threshold);
  18565. }
  18566. #endif
  18567. class EventDispatcher {
  18568. public:
  18569. EventDispatcher() {}
  18570. bool wait_event(DataSink *sink) {
  18571. unique_lock<mutex> lk(m_);
  18572. int id = id_;
  18573. // Wait with timeout to prevent hanging if client disconnects
  18574. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18575. [&] { return cid_ == id; })) {
  18576. return false; // Timeout occurred
  18577. }
  18578. sink->write(message_.data(), message_.size());
  18579. return true;
  18580. }
  18581. void send_event(const string &message) {
  18582. lock_guard<mutex> lk(m_);
  18583. cid_ = id_++;
  18584. message_ = message;
  18585. cv_.notify_all();
  18586. }
  18587. private:
  18588. mutex m_;
  18589. condition_variable cv_;
  18590. atomic_int id_{0};
  18591. atomic_int cid_{-1};
  18592. string message_;
  18593. };
  18594. TEST(ClientInThreadTest, Issue2068) {
  18595. EventDispatcher ed;
  18596. Server svr;
  18597. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18598. res.set_chunked_content_provider("text/event-stream",
  18599. [&](size_t /*offset*/, DataSink &sink) {
  18600. return ed.wait_event(&sink);
  18601. });
  18602. });
  18603. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18604. svr.wait_until_ready();
  18605. thread event_thread([&] {
  18606. int id = 0;
  18607. while (svr.is_running()) {
  18608. this_thread::sleep_for(chrono::milliseconds(500));
  18609. std::stringstream ss;
  18610. ss << "data: " << id << "\n\n";
  18611. ed.send_event(ss.str());
  18612. id++;
  18613. }
  18614. });
  18615. auto se = detail::scope_exit([&] {
  18616. svr.stop();
  18617. listen_thread.join();
  18618. event_thread.join();
  18619. ASSERT_FALSE(svr.is_running());
  18620. });
  18621. {
  18622. auto client = detail::make_unique<Client>(HOST, PORT);
  18623. client->set_read_timeout(std::chrono::minutes(10));
  18624. std::atomic<bool> stop{false};
  18625. std::thread t([&] {
  18626. client->Get("/event1",
  18627. [&](const char *, size_t) -> bool { return !stop; });
  18628. });
  18629. std::this_thread::sleep_for(std::chrono::seconds(2));
  18630. stop = true;
  18631. client->stop();
  18632. t.join();
  18633. // Reset client after thread has finished
  18634. client.reset();
  18635. }
  18636. }
  18637. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18638. auto handled = false;
  18639. Server svr;
  18640. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18641. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18642. auto se = detail::scope_exit([&] {
  18643. svr.stop();
  18644. t.join();
  18645. ASSERT_FALSE(svr.is_running());
  18646. ASSERT_FALSE(handled);
  18647. });
  18648. svr.wait_until_ready();
  18649. // Two Content-Length headers with different values — must be rejected
  18650. auto req = "POST /test HTTP/1.1\r\n"
  18651. "Content-Length: 5\r\n"
  18652. "Content-Length: 10\r\n"
  18653. "\r\n"
  18654. "hello";
  18655. std::string response;
  18656. ASSERT_TRUE(send_request(1, req, &response));
  18657. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18658. response.substr(0, response.find("\r\n")));
  18659. }
  18660. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18661. auto handled = false;
  18662. Server svr;
  18663. svr.Post("/test", [&](const Request &, Response &res) {
  18664. handled = true;
  18665. res.set_content("ok", "text/plain");
  18666. });
  18667. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18668. auto se = detail::scope_exit([&] {
  18669. svr.stop();
  18670. t.join();
  18671. ASSERT_FALSE(svr.is_running());
  18672. ASSERT_TRUE(handled);
  18673. });
  18674. svr.wait_until_ready();
  18675. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18676. auto req = "POST /test HTTP/1.1\r\n"
  18677. "Host: localhost\r\n"
  18678. "Content-Length: 5\r\n"
  18679. "Content-Length: 5\r\n"
  18680. "\r\n"
  18681. "hello";
  18682. std::string response;
  18683. ASSERT_TRUE(send_request(1, req, &response));
  18684. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18685. }
  18686. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18687. Server svr;
  18688. svr.Get("/test", [](const Request &, Response &res) {
  18689. res.set_content("ok", "text/plain");
  18690. });
  18691. auto port = svr.bind_to_any_port(HOST);
  18692. thread t = thread([&] { svr.listen_after_bind(); });
  18693. auto se = detail::scope_exit([&] {
  18694. svr.stop();
  18695. t.join();
  18696. ASSERT_FALSE(svr.is_running());
  18697. });
  18698. svr.wait_until_ready();
  18699. auto status_line = [&](const std::string &host_lines) {
  18700. std::string res;
  18701. send_request(
  18702. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18703. &res, port);
  18704. return res.substr(0, res.find("\r\n"));
  18705. };
  18706. const char *accepted[] = {
  18707. "Host: localhost\r\n",
  18708. "Host: a.example:8080\r\n",
  18709. "Host: my_service\r\n",
  18710. "Host: [::1]:8080\r\n",
  18711. "Host: [fe80::1%25eth0]\r\n",
  18712. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18713. };
  18714. for (auto host_lines : accepted) {
  18715. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18716. }
  18717. const char *rejected[] = {
  18718. "Host: a.example\r\nHost: b.example\r\n",
  18719. "Host: a.example\r\nHost: a.example\r\n",
  18720. "Host: a@b.example\r\n",
  18721. "Host: a.example/b\r\n",
  18722. "Host: a.example\\b\r\n",
  18723. "Host: a.example?b\r\n",
  18724. "Host: a.example#b\r\n",
  18725. "Host: a.example b.example\r\n",
  18726. };
  18727. for (auto host_lines : rejected) {
  18728. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18729. << host_lines;
  18730. }
  18731. }
  18732. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18733. Server svr;
  18734. svr.Get("/", [](const Request &req, Response &res) {
  18735. EXPECT_EQ(2U, req.trailers.size());
  18736. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18737. // Denied
  18738. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18739. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18740. // Accepted
  18741. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18742. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18743. EXPECT_TRUE(req.has_trailer("X-World"));
  18744. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18745. res.set_content("ok", "text/plain");
  18746. });
  18747. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18748. auto se = detail::scope_exit([&] {
  18749. svr.stop();
  18750. t.join();
  18751. ASSERT_FALSE(svr.is_running());
  18752. });
  18753. svr.wait_until_ready();
  18754. const std::string req = "GET / HTTP/1.1\r\n"
  18755. "Transfer-Encoding: chunked\r\n"
  18756. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18757. "\r\n"
  18758. "0\r\n"
  18759. "Content-Length: 10\r\n"
  18760. "Host: internal.local\r\n"
  18761. "Content-Type: malicious/content\r\n"
  18762. "Cookie: any\r\n"
  18763. "Set-Cookie: any\r\n"
  18764. "X-Forwarded-For: attacker.com\r\n"
  18765. "X-Real-Ip: 1.1.1.1\r\n"
  18766. "X-Hello: hello\r\n"
  18767. "X-World: world\r\n"
  18768. "\r\n";
  18769. std::string res;
  18770. ASSERT_TRUE(send_request(1, req, &res));
  18771. }
  18772. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18773. // several field lines, and the combined value is what has to be parsed. A
  18774. // Trailer field split across lines therefore declares every name it lists;
  18775. // reading only the first line silently drops the trailers the later lines
  18776. // declare. The prohibited-trailer filter still applies to every line.
  18777. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18778. Server svr;
  18779. size_t observed_trailer_count = 0;
  18780. std::string observed_hello;
  18781. std::string observed_world;
  18782. bool observed_content_length = true;
  18783. svr.Get("/", [&](const Request &req, Response &res) {
  18784. observed_trailer_count = req.trailers.size();
  18785. observed_hello = req.get_trailer_value("X-Hello");
  18786. observed_world = req.get_trailer_value("X-World");
  18787. observed_content_length = req.has_trailer("Content-Length");
  18788. res.set_content("ok", "text/plain");
  18789. });
  18790. auto port = svr.bind_to_any_port(HOST);
  18791. thread t = thread([&]() { svr.listen_after_bind(); });
  18792. auto se = detail::scope_exit([&] {
  18793. svr.stop();
  18794. t.join();
  18795. ASSERT_FALSE(svr.is_running());
  18796. });
  18797. svr.wait_until_ready();
  18798. const std::string req = "GET / HTTP/1.1\r\n"
  18799. "Host: localhost\r\n"
  18800. "Transfer-Encoding: chunked\r\n"
  18801. "Trailer: X-Hello\r\n"
  18802. "Trailer: X-World, Content-Length\r\n"
  18803. "\r\n"
  18804. "0\r\n"
  18805. "X-Hello: hello\r\n"
  18806. "X-World: world\r\n"
  18807. "Content-Length: 10\r\n"
  18808. "\r\n";
  18809. std::string res;
  18810. ASSERT_TRUE(send_request(1, req, &res, port));
  18811. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18812. // Accepted: both field lines contribute to the declared set
  18813. EXPECT_EQ(2U, observed_trailer_count);
  18814. EXPECT_EQ(observed_hello, "hello");
  18815. EXPECT_EQ(observed_world, "world");
  18816. // Denied: a prohibited name stays prohibited on a later field line
  18817. EXPECT_FALSE(observed_content_length);
  18818. }
  18819. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18820. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18821. // unbounded run of fields that are never declared, because the counter would
  18822. // only advance for declared fields.
  18823. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18824. Server svr;
  18825. bool handler_called = false;
  18826. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18827. handler_called = true;
  18828. res.set_content("ok", "text/plain");
  18829. });
  18830. auto port = svr.bind_to_any_port(HOST);
  18831. thread t = thread([&]() { svr.listen_after_bind(); });
  18832. auto se = detail::scope_exit([&] {
  18833. svr.stop();
  18834. t.join();
  18835. ASSERT_FALSE(svr.is_running());
  18836. });
  18837. svr.wait_until_ready();
  18838. // Declare nothing, then send far more undeclared trailer fields than the
  18839. // header-count limit. Parsing must stop and reject the request rather than
  18840. // read every line.
  18841. std::string req = "GET / HTTP/1.1\r\n"
  18842. "Transfer-Encoding: chunked\r\n"
  18843. "\r\n"
  18844. "0\r\n";
  18845. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18846. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18847. }
  18848. req += "\r\n";
  18849. std::string res;
  18850. ASSERT_TRUE(send_request(1, req, &res, port));
  18851. // The request is rejected before the handler runs.
  18852. EXPECT_FALSE(handler_called);
  18853. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18854. }
  18855. // The set of declared trailer names is capped so a peer cannot grow it without
  18856. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18857. // declared past the cap is not honored, even if the field is actually sent.
  18858. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18859. Server svr;
  18860. // One name inside the cap and one past it, so the test tracks the cap rather
  18861. // than a fixed count.
  18862. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18863. const std::string within_cap_name = "X-T-0";
  18864. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18865. bool observed_within_cap = false;
  18866. bool observed_past_cap = false;
  18867. svr.Get("/", [&](const Request &req, Response &res) {
  18868. observed_within_cap = req.has_trailer(within_cap_name);
  18869. observed_past_cap = req.has_trailer(past_cap_name);
  18870. res.set_content("ok", "text/plain");
  18871. });
  18872. auto port = svr.bind_to_any_port(HOST);
  18873. thread t = thread([&]() { svr.listen_after_bind(); });
  18874. auto se = detail::scope_exit([&] {
  18875. svr.stop();
  18876. t.join();
  18877. ASSERT_FALSE(svr.is_running());
  18878. });
  18879. svr.wait_until_ready();
  18880. // Declare more trailer names than the cap in a single Trailer field, then
  18881. // actually send the first (within the cap) and the last (past it).
  18882. std::string trailer_decl = "Trailer: ";
  18883. for (int i = 0; i < declared_count; i++) {
  18884. if (i != 0) { trailer_decl += ", "; }
  18885. trailer_decl += "X-T-" + std::to_string(i);
  18886. }
  18887. trailer_decl += "\r\n";
  18888. const std::string req = "GET / HTTP/1.1\r\n"
  18889. "Host: localhost\r\n"
  18890. "Transfer-Encoding: chunked\r\n" +
  18891. trailer_decl +
  18892. "\r\n"
  18893. "0\r\n" +
  18894. within_cap_name + ": a\r\n" + past_cap_name +
  18895. ": b\r\n"
  18896. "\r\n";
  18897. std::string res;
  18898. ASSERT_TRUE(send_request(1, req, &res, port));
  18899. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18900. // A name within the cap is honored; one declared past the cap is dropped.
  18901. EXPECT_TRUE(observed_within_cap);
  18902. EXPECT_FALSE(observed_past_cap);
  18903. }
  18904. // A direct client that is not listed in trusted_proxies must not be able to
  18905. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18906. // the peer address on the actual TCP connection determines whether the
  18907. // header is honored.
  18908. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18909. Server svr;
  18910. // Deliberately does NOT include the loopback address the test client
  18911. // actually connects from, so the direct connection is not a trusted proxy.
  18912. svr.set_trusted_proxies({"203.0.113.66"});
  18913. std::string observed_remote_addr;
  18914. svr.Get("/ip", [&](const Request &req, Response &res) {
  18915. observed_remote_addr = req.remote_addr;
  18916. res.set_content("ok", "text/plain");
  18917. });
  18918. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18919. auto se = detail::scope_exit([&] {
  18920. svr.stop();
  18921. t.join();
  18922. ASSERT_FALSE(svr.is_running());
  18923. });
  18924. svr.wait_until_ready();
  18925. Client cli(HOST, PORT);
  18926. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18928. EXPECT_EQ(StatusCode::OK_200, res->status);
  18929. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18930. // ignored entirely and the real connection-level address retained.
  18931. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18932. observed_remote_addr == "127.0.0.1");
  18933. }
  18934. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18935. Server svr;
  18936. std::string observed_remote_addr;
  18937. std::string observed_xff;
  18938. svr.Get("/ip", [&](const Request &req, Response &res) {
  18939. observed_remote_addr = req.remote_addr;
  18940. observed_xff = req.get_header_value("X-Forwarded-For");
  18941. res.set_content("ok", "text/plain");
  18942. });
  18943. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18944. auto se = detail::scope_exit([&] {
  18945. svr.stop();
  18946. t.join();
  18947. ASSERT_FALSE(svr.is_running());
  18948. });
  18949. svr.wait_until_ready();
  18950. Client cli(HOST, PORT);
  18951. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18953. EXPECT_EQ(StatusCode::OK_200, res->status);
  18954. EXPECT_EQ(observed_xff, "203.0.113.66");
  18955. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18956. observed_remote_addr == "127.0.0.1");
  18957. }
  18958. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18959. Server svr;
  18960. svr.set_trusted_proxies({"203.0.113.66"});
  18961. std::string observed_remote_addr;
  18962. std::string observed_xff;
  18963. svr.Get("/ip", [&](const Request &req, Response &res) {
  18964. observed_remote_addr = req.remote_addr;
  18965. observed_xff = req.get_header_value("X-Forwarded-For");
  18966. res.set_content("ok", "text/plain");
  18967. });
  18968. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18969. auto se = detail::scope_exit([&] {
  18970. svr.stop();
  18971. t.join();
  18972. ASSERT_FALSE(svr.is_running());
  18973. });
  18974. svr.wait_until_ready();
  18975. Client cli(HOST, PORT);
  18976. auto res = cli.Get("/ip");
  18977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18978. EXPECT_EQ(StatusCode::OK_200, res->status);
  18979. EXPECT_EQ(observed_xff, "");
  18980. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18981. observed_remote_addr == "127.0.0.1");
  18982. }
  18983. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  18984. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  18985. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  18986. Server svr;
  18987. svr.set_trusted_proxies({"127.0.0.1"});
  18988. svr.Get("/ip", [](const Request &req, Response &res) {
  18989. res.set_content(req.remote_addr, "text/plain");
  18990. });
  18991. auto port = svr.bind_to_any_port("::");
  18992. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  18993. thread t = thread([&] { svr.listen_after_bind(); });
  18994. auto se = detail::scope_exit([&] {
  18995. svr.stop();
  18996. t.join();
  18997. ASSERT_FALSE(svr.is_running());
  18998. });
  18999. svr.wait_until_ready();
  19000. Client cli("127.0.0.1", port);
  19001. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19003. EXPECT_EQ("198.51.100.23", res->body);
  19004. }
  19005. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19006. Server svr;
  19007. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19008. svr.Get("/ip", [](const Request &req, Response &res) {
  19009. res.set_content(req.remote_addr, "text/plain");
  19010. });
  19011. auto port = svr.bind_to_any_port(HOST);
  19012. ASSERT_GT(port, 0);
  19013. thread t = thread([&] { svr.listen_after_bind(); });
  19014. auto se = detail::scope_exit([&] {
  19015. svr.stop();
  19016. t.join();
  19017. ASSERT_FALSE(svr.is_running());
  19018. });
  19019. svr.wait_until_ready();
  19020. Client cli(HOST, port);
  19021. auto res = cli.Get(
  19022. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19024. EXPECT_EQ("198.51.100.23", res->body);
  19025. }
  19026. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19027. Server svr;
  19028. // Include the loopback address the test client actually connects from, so
  19029. // the direct connection itself is recognized as the trusted proxy hop.
  19030. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19031. std::string observed_remote_addr;
  19032. std::string observed_xff;
  19033. svr.Get("/ip", [&](const Request &req, Response &res) {
  19034. observed_remote_addr = req.remote_addr;
  19035. observed_xff = req.get_header_value("X-Forwarded-For");
  19036. res.set_content("ok", "text/plain");
  19037. });
  19038. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19039. auto se = detail::scope_exit([&] {
  19040. svr.stop();
  19041. t.join();
  19042. ASSERT_FALSE(svr.is_running());
  19043. });
  19044. svr.wait_until_ready();
  19045. Client cli(HOST, PORT);
  19046. auto res = cli.Get(
  19047. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19049. EXPECT_EQ(StatusCode::OK_200, res->status);
  19050. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19051. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19052. }
  19053. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19054. Server svr;
  19055. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19056. std::string observed_remote_addr;
  19057. std::string observed_xff;
  19058. svr.Get("/ip", [&](const Request &req, Response &res) {
  19059. observed_remote_addr = req.remote_addr;
  19060. observed_xff = req.get_header_value("X-Forwarded-For");
  19061. res.set_content("ok", "text/plain");
  19062. });
  19063. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19064. auto se = detail::scope_exit([&] {
  19065. svr.stop();
  19066. t.join();
  19067. ASSERT_FALSE(svr.is_running());
  19068. });
  19069. svr.wait_until_ready();
  19070. Client cli(HOST, PORT);
  19071. auto res = cli.Get(
  19072. "/ip",
  19073. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19075. EXPECT_EQ(StatusCode::OK_200, res->status);
  19076. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19077. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19078. }
  19079. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19080. Server svr;
  19081. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19082. std::string observed_remote_addr;
  19083. std::string observed_xff;
  19084. svr.Get("/ip", [&](const Request &req, Response &res) {
  19085. observed_remote_addr = req.remote_addr;
  19086. observed_xff = req.get_header_value("X-Forwarded-For");
  19087. res.set_content("ok", "text/plain");
  19088. });
  19089. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19090. auto se = detail::scope_exit([&] {
  19091. svr.stop();
  19092. t.join();
  19093. ASSERT_FALSE(svr.is_running());
  19094. });
  19095. svr.wait_until_ready();
  19096. Client cli(HOST, PORT);
  19097. auto res = cli.Get(
  19098. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19100. EXPECT_EQ(StatusCode::OK_200, res->status);
  19101. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19102. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19103. // and must not be selected.
  19104. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19105. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19106. }
  19107. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19108. Server svr;
  19109. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19110. std::string observed_remote_addr;
  19111. svr.Get("/ip", [&](const Request &req, Response &res) {
  19112. observed_remote_addr = req.remote_addr;
  19113. res.set_content("ok", "text/plain");
  19114. });
  19115. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19116. auto se = detail::scope_exit([&] {
  19117. svr.stop();
  19118. t.join();
  19119. ASSERT_FALSE(svr.is_running());
  19120. });
  19121. svr.wait_until_ready();
  19122. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19123. // a forged address and the trusted proxy's own address; the forged value must
  19124. // not win over the address the trusted proxy actually recorded.
  19125. Client cli(HOST, PORT);
  19126. auto res = cli.Get(
  19127. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19129. EXPECT_EQ(StatusCode::OK_200, res->status);
  19130. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19131. }
  19132. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19133. Server svr;
  19134. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19135. std::string observed_remote_addr;
  19136. std::string observed_xff;
  19137. svr.Get("/ip", [&](const Request &req, Response &res) {
  19138. observed_remote_addr = req.remote_addr;
  19139. observed_xff = req.get_header_value("X-Forwarded-For");
  19140. res.set_content("ok", "text/plain");
  19141. });
  19142. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19143. auto se = detail::scope_exit([&] {
  19144. svr.stop();
  19145. t.join();
  19146. ASSERT_FALSE(svr.is_running());
  19147. });
  19148. svr.wait_until_ready();
  19149. Client cli(HOST, PORT);
  19150. auto res = cli.Get(
  19151. "/ip",
  19152. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19154. EXPECT_EQ(StatusCode::OK_200, res->status);
  19155. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19156. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19157. }
  19158. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19159. Server svr;
  19160. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19161. std::string observed_remote_addr;
  19162. std::string observed_xff;
  19163. svr.Get("/ip", [&](const Request &req, Response &res) {
  19164. observed_remote_addr = req.remote_addr;
  19165. observed_xff = req.get_header_value("X-Forwarded-For");
  19166. res.set_content("ok", "text/plain");
  19167. });
  19168. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19169. auto se = detail::scope_exit([&] {
  19170. svr.stop();
  19171. t.join();
  19172. ASSERT_FALSE(svr.is_running());
  19173. });
  19174. svr.wait_until_ready();
  19175. std::string raw_req =
  19176. "GET /ip HTTP/1.1\r\n"
  19177. "Host: localhost\r\n"
  19178. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19179. "Connection: close\r\n"
  19180. "\r\n";
  19181. std::string out;
  19182. ASSERT_TRUE(send_request(5, raw_req, &out));
  19183. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19184. // Header parser trims surrounding whitespace of the header value
  19185. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19186. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19187. }
  19188. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19189. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19190. // their own X-Forwarded-For as a separate field line rather than extending the
  19191. // one the client sent, so every occurrence has to be taken into account.
  19192. // Reading only the first one hands back the address the client chose.
  19193. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19194. Server svr;
  19195. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19196. std::string observed_remote_addr;
  19197. size_t observed_xff_count = 0;
  19198. svr.Get("/ip", [&](const Request &req, Response &res) {
  19199. observed_remote_addr = req.remote_addr;
  19200. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19201. res.set_content("ok", "text/plain");
  19202. });
  19203. auto port = svr.bind_to_any_port(HOST);
  19204. thread t = thread([&]() { svr.listen_after_bind(); });
  19205. auto se = detail::scope_exit([&] {
  19206. svr.stop();
  19207. t.join();
  19208. ASSERT_FALSE(svr.is_running());
  19209. });
  19210. svr.wait_until_ready();
  19211. // The client supplies the first field line; the trusted proxy appends the
  19212. // address it observed as a second one.
  19213. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19214. "Host: localhost\r\n"
  19215. "X-Forwarded-For: 1.2.3.4\r\n"
  19216. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19217. "Connection: close\r\n"
  19218. "\r\n";
  19219. std::string out;
  19220. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19221. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19222. EXPECT_EQ(observed_xff_count, 2U);
  19223. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19224. // The same chain spread over one field line per hop derives the same client
  19225. // address, i.e. the split and the comma-joined representations agree.
  19226. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19227. "Host: localhost\r\n"
  19228. "X-Forwarded-For: 1.2.3.4\r\n"
  19229. "X-Forwarded-For: 198.51.100.23\r\n"
  19230. "X-Forwarded-For: 192.0.2.45\r\n"
  19231. "Connection: close\r\n"
  19232. "\r\n";
  19233. out.clear();
  19234. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19235. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19236. EXPECT_EQ(observed_xff_count, 3U);
  19237. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19238. }
  19239. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19240. // crash the server (it used to call front() on an empty vector inside
  19241. // get_client_ip). The connection-level remote address must be retained instead.
  19242. static void run_malformed_xff_test(const std::string &xff_value) {
  19243. Server svr;
  19244. svr.set_trusted_proxies({"192.0.2.45"});
  19245. std::string observed_remote_addr;
  19246. svr.Get("/ip", [&](const Request &req, Response &res) {
  19247. observed_remote_addr = req.remote_addr;
  19248. res.set_content("ok", "text/plain");
  19249. });
  19250. int port = 0;
  19251. thread t = thread([&]() {
  19252. port = svr.bind_to_any_port(HOST);
  19253. svr.listen_after_bind();
  19254. });
  19255. auto se = detail::scope_exit([&] {
  19256. svr.stop();
  19257. t.join();
  19258. ASSERT_FALSE(svr.is_running());
  19259. });
  19260. svr.wait_until_ready();
  19261. Client cli(HOST, port);
  19262. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19264. EXPECT_EQ(StatusCode::OK_200, res->status);
  19265. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19266. observed_remote_addr == "127.0.0.1");
  19267. }
  19268. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19269. run_malformed_xff_test("");
  19270. }
  19271. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19272. run_malformed_xff_test(",");
  19273. }
  19274. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19275. run_malformed_xff_test(", , ,");
  19276. }
  19277. // The same rule applies to Accept: a request whose acceptable types are spread
  19278. // over several field lines must be negotiated against all of them.
  19279. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19280. // case-insensitive connection options. Comparing the whole field value against
  19281. // one option misses a client that sends several of them, and misses every
  19282. // casing but the one written in the comparison.
  19283. //
  19284. // Sends req, reads the response, then reuses the same socket for a second
  19285. // request to find out whether the server kept the connection.
  19286. static void probe_connection_reuse(int port, const std::string &req,
  19287. bool *announced_close, bool *reusable) {
  19288. auto error = Error::Success;
  19289. auto sock = detail::create_client_socket(
  19290. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19291. /*connection_timeout_sec=*/5, 0,
  19292. /*read_timeout_sec=*/1, 0,
  19293. /*write_timeout_sec=*/5, 0, std::string(), error);
  19294. ASSERT_NE(sock, INVALID_SOCKET);
  19295. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19296. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19297. "Host: localhost\r\n"
  19298. "Connection: close\r\n"
  19299. "\r\n";
  19300. std::string first_response;
  19301. std::string second_response;
  19302. detail::process_client_socket(
  19303. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19304. [&](Stream &strm) {
  19305. if (strm.write(req.data(), req.size()) !=
  19306. static_cast<ssize_t>(req.size())) {
  19307. return false;
  19308. }
  19309. char buf[512];
  19310. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19311. // Headers plus the two-byte body of the handler below
  19312. while (reader.getline()) {
  19313. first_response += reader.ptr();
  19314. if (first_response.find("ok") != std::string::npos) { break; }
  19315. }
  19316. if (strm.write(second.data(), second.size()) !=
  19317. static_cast<ssize_t>(second.size())) {
  19318. return true;
  19319. }
  19320. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19321. while (reader2.getline()) {
  19322. second_response += reader2.ptr();
  19323. if (second_response.find("ok") != std::string::npos) { break; }
  19324. }
  19325. return true;
  19326. });
  19327. *announced_close =
  19328. first_response.find("Connection: close") != std::string::npos;
  19329. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19330. }
  19331. class ConnectionTokenTest : public ::testing::Test {
  19332. protected:
  19333. void SetUp() override {
  19334. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19335. res.set_content("ok", "text/plain");
  19336. });
  19337. port_ = svr_.bind_to_any_port(HOST);
  19338. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19339. svr_.wait_until_ready();
  19340. }
  19341. void TearDown() override {
  19342. svr_.stop();
  19343. if (thread_.joinable()) { thread_.join(); }
  19344. }
  19345. Server svr_;
  19346. int port_ = 0;
  19347. thread thread_;
  19348. };
  19349. // "close" alongside another option still closes the connection, and the
  19350. // response says so rather than leaving the peer to discover it.
  19351. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19352. bool announced_close = false;
  19353. bool reusable = true;
  19354. probe_connection_reuse(port_,
  19355. "GET /keepalive HTTP/1.1\r\n"
  19356. "Host: localhost\r\n"
  19357. "Connection: keep-alive, close\r\n"
  19358. "\r\n",
  19359. &announced_close, &reusable);
  19360. EXPECT_TRUE(announced_close);
  19361. EXPECT_FALSE(reusable);
  19362. }
  19363. // "close" split over two field lines is the same list, so it is honored too.
  19364. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19365. bool announced_close = false;
  19366. bool reusable = true;
  19367. probe_connection_reuse(port_,
  19368. "GET /keepalive HTTP/1.1\r\n"
  19369. "Host: localhost\r\n"
  19370. "Connection: keep-alive\r\n"
  19371. "Connection: close\r\n"
  19372. "\r\n",
  19373. &announced_close, &reusable);
  19374. EXPECT_TRUE(announced_close);
  19375. EXPECT_FALSE(reusable);
  19376. }
  19377. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19378. // keep-alive in the spelling everyone actually sends keeps its connection.
  19379. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19380. bool announced_close = false;
  19381. bool reusable = false;
  19382. probe_connection_reuse(port_,
  19383. "GET /keepalive HTTP/1.0\r\n"
  19384. "Host: localhost\r\n"
  19385. "Connection: keep-alive\r\n"
  19386. "\r\n",
  19387. &announced_close, &reusable);
  19388. EXPECT_FALSE(announced_close);
  19389. EXPECT_TRUE(reusable);
  19390. }
  19391. // A token the value merely contains is not the token itself.
  19392. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19393. bool announced_close = false;
  19394. bool reusable = false;
  19395. probe_connection_reuse(port_,
  19396. "GET /keepalive HTTP/1.1\r\n"
  19397. "Host: localhost\r\n"
  19398. "Connection: notclose\r\n"
  19399. "\r\n",
  19400. &announced_close, &reusable);
  19401. EXPECT_FALSE(announced_close);
  19402. EXPECT_TRUE(reusable);
  19403. }
  19404. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19405. Server svr;
  19406. std::vector<std::string> observed_types;
  19407. svr.Get("/", [&](const Request &req, Response &res) {
  19408. observed_types = req.accept_content_types;
  19409. res.set_content("ok", "text/plain");
  19410. });
  19411. auto port = svr.bind_to_any_port(HOST);
  19412. thread t = thread([&]() { svr.listen_after_bind(); });
  19413. auto se = detail::scope_exit([&] {
  19414. svr.stop();
  19415. t.join();
  19416. ASSERT_FALSE(svr.is_running());
  19417. });
  19418. svr.wait_until_ready();
  19419. Client cli(HOST, port);
  19420. Headers headers;
  19421. headers.emplace("Accept", "text/plain;q=0.5");
  19422. headers.emplace("Accept", "application/json");
  19423. auto res = cli.Get("/", headers);
  19424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19425. EXPECT_EQ(StatusCode::OK_200, res->status);
  19426. // Sorted by q-value, so the second field line's type comes first
  19427. ASSERT_EQ(2U, observed_types.size());
  19428. EXPECT_EQ("application/json", observed_types[0]);
  19429. EXPECT_EQ("text/plain", observed_types[1]);
  19430. }
  19431. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19432. // empty field line must not contribute a bare comma to the combined value.
  19433. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19434. Server svr;
  19435. std::vector<std::string> observed_types;
  19436. svr.Get("/", [&](const Request &req, Response &res) {
  19437. observed_types = req.accept_content_types;
  19438. res.set_content("ok", "text/plain");
  19439. });
  19440. auto port = svr.bind_to_any_port(HOST);
  19441. thread t = thread([&]() { svr.listen_after_bind(); });
  19442. auto se = detail::scope_exit([&] {
  19443. svr.stop();
  19444. t.join();
  19445. ASSERT_FALSE(svr.is_running());
  19446. });
  19447. svr.wait_until_ready();
  19448. // Empty first field line, then a real one
  19449. std::string raw_req = "GET / HTTP/1.1\r\n"
  19450. "Host: localhost\r\n"
  19451. "Accept:\r\n"
  19452. "Accept: application/json\r\n"
  19453. "Connection: close\r\n"
  19454. "\r\n";
  19455. std::string out;
  19456. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19457. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19458. ASSERT_EQ(1U, observed_types.size());
  19459. EXPECT_EQ("application/json", observed_types[0]);
  19460. }
  19461. // The skip in get_combined_header_value() is what keeps an empty field line
  19462. // from contributing a bare comma. Only a trailing empty field line exercises
  19463. // it: a leading one is already covered by the "combined is still empty" check,
  19464. // and parse_accept_header() now ignores the empty element either way, so the
  19465. // request-level test above can no longer tell the two apart.
  19466. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19467. Headers headers;
  19468. headers.emplace("Accept", "text/html");
  19469. headers.emplace("Accept", "");
  19470. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19471. headers.clear();
  19472. headers.emplace("Accept", "");
  19473. headers.emplace("Accept", "application/json");
  19474. EXPECT_EQ("application/json",
  19475. detail::get_combined_header_value(headers, "Accept"));
  19476. }
  19477. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19478. // An encoding offered on a later Accept-Encoding field line is still offered.
  19479. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19480. Server svr;
  19481. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19482. res.set_content(std::string(1024, 'x'), "text/plain");
  19483. });
  19484. auto port = svr.bind_to_any_port(HOST);
  19485. thread t = thread([&]() { svr.listen_after_bind(); });
  19486. auto se = detail::scope_exit([&] {
  19487. svr.stop();
  19488. t.join();
  19489. ASSERT_FALSE(svr.is_running());
  19490. });
  19491. svr.wait_until_ready();
  19492. Client cli(HOST, port);
  19493. cli.set_decompress(false);
  19494. Headers headers;
  19495. headers.emplace("Accept-Encoding", "identity");
  19496. headers.emplace("Accept-Encoding", "gzip");
  19497. auto res = cli.Get("/", headers);
  19498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19499. EXPECT_EQ(StatusCode::OK_200, res->status);
  19500. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19501. }
  19502. #endif
  19503. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19504. // Transfer-Encoding is not its body.
  19505. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19506. Server svr;
  19507. svr.set_payload_max_length(8);
  19508. svr.Post("/test", [](const Request &, Response &res) {
  19509. res.set_content("ok", "text/plain");
  19510. });
  19511. auto port = svr.bind_to_any_port(HOST);
  19512. ASSERT_GT(port, 0);
  19513. thread t = thread([&] { svr.listen_after_bind(); });
  19514. auto se = detail::scope_exit([&] {
  19515. svr.stop();
  19516. t.join();
  19517. ASSERT_FALSE(svr.is_running());
  19518. });
  19519. svr.wait_until_ready();
  19520. std::string resp;
  19521. ASSERT_TRUE(send_request(1,
  19522. "POST /test HTTP/1.1\r\n"
  19523. "Host: localhost\r\n"
  19524. "Connection: close\r\n"
  19525. "\r\n" +
  19526. std::string(16, 'X'),
  19527. &resp, port));
  19528. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19529. }
  19530. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19531. Server svr;
  19532. svr.Post("/post", [&](const Request &req, Response &res) {
  19533. res.set_content(req.body, "text/plain");
  19534. });
  19535. svr.Put("/put", [&](const Request &req, Response &res) {
  19536. res.set_content(req.body, "text/plain");
  19537. });
  19538. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19539. res.set_content(req.body, "text/plain");
  19540. });
  19541. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19542. res.set_content(req.body, "text/plain");
  19543. });
  19544. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19545. auto se = detail::scope_exit([&] {
  19546. svr.stop();
  19547. t.join();
  19548. ASSERT_FALSE(svr.is_running());
  19549. });
  19550. svr.wait_until_ready();
  19551. std::string resp;
  19552. // POST without Content-Length
  19553. ASSERT_TRUE(send_request(5,
  19554. "POST /post HTTP/1.1\r\n"
  19555. "Host: localhost\r\n"
  19556. "Connection: close\r\n"
  19557. "\r\n",
  19558. &resp));
  19559. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19560. // PUT without Content-Length
  19561. resp.clear();
  19562. ASSERT_TRUE(send_request(5,
  19563. "PUT /put HTTP/1.1\r\n"
  19564. "Host: localhost\r\n"
  19565. "Connection: close\r\n"
  19566. "\r\n",
  19567. &resp));
  19568. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19569. // PATCH without Content-Length
  19570. resp.clear();
  19571. ASSERT_TRUE(send_request(5,
  19572. "PATCH /patch HTTP/1.1\r\n"
  19573. "Host: localhost\r\n"
  19574. "Connection: close\r\n"
  19575. "\r\n",
  19576. &resp));
  19577. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19578. // DELETE without Content-Length
  19579. resp.clear();
  19580. ASSERT_TRUE(send_request(5,
  19581. "DELETE /delete HTTP/1.1\r\n"
  19582. "Host: localhost\r\n"
  19583. "Connection: close\r\n"
  19584. "\r\n",
  19585. &resp));
  19586. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19587. }
  19588. //==============================================================================
  19589. // open_stream() Tests
  19590. //==============================================================================
  19591. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19592. std::string result;
  19593. char buf[8192];
  19594. ssize_t n;
  19595. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19596. result.append(buf, static_cast<size_t>(n));
  19597. }
  19598. return result;
  19599. }
  19600. // Mock stream for unit tests
  19601. class MockStream : public Stream {
  19602. public:
  19603. std::string data;
  19604. size_t pos = 0;
  19605. ssize_t error_after = -1; // -1 = no error
  19606. explicit MockStream(const std::string &d, ssize_t err = -1)
  19607. : data(d), error_after(err) {}
  19608. bool is_readable() const override { return true; }
  19609. bool wait_readable() const override { return true; }
  19610. bool wait_writable() const override { return true; }
  19611. ssize_t read(char *ptr, size_t size) override {
  19612. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19613. if (pos >= data.size()) return 0;
  19614. size_t limit =
  19615. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19616. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19617. std::memcpy(ptr, data.data() + pos, to_read);
  19618. pos += to_read;
  19619. return static_cast<ssize_t>(to_read);
  19620. }
  19621. ssize_t write(const char *, size_t) override { return -1; }
  19622. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19623. ip = "127.0.0.1";
  19624. port = 0;
  19625. }
  19626. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19627. ip = "127.0.0.1";
  19628. port = 0;
  19629. }
  19630. socket_t socket() const override { return INVALID_SOCKET; }
  19631. time_t duration() const override { return 0; }
  19632. };
  19633. TEST(StreamHandleTest, Basic) {
  19634. ClientImpl::StreamHandle handle;
  19635. EXPECT_FALSE(handle.is_valid());
  19636. handle.response = detail::make_unique<Response>();
  19637. handle.error = Error::Connection;
  19638. EXPECT_FALSE(handle.is_valid());
  19639. handle.error = Error::Success;
  19640. EXPECT_TRUE(handle.is_valid());
  19641. }
  19642. TEST(BodyReaderTest, Basic) {
  19643. MockStream stream("Hello, World!");
  19644. detail::BodyReader reader;
  19645. reader.stream = &stream;
  19646. reader.content_length = 13;
  19647. char buf[32];
  19648. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19649. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19650. EXPECT_TRUE(reader.eof);
  19651. }
  19652. TEST(BodyReaderTest, NoStream) {
  19653. detail::BodyReader reader;
  19654. char buf[32];
  19655. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19656. EXPECT_EQ(Error::Connection, reader.last_error);
  19657. }
  19658. TEST(BodyReaderTest, Error) {
  19659. MockStream stream("Hello, World!", 5);
  19660. detail::BodyReader reader;
  19661. reader.stream = &stream;
  19662. reader.content_length = 13;
  19663. char buf[32];
  19664. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19665. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19666. EXPECT_EQ(Error::Read, reader.last_error);
  19667. }
  19668. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19669. // Mock-based StreamHandle tests relying on private internals are removed.
  19670. class OpenStreamTest : public ::testing::Test {
  19671. protected:
  19672. void SetUp() override {
  19673. svr_.Get("/hello", [](const Request &, Response &res) {
  19674. res.set_content("Hello World!", "text/plain");
  19675. });
  19676. svr_.Get("/large", [](const Request &, Response &res) {
  19677. res.set_content(std::string(10000, 'X'), "text/plain");
  19678. });
  19679. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19680. res.set_content("Hello World!", "image/jpeg");
  19681. res.set_header("Content-Encoding", "UTF-8");
  19682. });
  19683. svr_.Get("/chunked", [](const Request &, Response &res) {
  19684. res.set_chunked_content_provider("text/plain",
  19685. [](size_t offset, DataSink &sink) {
  19686. if (offset < 15) {
  19687. sink.write("chunk", 5);
  19688. return true;
  19689. }
  19690. sink.done();
  19691. return true;
  19692. });
  19693. });
  19694. svr_.Get("/compressible", [](const Request &, Response &res) {
  19695. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19696. DataSink &sink) {
  19697. if (offset < 100 * 1024) {
  19698. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19699. sink.write(chunk.data(), chunk.size());
  19700. return true;
  19701. }
  19702. sink.done();
  19703. return true;
  19704. });
  19705. });
  19706. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19707. [](const Request & /*req*/, Response &res) {
  19708. auto i = new int(0);
  19709. res.set_header("Trailer", "Content-Length, X-Allowed");
  19710. res.set_chunked_content_provider(
  19711. "text/plain",
  19712. [i](size_t /*offset*/, DataSink &sink) {
  19713. switch (*i) {
  19714. case 0: sink.os << "123"; break;
  19715. case 1: sink.os << "456"; break;
  19716. case 2: sink.os << "789"; break;
  19717. case 3: {
  19718. sink.done_with_trailer(
  19719. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19720. } break;
  19721. }
  19722. (*i)++;
  19723. return true;
  19724. },
  19725. [i](bool success) {
  19726. EXPECT_TRUE(success);
  19727. delete i;
  19728. });
  19729. });
  19730. // Echo headers endpoint for header-related tests
  19731. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19732. std::string body;
  19733. for (const auto &h : req.headers) {
  19734. body.append(h.first);
  19735. body.push_back(':');
  19736. body.append(h.second);
  19737. body.push_back('\n');
  19738. }
  19739. res.set_content(body, "text/plain");
  19740. });
  19741. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19742. std::string body;
  19743. for (const auto &h : req.headers) {
  19744. body.append(h.first);
  19745. body.push_back(':');
  19746. body.append(h.second);
  19747. body.push_back('\n');
  19748. }
  19749. res.set_content(body, "text/plain");
  19750. });
  19751. port_ = svr_.bind_to_any_port("127.0.0.1");
  19752. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19753. svr_.wait_until_ready();
  19754. }
  19755. void TearDown() override {
  19756. svr_.stop();
  19757. if (thread_.joinable()) thread_.join();
  19758. }
  19759. Server svr_;
  19760. std::thread thread_;
  19761. int port_ = 0;
  19762. };
  19763. TEST_F(OpenStreamTest, Basic) {
  19764. Client cli("127.0.0.1", port_);
  19765. auto handle = cli.open_stream("GET", "/hello");
  19766. EXPECT_TRUE(handle.is_valid());
  19767. EXPECT_EQ("Hello World!", read_all(handle));
  19768. }
  19769. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19770. Client cli("127.0.0.1", port_);
  19771. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19772. ASSERT_TRUE(handle.is_valid());
  19773. EXPECT_EQ("Hello World!", read_all(handle));
  19774. }
  19775. TEST_F(OpenStreamTest, SmallBuffer) {
  19776. Client cli("127.0.0.1", port_);
  19777. auto handle = cli.open_stream("GET", "/hello");
  19778. std::string result;
  19779. char buf[4];
  19780. ssize_t n;
  19781. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19782. result.append(buf, static_cast<size_t>(n));
  19783. EXPECT_EQ("Hello World!", result);
  19784. }
  19785. TEST_F(OpenStreamTest, DefaultHeaders) {
  19786. Client cli("127.0.0.1", port_);
  19787. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19788. {
  19789. auto handle = cli.open_stream("GET", "/echo-headers");
  19790. ASSERT_TRUE(handle.is_valid());
  19791. auto body = read_all(handle);
  19792. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19793. std::string::npos);
  19794. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19795. std::string::npos);
  19796. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19797. }
  19798. // open_stream POST with body and no explicit content_type should NOT add
  19799. // text/plain Content-Type (behavior differs from non-streaming path), but
  19800. // should include Content-Length
  19801. {
  19802. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19803. ASSERT_TRUE(handle.is_valid());
  19804. auto body = read_all(handle);
  19805. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19806. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19807. }
  19808. // open_stream POST with explicit Content-Type should preserve it
  19809. {
  19810. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19811. {{"Content-Type", "application/custom"}},
  19812. "{}", "application/custom");
  19813. ASSERT_TRUE(handle.is_valid());
  19814. auto body = read_all(handle);
  19815. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19816. }
  19817. // User-specified User-Agent must not be overwritten for stream API
  19818. {
  19819. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19820. {{"User-Agent", "MyAgent/1.2"}});
  19821. ASSERT_TRUE(handle.is_valid());
  19822. auto body = read_all(handle);
  19823. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19824. }
  19825. }
  19826. TEST_F(OpenStreamTest, Large) {
  19827. Client cli("127.0.0.1", port_);
  19828. auto handle = cli.open_stream("GET", "/large");
  19829. EXPECT_EQ(10000u, read_all(handle).size());
  19830. }
  19831. TEST_F(OpenStreamTest, ConnectionError) {
  19832. Client cli("127.0.0.1", 9999);
  19833. auto handle = cli.open_stream("GET", "/hello");
  19834. EXPECT_FALSE(handle.is_valid());
  19835. }
  19836. TEST_F(OpenStreamTest, Chunked) {
  19837. Client cli("127.0.0.1", port_);
  19838. auto handle = cli.open_stream("GET", "/chunked");
  19839. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19840. "Transfer-Encoding") == "chunked");
  19841. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19842. }
  19843. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19844. Client cli("127.0.0.1", port_);
  19845. auto handle =
  19846. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19847. ASSERT_TRUE(handle.is_valid());
  19848. // Consume body to allow trailers to be received/parsed
  19849. auto body = read_all(handle);
  19850. // Explicitly parse trailers (ensure trailers are available for assertion)
  19851. handle.parse_trailers_if_needed();
  19852. EXPECT_EQ(std::string("123456789"), body);
  19853. // The response should include a Trailer header declaring both names
  19854. ASSERT_TRUE(handle.response);
  19855. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19856. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19857. handle.response->get_header_value("Trailer"));
  19858. // Prohibited trailer must not be present
  19859. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19860. // Allowed trailer should be present
  19861. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19862. EXPECT_EQ(std::string("yes"),
  19863. handle.response->get_trailer_value("X-Allowed"));
  19864. // Verify trailers are NOT present as regular headers
  19865. EXPECT_EQ(std::string(""),
  19866. handle.response->get_header_value("Content-Length"));
  19867. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19868. }
  19869. // Accepts one connection on an OS-assigned port, which it hands over through
  19870. // port_promise, reads the request head and sends back response. after_send,
  19871. // if given, runs on the connection before it is closed.
  19872. static std::thread
  19873. serve_single_response(std::promise<int> &port_promise,
  19874. const std::string &response,
  19875. std::function<void(socket_t)> after_send = nullptr) {
  19876. return std::thread([&port_promise, response, after_send] {
  19877. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19878. default_socket_options(srv);
  19879. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19880. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19881. sockaddr_in addr{};
  19882. addr.sin_family = AF_INET;
  19883. addr.sin_port = htons(0); // Let OS assign a free port
  19884. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19885. int opt = 1;
  19886. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19887. #ifdef _WIN32
  19888. reinterpret_cast<const char *>(&opt),
  19889. #else
  19890. &opt,
  19891. #endif
  19892. sizeof(opt));
  19893. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19894. ::listen(srv, 1) != 0) {
  19895. port_promise.set_value(-1);
  19896. detail::close_socket(srv);
  19897. return;
  19898. }
  19899. socklen_t addr_len = sizeof(addr);
  19900. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19901. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19902. sockaddr_in cli_addr{};
  19903. socklen_t cli_len = sizeof(cli_addr);
  19904. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19905. if (cli != INVALID_SOCKET) {
  19906. // Read the complete HTTP request (until the blank line that terminates
  19907. // headers) before sending the response. If the server closes the socket
  19908. // while the client's request data is still unread in the kernel receive
  19909. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19910. // connection on both sides: it discards the client's receive buffer
  19911. // (which already holds our response) and causes any in-progress write on
  19912. // the client to fail with ECONNRESET. Reading all request data first
  19913. // ensures close() emits a graceful FIN.
  19914. {
  19915. char rbuf[256];
  19916. std::string req;
  19917. while (req.find("\r\n\r\n") == std::string::npos) {
  19918. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19919. if (n <= 0) { break; }
  19920. req.append(rbuf, static_cast<size_t>(n));
  19921. }
  19922. }
  19923. ::send(cli,
  19924. #ifdef _WIN32
  19925. static_cast<const char *>(response.c_str()),
  19926. static_cast<int>(response.size()),
  19927. #else
  19928. response.c_str(), response.size(),
  19929. #endif
  19930. 0);
  19931. if (after_send) { after_send(cli); }
  19932. detail::close_socket(cli);
  19933. }
  19934. detail::close_socket(srv);
  19935. });
  19936. }
  19937. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19938. #ifndef _WIN32
  19939. signal(SIGPIPE, SIG_IGN);
  19940. #endif
  19941. std::promise<int> port_promise;
  19942. auto port_future = port_promise.get_future();
  19943. auto server_thread =
  19944. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19945. "Content-Type: text/plain\r\n"
  19946. "Content-Length: not-a-number\r\n"
  19947. "Connection: close\r\n"
  19948. "\r\n"
  19949. "hello");
  19950. auto port = port_future.get();
  19951. ASSERT_GT(port, 0);
  19952. Client cli("127.0.0.1", port);
  19953. auto handle = cli.open_stream("GET", "/");
  19954. EXPECT_FALSE(handle.is_valid());
  19955. server_thread.join();
  19956. }
  19957. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19958. #ifndef _WIN32
  19959. signal(SIGPIPE, SIG_IGN);
  19960. #endif
  19961. std::promise<int> port_promise;
  19962. auto port_future = port_promise.get_future();
  19963. auto server_thread = serve_single_response(
  19964. port_promise, "HTTP/1.1 200 OK\r\n"
  19965. "Content-Type: text/plain\r\n"
  19966. "Content-Length: 99999999999999999999999999\r\n"
  19967. "Connection: close\r\n"
  19968. "\r\n"
  19969. "hello");
  19970. auto port = port_future.get();
  19971. ASSERT_GT(port, 0);
  19972. // Historically std::stoull would throw std::out_of_range here and crash
  19973. // the process, then parsing silently clamped to a bogus framing length and
  19974. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19975. // so the stream fails to open, matching the not-a-number case above. The
  19976. // process still must NOT terminate.
  19977. Client cli("127.0.0.1", port);
  19978. auto handle = cli.open_stream("GET", "/");
  19979. EXPECT_FALSE(handle.is_valid());
  19980. server_thread.join();
  19981. }
  19982. // Serves `response` to the single request `fn` makes with a fresh client.
  19983. template <typename Fn>
  19984. static void with_single_response(const std::string &response, Fn fn) {
  19985. #ifndef _WIN32
  19986. signal(SIGPIPE, SIG_IGN);
  19987. #endif
  19988. std::promise<int> port_promise;
  19989. auto port_future = port_promise.get_future();
  19990. auto server_thread = serve_single_response(port_promise, response);
  19991. auto se = detail::scope_exit([&] { server_thread.join(); });
  19992. auto port = port_future.get();
  19993. ASSERT_GT(port, 0);
  19994. Client cli("127.0.0.1", port);
  19995. fn(cli);
  19996. }
  19997. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19998. // Neither Content-Length nor chunked: the body ends at the close
  19999. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20000. "Connection: close\r\n"
  20001. "\r\n"
  20002. "hello";
  20003. with_single_response(close_delimited, [](Client &cli) {
  20004. auto handle = cli.open_stream("GET", "/");
  20005. ASSERT_TRUE(handle.is_valid());
  20006. EXPECT_EQ("hello", read_all(handle));
  20007. EXPECT_FALSE(handle.has_read_error());
  20008. });
  20009. // A close before the end of the Content-Length is still an error
  20010. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20011. "Content-Length: 10\r\n"
  20012. "\r\n"
  20013. "hello";
  20014. with_single_response(short_content_length, [](Client &cli) {
  20015. auto handle = cli.open_stream("GET", "/");
  20016. ASSERT_TRUE(handle.is_valid());
  20017. read_all(handle);
  20018. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20019. });
  20020. // So is a close before the last chunk
  20021. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20022. "Transfer-Encoding: chunked\r\n"
  20023. "\r\n"
  20024. "5\r\nhello\r\n";
  20025. with_single_response(short_chunked, [](Client &cli) {
  20026. auto handle = cli.open_stream("GET", "/");
  20027. ASSERT_TRUE(handle.is_valid());
  20028. read_all(handle);
  20029. EXPECT_TRUE(handle.has_read_error());
  20030. });
  20031. }
  20032. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20033. const char *responses[] = {
  20034. "HTTP/1.1 103 Early Hints\r\n"
  20035. "Link: </style.css>; rel=preload\r\n"
  20036. "\r\n"
  20037. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20038. "HTTP/1.1 100 Continue\r\n"
  20039. "X-Note: interim\r\n"
  20040. "\r\n"
  20041. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20042. };
  20043. for (auto response : responses) {
  20044. with_single_response(response, [](Client &cli) {
  20045. auto res = cli.Get("/");
  20046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20047. EXPECT_EQ(StatusCode::OK_200, res->status);
  20048. EXPECT_EQ("ok", res->body);
  20049. });
  20050. }
  20051. }
  20052. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20053. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20054. const std::string final_response =
  20055. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20056. std::string interims;
  20057. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20058. interims += interim;
  20059. }
  20060. with_single_response(interims + final_response, [](Client &cli) {
  20061. auto res = cli.Get("/");
  20062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20063. EXPECT_EQ("ok", res->body);
  20064. });
  20065. with_single_response(interims + interim + final_response, [](Client &cli) {
  20066. auto res = cli.Get("/");
  20067. ASSERT_FALSE(res);
  20068. EXPECT_EQ(Error::Read, res.error());
  20069. });
  20070. }
  20071. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20072. #ifndef _WIN32
  20073. signal(SIGPIPE, SIG_IGN);
  20074. #endif
  20075. // The server answers the head without asking for the body. Bytes it then
  20076. // reads on the connection would be taken for the body the request declared.
  20077. auto closed_by_client = false;
  20078. std::promise<int> port_promise;
  20079. auto server_thread = serve_single_response(
  20080. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20081. [&](socket_t sock) {
  20082. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20083. char buf[256];
  20084. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20085. });
  20086. Client cli("127.0.0.1", port_promise.get_future().get());
  20087. cli.set_keep_alive(true);
  20088. cli.set_read_timeout(1, 0);
  20089. // Long enough for the client to send Expect: 100-continue.
  20090. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20092. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20093. cli.Get("/second");
  20094. server_thread.join();
  20095. EXPECT_TRUE(closed_by_client);
  20096. }
  20097. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20098. // Long enough for the client to send Expect: 100-continue
  20099. with_single_response(
  20100. "HTTP/1.1 103 Early Hints\r\n"
  20101. "Link: </style.css>; rel=preload\r\n"
  20102. "\r\n"
  20103. "HTTP/1.1 401 Unauthorized\r\n"
  20104. "Content-Length: 0\r\n\r\n",
  20105. [](Client &cli) {
  20106. cli.set_read_timeout(2, 0);
  20107. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20109. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20110. });
  20111. }
  20112. #ifdef CPPHTTPLIB_SSL_ENABLED
  20113. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20114. #ifndef _WIN32
  20115. signal(SIGPIPE, SIG_IGN);
  20116. #endif
  20117. auto reused = false;
  20118. std::promise<int> port_promise;
  20119. auto server_thread = serve_single_response(
  20120. port_promise,
  20121. "HTTP/1.1 401 Unauthorized\r\n"
  20122. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20123. "Content-Length: 0\r\n\r\n",
  20124. [&](socket_t sock) {
  20125. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20126. char buf[256];
  20127. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20128. });
  20129. Client cli("127.0.0.1", port_promise.get_future().get());
  20130. cli.set_keep_alive(true);
  20131. cli.set_digest_auth("user", "pass");
  20132. cli.set_read_timeout(1, 0);
  20133. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20134. server_thread.join();
  20135. EXPECT_FALSE(reused);
  20136. }
  20137. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20138. // Any other answer to CONNECT would read as the origin's response.
  20139. struct {
  20140. const char *response;
  20141. bool passed_on;
  20142. } cases[] = {
  20143. {"HTTP/1.1 201 Created\r\n"
  20144. "Set-Cookie: session=from-proxy\r\n"
  20145. "Content-Length: 0\r\n\r\n",
  20146. false},
  20147. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20148. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20149. "Content-Length: 0\r\n\r\n",
  20150. true},
  20151. };
  20152. for (const auto &c : cases) {
  20153. std::promise<int> port_promise;
  20154. auto server_thread = serve_single_response(port_promise, c.response);
  20155. SSLClient cli("example.com", 443);
  20156. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20157. auto res = cli.Get("/");
  20158. server_thread.join();
  20159. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20160. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20161. if (res) {
  20162. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20163. }
  20164. }
  20165. }
  20166. #endif
  20167. // Records the client's error logger calls as "error METHOD path", or
  20168. // "error null" for a call without a request
  20169. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20170. return [&log](const Error &err, const Request *req) {
  20171. log.push_back(to_string(err) + " " +
  20172. (req ? req->method + " " + req->path : "null"));
  20173. };
  20174. }
  20175. // A failed request is reported once, with the request the caller made
  20176. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20177. Server svr;
  20178. svr.Get("/big", [](const Request &, Response &res) {
  20179. res.set_content(std::string(100000, 'b'), "text/plain");
  20180. });
  20181. auto port = svr.bind_to_any_port(HOST);
  20182. std::thread t([&]() { svr.listen_after_bind(); });
  20183. auto se = detail::scope_exit([&] {
  20184. svr.stop();
  20185. t.join();
  20186. });
  20187. svr.wait_until_ready();
  20188. Client cli(HOST, port);
  20189. std::vector<std::string> log;
  20190. cli.set_error_logger(record_errors(log));
  20191. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20192. cli.Get("/big", [](const char *, size_t) { return false; });
  20193. EXPECT_EQ(expected, log);
  20194. log.clear();
  20195. cli.Get("/big", [](size_t, size_t) { return false; });
  20196. EXPECT_EQ(expected, log);
  20197. }
  20198. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20199. // Fails while the body is read
  20200. auto broken = [](const Request &, Response &res) {
  20201. res.set_content_provider(10, "text/plain",
  20202. [](size_t, size_t, DataSink &) { return false; });
  20203. };
  20204. Server other;
  20205. other.Get("/broken", broken);
  20206. auto other_port = other.bind_to_any_port(HOST);
  20207. std::thread other_t([&]() { other.listen_after_bind(); });
  20208. auto other_se = detail::scope_exit([&] {
  20209. other.stop();
  20210. other_t.join();
  20211. });
  20212. other.wait_until_ready();
  20213. Server svr;
  20214. svr.Get("/broken", broken);
  20215. svr.Get("/same-origin",
  20216. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20217. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20218. res.set_redirect("http://" + std::string(HOST) + ":" +
  20219. std::to_string(other_port) + "/broken");
  20220. });
  20221. auto port = svr.bind_to_any_port(HOST);
  20222. std::thread t([&]() { svr.listen_after_bind(); });
  20223. auto se = detail::scope_exit([&] {
  20224. svr.stop();
  20225. t.join();
  20226. });
  20227. svr.wait_until_ready();
  20228. Client cli(HOST, port);
  20229. cli.set_follow_location(true);
  20230. std::vector<std::string> log;
  20231. cli.set_error_logger(record_errors(log));
  20232. for (auto path : {"/same-origin", "/cross-origin"}) {
  20233. log.clear();
  20234. auto res = cli.Get(path);
  20235. ASSERT_FALSE(res);
  20236. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20237. log);
  20238. }
  20239. }
  20240. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20241. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20242. std::vector<std::string> log;
  20243. cli.set_error_logger(record_errors(log));
  20244. auto handle = cli.open_stream("GET", "/x");
  20245. EXPECT_FALSE(handle.is_valid());
  20246. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20247. log);
  20248. });
  20249. }
  20250. #ifdef CPPHTTPLIB_SSL_ENABLED
  20251. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20252. // Not a TLS server, so the handshake fails. It waits for a request line in
  20253. // the handshake bytes, so a short read timeout lets it close quickly.
  20254. Server svr;
  20255. svr.set_read_timeout(0, 100000);
  20256. svr.Get("/x", [](const Request &, Response &res) {
  20257. res.set_content("x", "text/plain");
  20258. });
  20259. auto port = svr.bind_to_any_port(HOST);
  20260. std::thread t([&]() { svr.listen_after_bind(); });
  20261. auto se = detail::scope_exit([&] {
  20262. svr.stop();
  20263. t.join();
  20264. });
  20265. svr.wait_until_ready();
  20266. std::vector<std::string> log;
  20267. SSLClient cli(HOST, port);
  20268. cli.enable_server_certificate_verification(false);
  20269. cli.set_error_logger(record_errors(log));
  20270. auto res = cli.Get("/x");
  20271. ASSERT_FALSE(res);
  20272. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20273. log.clear();
  20274. auto handle = cli.open_stream("GET", "/x");
  20275. EXPECT_FALSE(handle.is_valid());
  20276. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20277. log.clear();
  20278. SSLClient no_ca(HOST, port);
  20279. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20280. no_ca.set_error_logger(record_errors(log));
  20281. res = no_ca.Get("/x");
  20282. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20283. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20284. }
  20285. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20286. #ifndef _WIN32
  20287. signal(SIGPIPE, SIG_IGN);
  20288. #endif
  20289. // Refused, answered with a challenge, or closed without an answer
  20290. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20291. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20292. "Content-Length: 0\r\n\r\n",
  20293. ""}) {
  20294. std::promise<int> port_promise;
  20295. auto server_thread = serve_single_response(port_promise, response);
  20296. SSLClient cli("example.com", 443);
  20297. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20298. std::vector<std::string> log;
  20299. cli.set_error_logger(record_errors(log));
  20300. auto res = cli.Get("/");
  20301. server_thread.join();
  20302. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20303. << response;
  20304. }
  20305. }
  20306. #endif
  20307. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20308. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20309. // the chunked coding and drop Content-Length, so a front-end that trusts
  20310. // Content-Length would disagree about where the body ends (response
  20311. // smuggling). The client must reject such a response.
  20312. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20313. for (const char *te : {"chunked", "gzip, chunked"}) {
  20314. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20315. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20316. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20317. "5\r\nhello\r\n0\r\n\r\n";
  20318. with_single_response(response, [&](Client &cli) {
  20319. auto res = cli.Get("/");
  20320. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20321. EXPECT_EQ(Error::Read, res.error()) << te;
  20322. });
  20323. with_single_response(response, [&](Client &cli) {
  20324. auto handle = cli.open_stream("GET", "/");
  20325. EXPECT_FALSE(handle.is_valid()) << te;
  20326. EXPECT_EQ(Error::Read, handle.error) << te;
  20327. });
  20328. }
  20329. }
  20330. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20331. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20332. // closing the connection (unlike a request, which must be rejected).
  20333. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20334. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20335. "Transfer-Encoding: chunked\r\n"
  20336. "Connection: close\r\n"
  20337. "\r\n"
  20338. "5\r\nhello\r\n0\r\n\r\n",
  20339. "HTTP/1.1 200 OK\r\n"
  20340. "Transfer-Encoding: gzip\r\n"
  20341. "Connection: close\r\n"
  20342. "\r\n"
  20343. "hello"}) {
  20344. with_single_response(response, [&](Client &cli) {
  20345. auto res = cli.Get("/");
  20346. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20347. EXPECT_EQ("hello", res->body);
  20348. });
  20349. with_single_response(response, [&](Client &cli) {
  20350. auto handle = cli.open_stream("GET", "/");
  20351. ASSERT_TRUE(handle.is_valid()) << response;
  20352. EXPECT_EQ("hello", read_all(handle));
  20353. });
  20354. }
  20355. }
  20356. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20357. // framing headers describe nothing to read and must not be rejected.
  20358. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20359. const std::string framing = "Content-Length: 5\r\n"
  20360. "Transfer-Encoding: chunked\r\n"
  20361. "Connection: close\r\n"
  20362. "\r\n";
  20363. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20364. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20365. });
  20366. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20367. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20368. });
  20369. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20370. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20371. with_single_response(response, [&](Client &cli) {
  20372. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20373. });
  20374. with_single_response(response, [&](Client &cli) {
  20375. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20376. });
  20377. }
  20378. }
  20379. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20380. // header section, so a stream opened on one has nothing to read, whatever
  20381. // framing or coding headers it carries.
  20382. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20383. struct Case {
  20384. const char *method;
  20385. const char *status;
  20386. };
  20387. // A reader of the declared body reports an early close when nothing
  20388. // follows, and hands back what does.
  20389. struct Framing {
  20390. const char *headers;
  20391. const char *after;
  20392. };
  20393. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20394. Case{"GET", "304 Not Modified"}}) {
  20395. for (const auto &f :
  20396. {Framing{"Content-Length: 5\r\n", ""},
  20397. Framing{"Content-Length: 5\r\n", "hello"},
  20398. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20399. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20400. // Not decoded, so a build without Brotli opens it too
  20401. Framing{"Content-Encoding: br\r\n", ""}}) {
  20402. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20403. "Connection: close\r\n"
  20404. "\r\n" +
  20405. f.after;
  20406. with_single_response(response, [&](Client &cli) {
  20407. auto handle = cli.open_stream(c.method, "/");
  20408. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20409. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20410. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20411. });
  20412. }
  20413. }
  20414. }
  20415. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20416. // response, is faulty framing, so the connection is not reused after it.
  20417. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20418. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20419. "Content-Length: 0\r\n"
  20420. "Transfer-Encoding: chunked\r\n"
  20421. "\r\n"
  20422. "5\r\nhello\r\n0\r\n\r\n",
  20423. "HTTP/1.0 200 Connection established\r\n"
  20424. "Connection: keep-alive\r\n"
  20425. "Transfer-Encoding: chunked\r\n"
  20426. "\r\n"
  20427. "5\r\nhello\r\n0\r\n\r\n"}) {
  20428. with_single_response(response, [&](Client &cli) {
  20429. cli.set_keep_alive(true);
  20430. auto res = cli.Get("/");
  20431. ASSERT_TRUE(res) << response;
  20432. EXPECT_EQ("hello", res->body);
  20433. EXPECT_FALSE(cli.is_socket_open()) << response;
  20434. });
  20435. }
  20436. }
  20437. // A payload max length of 0 means no limit, however the body is framed.
  20438. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20439. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20440. "Transfer-Encoding: chunked\r\n"
  20441. "\r\n"
  20442. "5\r\nhello\r\n0\r\n\r\n",
  20443. "HTTP/1.1 200 OK\r\n"
  20444. "Connection: close\r\n"
  20445. "\r\n"
  20446. "hello"}) {
  20447. with_single_response(response, [&](Client &cli) {
  20448. cli.set_payload_max_length(0);
  20449. auto res = cli.Get("/");
  20450. ASSERT_TRUE(res) << response;
  20451. EXPECT_EQ("hello", res->body) << response;
  20452. });
  20453. }
  20454. }
  20455. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20456. Server svr;
  20457. svr.set_payload_max_length(0);
  20458. svr.Post("/echo", [](const Request &req, Response &res) {
  20459. res.set_content(req.body, "text/plain");
  20460. });
  20461. auto port = svr.bind_to_any_port(HOST);
  20462. thread t = thread([&] { svr.listen_after_bind(); });
  20463. auto se = detail::scope_exit([&] {
  20464. svr.stop();
  20465. t.join();
  20466. ASSERT_FALSE(svr.is_running());
  20467. });
  20468. svr.wait_until_ready();
  20469. Client cli(HOST, port);
  20470. auto res = cli.Post(
  20471. "/echo",
  20472. [](size_t /*offset*/, DataSink &sink) {
  20473. sink.write("hello", 5);
  20474. sink.done();
  20475. return true;
  20476. },
  20477. "text/plain");
  20478. ASSERT_TRUE(res);
  20479. EXPECT_EQ(StatusCode::OK_200, res->status);
  20480. EXPECT_EQ("hello", res->body);
  20481. }
  20482. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20483. TEST_F(OpenStreamTest, Gzip) {
  20484. Client cli("127.0.0.1", port_);
  20485. auto handle = cli.open_stream("GET", "/compressible", {},
  20486. {{"Accept-Encoding", "gzip"}});
  20487. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20488. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20489. }
  20490. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20491. Client cli("127.0.0.1", port_);
  20492. auto handle =
  20493. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20494. {{"Accept-Encoding", "gzip"}});
  20495. ASSERT_TRUE(handle.is_valid());
  20496. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20497. EXPECT_EQ("123456789", read_all(handle));
  20498. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20499. }
  20500. #endif
  20501. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20502. TEST_F(OpenStreamTest, Brotli) {
  20503. Client cli("127.0.0.1", port_);
  20504. auto handle =
  20505. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20506. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20507. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20508. }
  20509. #endif
  20510. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20511. TEST_F(OpenStreamTest, Zstd) {
  20512. Client cli("127.0.0.1", port_);
  20513. auto handle = cli.open_stream("GET", "/compressible", {},
  20514. {{"Accept-Encoding", "zstd"}});
  20515. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20516. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20517. }
  20518. #endif
  20519. #ifdef CPPHTTPLIB_SSL_ENABLED
  20520. class SSLOpenStreamTest : public ::testing::Test {
  20521. protected:
  20522. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20523. void SetUp() override {
  20524. svr_.Get("/hello", [](const Request &, Response &res) {
  20525. res.set_content("Hello SSL World!", "text/plain");
  20526. });
  20527. svr_.Get("/chunked", [](const Request &, Response &res) {
  20528. res.set_chunked_content_provider("text/plain",
  20529. [](size_t offset, DataSink &sink) {
  20530. if (offset < 15) {
  20531. sink.write("chunk", 5);
  20532. return true;
  20533. }
  20534. sink.done();
  20535. return true;
  20536. });
  20537. });
  20538. svr_.Post("/echo", [](const Request &req, Response &res) {
  20539. res.set_content(req.body, req.get_header_value("Content-Type"));
  20540. });
  20541. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20542. std::string body = req.body;
  20543. res.set_chunked_content_provider(
  20544. "text/plain", [body](size_t offset, DataSink &sink) {
  20545. if (offset < body.size()) {
  20546. sink.write(body.data() + offset, body.size() - offset);
  20547. }
  20548. sink.done();
  20549. return true;
  20550. });
  20551. });
  20552. port_ = svr_.bind_to_any_port("127.0.0.1");
  20553. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20554. svr_.wait_until_ready();
  20555. }
  20556. void TearDown() override {
  20557. svr_.stop();
  20558. if (thread_.joinable()) thread_.join();
  20559. }
  20560. SSLServer svr_;
  20561. std::thread thread_;
  20562. int port_ = 0;
  20563. };
  20564. TEST_F(SSLOpenStreamTest, Basic) {
  20565. SSLClient cli("127.0.0.1", port_);
  20566. cli.enable_server_certificate_verification(false);
  20567. auto handle = cli.open_stream("GET", "/hello");
  20568. ASSERT_TRUE(handle.is_valid());
  20569. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20570. }
  20571. TEST_F(SSLOpenStreamTest, Chunked) {
  20572. SSLClient cli("127.0.0.1", port_);
  20573. cli.enable_server_certificate_verification(false);
  20574. auto handle = cli.open_stream("GET", "/chunked");
  20575. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20576. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20577. "Transfer-Encoding") == "chunked");
  20578. auto body = read_all(handle);
  20579. EXPECT_EQ("chunkchunkchunk", body);
  20580. }
  20581. TEST_F(SSLOpenStreamTest, Post) {
  20582. SSLClient cli("127.0.0.1", port_);
  20583. cli.enable_server_certificate_verification(false);
  20584. auto handle =
  20585. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20586. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20587. EXPECT_EQ(200, handle.response->status);
  20588. auto body = read_all(handle);
  20589. EXPECT_EQ("Hello SSL POST", body);
  20590. }
  20591. TEST_F(SSLOpenStreamTest, PostChunked) {
  20592. SSLClient cli("127.0.0.1", port_);
  20593. cli.enable_server_certificate_verification(false);
  20594. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20595. "Chunked SSL Data", "text/plain");
  20596. ASSERT_TRUE(handle.is_valid());
  20597. EXPECT_EQ(200, handle.response->status);
  20598. auto body = read_all(handle);
  20599. EXPECT_EQ("Chunked SSL Data", body);
  20600. }
  20601. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20602. // Content-Length is terminated by the server closing the connection. When the
  20603. // SSL peer sends a close_notify after the body, the client must treat it as a
  20604. // clean EOF and return a successful response rather than an error.
  20605. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20606. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20607. ASSERT_TRUE(svr.is_valid());
  20608. svr.set_keep_alive_max_count(1);
  20609. const std::string expected_body = "Hello from connection-close response!";
  20610. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20611. res.set_content_provider("text/plain",
  20612. [&](size_t offset, DataSink &sink) -> bool {
  20613. if (offset < expected_body.size()) {
  20614. sink.write(expected_body.data() + offset,
  20615. expected_body.size() - offset);
  20616. }
  20617. sink.done();
  20618. return true;
  20619. });
  20620. });
  20621. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20622. auto se = detail::scope_exit([&] {
  20623. svr.stop();
  20624. listen_thread.join();
  20625. ASSERT_FALSE(svr.is_running());
  20626. });
  20627. svr.wait_until_ready();
  20628. SSLClient cli(HOST, PORT);
  20629. cli.enable_server_certificate_verification(false);
  20630. auto res = cli.Get("/no-content-length");
  20631. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20632. EXPECT_EQ(StatusCode::OK_200, res->status);
  20633. EXPECT_EQ(expected_body, res->body);
  20634. }
  20635. #endif // CPPHTTPLIB_SSL_ENABLED
  20636. //==============================================================================
  20637. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20638. // results for various scenarios.
  20639. //==============================================================================
  20640. TEST(ParityTest, GetVsOpenStream) {
  20641. Server svr;
  20642. const std::string path = "/parity";
  20643. const std::string content = "Parity test content: hello world";
  20644. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20645. res.set_content(content, "text/plain");
  20646. });
  20647. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20648. auto se = detail::scope_exit([&] {
  20649. svr.stop();
  20650. t.join();
  20651. ASSERT_FALSE(svr.is_running());
  20652. });
  20653. svr.wait_until_ready();
  20654. Client cli(HOST, PORT);
  20655. // Non-stream path
  20656. auto r1 = cli.Get(path);
  20657. ASSERT_TRUE(r1);
  20658. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20659. // Stream path
  20660. auto h = cli.open_stream("GET", path);
  20661. ASSERT_TRUE(h.is_valid());
  20662. EXPECT_EQ(r1->body, read_all(h));
  20663. }
  20664. // Helper to compress data with provided compressor type T
  20665. template <typename Compressor>
  20666. static std::string compress_payload_for_parity(const std::string &in) {
  20667. std::string out;
  20668. Compressor compressor;
  20669. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20670. [&](const char *data, size_t n) {
  20671. out.append(data, n);
  20672. return true;
  20673. });
  20674. EXPECT_TRUE(ok);
  20675. return out;
  20676. }
  20677. // Helper function for compression parity tests
  20678. template <typename Compressor>
  20679. static void test_compression_parity(const std::string &original,
  20680. const std::string &path,
  20681. const std::string &encoding) {
  20682. const std::string compressed =
  20683. compress_payload_for_parity<Compressor>(original);
  20684. Server svr;
  20685. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20686. res.set_content(compressed, "application/octet-stream");
  20687. res.set_header("Content-Encoding", encoding);
  20688. });
  20689. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20690. auto se = detail::scope_exit([&] {
  20691. svr.stop();
  20692. t.join();
  20693. ASSERT_FALSE(svr.is_running());
  20694. });
  20695. svr.wait_until_ready();
  20696. Client cli(HOST, PORT);
  20697. // Non-streaming
  20698. {
  20699. auto res = cli.Get(path);
  20700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20701. EXPECT_EQ(StatusCode::OK_200, res->status);
  20702. EXPECT_EQ(original, res->body);
  20703. }
  20704. // Streaming
  20705. {
  20706. auto h = cli.open_stream("GET", path);
  20707. ASSERT_TRUE(h.is_valid());
  20708. EXPECT_EQ(original, read_all(h));
  20709. }
  20710. }
  20711. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20712. TEST(ParityTest, Gzip) {
  20713. test_compression_parity<detail::gzip_compressor>(
  20714. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20715. }
  20716. #endif
  20717. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20718. TEST(ParityTest, Brotli) {
  20719. test_compression_parity<detail::brotli_compressor>(
  20720. "Hello, brotli parity test payload", "/parity-br", "br");
  20721. }
  20722. #endif
  20723. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20724. TEST(ParityTest, Zstd) {
  20725. test_compression_parity<detail::zstd_compressor>(
  20726. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20727. }
  20728. #endif
  20729. //==============================================================================
  20730. // New Stream API Tests
  20731. //==============================================================================
  20732. inline std::string read_body(httplib::stream::Result &result) {
  20733. std::string body;
  20734. while (result.next()) {
  20735. body.append(result.data(), result.size());
  20736. }
  20737. return body;
  20738. }
  20739. TEST(ClientConnectionTest, Basic) {
  20740. httplib::ClientConnection conn;
  20741. EXPECT_FALSE(conn.is_open());
  20742. conn.sock = 1;
  20743. EXPECT_TRUE(conn.is_open());
  20744. httplib::ClientConnection conn2(std::move(conn));
  20745. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20746. conn2.sock = INVALID_SOCKET;
  20747. }
  20748. // Unified test server for all stream::* tests
  20749. class StreamApiTest : public ::testing::Test {
  20750. protected:
  20751. void SetUp() override {
  20752. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20753. res.set_content("Hello World!", "text/plain");
  20754. });
  20755. svr_.Get("/echo-params",
  20756. [](const httplib::Request &req, httplib::Response &res) {
  20757. std::string r;
  20758. for (const auto &p : req.params) {
  20759. if (!r.empty()) r += "&";
  20760. r += p.first + "=" + p.second;
  20761. }
  20762. res.set_content(r, "text/plain");
  20763. });
  20764. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20765. res.set_content(req.body, req.get_header_value("Content-Type"));
  20766. });
  20767. svr_.Post("/echo-headers",
  20768. [](const httplib::Request &req, httplib::Response &res) {
  20769. std::string r;
  20770. for (const auto &h : req.headers)
  20771. r += h.first + ": " + h.second + "\n";
  20772. res.set_content(r, "text/plain");
  20773. });
  20774. svr_.Post("/echo-params",
  20775. [](const httplib::Request &req, httplib::Response &res) {
  20776. std::string r = "params:";
  20777. for (const auto &p : req.params)
  20778. r += p.first + "=" + p.second + ";";
  20779. res.set_content(r + " body:" + req.body, "text/plain");
  20780. });
  20781. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20782. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20783. });
  20784. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20785. res.set_content("PUT:" + req.body, "text/plain");
  20786. });
  20787. svr_.Patch("/echo",
  20788. [](const httplib::Request &req, httplib::Response &res) {
  20789. res.set_content("PATCH:" + req.body, "text/plain");
  20790. });
  20791. svr_.Delete(
  20792. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20793. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20794. "text/plain");
  20795. });
  20796. svr_.Get("/head-test",
  20797. [](const httplib::Request &, httplib::Response &res) {
  20798. res.set_content("body for HEAD", "text/plain");
  20799. });
  20800. svr_.Options("/options",
  20801. [](const httplib::Request &, httplib::Response &res) {
  20802. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20803. });
  20804. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20805. svr_.wait_until_ready();
  20806. }
  20807. void TearDown() override {
  20808. svr_.stop();
  20809. if (thread_.joinable()) thread_.join();
  20810. }
  20811. httplib::Server svr_;
  20812. std::thread thread_;
  20813. };
  20814. // stream::Get tests
  20815. TEST_F(StreamApiTest, GetBasic) {
  20816. httplib::Client cli(HOST, PORT);
  20817. auto result = httplib::stream::Get(cli, "/hello");
  20818. ASSERT_TRUE(result.is_valid());
  20819. EXPECT_EQ(200, result.status());
  20820. EXPECT_EQ("Hello World!", read_body(result));
  20821. }
  20822. TEST_F(StreamApiTest, GetWithParams) {
  20823. httplib::Client cli(HOST, PORT);
  20824. httplib::Params params{{"foo", "bar"}};
  20825. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20826. ASSERT_TRUE(result.is_valid());
  20827. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20828. }
  20829. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20830. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20831. httplib::Client cli(HOST, PORT);
  20832. cli.set_payload_max_length(0);
  20833. auto result = httplib::stream::Get(cli, "/hello");
  20834. ASSERT_TRUE(result.is_valid());
  20835. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20836. EXPECT_EQ("Hello World!", read_body(result));
  20837. }
  20838. #endif
  20839. TEST_F(StreamApiTest, GetConnectionError) {
  20840. httplib::Client cli(HOST, 9999);
  20841. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20842. }
  20843. TEST_F(StreamApiTest, Get404) {
  20844. httplib::Client cli(HOST, PORT);
  20845. auto result = httplib::stream::Get(cli, "/nonexistent");
  20846. EXPECT_TRUE(result.is_valid());
  20847. EXPECT_EQ(404, result.status());
  20848. }
  20849. // stream::Post tests
  20850. TEST_F(StreamApiTest, PostBasic) {
  20851. httplib::Client cli(HOST, PORT);
  20852. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20853. "application/json");
  20854. ASSERT_TRUE(result.is_valid());
  20855. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20856. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20857. }
  20858. TEST_F(StreamApiTest, PostWithHeaders) {
  20859. httplib::Client cli(HOST, PORT);
  20860. httplib::Headers headers{{"X-Custom", "value"}};
  20861. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20862. "text/plain");
  20863. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20864. }
  20865. TEST_F(StreamApiTest, PostWithParams) {
  20866. httplib::Client cli(HOST, PORT);
  20867. httplib::Params params{{"k", "v"}};
  20868. auto result =
  20869. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20870. auto body = read_body(result);
  20871. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20872. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20873. }
  20874. TEST_F(StreamApiTest, PostLarge) {
  20875. httplib::Client cli(HOST, PORT);
  20876. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20877. size_t total = 0;
  20878. while (result.next()) {
  20879. total += result.size();
  20880. }
  20881. EXPECT_EQ(100u * 1024u, total);
  20882. }
  20883. // stream::Put/Patch tests
  20884. TEST_F(StreamApiTest, PutAndPatch) {
  20885. httplib::Client cli(HOST, PORT);
  20886. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20887. EXPECT_EQ("PUT:test", read_body(put));
  20888. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20889. EXPECT_EQ("PATCH:test", read_body(patch));
  20890. }
  20891. // stream::Delete tests
  20892. TEST_F(StreamApiTest, Delete) {
  20893. httplib::Client cli(HOST, PORT);
  20894. auto del1 = httplib::stream::Delete(cli, "/resource");
  20895. EXPECT_EQ("Deleted", read_body(del1));
  20896. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20897. EXPECT_EQ("Deleted:data", read_body(del2));
  20898. }
  20899. // stream::Head/Options tests
  20900. TEST_F(StreamApiTest, HeadAndOptions) {
  20901. httplib::Client cli(HOST, PORT);
  20902. auto head = httplib::stream::Head(cli, "/head-test");
  20903. EXPECT_TRUE(head.is_valid());
  20904. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20905. auto opts = httplib::stream::Options(cli, "/options");
  20906. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20907. }
  20908. // SSL stream::* tests
  20909. #ifdef CPPHTTPLIB_SSL_ENABLED
  20910. class SSLStreamApiTest : public ::testing::Test {
  20911. protected:
  20912. void SetUp() override {
  20913. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20914. res.set_content("Hello SSL!", "text/plain");
  20915. });
  20916. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20917. res.set_content(req.body, "text/plain");
  20918. });
  20919. port_ = svr_.bind_to_any_port("127.0.0.1");
  20920. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20921. svr_.wait_until_ready();
  20922. }
  20923. void TearDown() override {
  20924. svr_.stop();
  20925. if (thread_.joinable()) thread_.join();
  20926. }
  20927. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20928. std::thread thread_;
  20929. int port_ = 0;
  20930. };
  20931. TEST_F(SSLStreamApiTest, GetAndPost) {
  20932. httplib::SSLClient cli("127.0.0.1", port_);
  20933. cli.enable_server_certificate_verification(false);
  20934. auto get = httplib::stream::Get(cli, "/hello");
  20935. EXPECT_EQ("Hello SSL!", read_body(get));
  20936. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20937. EXPECT_EQ("test", read_body(post));
  20938. }
  20939. #endif
  20940. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20941. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20942. // BodyReader
  20943. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20944. // Test that read timeout during streaming is detected
  20945. // Use a large content-length response where server delays mid-stream
  20946. Server svr;
  20947. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20948. // Send a large response with delay in the middle
  20949. res.set_content_provider(
  20950. 1000, // content_length
  20951. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20952. if (offset < 100) {
  20953. // Send first 100 bytes immediately
  20954. std::string data(100, 'A');
  20955. sink.write(data.c_str(), data.size());
  20956. return true;
  20957. }
  20958. // Then delay longer than client timeout
  20959. std::this_thread::sleep_for(std::chrono::seconds(3));
  20960. std::string data(900, 'B');
  20961. sink.write(data.c_str(), data.size());
  20962. return true;
  20963. });
  20964. });
  20965. auto port = 8091;
  20966. std::thread t([&]() { svr.listen("localhost", port); });
  20967. svr.wait_until_ready();
  20968. Client cli("localhost", port);
  20969. cli.set_read_timeout(1, 0); // 1 second timeout
  20970. auto handle = cli.open_stream("GET", "/slow-stream");
  20971. ASSERT_TRUE(handle.is_valid());
  20972. char buf[256];
  20973. ssize_t total = 0;
  20974. ssize_t n;
  20975. bool got_error = false;
  20976. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20977. total += n;
  20978. }
  20979. if (n < 0) {
  20980. got_error = true;
  20981. // Should be timeout or read error
  20982. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20983. handle.get_read_error() == Error::Read)
  20984. << "Actual error: " << to_string(handle.get_read_error());
  20985. }
  20986. // Either we got an error, or we got less data than expected
  20987. EXPECT_TRUE(got_error || total < 1000)
  20988. << "Expected timeout but got all " << total << " bytes";
  20989. svr.stop();
  20990. t.join();
  20991. }
  20992. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20993. // Test connection closed detection via BodyReader
  20994. Server svr;
  20995. std::atomic<bool> close_now{false};
  20996. svr.Get("/will-close", [&](const Request &, Response &res) {
  20997. res.set_content_provider(
  20998. 10000, // Large content_length that we won't fully send
  20999. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21000. if (offset < 100) {
  21001. std::string data(100, 'X');
  21002. sink.write(data.c_str(), data.size());
  21003. return true;
  21004. }
  21005. // Wait for signal then abort
  21006. while (!close_now) {
  21007. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21008. }
  21009. return false; // Abort - server will close connection
  21010. });
  21011. });
  21012. auto port = 8092;
  21013. std::thread t([&]() { svr.listen("localhost", port); });
  21014. svr.wait_until_ready();
  21015. Client cli("localhost", port);
  21016. auto handle = cli.open_stream("GET", "/will-close");
  21017. ASSERT_TRUE(handle.is_valid());
  21018. char buf[256];
  21019. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21020. EXPECT_GT(n, 0) << "First read should succeed";
  21021. // Signal server to close
  21022. close_now = true;
  21023. // Keep reading until error or EOF
  21024. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21025. // Keep reading
  21026. }
  21027. // Should get an error since content_length wasn't satisfied
  21028. if (n < 0) {
  21029. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21030. handle.get_read_error() == Error::Read)
  21031. << "Actual error: " << to_string(handle.get_read_error());
  21032. }
  21033. svr.stop();
  21034. t.join();
  21035. }
  21036. #ifdef CPPHTTPLIB_SSL_ENABLED
  21037. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21038. // Test that read timeout during SSL streaming is detected
  21039. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21040. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21041. res.set_content_provider(
  21042. 1000, "text/plain",
  21043. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21044. if (offset < 100) {
  21045. std::string data(100, 'A');
  21046. sink.write(data.c_str(), data.size());
  21047. return true;
  21048. }
  21049. std::this_thread::sleep_for(std::chrono::seconds(3));
  21050. std::string data(900, 'B');
  21051. sink.write(data.c_str(), data.size());
  21052. return true;
  21053. });
  21054. });
  21055. auto port = 8093;
  21056. std::thread t([&]() { svr.listen("localhost", port); });
  21057. svr.wait_until_ready();
  21058. SSLClient cli("localhost", port);
  21059. cli.enable_server_certificate_verification(false);
  21060. cli.set_read_timeout(1, 0); // 1 second timeout
  21061. auto handle = cli.open_stream("GET", "/slow-stream");
  21062. ASSERT_TRUE(handle.is_valid());
  21063. char buf[256];
  21064. ssize_t total = 0;
  21065. ssize_t n;
  21066. bool got_error = false;
  21067. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21068. total += n;
  21069. }
  21070. if (n < 0) {
  21071. got_error = true;
  21072. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21073. handle.get_read_error() == Error::Read)
  21074. << "Actual error: " << to_string(handle.get_read_error());
  21075. }
  21076. EXPECT_TRUE(got_error || total < 1000)
  21077. << "Expected timeout but got all " << total << " bytes";
  21078. svr.stop();
  21079. t.join();
  21080. }
  21081. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21082. // Test SSL connection closed detection
  21083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21084. std::atomic<bool> close_now{false};
  21085. svr.Get("/will-close", [&](const Request &, Response &res) {
  21086. res.set_content_provider(
  21087. 10000, "text/plain",
  21088. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21089. if (offset < 100) {
  21090. std::string data(100, 'X');
  21091. sink.write(data.c_str(), data.size());
  21092. return true;
  21093. }
  21094. while (!close_now) {
  21095. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21096. }
  21097. return false;
  21098. });
  21099. });
  21100. auto port = 8094;
  21101. std::thread t([&]() { svr.listen("localhost", port); });
  21102. svr.wait_until_ready();
  21103. SSLClient cli("localhost", port);
  21104. cli.enable_server_certificate_verification(false);
  21105. auto handle = cli.open_stream("GET", "/will-close");
  21106. ASSERT_TRUE(handle.is_valid());
  21107. char buf[256];
  21108. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21109. EXPECT_GT(n, 0);
  21110. // Signal server to close
  21111. close_now = true;
  21112. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21113. // Keep reading
  21114. }
  21115. if (n < 0) {
  21116. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21117. handle.get_read_error() == Error::Read)
  21118. << "Actual error: " << to_string(handle.get_read_error());
  21119. }
  21120. svr.stop();
  21121. t.join();
  21122. }
  21123. #endif
  21124. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21125. using namespace httplib;
  21126. // Create a test file
  21127. const char *fname = "etag_testfile.txt";
  21128. const char *content = "etag-content";
  21129. {
  21130. std::ofstream ofs(fname);
  21131. ofs << content;
  21132. ASSERT_TRUE(ofs.good());
  21133. }
  21134. Server svr;
  21135. svr.set_mount_point("/static", ".");
  21136. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21137. svr.wait_until_ready();
  21138. Client cli(HOST, PORT);
  21139. // First request: should get 200 with ETag header
  21140. auto res1 = cli.Get("/static/etag_testfile.txt");
  21141. ASSERT_TRUE(res1);
  21142. ASSERT_EQ(200, res1->status);
  21143. ASSERT_TRUE(res1->has_header("ETag"));
  21144. std::string etag = res1->get_header_value("ETag");
  21145. EXPECT_FALSE(etag.empty());
  21146. // Verify ETag format: W/"hex-hex"
  21147. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21148. EXPECT_EQ('W', etag[0]);
  21149. EXPECT_EQ('/', etag[1]);
  21150. EXPECT_EQ('"', etag[2]);
  21151. EXPECT_EQ('"', etag.back());
  21152. // Exact match: expect 304 Not Modified
  21153. Headers h2 = {{"If-None-Match", etag}};
  21154. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21155. ASSERT_TRUE(res2);
  21156. EXPECT_EQ(304, res2->status);
  21157. // Wildcard match: expect 304 Not Modified
  21158. Headers h3 = {{"If-None-Match", "*"}};
  21159. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21160. ASSERT_TRUE(res3);
  21161. EXPECT_EQ(304, res3->status);
  21162. // Non-matching ETag: expect 200
  21163. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21164. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21165. ASSERT_TRUE(res4);
  21166. EXPECT_EQ(200, res4->status);
  21167. // Multiple ETags with one matching: expect 304
  21168. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21169. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21170. ASSERT_TRUE(res5);
  21171. EXPECT_EQ(304, res5->status);
  21172. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21173. // that equivalent to the single comma-separated list above, so the match on
  21174. // the second line must still be found.
  21175. Headers h6;
  21176. h6.emplace("If-None-Match", "W/\"other\"");
  21177. h6.emplace("If-None-Match", etag);
  21178. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21179. ASSERT_TRUE(res6);
  21180. EXPECT_EQ(304, res6->status);
  21181. svr.stop();
  21182. t.join();
  21183. std::remove(fname);
  21184. }
  21185. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21186. using namespace httplib;
  21187. Server svr;
  21188. svr.set_mount_point("/static", ".");
  21189. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21190. svr.wait_until_ready();
  21191. Client cli(HOST, PORT);
  21192. // Send If-None-Match: * to a non-existent file
  21193. Headers h = {{"If-None-Match", "*"}};
  21194. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21196. EXPECT_EQ(404, res->status);
  21197. svr.stop();
  21198. t.join();
  21199. }
  21200. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21201. using namespace httplib;
  21202. // Create a test file
  21203. const char *fname = "etag_boundary_testfile.txt";
  21204. const char *content = "boundary-test";
  21205. {
  21206. std::ofstream ofs(fname);
  21207. ofs << content;
  21208. ASSERT_TRUE(ofs.good());
  21209. }
  21210. Server svr;
  21211. svr.set_mount_point("/static", ".");
  21212. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21213. svr.wait_until_ready();
  21214. Client cli(HOST, PORT);
  21215. // Get the actual ETag
  21216. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21217. ASSERT_TRUE(res1);
  21218. ASSERT_EQ(200, res1->status);
  21219. ASSERT_TRUE(res1->has_header("ETag"));
  21220. std::string etag = res1->get_header_value("ETag");
  21221. // Test 1: Very long ETag value (longer than actual ETag)
  21222. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21223. Headers h1 = {{"If-None-Match", "W/"
  21224. "\"very-long-etag-value-that-is-much-longer-"
  21225. "than-the-actual-etag-value\""}};
  21226. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21227. ASSERT_TRUE(res2);
  21228. EXPECT_EQ(200, res2->status); // Should not match
  21229. // Test 2: Long string followed by wildcard
  21230. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21231. // string)
  21232. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21233. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21234. ASSERT_TRUE(res3);
  21235. EXPECT_EQ(304, res3->status); // Should match on "*"
  21236. // Test 3: Wildcard followed by long string
  21237. // Should match on "*" immediately and return 304
  21238. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21239. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21240. ASSERT_TRUE(res4);
  21241. EXPECT_EQ(304, res4->status); // Should match on "*"
  21242. // Test 4: Multiple long non-matching values
  21243. // Should NOT match and return 200 (test that all comparisons are safe)
  21244. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21245. "W/\"second-long-non-matching-value\", "
  21246. "W/\"third-long-non-matching-value\""}};
  21247. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21248. ASSERT_TRUE(res5);
  21249. EXPECT_EQ(200, res5->status); // Should not match
  21250. // Test 5: Single character that is not "*" (edge case)
  21251. Headers h5 = {{"If-None-Match", "X"}};
  21252. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21253. ASSERT_TRUE(res6);
  21254. EXPECT_EQ(200, res6->status); // Should not match
  21255. svr.stop();
  21256. t.join();
  21257. std::remove(fname);
  21258. }
  21259. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21260. using namespace httplib;
  21261. // Create a test file
  21262. const char *fname = "ims_testfile.txt";
  21263. const char *content = "if-modified-since-test";
  21264. {
  21265. std::ofstream ofs(fname);
  21266. ofs << content;
  21267. ASSERT_TRUE(ofs.good());
  21268. }
  21269. Server svr;
  21270. svr.set_mount_point("/static", ".");
  21271. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21272. svr.wait_until_ready();
  21273. Client cli(HOST, PORT);
  21274. // First request: should get 200 with Last-Modified header
  21275. auto res1 = cli.Get("/static/ims_testfile.txt");
  21276. ASSERT_TRUE(res1);
  21277. ASSERT_EQ(200, res1->status);
  21278. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21279. std::string last_modified = res1->get_header_value("Last-Modified");
  21280. EXPECT_FALSE(last_modified.empty());
  21281. // If-Modified-Since with same time: expect 304
  21282. Headers h2 = {{"If-Modified-Since", last_modified}};
  21283. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21284. ASSERT_TRUE(res2);
  21285. EXPECT_EQ(304, res2->status);
  21286. // If-Modified-Since with future time: expect 304
  21287. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21288. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21289. ASSERT_TRUE(res3);
  21290. EXPECT_EQ(304, res3->status);
  21291. // If-Modified-Since with past time: expect 200
  21292. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21293. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21294. ASSERT_TRUE(res4);
  21295. EXPECT_EQ(200, res4->status);
  21296. // If-None-Match takes precedence over If-Modified-Since
  21297. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21298. ASSERT_TRUE(res1->has_header("ETag"));
  21299. std::string etag = res1->get_header_value("ETag");
  21300. Headers h5 = {{"If-None-Match", etag},
  21301. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21302. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21303. ASSERT_TRUE(res5);
  21304. EXPECT_EQ(304, res5->status);
  21305. svr.stop();
  21306. t.join();
  21307. std::remove(fname);
  21308. }
  21309. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21310. using namespace httplib;
  21311. Server svr;
  21312. // Endpoint that returns compressible content
  21313. svr.Get("/compressible", [](const Request &, Response &res) {
  21314. // Return a large enough body to trigger compression
  21315. std::string body(1000, 'a');
  21316. res.set_content(body, "text/plain");
  21317. });
  21318. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21319. svr.wait_until_ready();
  21320. Client cli(HOST, PORT);
  21321. // Request with gzip support: should get Vary header when compressed
  21322. cli.set_compress(true);
  21323. auto res1 = cli.Get("/compressible");
  21324. ASSERT_TRUE(res1);
  21325. EXPECT_EQ(200, res1->status);
  21326. // If Content-Encoding is set, Vary should also be set
  21327. if (res1->has_header("Content-Encoding")) {
  21328. EXPECT_TRUE(res1->has_header("Vary"));
  21329. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21330. }
  21331. // Request without Accept-Encoding header: should not have compression
  21332. Headers h_no_compress;
  21333. auto res2 = cli.Get("/compressible", h_no_compress);
  21334. ASSERT_TRUE(res2);
  21335. EXPECT_EQ(200, res2->status);
  21336. // Verify Vary header is present when compression is applied
  21337. // (the exact behavior depends on server configuration)
  21338. svr.stop();
  21339. t.join();
  21340. }
  21341. TEST(ETagTest, IfRangeWithETag) {
  21342. using namespace httplib;
  21343. // Create a test file with known content
  21344. const char *fname = "if_range_testfile.txt";
  21345. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21346. {
  21347. std::ofstream ofs(fname);
  21348. ofs << content;
  21349. ASSERT_TRUE(ofs.good());
  21350. }
  21351. Server svr;
  21352. svr.set_mount_point("/static", ".");
  21353. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21354. svr.wait_until_ready();
  21355. Client cli(HOST, PORT);
  21356. // First request: get ETag
  21357. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21358. ASSERT_TRUE(res1);
  21359. ASSERT_EQ(200, res1->status);
  21360. ASSERT_TRUE(res1->has_header("ETag"));
  21361. std::string etag = res1->get_header_value("ETag");
  21362. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21363. // Since our server generates weak ETags (W/"..."), If-Range with our
  21364. // ETag should NOT result in partial content - it should return full content.
  21365. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21366. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21367. ASSERT_TRUE(res2);
  21368. // Weak ETag in If-Range -> full content (200), not partial (206)
  21369. EXPECT_EQ(200, res2->status);
  21370. EXPECT_EQ(content, res2->body);
  21371. EXPECT_FALSE(res2->has_header("Content-Range"));
  21372. // Range request with non-matching If-Range (ETag): should get 200 (full
  21373. // content)
  21374. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21375. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21376. ASSERT_TRUE(res3);
  21377. EXPECT_EQ(200, res3->status);
  21378. EXPECT_EQ(content, res3->body);
  21379. EXPECT_FALSE(res3->has_header("Content-Range"));
  21380. // Range request with strong ETag (hypothetical - our server doesn't generate
  21381. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21382. // should return full content)
  21383. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21384. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21385. ASSERT_TRUE(res4);
  21386. EXPECT_EQ(200, res4->status);
  21387. EXPECT_EQ(content, res4->body);
  21388. EXPECT_FALSE(res4->has_header("Content-Range"));
  21389. svr.stop();
  21390. t.join();
  21391. std::remove(fname);
  21392. }
  21393. TEST(ETagTest, IfRangeWithDate) {
  21394. using namespace httplib;
  21395. // Create a test file
  21396. const char *fname = "if_range_date_testfile.txt";
  21397. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21398. {
  21399. std::ofstream ofs(fname);
  21400. ofs << content;
  21401. ASSERT_TRUE(ofs.good());
  21402. }
  21403. Server svr;
  21404. svr.set_mount_point("/static", ".");
  21405. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21406. svr.wait_until_ready();
  21407. Client cli(HOST, PORT);
  21408. // First request: get Last-Modified
  21409. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21410. ASSERT_TRUE(res1);
  21411. ASSERT_EQ(200, res1->status);
  21412. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21413. std::string last_modified = res1->get_header_value("Last-Modified");
  21414. // Range request with matching If-Range (date): should get 206
  21415. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21416. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21417. ASSERT_TRUE(res2);
  21418. EXPECT_EQ(206, res2->status);
  21419. EXPECT_EQ("FGHIJ", res2->body);
  21420. // Range request with old If-Range date: should get 200 (full content)
  21421. Headers h3 = {{"Range", "bytes=5-9"},
  21422. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21423. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21424. ASSERT_TRUE(res3);
  21425. EXPECT_EQ(200, res3->status);
  21426. EXPECT_EQ(content, res3->body);
  21427. // Range request with future If-Range date: should get 206
  21428. Headers h4 = {{"Range", "bytes=0-4"},
  21429. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21430. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21431. ASSERT_TRUE(res4);
  21432. EXPECT_EQ(206, res4->status);
  21433. EXPECT_EQ("ABCDE", res4->body);
  21434. svr.stop();
  21435. t.join();
  21436. std::remove(fname);
  21437. }
  21438. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21439. using namespace httplib;
  21440. const char *fname = "etag_malformed.txt";
  21441. const char *content = "malformed-etag";
  21442. {
  21443. std::ofstream ofs(fname);
  21444. ofs << content;
  21445. ASSERT_TRUE(ofs.good());
  21446. }
  21447. Server svr;
  21448. svr.set_mount_point("/static", ".");
  21449. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21450. svr.wait_until_ready();
  21451. Client cli(HOST, PORT);
  21452. // baseline: should get 200 and an ETag
  21453. auto res1 = cli.Get("/static/etag_malformed.txt");
  21454. ASSERT_TRUE(res1);
  21455. ASSERT_EQ(200, res1->status);
  21456. ASSERT_TRUE(res1->has_header("ETag"));
  21457. // Malformed ETag value (missing quotes) should be treated as non-matching
  21458. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21459. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21460. ASSERT_TRUE(res_bad);
  21461. EXPECT_EQ(200, res_bad->status);
  21462. // Whitespace-only header value should be considered invalid / non-matching
  21463. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21464. "Host: localhost\r\n"
  21465. "If-None-Match: \r\n"
  21466. "Connection: close\r\n"
  21467. "\r\n";
  21468. std::string out;
  21469. ASSERT_TRUE(send_request(5, raw_req, &out));
  21470. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21471. svr.stop();
  21472. t.join();
  21473. std::remove(fname);
  21474. }
  21475. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21476. using namespace httplib;
  21477. const char *fname = "ims_invalid_format.txt";
  21478. const char *content = "ims-bad-format";
  21479. {
  21480. std::ofstream ofs(fname);
  21481. ofs << content;
  21482. ASSERT_TRUE(ofs.good());
  21483. }
  21484. Server svr;
  21485. svr.set_mount_point("/static", ".");
  21486. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21487. svr.wait_until_ready();
  21488. Client cli(HOST, PORT);
  21489. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21490. ASSERT_TRUE(res1);
  21491. ASSERT_EQ(200, res1->status);
  21492. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21493. // If-Modified-Since with invalid format should not result in 304
  21494. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21495. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21496. ASSERT_TRUE(res_bad);
  21497. EXPECT_EQ(200, res_bad->status);
  21498. // If-Range with invalid date format should be treated as mismatch -> full
  21499. // content (200)
  21500. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21501. {"If-Range", "invalid-date"}};
  21502. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21503. ASSERT_TRUE(res_ifrange);
  21504. EXPECT_EQ(200, res_ifrange->status);
  21505. svr.stop();
  21506. t.join();
  21507. std::remove(fname);
  21508. }
  21509. TEST(ETagTest, IfRangeWithMalformedETag) {
  21510. using namespace httplib;
  21511. const char *fname = "ifrange_malformed.txt";
  21512. const std::string content = "0123456789";
  21513. {
  21514. std::ofstream ofs(fname);
  21515. ofs << content;
  21516. ASSERT_TRUE(ofs.good());
  21517. }
  21518. Server svr;
  21519. svr.set_mount_point("/static", ".");
  21520. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21521. svr.wait_until_ready();
  21522. Client cli(HOST, PORT);
  21523. // First request: get ETag
  21524. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21525. ASSERT_TRUE(res1);
  21526. ASSERT_EQ(200, res1->status);
  21527. ASSERT_TRUE(res1->has_header("ETag"));
  21528. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21529. // full content (200)
  21530. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21531. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21532. ASSERT_TRUE(res2);
  21533. EXPECT_EQ(200, res2->status);
  21534. EXPECT_EQ(content, res2->body);
  21535. svr.stop();
  21536. t.join();
  21537. std::remove(fname);
  21538. }
  21539. TEST(ETagTest, ExtremeLargeDateValues) {
  21540. using namespace httplib;
  21541. const char *fname = "ims_extreme_date.txt";
  21542. const char *content = "ims-extreme-date";
  21543. {
  21544. std::ofstream ofs(fname);
  21545. ofs << content;
  21546. ASSERT_TRUE(ofs.good());
  21547. }
  21548. Server svr;
  21549. svr.set_mount_point("/static", ".");
  21550. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21551. svr.wait_until_ready();
  21552. Client cli(HOST, PORT);
  21553. auto res1 = cli.Get(std::string("/static/") + fname);
  21554. ASSERT_TRUE(res1);
  21555. ASSERT_EQ(200, res1->status);
  21556. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21557. // Extremely large year that may overflow date parsing routines.
  21558. Headers h_large_date = {
  21559. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21560. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21561. ASSERT_TRUE(res_bad);
  21562. // Expect server to treat this as invalid/mismatch and return full content
  21563. EXPECT_EQ(200, res_bad->status);
  21564. // If-Range with extremely large date should be treated as mismatch -> full
  21565. // content (200)
  21566. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21567. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21568. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21569. ASSERT_TRUE(res_ifrange);
  21570. EXPECT_EQ(200, res_ifrange->status);
  21571. svr.stop();
  21572. t.join();
  21573. std::remove(fname);
  21574. }
  21575. TEST(ETagTest, NegativeFileModificationTime) {
  21576. using namespace httplib;
  21577. const char *fname = "ims_negative_mtime.txt";
  21578. const std::string content = "negative-mtime";
  21579. {
  21580. std::ofstream ofs(fname);
  21581. ofs << content;
  21582. ASSERT_TRUE(ofs.good());
  21583. }
  21584. // Try to set file mtime to a negative value. This may fail on some
  21585. // platforms/filesystems; if it fails, the test will still verify server
  21586. // behaves safely by performing a regular conditional request.
  21587. #if defined(__APPLE__) || defined(__linux__)
  21588. bool set_negative = false;
  21589. do {
  21590. struct timeval times[2];
  21591. // access time: now
  21592. times[0].tv_sec = time(nullptr);
  21593. times[0].tv_usec = 0;
  21594. // modification time: negative (e.g., -1)
  21595. times[1].tv_sec = -1;
  21596. times[1].tv_usec = 0;
  21597. if (utimes(fname, times) == 0) { set_negative = true; }
  21598. } while (0);
  21599. #else
  21600. bool set_negative = false;
  21601. #endif
  21602. Server svr;
  21603. svr.set_mount_point("/static", ".");
  21604. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21605. svr.wait_until_ready();
  21606. Client cli(HOST, PORT);
  21607. auto res1 = cli.Get(std::string("/static/") + fname);
  21608. ASSERT_TRUE(res1);
  21609. ASSERT_EQ(200, res1->status);
  21610. bool has_last_modified = res1->has_header("Last-Modified");
  21611. std::string last_modified;
  21612. if (has_last_modified) {
  21613. last_modified = res1->get_header_value("Last-Modified");
  21614. }
  21615. if (set_negative) {
  21616. // If we successfully set a negative mtime, ensure server returns a
  21617. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21618. // with an old date and ensure server handles it without crash.
  21619. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21620. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21621. ASSERT_TRUE(res2);
  21622. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21623. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21624. } else {
  21625. // Could not set negative mtime on this platform; fall back to verifying
  21626. // that normal invalid/malformed dates are treated safely (non-304).
  21627. Headers h_bad_date = {
  21628. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21629. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21630. ASSERT_TRUE(res_bad);
  21631. EXPECT_EQ(200, res_bad->status);
  21632. }
  21633. svr.stop();
  21634. t.join();
  21635. std::remove(fname);
  21636. }
  21637. //==============================================================================
  21638. // Integration Tests with Server
  21639. //==============================================================================
  21640. class SSEIntegrationTest : public ::testing::Test {
  21641. protected:
  21642. void SetUp() override {
  21643. stop_server_.store(false);
  21644. events_.clear();
  21645. server_ = httplib::detail::make_unique<Server>();
  21646. setup_server();
  21647. start_server();
  21648. }
  21649. void TearDown() override {
  21650. stop_server_.store(true);
  21651. event_cv_.notify_all();
  21652. server_->stop();
  21653. if (server_thread_.joinable()) { server_thread_.join(); }
  21654. }
  21655. void setup_server() {
  21656. // Simple SSE endpoint
  21657. server_->Get("/events", [this](const Request &req, Response &res) {
  21658. auto last_id = req.get_header_value("Last-Event-ID");
  21659. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21660. res.set_chunked_content_provider(
  21661. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21662. std::unique_lock<std::mutex> lock(event_mutex_);
  21663. if (event_cv_.wait_for(
  21664. lock, std::chrono::milliseconds(200), [this] {
  21665. return !events_.empty() || stop_server_.load();
  21666. })) {
  21667. if (stop_server_.load()) { return false; }
  21668. if (!events_.empty()) {
  21669. std::string event = events_.front();
  21670. events_.erase(events_.begin());
  21671. sink.write(event.data(), event.size());
  21672. return true;
  21673. }
  21674. }
  21675. return !stop_server_.load();
  21676. });
  21677. });
  21678. // Endpoint that returns error
  21679. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21680. res.status = 500;
  21681. res.set_content("Internal Server Error", "text/plain");
  21682. });
  21683. // Endpoint for custom event types
  21684. server_->Get("/custom-events", [](const Request &, Response &res) {
  21685. res.set_chunked_content_provider(
  21686. "text/event-stream", [](size_t offset, DataSink &sink) {
  21687. if (offset == 0) {
  21688. std::string event = "event: update\ndata: updated\n\n"
  21689. "event: delete\ndata: deleted\n\n";
  21690. sink.write(event.data(), event.size());
  21691. }
  21692. return false; // End stream after sending
  21693. });
  21694. });
  21695. }
  21696. void start_server() {
  21697. port_ = server_->bind_to_any_port(HOST);
  21698. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21699. // Wait for server to start
  21700. while (!server_->is_running()) {
  21701. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21702. }
  21703. }
  21704. int get_port() const { return port_; }
  21705. void send_event(const std::string &event) {
  21706. std::lock_guard<std::mutex> lock(event_mutex_);
  21707. events_.push_back(event);
  21708. event_cv_.notify_all();
  21709. }
  21710. std::unique_ptr<Server> server_;
  21711. std::thread server_thread_;
  21712. std::mutex event_mutex_;
  21713. std::condition_variable event_cv_;
  21714. std::vector<std::string> events_;
  21715. std::atomic<bool> stop_server_{false};
  21716. std::string last_received_event_id_;
  21717. int port_ = 0;
  21718. };
  21719. //==============================================================================
  21720. // SSE Parsing Tests
  21721. //==============================================================================
  21722. class SSEParsingTest : public SSEIntegrationTest {
  21723. protected:
  21724. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21725. // A trailing sentinel event tells when the whole stream has been parsed.
  21726. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21727. auto body = stream + "event: end\ndata: end\n\n";
  21728. server_->Get("/parse", [body](const Request &, Response &res) {
  21729. res.set_content(body, "text/event-stream");
  21730. });
  21731. return collect("/parse");
  21732. }
  21733. // Runs SSEClient against path until an "end" event arrives and returns the
  21734. // messages dispatched before it
  21735. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21736. Client client(HOST, get_port());
  21737. sse::SSEClient sse(client, path);
  21738. std::mutex mutex;
  21739. std::condition_variable cv;
  21740. std::vector<sse::SSEMessage> messages;
  21741. auto done = false;
  21742. sse.on_message([&](const sse::SSEMessage &msg) {
  21743. std::lock_guard<std::mutex> lock(mutex);
  21744. // Ignore a replay from a reconnect that races with stop()
  21745. if (!done) { messages.push_back(msg); }
  21746. });
  21747. sse.on_event("end", [&](const sse::SSEMessage &) {
  21748. std::lock_guard<std::mutex> lock(mutex);
  21749. done = true;
  21750. cv.notify_all();
  21751. });
  21752. sse.set_reconnect_interval(100);
  21753. sse.start_async();
  21754. {
  21755. std::unique_lock<std::mutex> lock(mutex);
  21756. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21757. }
  21758. sse.stop();
  21759. EXPECT_TRUE(done);
  21760. return messages;
  21761. }
  21762. };
  21763. TEST_F(SSEParsingTest, SingleLineData) {
  21764. auto msgs = parse("data: hello\n\n");
  21765. ASSERT_EQ(msgs.size(), 1u);
  21766. EXPECT_EQ(msgs[0].data, "hello");
  21767. EXPECT_EQ(msgs[0].event, "message");
  21768. }
  21769. TEST_F(SSEParsingTest, MultiLineData) {
  21770. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21771. ASSERT_EQ(msgs.size(), 1u);
  21772. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21773. }
  21774. TEST_F(SSEParsingTest, CustomEventType) {
  21775. auto msgs = parse("event: update\ndata: payload\n\n");
  21776. ASSERT_EQ(msgs.size(), 1u);
  21777. EXPECT_EQ(msgs[0].event, "update");
  21778. EXPECT_EQ(msgs[0].data, "payload");
  21779. }
  21780. TEST_F(SSEParsingTest, EventIdHandling) {
  21781. auto msgs = parse("id: 12345\ndata: test\n\n");
  21782. ASSERT_EQ(msgs.size(), 1u);
  21783. EXPECT_EQ(msgs[0].id, "12345");
  21784. }
  21785. TEST_F(SSEParsingTest, EmptyEventId) {
  21786. auto msgs = parse("id:\ndata: test\n\n");
  21787. ASSERT_EQ(msgs.size(), 1u);
  21788. EXPECT_EQ(msgs[0].id, "");
  21789. }
  21790. TEST_F(SSEParsingTest, CommentsIgnored) {
  21791. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21792. ASSERT_EQ(msgs.size(), 1u);
  21793. EXPECT_EQ(msgs[0].data, "hello");
  21794. EXPECT_EQ(msgs[0].event, "message");
  21795. }
  21796. TEST_F(SSEParsingTest, ColonInValue) {
  21797. auto msgs = parse("data: hello:world:test\n\n");
  21798. ASSERT_EQ(msgs.size(), 1u);
  21799. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21800. }
  21801. TEST_F(SSEParsingTest, FieldNameOnly) {
  21802. // A line without a colon is a field name with an empty value
  21803. auto msgs = parse("data\n\n");
  21804. ASSERT_EQ(msgs.size(), 1u);
  21805. EXPECT_EQ(msgs[0].data, "");
  21806. }
  21807. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21808. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21809. ASSERT_EQ(msgs.size(), 1u);
  21810. EXPECT_EQ(msgs[0].event, "update");
  21811. EXPECT_EQ(msgs[0].data, "hello");
  21812. }
  21813. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21814. auto msgs = parse("data\r\n\r\n");
  21815. ASSERT_EQ(msgs.size(), 1u);
  21816. EXPECT_EQ(msgs[0].data, "");
  21817. }
  21818. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21819. auto msgs = parse("event: update\rdata: hello\r\r");
  21820. ASSERT_EQ(msgs.size(), 1u);
  21821. EXPECT_EQ(msgs[0].event, "update");
  21822. EXPECT_EQ(msgs[0].data, "hello");
  21823. }
  21824. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21825. // Chunk boundaries fall inside every \r\n and right before the first one
  21826. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21827. "\n\r", "\nevent: end\ndata: end\n\n"};
  21828. server_->Get("/split", [chunks](const Request &, Response &res) {
  21829. auto i = std::make_shared<size_t>(0);
  21830. res.set_chunked_content_provider(
  21831. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21832. if (*i == chunks.size()) {
  21833. sink.done();
  21834. } else {
  21835. sink.write(chunks[*i].data(), chunks[*i].size());
  21836. (*i)++;
  21837. }
  21838. return true;
  21839. });
  21840. });
  21841. auto msgs = collect("/split");
  21842. ASSERT_EQ(msgs.size(), 1u);
  21843. EXPECT_EQ(msgs[0].event, "update");
  21844. EXPECT_EQ(msgs[0].data, "hello");
  21845. }
  21846. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21847. // Only a BOM at the start of the stream is ignored
  21848. auto msgs = parse("\xEF\xBB\xBF"
  21849. "data: first\n\n"
  21850. "\xEF\xBB\xBF"
  21851. "data: second\n\n");
  21852. ASSERT_EQ(msgs.size(), 1u);
  21853. EXPECT_EQ(msgs[0].data, "first");
  21854. }
  21855. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21856. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21857. ASSERT_EQ(msgs.size(), 1u);
  21858. EXPECT_EQ(msgs[0].data, "hello");
  21859. EXPECT_EQ(msgs[0].event, "message");
  21860. }
  21861. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21862. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21863. ASSERT_EQ(msgs.size(), 2u);
  21864. EXPECT_EQ(msgs[0].data, "hello");
  21865. EXPECT_EQ(msgs[1].data, "hello");
  21866. }
  21867. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21868. // An event without data is not dispatched, and its type must not leak
  21869. // into the next event
  21870. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21871. ASSERT_EQ(msgs.size(), 1u);
  21872. EXPECT_EQ(msgs[0].event, "message");
  21873. EXPECT_EQ(msgs[0].data, "hello");
  21874. }
  21875. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21876. // Also when the empty field replaces an earlier type
  21877. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21878. ASSERT_EQ(msgs.size(), 2u);
  21879. EXPECT_EQ(msgs[0].event, "message");
  21880. EXPECT_EQ(msgs[1].event, "message");
  21881. }
  21882. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21883. // The first connection sends only an id; the second echoes back the
  21884. // Last-Event-ID it was reconnected with
  21885. std::atomic<int> connection_count{0};
  21886. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21887. if (connection_count++ == 0) {
  21888. res.set_content("id: 42\n\n", "text/event-stream");
  21889. } else {
  21890. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21891. "\n\nevent: end\ndata: end\n\n",
  21892. "text/event-stream");
  21893. }
  21894. });
  21895. auto msgs = collect("/id-only");
  21896. ASSERT_EQ(msgs.size(), 1u);
  21897. EXPECT_EQ(msgs[0].data, "42");
  21898. }
  21899. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21900. // The first connection sets an id and then clears it with an empty one; the
  21901. // second reports whether it was reconnected with a Last-Event-ID
  21902. std::atomic<int> connection_count{0};
  21903. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21904. if (connection_count++ == 0) {
  21905. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21906. "text/event-stream");
  21907. } else {
  21908. res.set_content(
  21909. std::string("data: ") +
  21910. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21911. "\n\nevent: end\ndata: end\n\n",
  21912. "text/event-stream");
  21913. }
  21914. });
  21915. auto msgs = collect("/id-clear");
  21916. ASSERT_EQ(msgs.size(), 3u);
  21917. EXPECT_EQ(msgs[0].id, "1");
  21918. EXPECT_EQ(msgs[1].id, "");
  21919. EXPECT_EQ(msgs[2].data, "not sent");
  21920. }
  21921. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21922. // The first connection sets an id and then sends ids that cannot be carried
  21923. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21924. // with
  21925. std::atomic<int> connection_count{0};
  21926. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21927. if (connection_count++ == 0) {
  21928. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21929. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21930. "text/event-stream");
  21931. } else {
  21932. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21933. "\n\nevent: end\ndata: end\n\n",
  21934. "text/event-stream");
  21935. }
  21936. });
  21937. auto msgs = collect("/id-unsendable");
  21938. ASSERT_EQ(msgs.size(), 1u);
  21939. EXPECT_EQ(msgs[0].data, "42");
  21940. }
  21941. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21942. auto msgs = parse("event: notification\nid: evt-42\n"
  21943. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21944. ASSERT_EQ(msgs.size(), 1u);
  21945. EXPECT_EQ(msgs[0].event, "notification");
  21946. EXPECT_EQ(msgs[0].id, "evt-42");
  21947. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21948. }
  21949. TEST(SSEMessageTest, Clear) {
  21950. sse::SSEMessage msg;
  21951. msg.event = "custom";
  21952. msg.data = "some data";
  21953. msg.id = "123";
  21954. msg.clear();
  21955. EXPECT_EQ(msg.event, "message");
  21956. EXPECT_EQ(msg.data, "");
  21957. EXPECT_EQ(msg.id, "");
  21958. }
  21959. //==============================================================================
  21960. // SSE Integration Tests
  21961. //==============================================================================
  21962. // Test: Successful connection and on_open callback
  21963. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21964. // Add a simple endpoint that sends one event and closes
  21965. server_->Get("/simple-event", [](const Request &, Response &res) {
  21966. res.set_chunked_content_provider(
  21967. "text/event-stream", [](size_t offset, DataSink &sink) {
  21968. if (offset == 0) {
  21969. std::string event = "data: hello\n\n";
  21970. sink.write(event.data(), event.size());
  21971. }
  21972. return false; // Close stream after sending
  21973. });
  21974. });
  21975. Client client("localhost", get_port());
  21976. sse::SSEClient sse(client, "/simple-event");
  21977. std::atomic<bool> open_called{false};
  21978. std::atomic<bool> message_received{false};
  21979. sse.on_open([&open_called]() { open_called.store(true); });
  21980. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21981. if (msg.data == "hello") { message_received.store(true); }
  21982. });
  21983. sse.set_reconnect_interval(100);
  21984. sse.set_max_reconnect_attempts(1);
  21985. // Start async
  21986. sse.start_async();
  21987. // Wait for message to be processed
  21988. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21989. sse.stop();
  21990. EXPECT_TRUE(open_called.load());
  21991. EXPECT_TRUE(message_received.load());
  21992. }
  21993. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21994. // A data line that never ends.
  21995. server_->Get("/endless-line", [](const Request &, Response &res) {
  21996. res.set_chunked_content_provider(
  21997. "text/event-stream", [](size_t offset, DataSink &sink) {
  21998. if (offset == 0) { sink.write("data: ", 6); }
  21999. std::string chunk(64 * 1024, 'A');
  22000. return sink.write(chunk.data(), chunk.size());
  22001. });
  22002. });
  22003. Client client("localhost", get_port());
  22004. sse::SSEClient sse(client, "/endless-line");
  22005. std::atomic<bool> too_long{false};
  22006. sse.on_error([&](Error err) {
  22007. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22008. });
  22009. sse.set_max_reconnect_attempts(1);
  22010. sse.start_async();
  22011. for (int i = 0; i < 500 && !too_long; i++) {
  22012. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22013. }
  22014. sse.stop();
  22015. EXPECT_TRUE(too_long);
  22016. }
  22017. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22018. // Far more in all than the client's payload limit below.
  22019. server_->Get("/many-events", [](const Request &, Response &res) {
  22020. res.set_chunked_content_provider(
  22021. "text/event-stream", [](size_t offset, DataSink &sink) {
  22022. if (offset == 0) {
  22023. std::string events;
  22024. for (int i = 0; i < 1000; i++) {
  22025. events += "data: message\n\n";
  22026. }
  22027. sink.write(events.data(), events.size());
  22028. }
  22029. return false;
  22030. });
  22031. });
  22032. Client client("localhost", get_port());
  22033. client.set_payload_max_length(1024);
  22034. sse::SSEClient sse(client, "/many-events");
  22035. std::atomic<int> messages{0};
  22036. std::atomic<bool> too_large{false};
  22037. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22038. sse.on_error([&](Error err) {
  22039. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22040. });
  22041. sse.set_max_reconnect_attempts(1);
  22042. sse.start_async();
  22043. for (int i = 0; i < 500 && messages < 1000; i++) {
  22044. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22045. }
  22046. sse.stop();
  22047. EXPECT_GE(messages.load(), 1000);
  22048. EXPECT_FALSE(too_large);
  22049. }
  22050. // Test: on_message callback
  22051. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22052. // Endpoint that sends multiple events then closes
  22053. server_->Get("/multi-event", [](const Request &, Response &res) {
  22054. res.set_chunked_content_provider(
  22055. "text/event-stream", [](size_t offset, DataSink &sink) {
  22056. if (offset == 0) {
  22057. std::string events = "data: message1\n\ndata: message2\n\n";
  22058. sink.write(events.data(), events.size());
  22059. }
  22060. return false;
  22061. });
  22062. });
  22063. Client client("localhost", get_port());
  22064. sse::SSEClient sse(client, "/multi-event");
  22065. std::vector<std::string> received_messages;
  22066. std::mutex messages_mutex;
  22067. sse.on_message([&](const sse::SSEMessage &msg) {
  22068. std::lock_guard<std::mutex> lock(messages_mutex);
  22069. received_messages.push_back(msg.data);
  22070. });
  22071. sse.set_reconnect_interval(100);
  22072. sse.set_max_reconnect_attempts(1);
  22073. sse.start_async();
  22074. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22075. sse.stop();
  22076. std::lock_guard<std::mutex> lock(messages_mutex);
  22077. EXPECT_GE(received_messages.size(), 2u);
  22078. if (received_messages.size() >= 2) {
  22079. EXPECT_EQ(received_messages[0], "message1");
  22080. EXPECT_EQ(received_messages[1], "message2");
  22081. }
  22082. }
  22083. // Test: on_event for specific types
  22084. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22085. Client client("localhost", get_port());
  22086. sse::SSEClient sse(client, "/custom-events");
  22087. std::atomic<bool> update_received{false};
  22088. std::atomic<bool> delete_received{false};
  22089. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22090. if (msg.data == "updated") { update_received.store(true); }
  22091. });
  22092. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22093. if (msg.data == "deleted") { delete_received.store(true); }
  22094. });
  22095. sse.set_max_reconnect_attempts(1);
  22096. sse.start_async();
  22097. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22098. sse.stop();
  22099. EXPECT_TRUE(update_received.load());
  22100. EXPECT_TRUE(delete_received.load());
  22101. }
  22102. // Test: on_error callback on connection failure
  22103. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22104. // Connect to a non-existent port
  22105. Client client("localhost", 59999);
  22106. sse::SSEClient sse(client, "/events");
  22107. std::atomic<bool> error_called{false};
  22108. Error received_error = Error::Success;
  22109. sse.on_error([&](Error err) {
  22110. error_called.store(true);
  22111. received_error = err;
  22112. });
  22113. sse.set_reconnect_interval(50);
  22114. sse.set_max_reconnect_attempts(1);
  22115. sse.start_async();
  22116. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22117. sse.stop();
  22118. EXPECT_TRUE(error_called.load());
  22119. EXPECT_NE(received_error, Error::Success);
  22120. }
  22121. // Test: Last-Event-ID header sent on reconnect
  22122. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22123. // Endpoint that sends event with ID
  22124. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22125. res.set_chunked_content_provider(
  22126. "text/event-stream", [](size_t offset, DataSink &sink) {
  22127. if (offset == 0) {
  22128. std::string event = "id: evt-123\ndata: test\n\n";
  22129. sink.write(event.data(), event.size());
  22130. }
  22131. return false;
  22132. });
  22133. });
  22134. Client client("localhost", get_port());
  22135. sse::SSEClient sse(client, "/event-with-id");
  22136. std::atomic<bool> id_received{false};
  22137. sse.on_message([&](const sse::SSEMessage &msg) {
  22138. if (!msg.id.empty()) { id_received.store(true); }
  22139. });
  22140. sse.set_reconnect_interval(100);
  22141. sse.set_max_reconnect_attempts(1);
  22142. sse.start_async();
  22143. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22144. sse.stop();
  22145. EXPECT_TRUE(id_received.load());
  22146. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22147. }
  22148. // Test: Manual stop
  22149. TEST_F(SSEIntegrationTest, ManualStop) {
  22150. // Endpoint that sends one event and stays open briefly. The server outlives
  22151. // this test body, so the provider uses the fixture's flag, not a local.
  22152. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22153. res.set_chunked_content_provider(
  22154. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22155. if (offset == 0) {
  22156. std::string event = "data: connected\n\n";
  22157. sink.write(event.data(), event.size());
  22158. }
  22159. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22160. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22161. }
  22162. return false;
  22163. });
  22164. });
  22165. Client client("localhost", get_port());
  22166. sse::SSEClient sse(client, "/stay-open");
  22167. std::atomic<bool> connected{false};
  22168. sse.on_open([&connected]() { connected.store(true); });
  22169. sse.set_reconnect_interval(100);
  22170. sse.set_max_reconnect_attempts(1);
  22171. sse.start_async();
  22172. // Wait for connection to establish
  22173. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22174. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22175. }
  22176. EXPECT_TRUE(connected.load());
  22177. EXPECT_TRUE(sse.is_connected());
  22178. // Signal handler to stop
  22179. stop_server_.store(true);
  22180. // Stop SSE client
  22181. sse.stop();
  22182. EXPECT_FALSE(sse.is_connected());
  22183. }
  22184. // Sends one event, then nothing until stop is set
  22185. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22186. return [&stop](const Request &, Response &res) {
  22187. res.set_chunked_content_provider(
  22188. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22189. if (offset == 0) {
  22190. std::string event = "data: hello\n\n";
  22191. sink.write(event.data(), event.size());
  22192. }
  22193. while (!stop.load()) {
  22194. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22195. }
  22196. return false;
  22197. });
  22198. };
  22199. }
  22200. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22201. static void check_stop_interrupts_blocked_read(Client &client) {
  22202. client.set_read_timeout(30, 0);
  22203. for (auto by_destructor : {false, true}) {
  22204. std::atomic<bool> received{false};
  22205. std::chrono::steady_clock::time_point start;
  22206. {
  22207. sse::SSEClient sse(client, "/idle-stream");
  22208. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22209. sse.start_async();
  22210. for (int i = 0; i < 500 && !received.load(); ++i) {
  22211. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22212. }
  22213. ASSERT_TRUE(received.load());
  22214. // Let the client block in the next read
  22215. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22216. start = std::chrono::steady_clock::now();
  22217. if (!by_destructor) { sse.stop(); }
  22218. }
  22219. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22220. std::chrono::seconds(2));
  22221. }
  22222. }
  22223. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22224. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22225. Client client("localhost", get_port());
  22226. check_stop_interrupts_blocked_read(client);
  22227. }
  22228. #ifdef CPPHTTPLIB_SSL_ENABLED
  22229. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22230. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22231. std::atomic<bool> done{false};
  22232. svr.Get("/idle-stream", idle_event_stream(done));
  22233. auto port = svr.bind_to_any_port(HOST);
  22234. std::thread t([&] { svr.listen_after_bind(); });
  22235. auto se = detail::scope_exit([&] {
  22236. done.store(true);
  22237. svr.stop();
  22238. t.join();
  22239. });
  22240. svr.wait_until_ready();
  22241. Client client("https://localhost:" + std::to_string(port));
  22242. client.enable_server_certificate_verification(false);
  22243. check_stop_interrupts_blocked_read(client);
  22244. }
  22245. #endif
  22246. // Test: SSEClient with custom headers
  22247. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22248. // Setup a server endpoint that checks for custom header
  22249. std::atomic<bool> header_received{false};
  22250. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22251. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22252. header_received.store(true);
  22253. }
  22254. res.set_chunked_content_provider("text/event-stream",
  22255. [](size_t, DataSink &) { return false; });
  22256. });
  22257. Client client("localhost", get_port());
  22258. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22259. sse::SSEClient sse(client, "/header-check", headers);
  22260. sse.set_max_reconnect_attempts(1);
  22261. sse.start_async();
  22262. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22263. sse.stop();
  22264. EXPECT_TRUE(header_received.load());
  22265. }
  22266. // Test: Reconnect interval configuration
  22267. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22268. Client client("localhost", get_port());
  22269. sse::SSEClient sse(client, "/events");
  22270. auto &result = sse.set_reconnect_interval(500);
  22271. // Builder pattern should return reference to self
  22272. EXPECT_EQ(&result, &sse);
  22273. }
  22274. // Test: Max reconnect attempts
  22275. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22276. // Connect to non-existent port to force reconnects
  22277. Client client("localhost", 59998);
  22278. sse::SSEClient sse(client, "/events");
  22279. std::atomic<int> error_count{0};
  22280. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22281. sse.set_reconnect_interval(50);
  22282. sse.set_max_reconnect_attempts(2);
  22283. auto start = std::chrono::steady_clock::now();
  22284. sse.start(); // Blocking call
  22285. auto end = std::chrono::steady_clock::now();
  22286. // Should have stopped after 2 failed attempts
  22287. EXPECT_GE(error_count.load(), 2);
  22288. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22289. auto duration =
  22290. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22291. #ifdef _WIN32
  22292. // Windows is much slower for socket connection failures
  22293. EXPECT_LT(duration.count(), 7000);
  22294. #else
  22295. EXPECT_LT(duration.count(), 1000);
  22296. #endif
  22297. }
  22298. // Test: Multi-line data in integration
  22299. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22300. // Endpoint with multi-line data
  22301. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22302. res.set_chunked_content_provider(
  22303. "text/event-stream", [](size_t offset, DataSink &sink) {
  22304. if (offset == 0) {
  22305. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22306. sink.write(event.data(), event.size());
  22307. }
  22308. return false;
  22309. });
  22310. });
  22311. Client client("localhost", get_port());
  22312. sse::SSEClient sse(client, "/multiline-data");
  22313. std::string received_data;
  22314. std::mutex data_mutex;
  22315. sse.on_message([&](const sse::SSEMessage &msg) {
  22316. std::lock_guard<std::mutex> lock(data_mutex);
  22317. received_data = msg.data;
  22318. });
  22319. sse.set_reconnect_interval(100);
  22320. sse.set_max_reconnect_attempts(1);
  22321. sse.start_async();
  22322. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22323. sse.stop();
  22324. std::lock_guard<std::mutex> lock(data_mutex);
  22325. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22326. }
  22327. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22328. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22329. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22330. DataSink &sink) {
  22331. if (offset == 0) {
  22332. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22333. sink.write(events.data(), events.size());
  22334. }
  22335. return false;
  22336. });
  22337. });
  22338. Client client("localhost", get_port());
  22339. sse::SSEClient sse(client, "/empty-data-lines");
  22340. std::mutex mutex;
  22341. std::condition_variable cv;
  22342. std::vector<std::string> received;
  22343. sse.on_message([&](const sse::SSEMessage &msg) {
  22344. std::lock_guard<std::mutex> lock(mutex);
  22345. received.push_back(msg.data);
  22346. cv.notify_all();
  22347. });
  22348. sse.set_max_reconnect_attempts(1);
  22349. sse.start_async();
  22350. {
  22351. std::unique_lock<std::mutex> lock(mutex);
  22352. cv.wait_for(lock, std::chrono::seconds(2),
  22353. [&] { return received.size() >= 3; });
  22354. }
  22355. sse.stop();
  22356. ASSERT_GE(received.size(), 3u);
  22357. EXPECT_EQ(received[0], "");
  22358. EXPECT_EQ(received[1], "\nhello");
  22359. EXPECT_EQ(received[2], "");
  22360. }
  22361. // Test: Auto-reconnect after server disconnection
  22362. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22363. std::atomic<int> connection_count{0};
  22364. std::atomic<int> message_count{0};
  22365. // Endpoint that sends one event and closes, forcing reconnect
  22366. server_->Get("/reconnect-test",
  22367. [&connection_count](const Request &, Response &res) {
  22368. connection_count.fetch_add(1);
  22369. res.set_chunked_content_provider(
  22370. "text/event-stream", [](size_t offset, DataSink &sink) {
  22371. if (offset == 0) {
  22372. std::string event = "data: hello\n\n";
  22373. sink.write(event.data(), event.size());
  22374. }
  22375. return false; // Close connection after sending
  22376. });
  22377. });
  22378. Client client("localhost", get_port());
  22379. sse::SSEClient sse(client, "/reconnect-test");
  22380. sse.on_message([&message_count](const sse::SSEMessage &) {
  22381. message_count.fetch_add(1);
  22382. });
  22383. sse.set_reconnect_interval(100);
  22384. sse.set_max_reconnect_attempts(3);
  22385. sse.start_async();
  22386. // Wait long enough for multiple reconnects
  22387. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22388. sse.stop();
  22389. // Should have connected multiple times (initial + reconnects)
  22390. EXPECT_GE(connection_count.load(), 2);
  22391. // Should have received messages from multiple connections
  22392. EXPECT_GE(message_count.load(), 2);
  22393. }
  22394. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22395. std::atomic<int> connection_count{0};
  22396. // Neither Content-Length nor chunked: the close ends the stream
  22397. server_->Get("/close-delimited",
  22398. [&connection_count](const Request &, Response &res) {
  22399. connection_count.fetch_add(1);
  22400. res.set_content_provider(
  22401. "text/event-stream", [](size_t offset, DataSink &sink) {
  22402. if (offset == 0) {
  22403. std::string event = "data: hello\n\n";
  22404. sink.write(event.data(), event.size());
  22405. } else {
  22406. sink.done();
  22407. }
  22408. return true;
  22409. });
  22410. });
  22411. Client client("localhost", get_port());
  22412. sse::SSEClient sse(client, "/close-delimited");
  22413. std::atomic<int> error_count{0};
  22414. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22415. sse.set_reconnect_interval(100);
  22416. sse.start_async();
  22417. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22418. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22419. }
  22420. sse.stop();
  22421. // Reconnects as after any end of the stream, but reports no error
  22422. EXPECT_GE(connection_count.load(), 2);
  22423. EXPECT_EQ(0, error_count.load());
  22424. }
  22425. // Test: A retry field that is not all ASCII digits is ignored
  22426. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22427. std::atomic<int> connection_count{0};
  22428. server_->Get("/bad-retry",
  22429. [&connection_count](const Request &, Response &res) {
  22430. connection_count.fetch_add(1);
  22431. res.set_chunked_content_provider(
  22432. "text/event-stream", [](size_t offset, DataSink &sink) {
  22433. if (offset == 0) {
  22434. std::string event = "retry: -1\ndata: hello\n\n";
  22435. sink.write(event.data(), event.size());
  22436. }
  22437. return false;
  22438. });
  22439. });
  22440. Client client("localhost", get_port());
  22441. sse::SSEClient sse(client, "/bad-retry");
  22442. sse.set_reconnect_interval(10000);
  22443. sse.start_async();
  22444. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22445. sse.stop();
  22446. EXPECT_EQ(connection_count.load(), 1);
  22447. }
  22448. // Test: A retry field of all ASCII digits sets the reconnection time
  22449. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22450. std::mutex mutex;
  22451. std::condition_variable cv;
  22452. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22453. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22454. {
  22455. std::lock_guard<std::mutex> lock(mutex);
  22456. connected_at.push_back(std::chrono::steady_clock::now());
  22457. cv.notify_all();
  22458. }
  22459. res.set_chunked_content_provider(
  22460. "text/event-stream", [](size_t offset, DataSink &sink) {
  22461. if (offset == 0) {
  22462. std::string event = "retry: 0\ndata: hello\n\n";
  22463. sink.write(event.data(), event.size());
  22464. }
  22465. return false;
  22466. });
  22467. });
  22468. Client client("localhost", get_port());
  22469. sse::SSEClient sse(client, "/zero-retry");
  22470. sse.set_reconnect_interval(10000);
  22471. sse.start_async();
  22472. {
  22473. std::unique_lock<std::mutex> lock(mutex);
  22474. cv.wait_for(lock, std::chrono::seconds(5),
  22475. [&] { return connected_at.size() >= 2; });
  22476. }
  22477. sse.stop();
  22478. // The server-supplied interval is applied, but never below 100ms, so
  22479. // "retry: 0" does not cause a busy reconnect loop
  22480. std::lock_guard<std::mutex> lock(mutex);
  22481. ASSERT_GE(connected_at.size(), 2u);
  22482. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22483. connected_at[1] - connected_at[0])
  22484. .count();
  22485. EXPECT_GE(interval_ms, 100);
  22486. }
  22487. // Test: Last-Event-ID sent on reconnect
  22488. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22489. std::atomic<int> connection_count{0};
  22490. std::vector<std::string> received_last_event_ids;
  22491. std::mutex id_mutex;
  22492. // Endpoint that checks Last-Event-ID header and sends event with ID
  22493. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22494. int conn = connection_count.fetch_add(1);
  22495. // Capture the Last-Event-ID header from each connection
  22496. {
  22497. std::lock_guard<std::mutex> lock(id_mutex);
  22498. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22499. }
  22500. res.set_chunked_content_provider(
  22501. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22502. if (offset == 0) {
  22503. std::string event =
  22504. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22505. sink.write(event.data(), event.size());
  22506. }
  22507. return false;
  22508. });
  22509. });
  22510. Client client("localhost", get_port());
  22511. sse::SSEClient sse(client, "/reconnect-with-id");
  22512. sse.set_reconnect_interval(100);
  22513. sse.set_max_reconnect_attempts(3);
  22514. sse.start_async();
  22515. // Wait for at least 2 connections
  22516. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22517. sse.stop();
  22518. // Verify behavior
  22519. std::lock_guard<std::mutex> lock(id_mutex);
  22520. EXPECT_GE(received_last_event_ids.size(), 2u);
  22521. // First connection should have no Last-Event-ID
  22522. if (!received_last_event_ids.empty()) {
  22523. EXPECT_EQ(received_last_event_ids[0], "");
  22524. }
  22525. // Second connection should have Last-Event-ID from first connection
  22526. if (received_last_event_ids.size() >= 2) {
  22527. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22528. }
  22529. }
  22530. // Test: set_headers updates headers used on reconnect
  22531. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22532. std::vector<std::string> received_tokens;
  22533. std::mutex token_mutex;
  22534. // Endpoint that captures Authorization header
  22535. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22536. {
  22537. std::lock_guard<std::mutex> lock(token_mutex);
  22538. received_tokens.push_back(req.get_header_value("Authorization"));
  22539. }
  22540. res.set_chunked_content_provider(
  22541. "text/event-stream", [](size_t offset, DataSink &sink) {
  22542. if (offset == 0) {
  22543. std::string event = "data: hello\n\n";
  22544. sink.write(event.data(), event.size());
  22545. }
  22546. return false; // Close connection to trigger reconnect
  22547. });
  22548. });
  22549. Client client("localhost", get_port());
  22550. Headers headers = {{"Authorization", "Bearer old-token"}};
  22551. sse::SSEClient sse(client, "/auth-check", headers);
  22552. // Update headers on each successful connection
  22553. sse.on_open(
  22554. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22555. sse.set_reconnect_interval(100);
  22556. sse.set_max_reconnect_attempts(3);
  22557. sse.start_async();
  22558. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22559. sse.stop();
  22560. std::lock_guard<std::mutex> lock(token_mutex);
  22561. ASSERT_GE(received_tokens.size(), 2u);
  22562. // First connection uses original header
  22563. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22564. // Second connection uses updated header from set_headers
  22565. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22566. }
  22567. // Test: 401 allows reconnection (so on_error can refresh headers)
  22568. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22569. std::atomic<int> connection_count{0};
  22570. // Endpoint: returns 401 on first attempt, 200 on second
  22571. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22572. int conn = connection_count.fetch_add(1);
  22573. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22574. res.status = StatusCode::Unauthorized_401;
  22575. res.set_content("Unauthorized", "text/plain");
  22576. return;
  22577. }
  22578. res.set_chunked_content_provider(
  22579. "text/event-stream", [](size_t offset, DataSink &sink) {
  22580. if (offset == 0) {
  22581. std::string event = "data: authenticated\n\n";
  22582. sink.write(event.data(), event.size());
  22583. }
  22584. return false;
  22585. });
  22586. });
  22587. Client client("localhost", get_port());
  22588. Headers headers = {{"Authorization", "Bearer expired"}};
  22589. sse::SSEClient sse(client, "/auth-retry", headers);
  22590. std::atomic<bool> message_received{false};
  22591. // Refresh token on error
  22592. sse.on_error(
  22593. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22594. sse.on_message([&](const sse::SSEMessage &msg) {
  22595. if (msg.data == "authenticated") { message_received.store(true); }
  22596. });
  22597. sse.set_reconnect_interval(100);
  22598. sse.set_max_reconnect_attempts(3);
  22599. sse.start_async();
  22600. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22601. sse.stop();
  22602. // Should have reconnected after 401 and succeeded with new token
  22603. EXPECT_GE(connection_count.load(), 2);
  22604. EXPECT_TRUE(message_received.load());
  22605. }
  22606. TEST(Issue2318Test, EmptyHostString) {
  22607. {
  22608. httplib::Client cli_empty("", PORT);
  22609. auto res = cli_empty.Get("/");
  22610. ASSERT_FALSE(res);
  22611. EXPECT_EQ(httplib::Error::Connection, res.error());
  22612. }
  22613. {
  22614. httplib::Client cli(" ", PORT);
  22615. auto res = cli.Get("/");
  22616. ASSERT_FALSE(res);
  22617. EXPECT_EQ(httplib::Error::Connection, res.error());
  22618. }
  22619. }
  22620. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22621. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22622. Server svr;
  22623. // Set a small payload limit (1KB)
  22624. svr.set_payload_max_length(1024);
  22625. svr.Post("/test", [&](const Request &req, Response &res) {
  22626. res.set_content("Body size: " + std::to_string(req.body.size()),
  22627. "text/plain");
  22628. });
  22629. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22630. auto se = detail::scope_exit([&] {
  22631. svr.stop();
  22632. listen_thread.join();
  22633. });
  22634. svr.wait_until_ready();
  22635. // Create data that compresses well but exceeds limit when decompressed
  22636. // 8KB of repeated null bytes compresses to a very small size
  22637. std::string original_data(8 * 1024, '\0');
  22638. // Compress the data using gzip
  22639. std::string compressed_data;
  22640. detail::gzip_compressor compressor;
  22641. compressor.compress(original_data.data(), original_data.size(), true,
  22642. [&](const char *data, size_t size) {
  22643. compressed_data.append(data, size);
  22644. return true;
  22645. });
  22646. // Verify compression worked (compressed should be much smaller)
  22647. ASSERT_LT(compressed_data.size(), original_data.size());
  22648. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22649. // Send compressed data with Content-Encoding: gzip
  22650. Client cli(HOST, PORT);
  22651. Headers headers = {{"Content-Encoding", "gzip"}};
  22652. auto res =
  22653. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22654. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22656. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22657. }
  22658. #endif
  22659. // ============================================================================
  22660. // OpenSSL-Specific Tests
  22661. // ============================================================================
  22662. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22663. X509 *readCertificate(const std::string &strFileName) {
  22664. std::ifstream inStream(strFileName);
  22665. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22666. std::istreambuf_iterator<char>());
  22667. if (strCertPEM.empty()) return (nullptr);
  22668. BIO *pbCert = BIO_new(BIO_s_mem());
  22669. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22670. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22671. BIO_free(pbCert);
  22672. return (pCert);
  22673. }
  22674. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22675. std::ifstream inStream(strFileName);
  22676. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22677. std::istreambuf_iterator<char>());
  22678. if (strPrivateKeyPEM.empty()) return (nullptr);
  22679. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22680. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22681. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22682. BIO_free(pbPrivKey);
  22683. return (pPrivateKey);
  22684. }
  22685. TEST(BindServerTest, UpdateCerts) {
  22686. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22687. int port = svr.bind_to_any_port("0.0.0.0");
  22688. ASSERT_TRUE(svr.is_valid());
  22689. ASSERT_TRUE(port > 0);
  22690. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22691. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22692. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22693. ASSERT_TRUE(cert != nullptr);
  22694. ASSERT_TRUE(ca_cert != nullptr);
  22695. ASSERT_TRUE(key != nullptr);
  22696. X509_STORE *cert_store = X509_STORE_new();
  22697. X509_STORE_add_cert(cert_store, ca_cert);
  22698. // svr.update_certs(cert, key, cert_store); // deprecated
  22699. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22700. CLIENT_CA_CERT_FILE);
  22701. ASSERT_TRUE(svr.is_valid());
  22702. svr.stop();
  22703. X509_STORE_free(cert_store);
  22704. X509_free(cert);
  22705. X509_free(ca_cert);
  22706. EVP_PKEY_free(key);
  22707. }
  22708. // Test that update_certs() updates client CA list correctly
  22709. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22710. // Start with file-based constructor
  22711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22712. ASSERT_TRUE(svr.is_valid());
  22713. // Initially no client CA list should be set
  22714. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22715. ASSERT_TRUE(ssl_ctx != nullptr);
  22716. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22717. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22718. // Now update with client CA (PEM string)
  22719. std::string cert_pem, key_pem, ca_pem;
  22720. read_file(SERVER_CERT_FILE, cert_pem);
  22721. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22722. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22723. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22724. ASSERT_TRUE(svr.is_valid());
  22725. // Now client CA list should be set
  22726. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22727. ASSERT_TRUE(ca_list_after != nullptr);
  22728. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22729. }
  22730. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22731. // Test that the file-path SSLServer constructor properly sets the client CA
  22732. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22733. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22734. ASSERT_TRUE(svr.is_valid());
  22735. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22736. ASSERT_TRUE(ssl_ctx != nullptr);
  22737. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22738. ASSERT_TRUE(ca_list != nullptr);
  22739. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22740. }
  22741. #endif
  22742. // ============================================================================
  22743. // MbedTLS-Specific Tests
  22744. // ============================================================================
  22745. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22746. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22747. using namespace httplib::tls;
  22748. // Track if callback was invoked
  22749. bool callback_invoked = false;
  22750. // The callback receives void* ctx which is actually MbedTlsContext*
  22751. // We can access the mbedtls_ssl_config via the context
  22752. auto setup_callback = [&callback_invoked](void *ctx) {
  22753. callback_invoked = true;
  22754. // Cast to MbedTlsContext* to access the ssl config
  22755. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22756. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22757. // Use static variables to hold certificate data (simplified for test)
  22758. static mbedtls_x509_crt own_cert;
  22759. static mbedtls_pk_context own_key;
  22760. static mbedtls_x509_crt ca_chain;
  22761. static bool initialized = false;
  22762. if (!initialized) {
  22763. mbedtls_x509_crt_init(&own_cert);
  22764. mbedtls_pk_init(&own_key);
  22765. mbedtls_x509_crt_init(&ca_chain);
  22766. // Load server certificate
  22767. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22768. return false;
  22769. }
  22770. // Load server private key.
  22771. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22772. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22773. #if MBEDTLS_VERSION_MAJOR == 3
  22774. ,
  22775. mbedtls_ctr_drbg_random, nullptr
  22776. #endif
  22777. ) != 0) {
  22778. return false;
  22779. }
  22780. // Load CA chain for client verification
  22781. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22782. return false;
  22783. }
  22784. initialized = true;
  22785. }
  22786. // Configure the SSL config
  22787. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22788. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22789. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22790. // Set minimum TLS version using mbedTLS native API
  22791. #if MBEDTLS_VERSION_MAJOR >= 3
  22792. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22793. #else
  22794. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22795. MBEDTLS_SSL_MINOR_VERSION_3);
  22796. #endif
  22797. return true;
  22798. };
  22799. SSLServer svr(setup_callback);
  22800. ASSERT_TRUE(svr.is_valid());
  22801. ASSERT_TRUE(callback_invoked);
  22802. svr.Get("/test", [&](const Request &req, Response &res) {
  22803. res.set_content("test", "text/plain");
  22804. auto cert = req.peer_cert();
  22805. ASSERT_TRUE(static_cast<bool>(cert));
  22806. auto common_name = cert.subject_cn();
  22807. EXPECT_EQ("Common Name", common_name);
  22808. });
  22809. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22810. auto se = detail::scope_exit([&] {
  22811. svr.stop();
  22812. t.join();
  22813. ASSERT_FALSE(svr.is_running());
  22814. });
  22815. svr.wait_until_ready();
  22816. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22817. cli.enable_server_certificate_verification(false);
  22818. cli.set_connection_timeout(30);
  22819. auto res = cli.Get("/test");
  22820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22821. ASSERT_EQ(StatusCode::OK_200, res->status);
  22822. }
  22823. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22824. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22825. // keep-alive SSL session, which reads through that config in
  22826. // mbedtls_ssl_close_notify.
  22827. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22828. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22829. ASSERT_TRUE(svr.is_valid());
  22830. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22831. res.set_content("test", "text/plain");
  22832. });
  22833. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22834. auto se = detail::scope_exit([&] {
  22835. svr.stop();
  22836. t.join();
  22837. ASSERT_FALSE(svr.is_running());
  22838. });
  22839. svr.wait_until_ready();
  22840. {
  22841. SSLClient cli(HOST, PORT);
  22842. cli.enable_server_certificate_verification(false);
  22843. cli.set_keep_alive(true);
  22844. auto res = cli.Get("/test");
  22845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22846. ASSERT_EQ(StatusCode::OK_200, res->status);
  22847. // cli is destructed here with the keep-alive SSL session still open.
  22848. }
  22849. }
  22850. #endif
  22851. // WebSocket Tests
  22852. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22853. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22854. // defining the meaning of these bits has been negotiated.
  22855. auto make_frame = [](uint8_t first_byte) {
  22856. std::string frame;
  22857. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22858. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22859. frame += "Hello";
  22860. return frame;
  22861. };
  22862. // RSV1 set (0x40)
  22863. {
  22864. detail::BufferStream strm;
  22865. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22866. ws::Opcode opcode;
  22867. std::string payload;
  22868. bool fin;
  22869. EXPECT_EQ(
  22870. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22871. ws::impl::FrameRead::Fail);
  22872. }
  22873. // RSV2 set (0x20)
  22874. {
  22875. detail::BufferStream strm;
  22876. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22877. ws::Opcode opcode;
  22878. std::string payload;
  22879. bool fin;
  22880. EXPECT_EQ(
  22881. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22882. ws::impl::FrameRead::Fail);
  22883. }
  22884. // RSV3 set (0x10)
  22885. {
  22886. detail::BufferStream strm;
  22887. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22888. ws::Opcode opcode;
  22889. std::string payload;
  22890. bool fin;
  22891. EXPECT_EQ(
  22892. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22893. ws::impl::FrameRead::Fail);
  22894. }
  22895. // No RSV bits set - should succeed
  22896. {
  22897. detail::BufferStream strm;
  22898. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22899. ws::Opcode opcode;
  22900. std::string payload;
  22901. bool fin;
  22902. EXPECT_EQ(
  22903. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22904. ws::impl::FrameRead::Ok);
  22905. EXPECT_EQ(ws::Opcode::Text, opcode);
  22906. EXPECT_EQ("Hello", payload);
  22907. EXPECT_TRUE(fin);
  22908. }
  22909. }
  22910. TEST(WebSocketTest, ControlFrameValidation) {
  22911. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22912. // payload length <= 125.
  22913. // Ping with FIN=0 - must be rejected
  22914. {
  22915. detail::BufferStream strm;
  22916. std::string frame;
  22917. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22918. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22919. strm.write(frame.data(), frame.size());
  22920. ws::Opcode opcode;
  22921. std::string payload;
  22922. bool fin;
  22923. EXPECT_EQ(
  22924. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22925. ws::impl::FrameRead::Fail);
  22926. }
  22927. // Close with FIN=0 - must be rejected
  22928. {
  22929. detail::BufferStream strm;
  22930. std::string frame;
  22931. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22932. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22933. strm.write(frame.data(), frame.size());
  22934. ws::Opcode opcode;
  22935. std::string payload;
  22936. bool fin;
  22937. EXPECT_EQ(
  22938. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22939. ws::impl::FrameRead::Fail);
  22940. }
  22941. // Ping with payload_len=126 (extended length) - must be rejected
  22942. {
  22943. detail::BufferStream strm;
  22944. std::string frame;
  22945. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22946. frame += static_cast<char>(126); // payload_len=126 (>125)
  22947. frame += static_cast<char>(0x00); // extended length high byte
  22948. frame += static_cast<char>(126); // extended length low byte
  22949. frame += std::string(126, 'x');
  22950. strm.write(frame.data(), frame.size());
  22951. ws::Opcode opcode;
  22952. std::string payload;
  22953. bool fin;
  22954. EXPECT_EQ(
  22955. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22956. ws::impl::FrameRead::Fail);
  22957. }
  22958. // Ping with FIN=1 and payload_len=125 - should succeed
  22959. {
  22960. detail::BufferStream strm;
  22961. std::string frame;
  22962. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22963. frame += static_cast<char>(125); // payload_len=125
  22964. frame += std::string(125, 'x');
  22965. strm.write(frame.data(), frame.size());
  22966. ws::Opcode opcode;
  22967. std::string payload;
  22968. bool fin;
  22969. EXPECT_EQ(
  22970. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22971. ws::impl::FrameRead::Ok);
  22972. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22973. EXPECT_EQ(125u, payload.size());
  22974. EXPECT_TRUE(fin);
  22975. }
  22976. }
  22977. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22978. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22979. // length MUST be 0.
  22980. // MSB set - must be rejected
  22981. {
  22982. detail::BufferStream strm;
  22983. std::string frame;
  22984. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22985. frame += static_cast<char>(127); // 64-bit extended length
  22986. frame += static_cast<char>(0x80); // MSB set (invalid)
  22987. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22988. strm.write(frame.data(), frame.size());
  22989. ws::Opcode opcode;
  22990. std::string payload;
  22991. bool fin;
  22992. EXPECT_EQ(
  22993. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22994. ws::impl::FrameRead::Fail);
  22995. }
  22996. // MSB clear - should pass length parsing (will be rejected by max_len,
  22997. // but that's a different check; use a small length to verify)
  22998. {
  22999. detail::BufferStream strm;
  23000. std::string frame;
  23001. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23002. frame += static_cast<char>(127); // 64-bit extended length
  23003. frame += std::string(7, '\0'); // high bytes = 0
  23004. frame += static_cast<char>(0x03); // length = 3
  23005. frame += "abc";
  23006. strm.write(frame.data(), frame.size());
  23007. ws::Opcode opcode;
  23008. std::string payload;
  23009. bool fin;
  23010. EXPECT_EQ(
  23011. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23012. ws::impl::FrameRead::Ok);
  23013. EXPECT_EQ(ws::Opcode::Text, opcode);
  23014. EXPECT_EQ("abc", payload);
  23015. }
  23016. }
  23017. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23018. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23019. // Valid UTF-8
  23020. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23021. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23022. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23023. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23024. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23025. // Invalid UTF-8
  23026. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23027. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23028. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23029. EXPECT_FALSE(
  23030. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23031. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23032. }
  23033. TEST(WebSocketTest, ConnectAndDisconnect) {
  23034. Server svr;
  23035. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23036. std::string msg;
  23037. while (ws.read(msg)) {}
  23038. });
  23039. auto port = svr.bind_to_any_port(HOST);
  23040. std::thread t([&]() { svr.listen_after_bind(); });
  23041. svr.wait_until_ready();
  23042. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23043. auto res = client.connect();
  23044. ASSERT_TRUE(res);
  23045. EXPECT_EQ(Error::Success, res.error());
  23046. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23047. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23048. EXPECT_TRUE(client.is_open());
  23049. client.close();
  23050. EXPECT_FALSE(client.is_open());
  23051. svr.stop();
  23052. t.join();
  23053. }
  23054. TEST(WebSocketTest, ValidURL) {
  23055. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23056. EXPECT_TRUE(ws1.is_valid());
  23057. ws::WebSocketClient ws2("ws://example.com/path");
  23058. EXPECT_TRUE(ws2.is_valid());
  23059. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23060. EXPECT_TRUE(ws3.is_valid());
  23061. #ifdef CPPHTTPLIB_SSL_ENABLED
  23062. ws::WebSocketClient wss1("wss://example.com/path");
  23063. EXPECT_TRUE(wss1.is_valid());
  23064. ws::WebSocketClient wss2("wss://example.com:443/path");
  23065. EXPECT_TRUE(wss2.is_valid());
  23066. #endif
  23067. }
  23068. TEST(WebSocketTest, InvalidURL) {
  23069. // No scheme
  23070. ws::WebSocketClient ws1("localhost:8080/path");
  23071. EXPECT_FALSE(ws1.is_valid());
  23072. // No path
  23073. ws::WebSocketClient ws2("ws://localhost:8080");
  23074. EXPECT_FALSE(ws2.is_valid());
  23075. // Empty string
  23076. ws::WebSocketClient ws3("");
  23077. EXPECT_FALSE(ws3.is_valid());
  23078. // Missing host
  23079. ws::WebSocketClient ws4("ws://:8080/path");
  23080. EXPECT_FALSE(ws4.is_valid());
  23081. // Port number overflow — should not crash
  23082. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23083. EXPECT_FALSE(ws5.is_valid());
  23084. // Port out of range
  23085. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23086. EXPECT_FALSE(ws6.is_valid());
  23087. }
  23088. TEST(WebSocketTest, UnsupportedScheme) {
  23089. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23090. ws::WebSocketClient ws1("http://localhost:8080/path");
  23091. EXPECT_FALSE(ws1.is_valid());
  23092. ws::WebSocketClient ws2("https://localhost:8080/path");
  23093. EXPECT_FALSE(ws2.is_valid());
  23094. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23095. EXPECT_FALSE(ws3.is_valid());
  23096. #else
  23097. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23098. std::invalid_argument);
  23099. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23100. std::invalid_argument);
  23101. #endif
  23102. }
  23103. TEST(WebSocketTest, ConnectWhenInvalid) {
  23104. ws::WebSocketClient ws("not a valid url");
  23105. EXPECT_FALSE(ws.is_valid());
  23106. auto res = ws.connect();
  23107. EXPECT_FALSE(res);
  23108. EXPECT_EQ(Error::Connection, res.error());
  23109. EXPECT_EQ(-1, res.status());
  23110. }
  23111. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23112. // Grab a port that is free, then close it again so nothing listens there
  23113. Server svr;
  23114. auto port = svr.bind_to_any_port(HOST);
  23115. svr.stop();
  23116. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23117. auto res = client.connect();
  23118. ASSERT_FALSE(res);
  23119. EXPECT_EQ(Error::Connection, res.error());
  23120. EXPECT_EQ(-1, res.status());
  23121. }
  23122. TEST(WebSocketTest, DefaultPort) {
  23123. ws::WebSocketClient ws1("ws://example.com/path");
  23124. EXPECT_TRUE(ws1.is_valid());
  23125. // ws:// defaults to port 80 (verified by successful parse)
  23126. #ifdef CPPHTTPLIB_SSL_ENABLED
  23127. ws::WebSocketClient ws2("wss://example.com/path");
  23128. EXPECT_TRUE(ws2.is_valid());
  23129. // wss:// defaults to port 443 (verified by successful parse)
  23130. #endif
  23131. }
  23132. TEST(WebSocketTest, IPv6LiteralAddress) {
  23133. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23134. EXPECT_TRUE(ws1.is_valid());
  23135. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23136. EXPECT_TRUE(ws2.is_valid());
  23137. }
  23138. TEST(WebSocketTest, ComplexPath) {
  23139. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23140. EXPECT_TRUE(ws1.is_valid());
  23141. ws::WebSocketClient ws2("ws://localhost:8080/");
  23142. EXPECT_TRUE(ws2.is_valid());
  23143. }
  23144. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23145. Server svr;
  23146. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23147. std::string msg;
  23148. while (ws.read(msg)) {}
  23149. });
  23150. auto port = svr.bind_to_any_port(HOST);
  23151. std::thread t([&]() { svr.listen_after_bind(); });
  23152. svr.wait_until_ready();
  23153. auto another_host = "example.com";
  23154. auto wrong_ip = "192.0.2.1";
  23155. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23156. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23157. ASSERT_TRUE(client.connect());
  23158. EXPECT_TRUE(client.is_open());
  23159. client.close();
  23160. svr.stop();
  23161. t.join();
  23162. }
  23163. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23164. Server svr;
  23165. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23166. std::string msg;
  23167. while (ws.read(msg)) {}
  23168. });
  23169. auto port = svr.bind_to_any_port(HOST);
  23170. std::thread t([&]() { svr.listen_after_bind(); });
  23171. svr.wait_until_ready();
  23172. auto wrong_ip = "192.0.2.1";
  23173. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23174. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23175. client.set_connection_timeout(1);
  23176. client.set_read_timeout(1);
  23177. client.set_write_timeout(1);
  23178. EXPECT_FALSE(client.connect());
  23179. EXPECT_FALSE(client.is_open());
  23180. svr.stop();
  23181. t.join();
  23182. }
  23183. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23184. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23185. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23186. // (RFC 6761) is only a map key and the Host header value.
  23187. auto host = "target.invalid";
  23188. Server svr;
  23189. std::string received_host;
  23190. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23191. received_host = req.get_header_value("Host");
  23192. std::string msg;
  23193. while (ws.read(msg)) {}
  23194. });
  23195. auto port = svr.bind_to_any_port(HOST);
  23196. std::thread t([&]() { svr.listen_after_bind(); });
  23197. // ASSERT_* below returns from the test body, which would leave t joinable
  23198. // and make ~thread call std::terminate.
  23199. auto se = detail::scope_exit([&] {
  23200. svr.stop();
  23201. if (t.joinable()) { t.join(); }
  23202. });
  23203. svr.wait_until_ready();
  23204. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23205. std::to_string(port) + "/ws");
  23206. client.set_hostname_addr_map({{host, HOST}});
  23207. ASSERT_TRUE(client.connect());
  23208. EXPECT_TRUE(client.is_open());
  23209. client.close();
  23210. svr.stop();
  23211. t.join();
  23212. // The mapping only redirects the connection; the identity stays host_.
  23213. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23214. }
  23215. class WebSocketIntegrationTest : public ::testing::Test {
  23216. protected:
  23217. void SetUp() override {
  23218. server_ = httplib::detail::make_unique<Server>();
  23219. setup_server();
  23220. start_server();
  23221. }
  23222. void TearDown() override {
  23223. server_->stop();
  23224. if (server_thread_.joinable()) { server_thread_.join(); }
  23225. }
  23226. void setup_server() {
  23227. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23228. std::string msg;
  23229. ws::ReadResult ret;
  23230. while ((ret = ws.read(msg))) {
  23231. if (ret == ws::Binary) {
  23232. ws.send(msg.data(), msg.size());
  23233. } else {
  23234. ws.send(msg);
  23235. }
  23236. }
  23237. });
  23238. server_->WebSocket("/ws-echo-string",
  23239. [](const Request &, ws::WebSocket &ws) {
  23240. std::string msg;
  23241. while (ws.read(msg)) {
  23242. ws.send("echo: " + msg);
  23243. }
  23244. });
  23245. server_->WebSocket(
  23246. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23247. // Echo back request metadata
  23248. ws.send("path:" + req.path);
  23249. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23250. std::string msg;
  23251. while (ws.read(msg)) {}
  23252. });
  23253. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23254. std::string msg;
  23255. ws.read(msg); // wait for a message
  23256. ws.close();
  23257. });
  23258. server_->WebSocket("/ws-close-status",
  23259. [](const Request &, ws::WebSocket &ws) {
  23260. std::string msg;
  23261. ws.read(msg); // wait for a message
  23262. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23263. });
  23264. server_->WebSocket(
  23265. "/ws-subprotocol",
  23266. [](const Request &, ws::WebSocket &ws) {
  23267. std::string msg;
  23268. while (ws.read(msg)) {
  23269. ws.send(msg);
  23270. }
  23271. },
  23272. [](const std::vector<std::string> &protocols) -> std::string {
  23273. for (const auto &p : protocols) {
  23274. if (p == "graphql-ws") { return p; }
  23275. }
  23276. return "";
  23277. });
  23278. server_->WebSocket(
  23279. "/ws-subprotocol-unoffered",
  23280. [](const Request &, ws::WebSocket &ws) {
  23281. std::string msg;
  23282. while (ws.read(msg)) {
  23283. ws.send(msg);
  23284. }
  23285. },
  23286. [](const std::vector<std::string> &) -> std::string {
  23287. return "admin";
  23288. });
  23289. }
  23290. void start_server() {
  23291. port_ = server_->bind_to_any_port(HOST);
  23292. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23293. server_->wait_until_ready();
  23294. }
  23295. std::unique_ptr<Server> server_;
  23296. std::thread server_thread_;
  23297. int port_ = 0;
  23298. };
  23299. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23300. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23301. "/ws-echo");
  23302. ASSERT_TRUE(client.connect());
  23303. ASSERT_TRUE(client.is_open());
  23304. ASSERT_TRUE(client.send("Hello WebSocket"));
  23305. std::string msg;
  23306. EXPECT_EQ(ws::Text, client.read(msg));
  23307. EXPECT_EQ("Hello WebSocket", msg);
  23308. client.close();
  23309. }
  23310. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23311. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23312. "/ws-echo");
  23313. ASSERT_TRUE(client.connect());
  23314. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23315. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23316. std::string msg;
  23317. EXPECT_EQ(ws::Binary, client.read(msg));
  23318. EXPECT_EQ(binary_data, msg);
  23319. client.close();
  23320. }
  23321. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23322. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23323. "/ws-echo");
  23324. ASSERT_TRUE(client.connect());
  23325. for (int i = 0; i < 10; i++) {
  23326. auto text = "message " + std::to_string(i);
  23327. ASSERT_TRUE(client.send(text));
  23328. std::string msg;
  23329. ASSERT_TRUE(client.read(msg));
  23330. EXPECT_EQ(text, msg);
  23331. }
  23332. client.close();
  23333. }
  23334. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23335. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23336. "/ws-close");
  23337. ASSERT_TRUE(client.connect());
  23338. // Send a message to trigger the server to close
  23339. ASSERT_TRUE(client.send("trigger close"));
  23340. // The server will close, so read should return false
  23341. std::string msg;
  23342. EXPECT_FALSE(client.read(msg));
  23343. EXPECT_FALSE(client.is_open());
  23344. }
  23345. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23346. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23347. "/ws-echo");
  23348. ASSERT_TRUE(client.connect());
  23349. // 128KB message
  23350. std::string large_data(128 * 1024, 'X');
  23351. ASSERT_TRUE(client.send(large_data));
  23352. std::string msg;
  23353. ASSERT_TRUE(client.read(msg));
  23354. EXPECT_EQ(large_data, msg);
  23355. client.close();
  23356. }
  23357. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23358. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23359. "/ws-echo");
  23360. ASSERT_TRUE(client.connect());
  23361. const int num_threads = 4;
  23362. std::vector<std::thread> threads;
  23363. std::atomic<int> send_count{0};
  23364. for (int t = 0; t < num_threads; t++) {
  23365. threads.emplace_back([&client, &send_count, t]() {
  23366. for (int i = 0; i < 5; i++) {
  23367. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23368. if (client.send(text)) { send_count++; }
  23369. }
  23370. });
  23371. }
  23372. for (auto &th : threads) {
  23373. th.join();
  23374. }
  23375. int received = 0;
  23376. std::string msg;
  23377. while (received < send_count.load()) {
  23378. if (!client.read(msg)) { break; }
  23379. received++;
  23380. }
  23381. EXPECT_EQ(send_count.load(), received);
  23382. client.close();
  23383. }
  23384. TEST_F(WebSocketIntegrationTest, ReadString) {
  23385. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23386. "/ws-echo-string");
  23387. ASSERT_TRUE(client.connect());
  23388. ASSERT_TRUE(client.send("hello"));
  23389. std::string msg;
  23390. ASSERT_TRUE(client.read(msg));
  23391. EXPECT_EQ("echo: hello", msg);
  23392. ASSERT_TRUE(client.send("world"));
  23393. ASSERT_TRUE(client.read(msg));
  23394. EXPECT_EQ("echo: world", msg);
  23395. client.close();
  23396. }
  23397. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23398. Headers headers = {{"X-Test-Header", "test-value"}};
  23399. ws::WebSocketClient client(
  23400. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23401. ASSERT_TRUE(client.connect());
  23402. std::string msg;
  23403. ASSERT_TRUE(client.read(msg));
  23404. EXPECT_EQ("path:/ws-request-info", msg);
  23405. ASSERT_TRUE(client.read(msg));
  23406. EXPECT_EQ("header:test-value", msg);
  23407. client.close();
  23408. }
  23409. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23410. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23411. "/ws-echo");
  23412. client.set_read_timeout(1, 0); // 1 second
  23413. ASSERT_TRUE(client.connect());
  23414. // Don't send anything — server echo handler waits for a message, so read()
  23415. // should time out. The connection survives it: nothing was consumed.
  23416. std::string msg;
  23417. EXPECT_EQ(client.read(msg), ws::Timeout);
  23418. EXPECT_TRUE(client.is_open());
  23419. // And it is still usable afterwards.
  23420. EXPECT_TRUE(client.send("after timeout"));
  23421. EXPECT_EQ(client.read(msg), ws::Text);
  23422. EXPECT_EQ(msg, "after timeout");
  23423. }
  23424. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23425. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23426. "/ws-echo");
  23427. client.set_read_timeout(1, 0);
  23428. ASSERT_TRUE(client.connect());
  23429. ASSERT_TRUE(client.send("first"));
  23430. std::string msg;
  23431. ASSERT_EQ(client.read(msg), ws::Text);
  23432. ASSERT_EQ(msg, "first");
  23433. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23434. // not be used with a read timeout: it would reprocess the previous message.
  23435. EXPECT_EQ(client.read(msg), ws::Timeout);
  23436. EXPECT_EQ(msg, "first");
  23437. }
  23438. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23439. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23440. "/ws-echo");
  23441. ASSERT_TRUE(client.connect());
  23442. // Setting it once the connection is open reaches the live stream, not just
  23443. // the seed for the next connect().
  23444. client.set_read_timeout(1, 0);
  23445. std::string msg;
  23446. EXPECT_EQ(client.read(msg), ws::Timeout);
  23447. EXPECT_TRUE(client.is_open());
  23448. }
  23449. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23450. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23451. "/ws-echo");
  23452. client.set_read_timeout(5, 0);
  23453. ASSERT_TRUE(client.connect());
  23454. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23455. // The server should reject it and close the connection.
  23456. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23457. client.send(oversized);
  23458. // The server's read() should have failed due to payload limit,
  23459. // so our read() should return false (connection closed).
  23460. std::string msg;
  23461. EXPECT_FALSE(client.read(msg));
  23462. }
  23463. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23464. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23465. "/ws-echo");
  23466. client.set_read_timeout(10, 0);
  23467. ASSERT_TRUE(client.connect());
  23468. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23469. // This should succeed.
  23470. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23471. ASSERT_TRUE(client.send(at_limit));
  23472. std::string msg;
  23473. ASSERT_TRUE(client.read(msg));
  23474. EXPECT_EQ(at_limit.size(), msg.size());
  23475. client.close();
  23476. }
  23477. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23478. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23479. "/nonexistent");
  23480. auto res = client.connect();
  23481. EXPECT_FALSE(res);
  23482. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23483. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23484. EXPECT_FALSE(client.is_open());
  23485. }
  23486. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23487. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23488. "/ws-echo");
  23489. ASSERT_TRUE(client.connect());
  23490. ASSERT_TRUE(client.send(""));
  23491. std::string msg;
  23492. EXPECT_EQ(ws::Text, client.read(msg));
  23493. EXPECT_EQ("", msg);
  23494. client.close();
  23495. }
  23496. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23497. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23498. "/ws-echo");
  23499. // First connection
  23500. ASSERT_TRUE(client.connect());
  23501. ASSERT_TRUE(client.send("first"));
  23502. std::string msg;
  23503. ASSERT_TRUE(client.read(msg));
  23504. EXPECT_EQ("first", msg);
  23505. client.close();
  23506. EXPECT_FALSE(client.is_open());
  23507. // Reconnect using the same client object
  23508. ASSERT_TRUE(client.connect());
  23509. ASSERT_TRUE(client.is_open());
  23510. ASSERT_TRUE(client.send("second"));
  23511. ASSERT_TRUE(client.read(msg));
  23512. EXPECT_EQ("second", msg);
  23513. client.close();
  23514. }
  23515. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23516. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23517. "/ws-close-status");
  23518. ASSERT_TRUE(client.connect());
  23519. // Trigger the server to close with GoingAway status
  23520. ASSERT_TRUE(client.send("trigger"));
  23521. // read() should return false after receiving the close frame
  23522. std::string msg;
  23523. EXPECT_FALSE(client.read(msg));
  23524. EXPECT_FALSE(client.is_open());
  23525. }
  23526. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23527. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23528. "/ws-echo");
  23529. ASSERT_TRUE(client.connect());
  23530. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23531. EXPECT_FALSE(client.is_open());
  23532. }
  23533. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23534. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23535. ws::WebSocketClient client(
  23536. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23537. ASSERT_TRUE(client.connect());
  23538. // Server should have selected graphql-ws
  23539. EXPECT_EQ("graphql-ws", client.subprotocol());
  23540. client.close();
  23541. }
  23542. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23543. Headers headers;
  23544. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23545. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23546. ws::WebSocketClient client(
  23547. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23548. ASSERT_TRUE(client.connect());
  23549. // The offer on the second field line counts too, so graphql-ws is selected
  23550. EXPECT_EQ("graphql-ws", client.subprotocol());
  23551. client.close();
  23552. }
  23553. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23554. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23555. ws::WebSocketClient client(
  23556. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23557. ASSERT_TRUE(client.connect());
  23558. // Server should not have selected any subprotocol
  23559. EXPECT_TRUE(client.subprotocol().empty());
  23560. client.close();
  23561. }
  23562. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23563. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23564. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23565. "/ws-subprotocol-unoffered",
  23566. headers);
  23567. ASSERT_TRUE(client.connect());
  23568. EXPECT_TRUE(client.subprotocol().empty());
  23569. client.close();
  23570. }
  23571. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23572. // Connect without requesting any subprotocol
  23573. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23574. "/ws-subprotocol");
  23575. ASSERT_TRUE(client.connect());
  23576. EXPECT_TRUE(client.subprotocol().empty());
  23577. client.close();
  23578. }
  23579. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23580. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23581. "/ws-echo");
  23582. client.set_tcp_nodelay(true);
  23583. client.set_connection_timeout(3, 0);
  23584. bool socket_options_called = false;
  23585. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23586. ASSERT_TRUE(client.connect());
  23587. ASSERT_TRUE(client.is_open());
  23588. EXPECT_TRUE(socket_options_called);
  23589. ASSERT_TRUE(client.send("hello"));
  23590. std::string msg;
  23591. auto result = client.read(msg);
  23592. EXPECT_EQ(result, ws::ReadResult::Text);
  23593. EXPECT_EQ(msg, "hello");
  23594. client.close();
  23595. }
  23596. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23597. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23598. "/ws-echo");
  23599. client.set_connection_timeout(std::chrono::seconds(3));
  23600. client.set_write_timeout(std::chrono::seconds(3));
  23601. // A sub-second remainder exercises the seconds/microseconds split.
  23602. client.set_read_timeout(std::chrono::milliseconds(1500));
  23603. ASSERT_TRUE(client.connect());
  23604. auto start = std::chrono::steady_clock::now();
  23605. std::string msg;
  23606. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23607. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23608. std::chrono::steady_clock::now() - start)
  23609. .count();
  23610. // Above 1s so that dropping the microseconds half of the split fails here.
  23611. // Ignoring the setter altogether would not reach this line at all: a client
  23612. // waits forever by default.
  23613. EXPECT_GE(elapsed, 1400);
  23614. EXPECT_LT(elapsed, 30000);
  23615. }
  23616. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23617. Server svr;
  23618. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23619. if (!req.has_header("Authorization")) {
  23620. res.status = StatusCode::Unauthorized_401;
  23621. res.set_content("Unauthorized", "text/plain");
  23622. return Server::HandlerResponse::Handled;
  23623. }
  23624. return Server::HandlerResponse::Unhandled;
  23625. });
  23626. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23627. std::string msg;
  23628. while (ws.read(msg)) {
  23629. ws.send(msg);
  23630. }
  23631. });
  23632. auto port = svr.bind_to_any_port("localhost");
  23633. std::thread t([&]() { svr.listen_after_bind(); });
  23634. svr.wait_until_ready();
  23635. // Without Authorization header - should be rejected before upgrade
  23636. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23637. EXPECT_FALSE(client1.connect());
  23638. // The rejection is framed like any other HTTP response
  23639. {
  23640. Client cli("localhost", port);
  23641. Headers headers = {{"Upgrade", "websocket"},
  23642. {"Connection", "Upgrade"},
  23643. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23644. {"Sec-WebSocket-Version", "13"}};
  23645. auto res = cli.Get("/ws", headers);
  23646. ASSERT_TRUE(res);
  23647. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23648. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23649. EXPECT_EQ("Unauthorized", res->body);
  23650. }
  23651. // With Authorization header - should succeed
  23652. Headers headers = {{"Authorization", "Bearer token123"}};
  23653. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23654. headers);
  23655. ASSERT_TRUE(client2.connect());
  23656. ASSERT_TRUE(client2.send("hello"));
  23657. std::string msg;
  23658. ASSERT_TRUE(client2.read(msg));
  23659. EXPECT_EQ("hello", msg);
  23660. client2.close();
  23661. svr.stop();
  23662. t.join();
  23663. }
  23664. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23665. Server svr;
  23666. std::atomic<int> pre_routing_calls{0};
  23667. std::atomic<int> pre_request_calls{0};
  23668. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23669. pre_routing_calls++;
  23670. if (req.path == "/handled") {
  23671. res.set_content("handled", "text/plain");
  23672. return Server::HandlerResponse::Handled;
  23673. }
  23674. return Server::HandlerResponse::Unhandled;
  23675. });
  23676. svr.set_pre_request_handler([&](const Request &, Response &) {
  23677. pre_request_calls++;
  23678. return Server::HandlerResponse::Unhandled;
  23679. });
  23680. svr.Get("/http", [](const Request &, Response &res) {
  23681. res.set_content("http", "text/plain");
  23682. });
  23683. svr.WebSocket("/ws",
  23684. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23685. auto port = svr.bind_to_any_port("localhost");
  23686. std::thread t([&]() { svr.listen_after_bind(); });
  23687. auto se = detail::scope_exit([&] {
  23688. svr.stop();
  23689. t.join();
  23690. });
  23691. svr.wait_until_ready();
  23692. Headers upgrade = {{"Upgrade", "websocket"},
  23693. {"Connection", "Upgrade"},
  23694. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23695. {"Sec-WebSocket-Version", "13"}};
  23696. auto get = [&](const char *path) {
  23697. pre_routing_calls = 0;
  23698. return Client("localhost", port).Get(path, upgrade);
  23699. };
  23700. // No WebSocket route, but an HTTP one
  23701. auto res = get("/http");
  23702. ASSERT_TRUE(res);
  23703. EXPECT_EQ(StatusCode::OK_200, res->status);
  23704. EXPECT_EQ("http", res->body);
  23705. EXPECT_EQ(1, pre_routing_calls);
  23706. EXPECT_EQ(1, pre_request_calls);
  23707. // No route at all
  23708. res = get("/none");
  23709. ASSERT_TRUE(res);
  23710. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23711. EXPECT_EQ(1, pre_routing_calls);
  23712. // Answered by the pre-routing handler
  23713. res = get("/handled");
  23714. ASSERT_TRUE(res);
  23715. EXPECT_EQ(StatusCode::OK_200, res->status);
  23716. EXPECT_EQ("handled", res->body);
  23717. EXPECT_EQ(1, pre_routing_calls);
  23718. // A WebSocket route
  23719. pre_routing_calls = 0;
  23720. pre_request_calls = 0;
  23721. {
  23722. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23723. "/ws");
  23724. ASSERT_TRUE(client.connect());
  23725. std::string msg;
  23726. ASSERT_TRUE(client.read(msg));
  23727. EXPECT_EQ("ws", msg);
  23728. client.close();
  23729. }
  23730. EXPECT_EQ(1, pre_routing_calls);
  23731. EXPECT_EQ(1, pre_request_calls);
  23732. }
  23733. // An upgrade request answered by a hook leaves its body unread, so that body
  23734. // must not be served as the next request on the connection.
  23735. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23736. Server svr;
  23737. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23738. if (req.path == "/pre-routing") {
  23739. res.set_content("pre-routing", "text/plain");
  23740. return Server::HandlerResponse::Handled;
  23741. }
  23742. return Server::HandlerResponse::Unhandled;
  23743. });
  23744. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23745. if (req.matched_route == "/pre-request") {
  23746. res.set_content("pre-request", "text/plain");
  23747. return Server::HandlerResponse::Handled;
  23748. }
  23749. return Server::HandlerResponse::Unhandled;
  23750. });
  23751. svr.Get("/smuggled", [](const Request &, Response &res) {
  23752. res.set_content("smuggled", "text/plain");
  23753. });
  23754. svr.WebSocket("/pre-request",
  23755. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23756. auto port = svr.bind_to_any_port(HOST);
  23757. std::thread t([&]() { svr.listen_after_bind(); });
  23758. auto se = detail::scope_exit([&] {
  23759. svr.stop();
  23760. t.join();
  23761. });
  23762. svr.wait_until_ready();
  23763. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23764. for (auto path : {"/pre-routing", "/pre-request"}) {
  23765. std::string req = std::string("GET ") + path +
  23766. " HTTP/1.1\r\n"
  23767. "Host: localhost\r\n"
  23768. "Upgrade: websocket\r\n"
  23769. "Connection: Upgrade\r\n"
  23770. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23771. "Sec-WebSocket-Version: 13\r\n"
  23772. "Content-Length: " +
  23773. std::to_string(body.size()) + "\r\n\r\n" + body;
  23774. std::string res;
  23775. ASSERT_TRUE(send_request(5, req, &res, port));
  23776. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23777. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23778. // Only one response, and the body was not served as a request
  23779. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23780. }
  23781. }
  23782. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23783. Server svr;
  23784. std::atomic<int> pre_request_calls{0};
  23785. std::atomic<bool> route_matched{false};
  23786. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23787. pre_request_calls++;
  23788. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23789. if (req.get_header_value("Authorization") != "Bearer token123") {
  23790. res.status = StatusCode::Unauthorized_401;
  23791. res.set_content("Unauthorized", "text/plain");
  23792. return Server::HandlerResponse::Handled;
  23793. }
  23794. return Server::HandlerResponse::Unhandled;
  23795. });
  23796. std::atomic<bool> handler_called{false};
  23797. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23798. handler_called = true;
  23799. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23800. });
  23801. auto port = svr.bind_to_any_port("localhost");
  23802. std::thread t([&]() { svr.listen_after_bind(); });
  23803. svr.wait_until_ready();
  23804. // Without Authorization header - should be rejected before upgrade
  23805. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23806. "/ws/1");
  23807. EXPECT_FALSE(client1.connect());
  23808. EXPECT_FALSE(handler_called);
  23809. EXPECT_EQ(1, pre_request_calls);
  23810. EXPECT_TRUE(route_matched);
  23811. // The rejection is an ordinary HTTP response, not a protocol switch
  23812. {
  23813. Client cli("localhost", port);
  23814. Headers headers = {{"Upgrade", "websocket"},
  23815. {"Connection", "Upgrade"},
  23816. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23817. {"Sec-WebSocket-Version", "13"}};
  23818. auto res = cli.Get("/ws/1", headers);
  23819. ASSERT_TRUE(res);
  23820. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23821. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23822. EXPECT_EQ("Unauthorized", res->body);
  23823. }
  23824. EXPECT_FALSE(handler_called);
  23825. // With Authorization header - should succeed
  23826. Headers headers = {{"Authorization", "Bearer token123"}};
  23827. ws::WebSocketClient client2(
  23828. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23829. ASSERT_TRUE(client2.connect());
  23830. std::string msg;
  23831. ASSERT_TRUE(client2.read(msg));
  23832. EXPECT_EQ("/ws/:id 2", msg);
  23833. EXPECT_TRUE(handler_called);
  23834. client2.close();
  23835. svr.stop();
  23836. t.join();
  23837. }
  23838. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  23839. static Headers websocket_upgrade_headers() {
  23840. return {{"Upgrade", "websocket"},
  23841. {"Connection", "Upgrade"},
  23842. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23843. {"Sec-WebSocket-Version", "13"},
  23844. {"Sec-WebSocket-Protocol", "chat"}};
  23845. }
  23846. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  23847. Server svr;
  23848. svr.set_pre_routing_handler([](const Request &req, Response &) {
  23849. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  23850. return Server::HandlerResponse::Unhandled;
  23851. });
  23852. svr.set_pre_request_handler([](const Request &req, Response &) {
  23853. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  23854. return Server::HandlerResponse::Unhandled;
  23855. });
  23856. svr.set_exception_handler(
  23857. [](const Request &, Response &res, std::exception_ptr ep) {
  23858. try {
  23859. std::rethrow_exception(ep);
  23860. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  23861. });
  23862. auto handler = [](const Request &, ws::WebSocket &) {};
  23863. svr.WebSocket("/pre-routing", handler);
  23864. svr.WebSocket("/pre-request", handler);
  23865. svr.WebSocket("/sub-protocol", handler,
  23866. [](const std::vector<std::string> &) -> std::string {
  23867. throw std::runtime_error("/sub-protocol");
  23868. });
  23869. auto port = svr.bind_to_any_port(HOST);
  23870. ASSERT_GT(port, 0);
  23871. thread t = thread([&] { svr.listen_after_bind(); });
  23872. auto se = detail::scope_exit([&] {
  23873. svr.stop();
  23874. t.join();
  23875. ASSERT_FALSE(svr.is_running());
  23876. });
  23877. svr.wait_until_ready();
  23878. Client cli(HOST, port);
  23879. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  23880. auto res = cli.Get(path, websocket_upgrade_headers());
  23881. if (!res) {
  23882. ADD_FAILURE() << path << ": " << to_string(res.error());
  23883. continue;
  23884. }
  23885. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  23886. EXPECT_EQ(path, res->body);
  23887. }
  23888. }
  23889. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  23890. Server svr;
  23891. svr.set_pre_routing_handler(
  23892. [](const Request &, Response &) -> Server::HandlerResponse {
  23893. throw std::runtime_error("pre-routing");
  23894. });
  23895. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23896. auto port = svr.bind_to_any_port(HOST);
  23897. ASSERT_GT(port, 0);
  23898. thread t = thread([&] { svr.listen_after_bind(); });
  23899. auto se = detail::scope_exit([&] {
  23900. svr.stop();
  23901. t.join();
  23902. ASSERT_FALSE(svr.is_running());
  23903. });
  23904. svr.wait_until_ready();
  23905. Client cli(HOST, port);
  23906. auto res = cli.Get("/ws", websocket_upgrade_headers());
  23907. ASSERT_TRUE(res) << to_string(res.error());
  23908. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  23909. }
  23910. #endif
  23911. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23912. Server svr;
  23913. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23914. // A read timeout is how a handler gets control back. Without it, a handler
  23915. // parked in read() can never write on the connection it is reading.
  23916. ws.set_read_timeout(std::chrono::milliseconds(100));
  23917. std::string msg;
  23918. while (ws.is_open()) {
  23919. auto r = ws.read(msg);
  23920. if (r == httplib::ws::Timeout) {
  23921. ws.send("tick");
  23922. continue;
  23923. }
  23924. if (r == httplib::ws::Fail) { break; }
  23925. ws.send(msg);
  23926. }
  23927. });
  23928. auto port = svr.bind_to_any_port("localhost");
  23929. std::thread t([&]() { svr.listen_after_bind(); });
  23930. svr.wait_until_ready();
  23931. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23932. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23933. ASSERT_TRUE(client.connect());
  23934. // The client sends nothing, so anything it receives came out of the
  23935. // handler's timeout path.
  23936. std::string msg;
  23937. ASSERT_EQ(client.read(msg), ws::Text);
  23938. EXPECT_EQ("tick", msg);
  23939. client.close();
  23940. svr.stop();
  23941. t.join();
  23942. }
  23943. // Stream::read may return fewer bytes than asked for. This is that contract at
  23944. // its worst -- one byte per call -- which is what a frame header straddling a
  23945. // read buffer's boundary looks like to the frame parser.
  23946. class WsByteAtATimeStream : public Stream {
  23947. public:
  23948. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23949. bool is_readable() const override { return true; }
  23950. bool wait_readable() const override { return true; }
  23951. bool wait_writable() const override { return true; }
  23952. ssize_t read(char *ptr, size_t size) override {
  23953. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23954. *ptr = data_[pos_++];
  23955. return 1;
  23956. }
  23957. ssize_t write(const char *, size_t size) override {
  23958. return static_cast<ssize_t>(size);
  23959. }
  23960. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23961. ip = "127.0.0.1";
  23962. port = 0;
  23963. }
  23964. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23965. ip = "127.0.0.1";
  23966. port = 0;
  23967. }
  23968. socket_t socket() const override { return INVALID_SOCKET; }
  23969. time_t duration() const override { return 0; }
  23970. private:
  23971. std::string data_;
  23972. size_t pos_ = 0;
  23973. };
  23974. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23975. // The payload uses the 16-bit extended length, so the header, the length
  23976. // and the mask key are all multi-byte fields here. Each used to be read
  23977. // with a single read() call, which fails as soon as one is split. The
  23978. // payload is also a little over one read chunk, so it is read in two.
  23979. std::string body;
  23980. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23981. body += static_cast<char>(i % 251);
  23982. }
  23983. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23984. std::string frame;
  23985. frame += static_cast<char>(0x81); // FIN + Text
  23986. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23987. frame += static_cast<char>(body.size() >> 8);
  23988. frame += static_cast<char>(body.size() & 0xff);
  23989. for (size_t i = 0; i < 4; i++) {
  23990. frame += static_cast<char>(mask[i]);
  23991. }
  23992. for (size_t i = 0; i < body.size(); i++) {
  23993. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23994. }
  23995. WsByteAtATimeStream strm(frame);
  23996. ws::Opcode opcode;
  23997. std::string payload;
  23998. bool fin = false;
  23999. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24000. /*expect_masked=*/true, body.size()),
  24001. ws::impl::FrameRead::Ok);
  24002. EXPECT_TRUE(fin);
  24003. EXPECT_EQ(opcode, ws::Opcode::Text);
  24004. EXPECT_EQ(payload, body);
  24005. }
  24006. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24007. std::string body(2000, 'x');
  24008. std::string frame;
  24009. frame += static_cast<char>(0x82); // FIN + Binary
  24010. frame += static_cast<char>(126); // 16-bit length follows
  24011. frame += static_cast<char>(body.size() >> 8);
  24012. frame += static_cast<char>(body.size() & 0xff);
  24013. frame += body;
  24014. detail::BufferStream strm;
  24015. strm.write(frame.data(), frame.size());
  24016. ws::Opcode opcode;
  24017. std::string payload;
  24018. bool fin;
  24019. EXPECT_EQ(
  24020. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24021. ws::impl::FrameRead::Ok);
  24022. EXPECT_EQ(body, payload);
  24023. }
  24024. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24025. // The header announces the largest payload allowed, and only 3 bytes of it
  24026. // ever arrive.
  24027. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24028. std::string frame;
  24029. frame += static_cast<char>(0x82); // FIN + Binary
  24030. frame += static_cast<char>(127); // 64-bit length follows
  24031. for (int shift = 56; shift >= 0; shift -= 8) {
  24032. frame += static_cast<char>((len >> shift) & 0xff);
  24033. }
  24034. frame += "abc";
  24035. detail::BufferStream strm;
  24036. strm.write(frame.data(), frame.size());
  24037. ws::Opcode opcode;
  24038. std::string payload;
  24039. bool fin;
  24040. EXPECT_EQ(
  24041. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24042. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24043. ws::impl::FrameRead::Fail);
  24044. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24045. }
  24046. TEST(WebSocketTest, QueryStringInHandshake) {
  24047. Server svr;
  24048. std::mutex mtx;
  24049. std::string received_target;
  24050. std::string received_token;
  24051. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24052. {
  24053. std::lock_guard<std::mutex> lock(mtx);
  24054. received_target = req.target;
  24055. if (req.has_param("token")) {
  24056. received_token = req.get_param_value("token");
  24057. }
  24058. }
  24059. std::string msg;
  24060. while (ws.read(msg)) {
  24061. ws.send(msg);
  24062. }
  24063. });
  24064. auto port = svr.bind_to_any_port("localhost");
  24065. std::thread t([&]() { svr.listen_after_bind(); });
  24066. svr.wait_until_ready();
  24067. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24068. "/ws?token=ABC&session=123");
  24069. ASSERT_TRUE(client.connect());
  24070. // Round-trip ensures the handler has run and captured the request.
  24071. ASSERT_TRUE(client.send("hello"));
  24072. std::string msg;
  24073. ASSERT_TRUE(client.read(msg));
  24074. EXPECT_EQ("hello", msg);
  24075. client.close();
  24076. {
  24077. std::lock_guard<std::mutex> lock(mtx);
  24078. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24079. EXPECT_EQ("ABC", received_token);
  24080. }
  24081. svr.stop();
  24082. t.join();
  24083. }
  24084. // Run a handshake against a throwaway server and hand the request the server
  24085. // received back to the caller, so tests can assert on the headers the client
  24086. // actually put on the wire.
  24087. static void capture_websocket_handshake_request(
  24088. const Headers &client_headers,
  24089. std::function<void(const Request &, int port)> verify) {
  24090. Server svr;
  24091. std::mutex mtx;
  24092. Request received;
  24093. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24094. {
  24095. std::lock_guard<std::mutex> lock(mtx);
  24096. received = req;
  24097. }
  24098. std::string msg;
  24099. while (ws.read(msg)) {
  24100. ws.send(msg);
  24101. }
  24102. });
  24103. auto port = svr.bind_to_any_port("localhost");
  24104. std::thread t([&]() { svr.listen_after_bind(); });
  24105. auto se = detail::scope_exit([&] {
  24106. svr.stop();
  24107. t.join();
  24108. });
  24109. svr.wait_until_ready();
  24110. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24111. client_headers);
  24112. ASSERT_TRUE(client.connect());
  24113. ASSERT_TRUE(client.send("hello"));
  24114. std::string msg;
  24115. ASSERT_TRUE(client.read(msg));
  24116. client.close();
  24117. {
  24118. std::lock_guard<std::mutex> lock(mtx);
  24119. verify(received, port);
  24120. }
  24121. }
  24122. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24123. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24124. // Non-default port must be present in the Host header. Default ports
  24125. // (80/443) are omitted; that logic is covered by
  24126. // MakeHostAndPortStringTest.
  24127. EXPECT_EQ("localhost:" + std::to_string(port),
  24128. req.get_header_value("Host"));
  24129. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24130. req.get_header_value("User-Agent"));
  24131. EXPECT_FALSE(req.has_header("Accept"));
  24132. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24133. EXPECT_FALSE(req.has_header("Content-Length"));
  24134. });
  24135. }
  24136. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24137. capture_websocket_handshake_request(
  24138. {{"Host", "example.com"},
  24139. {"User-Agent", "custom-agent"},
  24140. {"X-Custom", "value"}},
  24141. [](const Request &req, int) {
  24142. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24143. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24144. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24145. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24146. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24147. });
  24148. }
  24149. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24150. capture_websocket_handshake_request(
  24151. {{"Upgrade", "bogus"},
  24152. {"Connection", "close"},
  24153. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24154. {"Sec-WebSocket-Version", "8"}},
  24155. [](const Request &req, int) {
  24156. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24157. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24158. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24159. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24160. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24161. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24162. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24163. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24164. req.get_header_value("Sec-WebSocket-Key"));
  24165. });
  24166. }
  24167. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24168. // A header the client refuses to send must abort the handshake before any
  24169. // part of it reaches the wire; a lone request line would otherwise sit in
  24170. // the peer's buffer as a truncated request.
  24171. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24172. ASSERT_NE(INVALID_SOCKET, srv);
  24173. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24174. sockaddr_in addr{};
  24175. addr.sin_family = AF_INET;
  24176. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24177. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24178. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24179. ASSERT_EQ(0, ::listen(srv, 1));
  24180. sockaddr_in bound{};
  24181. socklen_t bound_len = sizeof(bound);
  24182. ASSERT_EQ(
  24183. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24184. auto port = ntohs(bound.sin_port);
  24185. ssize_t received = -1;
  24186. std::thread t([&] {
  24187. // Bound every blocking call so a regression fails the test with a bad
  24188. // value instead of hanging the suite.
  24189. fd_set rfds;
  24190. FD_ZERO(&rfds);
  24191. FD_SET(srv, &rfds);
  24192. timeval tv{5, 0};
  24193. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24194. 0) {
  24195. return;
  24196. }
  24197. sockaddr_in cli_addr{};
  24198. socklen_t cli_len = sizeof(cli_addr);
  24199. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24200. if (cli == INVALID_SOCKET) { return; }
  24201. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24202. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24203. char buf[4096];
  24204. received = ::recv(cli, buf, sizeof(buf), 0);
  24205. });
  24206. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24207. // connect() has already shut the socket down by the time it returns false,
  24208. // so the peer sees EOF without waiting for the client to be destroyed.
  24209. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24210. {{"X-Bad", "a\r\nInjected: 1"}});
  24211. EXPECT_FALSE(client.connect());
  24212. t.join();
  24213. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24214. EXPECT_EQ(0, received);
  24215. }
  24216. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24217. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24218. // contains "upgrade" as a substring is a different token and must not
  24219. // start a WebSocket handshake.
  24220. auto make_request = [](const std::vector<std::string> &connection_values) {
  24221. Request req;
  24222. req.method = "GET";
  24223. req.headers.emplace("Upgrade", "websocket");
  24224. for (const auto &value : connection_values) {
  24225. req.headers.emplace("Connection", value);
  24226. }
  24227. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24228. req.headers.emplace("Sec-WebSocket-Version", "13");
  24229. return req;
  24230. };
  24231. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24232. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24233. EXPECT_TRUE(
  24234. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24235. EXPECT_TRUE(
  24236. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24237. EXPECT_TRUE(
  24238. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24239. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24240. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24241. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24242. EXPECT_FALSE(
  24243. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24244. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24245. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24246. }
  24247. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24248. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24249. // asks recipients to match each protocol-name case-insensitively, and RFC
  24250. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24251. // client naming websocket alongside another protocol, or on a second field
  24252. // line, is offering websocket; a value that merely contains "websocket" as a
  24253. // substring is a different protocol name and is not.
  24254. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24255. Request req;
  24256. req.method = "GET";
  24257. for (const auto &value : upgrade_values) {
  24258. req.headers.emplace("Upgrade", value);
  24259. }
  24260. req.headers.emplace("Connection", "Upgrade");
  24261. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24262. req.headers.emplace("Sec-WebSocket-Version", "13");
  24263. return req;
  24264. };
  24265. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24266. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24267. EXPECT_TRUE(
  24268. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24269. EXPECT_TRUE(
  24270. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24271. EXPECT_TRUE(
  24272. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24273. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24274. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24275. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24276. EXPECT_FALSE(
  24277. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24278. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24279. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24280. }
  24281. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24282. Server svr;
  24283. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24284. auto port = svr.bind_to_any_port("localhost");
  24285. std::thread t([&]() { svr.listen_after_bind(); });
  24286. auto se = detail::scope_exit([&] {
  24287. svr.stop();
  24288. t.join();
  24289. });
  24290. svr.wait_until_ready();
  24291. Headers headers = {{"Upgrade", "websocket"},
  24292. {"Connection", "notupgrade"},
  24293. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24294. {"Sec-WebSocket-Version", "13"}};
  24295. Client cli("localhost", port);
  24296. auto res = cli.Get("/ws", headers);
  24297. // The route exists only as a WebSocket route, so a request that fails the
  24298. // handshake check falls through to ordinary routing.
  24299. ASSERT_TRUE(res);
  24300. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24301. }
  24302. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24303. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24304. // Connection value is the only thing left for the client to reject.
  24305. Server svr;
  24306. svr.Get("/ws", [](const Request &req, Response &res) {
  24307. res.status = StatusCode::SwitchingProtocol_101;
  24308. res.set_header("Upgrade", "websocket");
  24309. res.set_header("Connection", "notupgrade");
  24310. res.set_header("Sec-WebSocket-Accept",
  24311. detail::websocket_accept_key(
  24312. req.get_header_value("Sec-WebSocket-Key")));
  24313. });
  24314. auto port = svr.bind_to_any_port("localhost");
  24315. std::thread t([&]() { svr.listen_after_bind(); });
  24316. auto se = detail::scope_exit([&] {
  24317. svr.stop();
  24318. t.join();
  24319. });
  24320. svr.wait_until_ready();
  24321. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24322. auto res = client.connect();
  24323. EXPECT_FALSE(res);
  24324. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24325. EXPECT_FALSE(client.is_open());
  24326. }
  24327. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24328. Server svr;
  24329. svr.Get("/ws", [](const Request &req, Response &res) {
  24330. res.status = StatusCode::SwitchingProtocol_101;
  24331. res.set_header("Upgrade", "websocket");
  24332. res.set_header("Connection", "Upgrade");
  24333. res.set_header("Sec-WebSocket-Accept",
  24334. detail::websocket_accept_key(
  24335. req.get_header_value("Sec-WebSocket-Key")));
  24336. res.set_header("Sec-WebSocket-Protocol", "admin");
  24337. });
  24338. auto port = svr.bind_to_any_port("localhost");
  24339. std::thread t([&]() { svr.listen_after_bind(); });
  24340. auto se = detail::scope_exit([&] {
  24341. svr.stop();
  24342. t.join();
  24343. });
  24344. svr.wait_until_ready();
  24345. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24346. // Server selects a subprotocol the client never offered
  24347. {
  24348. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24349. ws::WebSocketClient client(url, headers);
  24350. auto res = client.connect();
  24351. EXPECT_FALSE(res);
  24352. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24353. EXPECT_FALSE(client.is_open());
  24354. EXPECT_TRUE(client.subprotocol().empty());
  24355. }
  24356. // Client offered none but the server named one anyway
  24357. {
  24358. ws::WebSocketClient client(url);
  24359. auto res = client.connect();
  24360. EXPECT_FALSE(res);
  24361. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24362. EXPECT_FALSE(client.is_open());
  24363. EXPECT_TRUE(client.subprotocol().empty());
  24364. }
  24365. }
  24366. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24367. // The socket path doubles as the URL host, so it must not contain '/'.
  24368. const char *shard = getenv("GTEST_SHARD_INDEX");
  24369. const std::string sock_path =
  24370. shard ? std::string("httplib-ws-") + shard + ".sock"
  24371. : std::string("httplib-ws.sock");
  24372. std::remove(sock_path.c_str());
  24373. Server svr;
  24374. std::mutex mtx;
  24375. std::string received_host;
  24376. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24377. {
  24378. std::lock_guard<std::mutex> lock(mtx);
  24379. received_host = req.get_header_value("Host");
  24380. }
  24381. std::string msg;
  24382. while (ws.read(msg)) {
  24383. ws.send(msg);
  24384. }
  24385. });
  24386. svr.set_address_family(AF_UNIX);
  24387. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24388. auto se = detail::scope_exit([&] {
  24389. svr.stop();
  24390. t.join();
  24391. std::remove(sock_path.c_str());
  24392. });
  24393. svr.wait_until_ready();
  24394. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24395. client.set_address_family(AF_UNIX);
  24396. ASSERT_TRUE(client.connect());
  24397. ASSERT_TRUE(client.send("hello"));
  24398. std::string msg;
  24399. ASSERT_TRUE(client.read(msg));
  24400. client.close();
  24401. {
  24402. std::lock_guard<std::mutex> lock(mtx);
  24403. // There is no host:port for a Unix socket, so the same "localhost"
  24404. // placeholder the HTTP client uses is expected.
  24405. EXPECT_EQ("localhost", received_host);
  24406. }
  24407. }
  24408. // Two threads must never parse WebSocket frames from the same stream.
  24409. // close() used to read the peer's Close reply with its own frame read, so it
  24410. // raced a reader thread that was in the middle of a payload: the payload loop
  24411. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24412. // so bytes taken by close() were replaced with bytes from further along the
  24413. // stream. The message kept its length and silently changed content.
  24414. //
  24415. // The raw peer below sends a frame header plus part of the payload, waits for
  24416. // the handler to call close(), and only then sends the rest. Whichever thread
  24417. // would win the race for those bytes, the message must arrive intact, because
  24418. // close() must not touch the stream while read() owns it.
  24419. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24420. #ifndef _WIN32
  24421. signal(SIGPIPE, SIG_IGN);
  24422. #endif
  24423. const size_t payload_len = 120; // fits the 7-bit length field
  24424. const size_t prefix_len = 8;
  24425. const int attempts = 8;
  24426. std::string expected(payload_len, '\0');
  24427. for (size_t i = 0; i < payload_len; i++) {
  24428. expected[i] = static_cast<char>('a' + i % 26);
  24429. }
  24430. std::atomic<bool> peer_stalled{false};
  24431. std::atomic<bool> handler_done{false};
  24432. std::mutex received_mutex;
  24433. std::vector<std::string> received;
  24434. // Bound every wait, so a regression fails the test instead of hanging the
  24435. // suite.
  24436. auto wait_for = [](const std::atomic<bool> &flag) {
  24437. for (int i = 0; i < 500 && !flag; i++) {
  24438. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24439. }
  24440. };
  24441. Server svr;
  24442. svr.set_websocket_ping_interval(0);
  24443. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24444. std::thread reader([&]() {
  24445. std::string msg;
  24446. while (ws.read(msg)) {
  24447. std::lock_guard<std::mutex> guard(received_mutex);
  24448. received.push_back(msg);
  24449. }
  24450. });
  24451. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24452. // inside read_websocket_frame() when close() runs.
  24453. wait_for(peer_stalled);
  24454. ws.close();
  24455. reader.join();
  24456. handler_done = true;
  24457. });
  24458. auto port = svr.bind_to_any_port("127.0.0.1");
  24459. std::thread t([&]() { svr.listen_after_bind(); });
  24460. auto se = detail::scope_exit([&] {
  24461. svr.stop();
  24462. t.join();
  24463. });
  24464. svr.wait_until_ready();
  24465. auto send_bytes = [](socket_t s, const std::string &data) {
  24466. #ifdef _WIN32
  24467. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24468. #else
  24469. auto n = ::send(s, data.data(), data.size(), 0);
  24470. #endif
  24471. return n == static_cast<decltype(n)>(data.size());
  24472. };
  24473. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24474. // Every length used here fits the 7-bit length field.
  24475. auto masked_header = [](uint8_t first_byte, size_t len) {
  24476. std::string h;
  24477. h += static_cast<char>(first_byte);
  24478. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24479. h.append(4, '\0'); // mask key
  24480. return h;
  24481. };
  24482. for (int attempt = 0; attempt < attempts; attempt++) {
  24483. peer_stalled = false;
  24484. handler_done = false;
  24485. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24486. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24487. auto se_sock = detail::scope_exit([&] {
  24488. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24489. });
  24490. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24491. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24492. sockaddr_in addr{};
  24493. addr.sin_family = AF_INET;
  24494. addr.sin_port = htons(static_cast<uint16_t>(port));
  24495. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24496. ASSERT_EQ(
  24497. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24498. << "attempt " << attempt;
  24499. ASSERT_TRUE(send_bytes(sock,
  24500. "GET /ws HTTP/1.1\r\n"
  24501. "Host: 127.0.0.1\r\n"
  24502. "Upgrade: websocket\r\n"
  24503. "Connection: Upgrade\r\n"
  24504. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24505. "Sec-WebSocket-Version: 13\r\n"
  24506. "\r\n"))
  24507. << "attempt " << attempt;
  24508. std::string response;
  24509. while (response.find("\r\n\r\n") == std::string::npos) {
  24510. char buf[512];
  24511. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24512. if (n <= 0) { break; }
  24513. response.append(buf, static_cast<size_t>(n));
  24514. }
  24515. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24516. << "attempt " << attempt;
  24517. // Send the header of a Binary message but only the first prefix_len bytes
  24518. // of its payload, leaving the reader thread stalled inside the payload.
  24519. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24520. expected.substr(0, prefix_len)))
  24521. << "attempt " << attempt;
  24522. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24523. peer_stalled = true;
  24524. // Let close() send its Close frame and park in its own read before the
  24525. // rest of the payload arrives, so both threads are waiting for it.
  24526. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24527. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24528. close_frame += static_cast<char>(0x03); // status 1000
  24529. close_frame += static_cast<char>(0xE8);
  24530. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24531. << "attempt " << attempt;
  24532. // Closing the peer releases the reader thread even on the buggy path,
  24533. // where it waits for bytes another thread already consumed.
  24534. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24535. detail::close_socket(sock);
  24536. sock = INVALID_SOCKET;
  24537. wait_for(handler_done);
  24538. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24539. }
  24540. std::lock_guard<std::mutex> guard(received_mutex);
  24541. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24542. << "a message in flight when close() ran was dropped";
  24543. for (size_t i = 0; i < received.size(); i++) {
  24544. EXPECT_EQ(expected, received[i]) << "message " << i;
  24545. }
  24546. }
  24547. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24548. // returning the socket, or INVALID_SOCKET.
  24549. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24550. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24551. if (sock == INVALID_SOCKET) { return sock; }
  24552. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24553. sockaddr_in addr{};
  24554. addr.sin_family = AF_INET;
  24555. addr.sin_port = htons(static_cast<uint16_t>(port));
  24556. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24557. std::string req = "GET " + path +
  24558. " HTTP/1.1\r\n"
  24559. "Host: 127.0.0.1\r\n"
  24560. "Upgrade: websocket\r\n"
  24561. "Connection: Upgrade\r\n"
  24562. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24563. "Sec-WebSocket-Version: 13\r\n"
  24564. "\r\n";
  24565. std::string res;
  24566. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24567. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24568. static_cast<ssize_t>(req.size())) {
  24569. char c;
  24570. while (res.find("\r\n\r\n") == std::string::npos &&
  24571. ::recv(sock, &c, 1, 0) == 1) {
  24572. res += c;
  24573. }
  24574. }
  24575. if (res.find(" 101 ") == std::string::npos) {
  24576. detail::close_socket(sock);
  24577. return INVALID_SOCKET;
  24578. }
  24579. return sock;
  24580. }
  24581. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24582. // The payload must fit the 7-bit length field.
  24583. static std::string masked_frame(uint8_t first_byte,
  24584. const std::string &payload) {
  24585. std::string f;
  24586. f += static_cast<char>(first_byte);
  24587. f += static_cast<char>(0x80 | payload.size());
  24588. f.append(4, '\0');
  24589. return f + payload;
  24590. }
  24591. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24592. std::atomic<bool> done{false};
  24593. std::string received;
  24594. Server svr;
  24595. svr.set_websocket_ping_interval(0);
  24596. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24597. std::string msg;
  24598. if (ws.read(msg) == ws::Binary) { received = msg; }
  24599. done = true;
  24600. });
  24601. auto port = svr.bind_to_any_port("127.0.0.1");
  24602. std::thread t([&]() { svr.listen_after_bind(); });
  24603. auto se = detail::scope_exit([&] {
  24604. svr.stop();
  24605. t.join();
  24606. });
  24607. svr.wait_until_ready();
  24608. auto sock = connect_raw_websocket(port, "/ws");
  24609. ASSERT_NE(INVALID_SOCKET, sock);
  24610. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24611. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24612. masked_frame(0x89, "p") + // FIN + Ping
  24613. masked_frame(0x80, "lo"); // FIN + Continuation
  24614. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24615. for (int i = 0; i < 500 && !done; i++) {
  24616. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24617. }
  24618. ASSERT_TRUE(done);
  24619. EXPECT_EQ("Hello", received);
  24620. // The Ping between the fragments is answered with a Pong.
  24621. char pong[3];
  24622. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24623. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24624. }
  24625. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24626. Server svr;
  24627. svr.set_websocket_ping_interval(-1);
  24628. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24629. std::string msg;
  24630. while (ws.read(msg)) {}
  24631. });
  24632. auto port = svr.bind_to_any_port("127.0.0.1");
  24633. std::thread t([&]() { svr.listen_after_bind(); });
  24634. auto se = detail::scope_exit([&] {
  24635. svr.stop();
  24636. t.join();
  24637. });
  24638. svr.wait_until_ready();
  24639. auto sock = connect_raw_websocket(port, "/ws");
  24640. ASSERT_NE(INVALID_SOCKET, sock);
  24641. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24642. // Nothing comes while the client stays quiet.
  24643. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24644. char c;
  24645. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24646. }
  24647. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24648. // and that has to end a read() already waiting on the peer, on every platform.
  24649. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24650. // The peer sends no pings, and its handler never calls read(), which is
  24651. // where pongs are written.
  24652. std::mutex mutex;
  24653. std::condition_variable cv;
  24654. auto release = false;
  24655. svr.set_websocket_ping_interval(0);
  24656. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24657. std::unique_lock<std::mutex> lock(mutex);
  24658. cv.wait(lock, [&] { return release; });
  24659. });
  24660. auto port = svr.bind_to_any_port(HOST);
  24661. std::thread t([&]() { svr.listen_after_bind(); });
  24662. auto se = detail::scope_exit([&] {
  24663. {
  24664. std::lock_guard<std::mutex> lock(mutex);
  24665. release = true;
  24666. }
  24667. cv.notify_all();
  24668. svr.stop();
  24669. t.join();
  24670. });
  24671. svr.wait_until_ready();
  24672. ws::WebSocketClient client(std::string(scheme) +
  24673. "://localhost:" + std::to_string(port) + "/ws");
  24674. #ifdef CPPHTTPLIB_SSL_ENABLED
  24675. client.enable_server_certificate_verification(false);
  24676. #endif
  24677. // A ping a second, given up on after two go unanswered: about 3s
  24678. client.set_websocket_ping_interval(1);
  24679. client.set_websocket_max_missed_pongs(2);
  24680. // Well past that, so that a read the timeout ends instead stands out
  24681. client.set_read_timeout(10);
  24682. ASSERT_TRUE(client.connect());
  24683. auto start = std::chrono::steady_clock::now();
  24684. std::string msg;
  24685. EXPECT_EQ(ws::Fail, client.read(msg));
  24686. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24687. std::chrono::steady_clock::now() - start)
  24688. .count(),
  24689. 6000);
  24690. EXPECT_FALSE(client.is_open());
  24691. }
  24692. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24693. Server svr;
  24694. check_pong_timeout_ends_read(svr, "ws");
  24695. }
  24696. #ifdef CPPHTTPLIB_SSL_ENABLED
  24697. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24698. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24699. ASSERT_TRUE(svr.is_valid());
  24700. check_pong_timeout_ends_read(svr, "wss");
  24701. }
  24702. #endif
  24703. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24704. Server svr;
  24705. svr.set_websocket_ping_interval(0);
  24706. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24707. std::string msg;
  24708. while (ws.read(msg)) {}
  24709. });
  24710. auto port = svr.bind_to_any_port("127.0.0.1");
  24711. std::thread t([&]() { svr.listen_after_bind(); });
  24712. auto se = detail::scope_exit([&] {
  24713. svr.stop();
  24714. t.join();
  24715. });
  24716. svr.wait_until_ready();
  24717. // Each Close payload and the reply it should get: an echo when valid, 1002
  24718. // otherwise.
  24719. std::vector<std::pair<std::string, std::string>> cases = {
  24720. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24721. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24722. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24723. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24724. };
  24725. // Also between the fragments of a message.
  24726. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24727. for (const auto &c : cases) {
  24728. auto sock = connect_raw_websocket(port, "/ws");
  24729. ASSERT_NE(INVALID_SOCKET, sock);
  24730. auto frames = prefix + masked_frame(0x88, c.first);
  24731. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24732. std::string reply;
  24733. char buf[256];
  24734. while (reply.size() < 2 + c.second.size()) {
  24735. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24736. if (n <= 0) { break; }
  24737. reply.append(buf, static_cast<size_t>(n));
  24738. }
  24739. detail::close_socket(sock);
  24740. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24741. c.second,
  24742. reply);
  24743. }
  24744. }
  24745. }
  24746. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24747. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24748. protected:
  24749. void SetUp() override {
  24750. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24751. SERVER_PRIVATE_KEY_FILE);
  24752. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24753. std::string msg;
  24754. ws::ReadResult ret;
  24755. while ((ret = ws.read(msg))) {
  24756. if (ret == ws::Binary) {
  24757. ws.send(msg.data(), msg.size());
  24758. } else {
  24759. ws.send(msg);
  24760. }
  24761. }
  24762. });
  24763. port_ = server_->bind_to_any_port(HOST);
  24764. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24765. server_->wait_until_ready();
  24766. }
  24767. void TearDown() override {
  24768. server_->stop();
  24769. if (server_thread_.joinable()) { server_thread_.join(); }
  24770. }
  24771. std::unique_ptr<SSLServer> server_;
  24772. std::thread server_thread_;
  24773. int port_ = 0;
  24774. };
  24775. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24776. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24777. {
  24778. ws::WebSocketClient client(url);
  24779. client.enable_server_certificate_verification(false);
  24780. auto calls = 0;
  24781. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24782. calls++;
  24783. return false;
  24784. });
  24785. EXPECT_FALSE(client.connect());
  24786. EXPECT_GT(calls, 0);
  24787. }
  24788. {
  24789. ws::WebSocketClient client(url);
  24790. client.enable_server_certificate_verification(false);
  24791. client.set_session_verifier([](tls::session_t) {
  24792. return SSLVerifierResponse::CertificateRejected;
  24793. });
  24794. EXPECT_FALSE(client.connect());
  24795. }
  24796. {
  24797. ws::WebSocketClient client(url);
  24798. client.enable_server_certificate_verification(false);
  24799. client.set_session_verifier([](tls::session_t) {
  24800. return SSLVerifierResponse::CertificateAccepted;
  24801. });
  24802. EXPECT_TRUE(client.connect());
  24803. }
  24804. }
  24805. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24806. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24807. "/ws-echo");
  24808. client.enable_server_certificate_verification(false);
  24809. ASSERT_TRUE(client.connect());
  24810. ASSERT_TRUE(client.is_open());
  24811. ASSERT_TRUE(client.send("Hello WSS"));
  24812. std::string msg;
  24813. EXPECT_EQ(ws::Text, client.read(msg));
  24814. EXPECT_EQ("Hello WSS", msg);
  24815. client.close();
  24816. }
  24817. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24818. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24819. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24820. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24821. // client (without calling close() first) is the only path that runs
  24822. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24823. // bug exactly.
  24824. //
  24825. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24826. // when linked against an instrumented libssl; run under Valgrind to catch it
  24827. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24828. // suite (the freed session otherwise stalls on the close handshake) — this test
  24829. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24830. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24831. {
  24832. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24833. "/ws-echo");
  24834. client.enable_server_certificate_verification(false);
  24835. client.set_read_timeout(2, 0);
  24836. client.set_write_timeout(2, 0);
  24837. ASSERT_TRUE(client.connect());
  24838. ASSERT_TRUE(client.is_open());
  24839. ASSERT_TRUE(client.send("still open"));
  24840. // Intentionally do NOT call client.close(): leaving scope runs
  24841. // shutdown_and_close() with the WebSocket still open, which must send the
  24842. // close frame while the TLS session is still alive.
  24843. }
  24844. }
  24845. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24846. // shutdown_and_close() at the start of connect(), reproducing the same
  24847. // use-after-free within the test body rather than at scope exit. The second
  24848. // connect must succeed and echo, proving the close handshake ran over a live
  24849. // session. See the note above about memory-tool requirements.
  24850. TEST_F(WebSocketSSLIntegrationTest,
  24851. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24852. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24853. "/ws-echo");
  24854. client.enable_server_certificate_verification(false);
  24855. client.set_read_timeout(2, 0);
  24856. client.set_write_timeout(2, 0);
  24857. ASSERT_TRUE(client.connect());
  24858. ASSERT_TRUE(client.is_open());
  24859. ASSERT_TRUE(client.send("still open"));
  24860. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24861. // the still-open connection, which must not touch a freed TLS session.
  24862. ASSERT_TRUE(client.connect());
  24863. ASSERT_TRUE(client.is_open());
  24864. ASSERT_TRUE(client.send("after reconnect"));
  24865. std::string msg;
  24866. EXPECT_EQ(ws::Text, client.read(msg));
  24867. EXPECT_EQ("after reconnect", msg);
  24868. client.close();
  24869. }
  24870. #endif
  24871. #ifdef CPPHTTPLIB_SSL_ENABLED
  24872. class WebSocketSSLCATest : public ::testing::Test {
  24873. protected:
  24874. void SetUp() override {
  24875. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24876. SERVER_PRIVATE_KEY_FILE);
  24877. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24878. std::string msg;
  24879. while (ws.read(msg)) {
  24880. ws.send(msg);
  24881. }
  24882. });
  24883. port_ = server_->bind_to_any_port("127.0.0.1");
  24884. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24885. server_->wait_until_ready();
  24886. }
  24887. void TearDown() override {
  24888. server_->stop();
  24889. if (server_thread_.joinable()) { server_thread_.join(); }
  24890. }
  24891. std::string url() const {
  24892. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24893. }
  24894. std::unique_ptr<SSLServer> server_;
  24895. std::thread server_thread_;
  24896. int port_ = 0;
  24897. };
  24898. // A custom CA loaded as PEM verifies the server with full certificate
  24899. // verification enabled
  24900. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24901. ws::WebSocketClient client(url());
  24902. std::string cert;
  24903. read_file(SERVER_CERT2_FILE, cert);
  24904. client.load_ca_cert_store(cert.c_str(), cert.size());
  24905. ASSERT_TRUE(client.connect());
  24906. ASSERT_TRUE(client.send("hello"));
  24907. std::string msg;
  24908. EXPECT_EQ(ws::Text, client.read(msg));
  24909. EXPECT_EQ("hello", msg);
  24910. client.close();
  24911. }
  24912. // A custom CA that does not cover the server must fail verification (the
  24913. // custom CA is exclusive; system certs are not loaded alongside it)
  24914. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24915. ws::WebSocketClient client(url());
  24916. std::string cert;
  24917. read_file(CLIENT_CA_CERT_FILE, cert);
  24918. client.load_ca_cert_store(cert.c_str(), cert.size());
  24919. auto res = client.connect();
  24920. ASSERT_FALSE(res);
  24921. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24922. EXPECT_EQ(-1, res.status());
  24923. EXPECT_NE(0u, res.ssl_backend_error());
  24924. }
  24925. // The same CA as a file path rather than PEM in memory
  24926. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24927. ws::WebSocketClient client(url());
  24928. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24929. ASSERT_TRUE(client.connect());
  24930. ASSERT_TRUE(client.send("hello"));
  24931. std::string msg;
  24932. EXPECT_EQ(ws::Text, client.read(msg));
  24933. EXPECT_EQ("hello", msg);
  24934. client.close();
  24935. }
  24936. // ...and a CA file that does not cover the server still fails, so it is the
  24937. // path above that decides the outcome
  24938. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24939. ws::WebSocketClient client(url());
  24940. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24941. ASSERT_FALSE(client.connect());
  24942. }
  24943. // Regression test: reconnecting with a native custom CA store used to reuse
  24944. // a store handle the previous TLS context had already freed (use-after-free
  24945. // under the OpenSSL backend). The context now lives as long as the client.
  24946. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24947. ws::WebSocketClient client(url());
  24948. std::string cert;
  24949. read_file(SERVER_CERT2_FILE, cert);
  24950. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24951. ASSERT_TRUE(client.connect());
  24952. client.close();
  24953. ASSERT_TRUE(client.connect());
  24954. ASSERT_TRUE(client.send("again"));
  24955. std::string msg;
  24956. EXPECT_EQ(ws::Text, client.read(msg));
  24957. EXPECT_EQ("again", msg);
  24958. client.close();
  24959. }
  24960. // Regression test: a certificate with a trusted chain but no identity match
  24961. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24962. // verification entirely for IP hosts, so this connection succeeded there.
  24963. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24964. // chain verification while the identity check must still fail.
  24965. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24967. ASSERT_TRUE(svr.is_valid());
  24968. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24969. std::string msg;
  24970. while (ws.read(msg)) {
  24971. ws.send(msg);
  24972. }
  24973. });
  24974. auto port = svr.bind_to_any_port("127.0.0.1");
  24975. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24976. auto se = detail::scope_exit([&] {
  24977. svr.stop();
  24978. t.join();
  24979. });
  24980. svr.wait_until_ready();
  24981. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24982. "/echo");
  24983. std::string cert;
  24984. read_file(SERVER_CERT_FILE, cert);
  24985. client.load_ca_cert_store(cert.c_str(), cert.size());
  24986. ASSERT_FALSE(client.connect());
  24987. }
  24988. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24989. // SNI, so nothing binds the host name to the TLS session. These bind the
  24990. // server to "localhost" instead, the only shape that exercises the SNI and
  24991. // hostname-verification path with certificate verification left enabled.
  24992. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24993. protected:
  24994. void Start(const char *cert_file) {
  24995. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24996. SERVER_PRIVATE_KEY_FILE);
  24997. ASSERT_TRUE(server_->is_valid());
  24998. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24999. std::string msg;
  25000. while (ws.read(msg)) {
  25001. ws.send(msg);
  25002. }
  25003. });
  25004. port_ = server_->bind_to_any_port("localhost");
  25005. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25006. server_->wait_until_ready();
  25007. }
  25008. void TearDown() override {
  25009. if (server_) { server_->stop(); }
  25010. if (server_thread_.joinable()) { server_thread_.join(); }
  25011. }
  25012. std::string url() const {
  25013. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25014. }
  25015. std::unique_ptr<SSLServer> server_;
  25016. std::thread server_thread_;
  25017. int port_ = 0;
  25018. };
  25019. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25020. // out and the connection is usable
  25021. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25022. Start(SERVER_CERT2_FILE);
  25023. ws::WebSocketClient client(url());
  25024. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25025. ASSERT_TRUE(client.connect());
  25026. ASSERT_TRUE(client.send("hello"));
  25027. std::string msg;
  25028. EXPECT_EQ(ws::Text, client.read(msg));
  25029. EXPECT_EQ("hello", msg);
  25030. client.close();
  25031. }
  25032. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25033. // while the identity check must still reject "localhost"
  25034. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25035. Start(SERVER_CERT_FILE);
  25036. ws::WebSocketClient client(url());
  25037. client.set_ca_cert_path(SERVER_CERT_FILE);
  25038. auto res = client.connect();
  25039. ASSERT_FALSE(res);
  25040. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25041. EXPECT_EQ(-1, res.status());
  25042. }
  25043. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25044. // disabled: the chain is still checked, only the identity check is skipped
  25045. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25046. Start(SERVER_CERT_FILE);
  25047. ws::WebSocketClient client(url());
  25048. client.set_ca_cert_path(SERVER_CERT_FILE);
  25049. client.enable_server_hostname_verification(false);
  25050. ASSERT_TRUE(client.connect());
  25051. ASSERT_TRUE(client.send("hello"));
  25052. std::string msg;
  25053. EXPECT_EQ(ws::Text, client.read(msg));
  25054. EXPECT_EQ("hello", msg);
  25055. client.close();
  25056. }
  25057. // A CA that did not sign the server certificate fails the chain, even though
  25058. // the name would match
  25059. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25060. Start(SERVER_CERT2_FILE);
  25061. ws::WebSocketClient client(url());
  25062. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25063. ASSERT_FALSE(client.connect());
  25064. }
  25065. // With verification disabled, neither the chain nor the name is checked
  25066. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25067. Start(SERVER_CERT_FILE);
  25068. ws::WebSocketClient client(url());
  25069. client.enable_server_certificate_verification(false);
  25070. ASSERT_TRUE(client.connect());
  25071. ASSERT_TRUE(client.send("hello"));
  25072. std::string msg;
  25073. EXPECT_EQ(ws::Text, client.read(msg));
  25074. EXPECT_EQ("hello", msg);
  25075. client.close();
  25076. }
  25077. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25078. protected:
  25079. void SetUp() override {
  25080. server_ = httplib::detail::make_unique<SSLServer>(
  25081. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25082. ASSERT_TRUE(server_->is_valid());
  25083. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25084. std::string msg;
  25085. while (ws.read(msg)) {
  25086. ws.send(msg);
  25087. }
  25088. });
  25089. port_ = server_->bind_to_any_port("localhost");
  25090. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25091. server_->wait_until_ready();
  25092. }
  25093. void TearDown() override {
  25094. server_->stop();
  25095. if (server_thread_.joinable()) { server_thread_.join(); }
  25096. }
  25097. std::string url() const {
  25098. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25099. }
  25100. void ConnectWithClientCert(const std::string &client_cert_file,
  25101. const std::string &client_private_key_file,
  25102. const char *private_key_password) {
  25103. std::string cert_pem, key_pem;
  25104. read_file(client_cert_file, cert_pem);
  25105. read_file(client_private_key_file, key_pem);
  25106. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25107. key_pem.c_str(), key_pem.size(),
  25108. private_key_password};
  25109. ConnectWithPem(pem);
  25110. }
  25111. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25112. ws::WebSocketClient client(url(), pem);
  25113. ASSERT_TRUE(client.is_valid());
  25114. client.enable_server_certificate_verification(false);
  25115. ASSERT_TRUE(client.connect());
  25116. ASSERT_TRUE(client.send("hello"));
  25117. std::string msg;
  25118. EXPECT_EQ(ws::Text, client.read(msg));
  25119. EXPECT_EQ("hello", msg);
  25120. client.close();
  25121. }
  25122. std::unique_ptr<SSLServer> server_;
  25123. std::thread server_thread_;
  25124. int port_ = 0;
  25125. };
  25126. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25127. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25128. }
  25129. // Control for the tests above: the fixture's server really does require a
  25130. // client certificate, so it is the PEM the constructor installed that decides
  25131. // the outcome.
  25132. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25133. ws::WebSocketClient client(url());
  25134. ASSERT_TRUE(client.is_valid());
  25135. client.enable_server_certificate_verification(false);
  25136. EXPECT_FALSE(client.connect());
  25137. }
  25138. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25139. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25140. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25141. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25142. }
  25143. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25144. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25145. std::string cert_pem, key_pem;
  25146. read_file(CLIENT_CERT_FILE, cert_pem);
  25147. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25148. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25149. std::vector<char> key(key_pem.begin(), key_pem.end());
  25150. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25151. key.size(), nullptr};
  25152. ConnectWithPem(pem);
  25153. }
  25154. #endif
  25155. #if !defined(_WIN32)
  25156. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25157. auto secret_dir = std::string("./symlink_test_secret");
  25158. auto served_dir = std::string("./symlink_test_served");
  25159. auto secret_file = secret_dir + "/secret.txt";
  25160. auto symlink_path = served_dir + "/escape";
  25161. // Setup: create directories and files
  25162. mkdir(secret_dir.c_str(), 0755);
  25163. mkdir(served_dir.c_str(), 0755);
  25164. {
  25165. std::ofstream ofs(secret_file);
  25166. ofs << "SECRET_DATA";
  25167. }
  25168. // Create symlink using absolute path so it resolves correctly
  25169. #ifdef PATH_MAX
  25170. char abs_secret[PATH_MAX];
  25171. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25172. #else
  25173. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25174. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25175. ASSERT_NE(nullptr, abs_secret);
  25176. #endif
  25177. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25178. auto se = detail::scope_exit([&] {
  25179. unlink(symlink_path.c_str());
  25180. unlink(secret_file.c_str());
  25181. rmdir(served_dir.c_str());
  25182. rmdir(secret_dir.c_str());
  25183. });
  25184. Server svr;
  25185. svr.set_mount_point("/", served_dir);
  25186. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25187. auto se2 = detail::scope_exit([&] {
  25188. svr.stop();
  25189. listen_thread.join();
  25190. });
  25191. svr.wait_until_ready();
  25192. Client cli("localhost", PORT);
  25193. // Symlink pointing outside base dir should be blocked
  25194. auto res = cli.Get("/escape/secret.txt");
  25195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25196. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25197. }
  25198. #endif
  25199. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25200. // "GET /smuggled" request), reads the first response, and only then sends the
  25201. // embedded request as the body. Returns how many times /smuggled ran.
  25202. //
  25203. // The body is sent AFTER receiving the first response (as in the original
  25204. // PoC) so that the stream_line_reader cannot buffer it together with the
  25205. // headers of the first request.
  25206. static int count_smuggled_requests(const std::string &outer_head,
  25207. std::string &first_response) {
  25208. Server svr;
  25209. svr.set_mount_point("/", "./www");
  25210. std::atomic<int> smuggled_count(0);
  25211. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25212. smuggled_count++;
  25213. res.set_content("oops", "text/plain");
  25214. });
  25215. svr.Post("/post", [&](const Request &req, Response &res) {
  25216. res.set_content(req.body, "text/plain");
  25217. });
  25218. auto port = svr.bind_to_any_port("localhost");
  25219. thread t = thread([&] { svr.listen_after_bind(); });
  25220. auto se = detail::scope_exit([&] {
  25221. svr.stop();
  25222. t.join();
  25223. });
  25224. svr.wait_until_ready();
  25225. auto error = Error::Success;
  25226. auto sock = detail::create_client_socket(
  25227. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25228. /*connection_timeout_sec=*/2, 0,
  25229. /*read_timeout_sec=*/2, 0,
  25230. /*write_timeout_sec=*/2, 0, std::string(), error);
  25231. EXPECT_NE(INVALID_SOCKET, sock);
  25232. if (sock == INVALID_SOCKET) { return -1; }
  25233. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25234. // The "smuggled" request will be sent as the body of the outer request
  25235. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25236. "Host: localhost\r\n"
  25237. "Connection: close\r\n"
  25238. "\r\n";
  25239. auto head = outer_head;
  25240. auto len = std::to_string(smuggled.size());
  25241. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25242. pos = head.find("{len}", pos + len.size())) {
  25243. head.replace(pos, 5, len);
  25244. }
  25245. // Step 1: Send only the outer request headers (no body yet)
  25246. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25247. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25248. // Step 2: Read the first response
  25249. char buf[4096];
  25250. for (;;) {
  25251. auto n = recv(sock, buf, sizeof(buf), 0);
  25252. if (n <= 0) break;
  25253. first_response.append(buf, static_cast<size_t>(n));
  25254. // Stop once we have a complete response (headers + body)
  25255. auto hdr_end = first_response.find("\r\n\r\n");
  25256. if (hdr_end != std::string::npos) {
  25257. // Check for Content-Length to know when the body is complete
  25258. auto cl_pos = first_response.find("Content-Length:");
  25259. if (cl_pos != std::string::npos) {
  25260. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25261. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25262. auto cl = std::stoul(
  25263. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25264. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25265. } else {
  25266. break; // No Content-Length, assume headers-only response
  25267. }
  25268. }
  25269. }
  25270. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25271. // vulnerable server the keep-alive loop reads this as a second request. The
  25272. // server may already have closed the connection, so the result is ignored.
  25273. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25274. // Half-close so that a server which drained the body sees EOF and closes,
  25275. // instead of the read below waiting for the read timeout.
  25276. #ifdef _WIN32
  25277. ::shutdown(sock, SD_SEND);
  25278. #else
  25279. ::shutdown(sock, SHUT_WR);
  25280. #endif
  25281. // Step 4: Read until the server closes the connection
  25282. for (;;) {
  25283. auto n = recv(sock, buf, sizeof(buf), 0);
  25284. if (n <= 0) break;
  25285. }
  25286. return smuggled_count.load();
  25287. }
  25288. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25289. // A GET request with Content-Length to a static file handler must have its
  25290. // body drained before the keep-alive connection is reused. Otherwise the
  25291. // unread body bytes are interpreted as the next HTTP request.
  25292. std::string first_response;
  25293. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25294. "Host: localhost\r\n"
  25295. "Content-Length: {len}\r\n"
  25296. "\r\n",
  25297. first_response));
  25298. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25299. }
  25300. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25301. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25302. // be answered with 400 and the connection closed. Treating it as "no body"
  25303. // leaves the body to be parsed as the next request.
  25304. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25305. const char *targets[] = {
  25306. "GET /file", // handler that never reads the body
  25307. "GET /not-found", // no handler matches (404)
  25308. "POST /post", // handler that reads the body
  25309. };
  25310. for (auto target : targets) {
  25311. for (auto value : values) {
  25312. std::string first_response;
  25313. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25314. " HTTP/1.1\r\n"
  25315. "Host: localhost\r\n"
  25316. "Content-Length: " +
  25317. value + "\r\n\r\n",
  25318. first_response))
  25319. << target << " with Content-Length: " << value;
  25320. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25321. << target << " with Content-Length: " << value;
  25322. }
  25323. }
  25324. }
  25325. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25326. // A 400 for an unparseable request line leaves the rest of the message
  25327. // unread, so the connection must be closed rather than reused.
  25328. std::string first_response;
  25329. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25330. "Host: localhost\r\n"
  25331. "Content-Length: {len}\r\n"
  25332. "\r\n",
  25333. first_response));
  25334. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25335. }
  25336. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25337. // Same as above for a header block that fails to parse.
  25338. std::string first_response;
  25339. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25340. "Host: localhost\r\n"
  25341. "Bad Header\r\n"
  25342. "Content-Length: {len}\r\n"
  25343. "\r\n",
  25344. first_response));
  25345. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25346. }
  25347. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25348. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25349. // server must not read another request on that connection, even when the
  25350. // request had no body to drain.
  25351. std::string first_response;
  25352. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25353. "Host: localhost\r\n"
  25354. "\r\n",
  25355. first_response));
  25356. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25357. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25358. }
  25359. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25360. // A content reader that stops early leaves the stream inside the body.
  25361. // Draining the whole Content-Length from there, or reading the body again,
  25362. // reads into the next request, and whatever follows is parsed as a request
  25363. // of its own.
  25364. Server svr;
  25365. std::atomic<int> smuggled_count(0);
  25366. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25367. svr.Post("/upload", [](const Request &req, Response &res,
  25368. const ContentReader &content_reader) {
  25369. // Stop at the last chunk, so the whole body has been read however it
  25370. // arrives.
  25371. auto length = req.get_header_value_u64("Content-Length");
  25372. size_t total = 0;
  25373. auto consumed = content_reader([&](const char *, size_t n) {
  25374. total += n;
  25375. return total < length;
  25376. });
  25377. EXPECT_FALSE(consumed);
  25378. if (req.has_param("retry")) {
  25379. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25380. }
  25381. // Replace the 400 the aborted read set, which would close the connection.
  25382. res.set_redirect("/done");
  25383. });
  25384. auto port = svr.bind_to_any_port(HOST);
  25385. thread t = thread([&] { svr.listen_after_bind(); });
  25386. auto se = detail::scope_exit([&] {
  25387. svr.stop();
  25388. t.join();
  25389. });
  25390. svr.wait_until_ready();
  25391. // A front end sees the second request as a POST whose body is the GET. The
  25392. // first body is as long as the POST's headers, so draining it again reads
  25393. // exactly those and leaves the GET to be parsed next.
  25394. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25395. "Host: localhost\r\n"
  25396. "\r\n";
  25397. std::string second_head = "POST /post HTTP/1.1\r\n"
  25398. "Host: localhost\r\n"
  25399. "Content-Length: " +
  25400. std::to_string(inner.size()) +
  25401. "\r\n"
  25402. "\r\n";
  25403. for (auto target : {"/upload", "/upload?retry"}) {
  25404. smuggled_count = 0;
  25405. std::string request = "POST " + std::string(target) +
  25406. " HTTP/1.1\r\n"
  25407. "Host: localhost\r\n"
  25408. "Content-Length: " +
  25409. std::to_string(second_head.size()) +
  25410. "\r\n"
  25411. "\r\n" +
  25412. std::string(second_head.size(), 'A') + second_head +
  25413. inner;
  25414. std::string response;
  25415. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25416. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25417. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25418. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25419. EXPECT_EQ(0, smuggled_count.load()) << target;
  25420. }
  25421. }
  25422. // An error response closes the connection anyway, so the body is left unread
  25423. // with a redirect, such as one to a login page.
  25424. static void serve_redirects(Server &svr,
  25425. const std::function<void(int)> &client) {
  25426. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25427. res.set_redirect("/login");
  25428. return Server::HandlerResponse::Handled;
  25429. });
  25430. auto port = svr.bind_to_any_port(HOST);
  25431. ASSERT_GT(port, 0);
  25432. thread t = thread([&] { svr.listen_after_bind(); });
  25433. auto se = detail::scope_exit([&] {
  25434. svr.stop();
  25435. t.join();
  25436. ASSERT_FALSE(svr.is_running());
  25437. });
  25438. svr.wait_until_ready();
  25439. client(port);
  25440. }
  25441. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25442. Server svr;
  25443. serve_redirects(svr, [](int port) {
  25444. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25445. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25446. std::to_string(body.size()) + "\r\n\r\n" + body +
  25447. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25448. std::string resp;
  25449. ASSERT_TRUE(send_request(1, req, &resp, port));
  25450. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25451. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25452. });
  25453. }
  25454. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25455. Server svr;
  25456. svr.set_read_timeout(0, 200000);
  25457. serve_redirects(svr, [](int port) {
  25458. // A byte every 100 ms keeps each read within the read timeout, but not the
  25459. // body as a whole, so the server closes and the bytes sent after that fail.
  25460. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25461. "Content-Length: 10\r\n\r\n"};
  25462. parts.resize(11, "x");
  25463. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  25464. });
  25465. }
  25466. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25467. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25468. // must be rejected with 400 Bad Request.
  25469. Server svr;
  25470. svr.Post("/test", [&](const Request &, Response &res) {
  25471. res.set_content("ok", "text/plain");
  25472. });
  25473. thread t = thread([&] { svr.listen(HOST, PORT); });
  25474. auto se = detail::scope_exit([&] {
  25475. svr.stop();
  25476. t.join();
  25477. ASSERT_FALSE(svr.is_running());
  25478. });
  25479. svr.wait_until_ready();
  25480. // Exact "chunked"
  25481. {
  25482. auto req = "POST /test HTTP/1.1\r\n"
  25483. "Host: localhost\r\n"
  25484. "Content-Length: 5\r\n"
  25485. "Transfer-Encoding: chunked\r\n"
  25486. "Connection: close\r\n"
  25487. "\r\n"
  25488. "hello";
  25489. std::string response;
  25490. ASSERT_TRUE(send_request(1, req, &response));
  25491. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25492. response.substr(0, response.find("\r\n")));
  25493. }
  25494. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25495. {
  25496. auto req = "POST /test HTTP/1.1\r\n"
  25497. "Host: localhost\r\n"
  25498. "Content-Length: 5\r\n"
  25499. "Transfer-Encoding: gzip, chunked\r\n"
  25500. "Connection: close\r\n"
  25501. "\r\n"
  25502. "hello";
  25503. std::string response;
  25504. ASSERT_TRUE(send_request(1, req, &response));
  25505. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25506. response.substr(0, response.find("\r\n")));
  25507. }
  25508. }
  25509. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25510. Server svr;
  25511. svr.Post("/test", [&](const Request &, Response &res) {
  25512. res.set_content("ok", "text/plain");
  25513. });
  25514. thread t = thread([&] { svr.listen(HOST, PORT); });
  25515. auto se = detail::scope_exit([&] {
  25516. svr.stop();
  25517. t.join();
  25518. ASSERT_FALSE(svr.is_running());
  25519. });
  25520. svr.wait_until_ready();
  25521. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25522. // length cannot be determined, so the server must answer 400 and close
  25523. // rather than treat the request as bodyless and leave the body in the
  25524. // socket for the next request to pick up.
  25525. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25526. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25527. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25528. std::string response;
  25529. ASSERT_TRUE(send_request(1, req, &response));
  25530. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25531. response.substr(0, response.find("\r\n")))
  25532. << transfer_encoding;
  25533. }
  25534. // RFC 9110 5.3: the codings may also be split across several
  25535. // Transfer-Encoding lines, which combine in the order they were received.
  25536. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25537. // just like the single-line "chunked, gzip" above.
  25538. {
  25539. auto req = "POST /test HTTP/1.1\r\n"
  25540. "Host: localhost\r\n"
  25541. "Transfer-Encoding: chunked\r\n"
  25542. "Transfer-Encoding: gzip\r\n"
  25543. "\r\n"
  25544. "0\r\n\r\n";
  25545. std::string response;
  25546. ASSERT_TRUE(send_request(1, req, &response));
  25547. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25548. response.substr(0, response.find("\r\n")));
  25549. }
  25550. }
  25551. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25552. Server svr;
  25553. svr.Post("/test", [&](const Request &, Response &res) {
  25554. res.set_content("ok", "text/plain");
  25555. });
  25556. auto port = svr.bind_to_any_port(HOST);
  25557. ASSERT_GT(port, 0);
  25558. thread t = thread([&] { svr.listen_after_bind(); });
  25559. auto se = detail::scope_exit([&] {
  25560. svr.stop();
  25561. t.join();
  25562. ASSERT_FALSE(svr.is_running());
  25563. });
  25564. svr.wait_until_ready();
  25565. for (auto transfer_encoding :
  25566. {"Transfer-Encoding: gzip, chunked\r\n",
  25567. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25568. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25569. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25570. transfer_encoding + "\r\n0\r\n\r\n";
  25571. std::string response;
  25572. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25573. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25574. response.substr(0, response.find("\r\n")))
  25575. << transfer_encoding;
  25576. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25577. << transfer_encoding;
  25578. }
  25579. }
  25580. // Regression for issue #2450: a DELETE without Content-Length on a
  25581. // keep-alive connection must not let the post-response drain consume the
  25582. // next request's bytes.
  25583. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25584. Server svr;
  25585. std::atomic<int> delete_count(0);
  25586. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25587. delete_count++;
  25588. res.status = StatusCode::NoContent_204;
  25589. });
  25590. auto port = svr.bind_to_any_port(HOST);
  25591. thread t = thread([&] { svr.listen_after_bind(); });
  25592. auto se = detail::scope_exit([&] {
  25593. svr.stop();
  25594. t.join();
  25595. });
  25596. svr.wait_until_ready();
  25597. auto error = Error::Success;
  25598. auto sock = detail::create_client_socket(
  25599. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25600. /*connection_timeout_sec=*/2, 0,
  25601. /*read_timeout_sec=*/2, 0,
  25602. /*write_timeout_sec=*/2, 0, std::string(), error);
  25603. ASSERT_NE(INVALID_SOCKET, sock);
  25604. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25605. auto send_request_and_read_response = [&](const std::string &req,
  25606. std::string &out) -> bool {
  25607. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25608. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25609. char buf[4096];
  25610. for (;;) {
  25611. auto n = recv(sock, buf, sizeof(buf), 0);
  25612. if (n <= 0) { return !out.empty(); }
  25613. out.append(buf, static_cast<size_t>(n));
  25614. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25615. }
  25616. };
  25617. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25618. "Host: localhost\r\n"
  25619. "\r\n";
  25620. std::string resp1;
  25621. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25622. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25623. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25624. "Host: localhost\r\n"
  25625. "Connection: close\r\n"
  25626. "\r\n";
  25627. std::string resp2;
  25628. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25629. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25630. EXPECT_EQ(2, delete_count.load());
  25631. }
  25632. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25633. Server svr;
  25634. svr.Post("/ingest", [&](const Request &, Response &res,
  25635. const ContentReader &content_reader) {
  25636. auto consumed = content_reader([](const char *, size_t) { return false; });
  25637. EXPECT_FALSE(consumed);
  25638. res.status = StatusCode::Conflict_409;
  25639. res.set_header("Connection", "close");
  25640. });
  25641. auto port = svr.bind_to_any_port(HOST);
  25642. thread t = thread([&] { svr.listen_after_bind(); });
  25643. auto se = detail::scope_exit([&] {
  25644. svr.stop();
  25645. t.join();
  25646. });
  25647. svr.wait_until_ready();
  25648. auto error = Error::Success;
  25649. auto sock = detail::create_client_socket(
  25650. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25651. /*connection_timeout_sec=*/2, 0,
  25652. /*read_timeout_sec=*/1, 0,
  25653. /*write_timeout_sec=*/2, 0, std::string(), error);
  25654. ASSERT_NE(INVALID_SOCKET, sock);
  25655. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25656. std::string request = "POST /ingest HTTP/1.1\r\n"
  25657. "Host: localhost\r\n"
  25658. "Transfer-Encoding: chunked\r\n"
  25659. "\r\n"
  25660. "4\r\n"
  25661. "data\r\n";
  25662. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25663. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25664. std::string response;
  25665. ssize_t received = 0;
  25666. do {
  25667. char buf[4096];
  25668. received = recv(sock, buf, sizeof(buf), 0);
  25669. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25670. } while (received > 0);
  25671. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25672. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25673. EXPECT_EQ(0, received);
  25674. }
  25675. namespace no_proxy_test {
  25676. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25677. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25678. // calling listen().
  25679. class ScopedServer {
  25680. public:
  25681. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25682. ~ScopedServer() {
  25683. svr_.stop();
  25684. if (th_.joinable()) { th_.join(); }
  25685. }
  25686. Server &svr() { return svr_; }
  25687. int port() const { return port_; }
  25688. void listen() {
  25689. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25690. svr_.wait_until_ready();
  25691. }
  25692. private:
  25693. Server svr_;
  25694. std::thread th_;
  25695. int port_ = 0;
  25696. };
  25697. class ProxyAndTargetServers {
  25698. public:
  25699. ProxyAndTargetServers() {
  25700. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25701. proxy_hits_++;
  25702. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25703. res.set_content("via-proxy", "text/plain");
  25704. });
  25705. target_.Get(".*", [this](const Request &req, Response &res) {
  25706. target_hits_++;
  25707. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25708. res.set_content("direct", "text/plain");
  25709. });
  25710. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25711. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25712. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25713. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25714. proxy_mock_.wait_until_ready();
  25715. target_.wait_until_ready();
  25716. }
  25717. ~ProxyAndTargetServers() {
  25718. proxy_mock_.stop();
  25719. target_.stop();
  25720. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25721. if (target_thread_.joinable()) { target_thread_.join(); }
  25722. }
  25723. Server &proxy_mock() { return proxy_mock_; }
  25724. Server &target() { return target_; }
  25725. int proxy_port() const { return proxy_port_; }
  25726. int target_port() const { return target_port_; }
  25727. int proxy_hits() const { return proxy_hits_.load(); }
  25728. int target_hits() const { return target_hits_.load(); }
  25729. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25730. void reset_counters() {
  25731. proxy_hits_ = 0;
  25732. target_hits_ = 0;
  25733. last_had_proxy_authz_ = false;
  25734. }
  25735. private:
  25736. Server proxy_mock_;
  25737. Server target_;
  25738. std::thread proxy_thread_;
  25739. std::thread target_thread_;
  25740. int proxy_port_ = 0;
  25741. int target_port_ = 0;
  25742. std::atomic<int> proxy_hits_{0};
  25743. std::atomic<int> target_hits_{0};
  25744. std::atomic<bool> last_had_proxy_authz_{false};
  25745. };
  25746. inline std::unique_ptr<Client> make_client(const std::string &host,
  25747. ProxyAndTargetServers &s) {
  25748. auto cli = detail::make_unique<Client>(host, s.target_port());
  25749. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25750. cli->set_proxy("127.0.0.1", s.proxy_port());
  25751. return cli;
  25752. }
  25753. } // namespace no_proxy_test
  25754. using no_proxy_test::make_client;
  25755. using no_proxy_test::ProxyAndTargetServers;
  25756. // A stream request carries the credentials a buffered request does
  25757. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25758. no_proxy_test::ScopedServer origin;
  25759. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25760. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25761. });
  25762. origin.listen();
  25763. Client cli("127.0.0.1", origin.port());
  25764. cli.set_basic_auth("user", "pass");
  25765. auto handle = cli.open_stream("GET", "/x");
  25766. ASSERT_TRUE(handle.is_valid());
  25767. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25768. Client bearer("127.0.0.1", origin.port());
  25769. bearer.set_bearer_token_auth("tok");
  25770. auto handle2 = bearer.open_stream("GET", "/x");
  25771. ASSERT_TRUE(handle2.is_valid());
  25772. EXPECT_EQ("Bearer tok", read_all(handle2));
  25773. }
  25774. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25775. // takes its own credentials, as for a buffered request
  25776. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25777. std::string target, authz, proxy_authz;
  25778. no_proxy_test::ScopedServer proxy;
  25779. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25780. target = req.target;
  25781. authz = req.get_header_value("Authorization");
  25782. proxy_authz = req.get_header_value("Proxy-Authorization");
  25783. res.set_content("ok", "text/plain");
  25784. });
  25785. proxy.listen();
  25786. Client cli("origin.example", 8080);
  25787. cli.set_proxy("127.0.0.1", proxy.port());
  25788. cli.set_proxy_basic_auth("puser", "ppass");
  25789. cli.set_basic_auth("user", "pass");
  25790. auto handle = cli.open_stream("GET", "/x");
  25791. ASSERT_TRUE(handle.is_valid());
  25792. EXPECT_EQ("ok", read_all(handle));
  25793. EXPECT_EQ("http://origin.example:8080/x", target);
  25794. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25795. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25796. }
  25797. // In absolute-form the path follows the authority, so a path that does not
  25798. // begin with '/' would make the proxy connect to another host
  25799. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  25800. std::vector<std::string> targets;
  25801. no_proxy_test::ScopedServer proxy;
  25802. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25803. targets.push_back(req.target);
  25804. res.set_content("ok", "text/plain");
  25805. });
  25806. proxy.listen();
  25807. Client cli("origin.example", 8080);
  25808. cli.set_proxy("127.0.0.1", proxy.port());
  25809. cli.set_basic_auth("user", "pass");
  25810. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  25811. auto res = cli.Get(path);
  25812. EXPECT_FALSE(res) << path;
  25813. auto handle = cli.open_stream("GET", path);
  25814. EXPECT_FALSE(handle.is_valid()) << path;
  25815. }
  25816. EXPECT_TRUE(targets.empty());
  25817. auto res = cli.Get("/x");
  25818. ASSERT_TRUE(res);
  25819. ASSERT_EQ(1u, targets.size());
  25820. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  25821. }
  25822. TEST(NoProxyTest, ExactHostnameBypasses) {
  25823. ProxyAndTargetServers s;
  25824. auto cli = make_client("example.com", s);
  25825. cli->set_no_proxy({"example.com"});
  25826. auto res = cli->Get("/");
  25827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25828. EXPECT_EQ(0, s.proxy_hits());
  25829. EXPECT_EQ(1, s.target_hits());
  25830. }
  25831. TEST(NoProxyTest, SubdomainBypasses) {
  25832. ProxyAndTargetServers s;
  25833. auto cli = make_client("foo.example.com", s);
  25834. cli->set_no_proxy({"example.com"});
  25835. auto res = cli->Get("/");
  25836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25837. EXPECT_EQ(0, s.proxy_hits());
  25838. EXPECT_EQ(1, s.target_hits());
  25839. }
  25840. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25841. // Regression guard: "evilexample.com" must not be considered a subdomain
  25842. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25843. // check would let traffic bypass the proxy and leak credentials direct
  25844. // to the attacker host.
  25845. ProxyAndTargetServers s;
  25846. auto cli = make_client("evilexample.com", s);
  25847. cli->set_no_proxy({"example.com"});
  25848. auto res = cli->Get("/");
  25849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25850. EXPECT_GE(s.proxy_hits(), 1);
  25851. EXPECT_EQ(0, s.target_hits());
  25852. }
  25853. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25854. ProxyAndTargetServers s;
  25855. auto cli = make_client("example.com.evil.com", s);
  25856. cli->set_no_proxy({"example.com"});
  25857. auto res = cli->Get("/");
  25858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25859. EXPECT_GE(s.proxy_hits(), 1);
  25860. EXPECT_EQ(0, s.target_hits());
  25861. }
  25862. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25863. ProxyAndTargetServers s;
  25864. auto cli = make_client("example.com", s);
  25865. cli->set_no_proxy({".example.com"});
  25866. auto res = cli->Get("/");
  25867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25868. EXPECT_EQ(0, s.proxy_hits());
  25869. EXPECT_EQ(1, s.target_hits());
  25870. }
  25871. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25872. ProxyAndTargetServers s;
  25873. auto cli = make_client("Example.COM", s);
  25874. cli->set_no_proxy({"EXAMPLE.com"});
  25875. auto res = cli->Get("/");
  25876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25877. EXPECT_EQ(0, s.proxy_hits());
  25878. EXPECT_EQ(1, s.target_hits());
  25879. }
  25880. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25881. ProxyAndTargetServers s;
  25882. auto cli = make_client("example.com.", s);
  25883. cli->set_no_proxy({"example.com"});
  25884. auto res = cli->Get("/");
  25885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25886. EXPECT_EQ(0, s.proxy_hits());
  25887. EXPECT_EQ(1, s.target_hits());
  25888. }
  25889. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25890. // Trailing dots must be normalized on BOTH sides — host and entry.
  25891. // An implementation that only strips the host-side trailing dot would
  25892. // fail to match host "example.com" against entry "example.com." because
  25893. // a literal substring search would compare 11 chars against 12.
  25894. ProxyAndTargetServers s;
  25895. auto cli = make_client("example.com", s);
  25896. cli->set_no_proxy({"example.com."});
  25897. auto res = cli->Get("/");
  25898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25899. EXPECT_EQ(0, s.proxy_hits());
  25900. EXPECT_EQ(1, s.target_hits());
  25901. }
  25902. TEST(NoProxyTest, WildcardBypassesEverything) {
  25903. ProxyAndTargetServers s;
  25904. auto cli = make_client("anything.invalid.test", s);
  25905. cli->set_no_proxy({"*"});
  25906. auto res = cli->Get("/");
  25907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25908. EXPECT_EQ(0, s.proxy_hits());
  25909. EXPECT_EQ(1, s.target_hits());
  25910. }
  25911. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25912. ProxyAndTargetServers s;
  25913. Client cli("127.0.0.1", s.target_port());
  25914. cli.set_proxy("127.0.0.1", s.proxy_port());
  25915. cli.set_no_proxy({"127.0.0.1"});
  25916. auto res = cli.Get("/");
  25917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25918. EXPECT_EQ(0, s.proxy_hits());
  25919. EXPECT_EQ(1, s.target_hits());
  25920. }
  25921. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25922. ProxyAndTargetServers s;
  25923. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25924. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25925. cli.set_proxy("127.0.0.1", s.proxy_port());
  25926. cli.set_no_proxy({"::1"});
  25927. auto res = cli.Get("/");
  25928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25929. EXPECT_EQ(0, s.proxy_hits());
  25930. EXPECT_EQ(1, s.target_hits());
  25931. }
  25932. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25933. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25934. // must still be recognized as IPv6 for CIDR matching. Implementations
  25935. // that detect IPv6 only when the host begins with '[' would parse the
  25936. // host as a hostname and miss the match.
  25937. ProxyAndTargetServers s;
  25938. Client cli("fe80::1", s.target_port());
  25939. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25940. cli.set_proxy("127.0.0.1", s.proxy_port());
  25941. cli.set_no_proxy({"fe80::/10"});
  25942. auto res = cli.Get("/");
  25943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25944. EXPECT_EQ(0, s.proxy_hits());
  25945. EXPECT_EQ(1, s.target_hits());
  25946. }
  25947. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25948. ProxyAndTargetServers s;
  25949. Client cli("::1", s.target_port());
  25950. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25951. cli.set_proxy("127.0.0.1", s.proxy_port());
  25952. cli.set_no_proxy({"[::1]"});
  25953. auto res = cli.Get("/");
  25954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25955. EXPECT_EQ(0, s.proxy_hits());
  25956. EXPECT_EQ(1, s.target_hits());
  25957. }
  25958. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25959. ProxyAndTargetServers s;
  25960. Client cli("fe80::1", s.target_port());
  25961. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25962. cli.set_proxy("127.0.0.1", s.proxy_port());
  25963. cli.set_no_proxy({"[fe80::]/10"});
  25964. auto res = cli.Get("/");
  25965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25966. EXPECT_EQ(0, s.proxy_hits());
  25967. EXPECT_EQ(1, s.target_hits());
  25968. }
  25969. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25970. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25971. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25972. // tricks via address-family conversion.
  25973. ProxyAndTargetServers s;
  25974. Client cli("::ffff:127.0.0.1", s.target_port());
  25975. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25976. cli.set_proxy("127.0.0.1", s.proxy_port());
  25977. cli.set_no_proxy({"127.0.0.1"});
  25978. auto res = cli.Get("/");
  25979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25980. EXPECT_GE(s.proxy_hits(), 1);
  25981. EXPECT_EQ(0, s.target_hits());
  25982. }
  25983. TEST(NoProxyTest, IPv4CidrMatch) {
  25984. ProxyAndTargetServers s;
  25985. Client cli("127.0.0.1", s.target_port());
  25986. cli.set_proxy("127.0.0.1", s.proxy_port());
  25987. cli.set_no_proxy({"127.0.0.0/8"});
  25988. auto res = cli.Get("/");
  25989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25990. EXPECT_EQ(0, s.proxy_hits());
  25991. EXPECT_EQ(1, s.target_hits());
  25992. }
  25993. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25994. ProxyAndTargetServers s;
  25995. Client cli("127.0.0.1", s.target_port());
  25996. cli.set_proxy("127.0.0.1", s.proxy_port());
  25997. cli.set_no_proxy({"10.0.0.0/8"});
  25998. auto res = cli.Get("/");
  25999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26000. EXPECT_GE(s.proxy_hits(), 1);
  26001. EXPECT_EQ(0, s.target_hits());
  26002. }
  26003. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26004. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26005. // IPv4 target matches.
  26006. ProxyAndTargetServers s;
  26007. Client cli("127.0.0.1", s.target_port());
  26008. cli.set_proxy("127.0.0.1", s.proxy_port());
  26009. cli.set_no_proxy({"0.0.0.0/0"});
  26010. auto res = cli.Get("/");
  26011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26012. EXPECT_EQ(0, s.proxy_hits());
  26013. EXPECT_EQ(1, s.target_hits());
  26014. }
  26015. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26016. ProxyAndTargetServers s;
  26017. Client cli("127.0.0.1", s.target_port());
  26018. cli.set_proxy("127.0.0.1", s.proxy_port());
  26019. cli.set_no_proxy({"127.0.0.1"});
  26020. auto res = cli.Get("/");
  26021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26022. EXPECT_EQ(0, s.proxy_hits());
  26023. EXPECT_EQ(1, s.target_hits());
  26024. }
  26025. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26026. ProxyAndTargetServers s;
  26027. Client cli("127.0.0.1", s.target_port());
  26028. cli.set_proxy("127.0.0.1", s.proxy_port());
  26029. cli.set_no_proxy({"127.0.0.0/33"});
  26030. auto res = cli.Get("/");
  26031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26032. EXPECT_GE(s.proxy_hits(), 1);
  26033. EXPECT_EQ(0, s.target_hits());
  26034. }
  26035. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26036. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26037. ProxyAndTargetServers s;
  26038. Client cli("127.0.0.1", s.target_port());
  26039. cli.set_proxy("127.0.0.1", s.proxy_port());
  26040. cli.set_no_proxy({"127.0.0.1/"});
  26041. auto res = cli.Get("/");
  26042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26043. EXPECT_GE(s.proxy_hits(), 1);
  26044. EXPECT_EQ(0, s.target_hits());
  26045. }
  26046. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26047. ProxyAndTargetServers s;
  26048. auto cli = make_client("internal.corp", s);
  26049. cli->set_proxy_basic_auth("u", "p");
  26050. cli->set_no_proxy({"internal.corp"});
  26051. auto res = cli->Get("/");
  26052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26053. EXPECT_EQ(1, s.target_hits());
  26054. EXPECT_EQ(0, s.proxy_hits());
  26055. EXPECT_FALSE(s.last_had_proxy_authz())
  26056. << "Proxy-Authorization must not be sent direct to the target";
  26057. }
  26058. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26059. ProxyAndTargetServers s;
  26060. auto cli = make_client("public.example", s);
  26061. cli->set_proxy_basic_auth("u", "p");
  26062. cli->set_no_proxy({"internal.corp"}); // does not match
  26063. auto res = cli->Get("/");
  26064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26065. EXPECT_GE(s.proxy_hits(), 1);
  26066. EXPECT_TRUE(s.last_had_proxy_authz());
  26067. }
  26068. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26069. std::atomic<int> hits{0};
  26070. std::atomic<int> hits_with_authz{0};
  26071. no_proxy_test::ScopedServer proxy_mock;
  26072. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26073. hits++;
  26074. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26075. if (req.target.find("/redir") != std::string::npos) {
  26076. res.set_redirect("http://other.example/landed");
  26077. } else {
  26078. res.set_content("via-proxy", "text/plain");
  26079. }
  26080. });
  26081. proxy_mock.listen();
  26082. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26083. hits = 0;
  26084. hits_with_authz = 0;
  26085. Client cli("public.example", 80);
  26086. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26087. cli.set_proxy_basic_auth(c.first, c.second);
  26088. cli.set_follow_location(true);
  26089. // The redirect to another host goes through the proxy as well
  26090. auto res = cli.Get("/redir");
  26091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26092. EXPECT_EQ(2, hits.load());
  26093. EXPECT_EQ(2, hits_with_authz.load());
  26094. }
  26095. }
  26096. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26097. ProxyAndTargetServers s;
  26098. auto cli = make_client("anything.test", s);
  26099. auto res = cli->Get("/");
  26100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26101. EXPECT_GE(s.proxy_hits(), 1);
  26102. EXPECT_EQ(0, s.target_hits());
  26103. }
  26104. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26105. ProxyAndTargetServers s;
  26106. auto cli = make_client("example.com", s);
  26107. cli->set_no_proxy({"example.com:8080"});
  26108. auto res = cli->Get("/");
  26109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26110. EXPECT_GE(s.proxy_hits(), 1);
  26111. EXPECT_EQ(0, s.target_hits());
  26112. }
  26113. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26114. ProxyAndTargetServers s;
  26115. auto cli = make_client("anything.test", s);
  26116. cli->set_no_proxy({"", " ", "\t"});
  26117. auto res = cli->Get("/");
  26118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26119. EXPECT_GE(s.proxy_hits(), 1);
  26120. EXPECT_EQ(0, s.target_hits());
  26121. }
  26122. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26123. // An entry with leading/trailing whitespace must still match — env-style
  26124. // values are commonly pasted with stray spaces and an implementation
  26125. // that feeds the raw token directly to inet_pton would fail to match
  26126. // valid CIDRs because of the spaces.
  26127. ProxyAndTargetServers s;
  26128. Client cli("127.0.0.1", s.target_port());
  26129. cli.set_proxy("127.0.0.1", s.proxy_port());
  26130. cli.set_no_proxy({" 127.0.0.0/8 "});
  26131. auto res = cli.Get("/");
  26132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26133. EXPECT_EQ(0, s.proxy_hits());
  26134. EXPECT_EQ(1, s.target_hits());
  26135. }
  26136. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26137. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26138. // go direct and must NOT carry Proxy-Authorization.
  26139. std::atomic<int> proxy_hits{0};
  26140. std::atomic<int> target_hits{0};
  26141. std::atomic<bool> target_saw_authz{false};
  26142. no_proxy_test::ScopedServer proxy_mock, target;
  26143. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26144. proxy_hits++;
  26145. res.status = 302;
  26146. res.set_header("Location", "http://127.0.0.1:" +
  26147. std::to_string(target.port()) + "/landed");
  26148. });
  26149. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26150. target_hits++;
  26151. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26152. res.set_content("direct", "text/plain");
  26153. });
  26154. proxy_mock.listen();
  26155. target.listen();
  26156. Client cli("public.example", target.port());
  26157. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26158. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26159. cli.set_proxy_basic_auth("u", "p");
  26160. cli.set_no_proxy({"127.0.0.1"});
  26161. cli.set_follow_location(true);
  26162. auto res = cli.Get("/redir");
  26163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26164. EXPECT_GE(proxy_hits.load(), 1);
  26165. EXPECT_GE(target_hits.load(), 1);
  26166. EXPECT_FALSE(target_saw_authz.load());
  26167. }
  26168. #ifdef CPPHTTPLIB_SSL_ENABLED
  26169. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26170. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26171. // proxy creds would be sent to the (possibly hostile) origin.
  26172. std::atomic<int> target_hits{0};
  26173. std::atomic<bool> target_saw_proxy_authz{false};
  26174. no_proxy_test::ScopedServer target;
  26175. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26176. target_hits++;
  26177. if (req.has_header("Proxy-Authorization")) {
  26178. target_saw_proxy_authz = true;
  26179. }
  26180. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26181. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26182. "nonce=\"abc\", algorithm=MD5");
  26183. });
  26184. target.listen();
  26185. // The proxy address is set to the target's port: the bypass MUST kick in;
  26186. // if it doesn't, the test still routes "via proxy" to the same server and
  26187. // the Proxy-Authorization assertion below catches the leak.
  26188. Client cli("evil.example", target.port());
  26189. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26190. cli.set_proxy("127.0.0.1", target.port());
  26191. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26192. cli.set_no_proxy({"evil.example"});
  26193. auto res = cli.Get("/x");
  26194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26195. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26196. EXPECT_EQ(1, target_hits.load());
  26197. EXPECT_FALSE(target_saw_proxy_authz.load());
  26198. }
  26199. #endif
  26200. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26201. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26202. std::atomic<int> proxy_hits{0};
  26203. std::atomic<int> bypass_hits{0};
  26204. std::atomic<bool> proxy_saw_c_url{false};
  26205. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26206. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26207. proxy_hits++;
  26208. if (req.path.find("/start") != std::string::npos) {
  26209. res.status = 302;
  26210. res.set_header("Location", "http://127.0.0.1:" +
  26211. std::to_string(bypass_server.port()) +
  26212. "/middle");
  26213. return;
  26214. }
  26215. if (req.path.find("/end") != std::string::npos) {
  26216. proxy_saw_c_url = true;
  26217. res.set_content("c-via-proxy", "text/plain");
  26218. return;
  26219. }
  26220. res.set_content("unexpected", "text/plain");
  26221. });
  26222. // public.example's "advertised" port is arbitrary (the request never lands
  26223. // there — it goes through the proxy), but use a dynamic value to stay
  26224. // friendly with sharded parallel runs.
  26225. int public_port = bypass_server.port();
  26226. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26227. bypass_hits++;
  26228. res.status = 302;
  26229. res.set_header("Location", "http://public.example:" +
  26230. std::to_string(public_port) + "/end");
  26231. });
  26232. proxy_mock.listen();
  26233. bypass_server.listen();
  26234. Client cli("public.example", public_port);
  26235. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26236. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26237. cli.set_no_proxy({"127.0.0.1"});
  26238. cli.set_follow_location(true);
  26239. auto res = cli.Get("/start");
  26240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26241. EXPECT_EQ(StatusCode::OK_200, res->status);
  26242. EXPECT_EQ("c-via-proxy", res->body);
  26243. EXPECT_GE(proxy_hits.load(), 2);
  26244. EXPECT_GE(bypass_hits.load(), 1);
  26245. EXPECT_TRUE(proxy_saw_c_url.load());
  26246. }
  26247. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26248. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26249. // request reconnects to the correct endpoint.
  26250. std::atomic<int> proxy_hits{0};
  26251. std::atomic<int> target_hits{0};
  26252. no_proxy_test::ScopedServer proxy_mock, target;
  26253. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26254. proxy_hits++;
  26255. res.set_content("via-proxy", "text/plain");
  26256. });
  26257. target.svr().Get(".*", [&](const Request &, Response &res) {
  26258. target_hits++;
  26259. res.set_content("direct", "text/plain");
  26260. });
  26261. proxy_mock.listen();
  26262. target.listen();
  26263. Client cli("public.example", target.port());
  26264. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26265. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26266. cli.set_keep_alive(true);
  26267. auto res1 = cli.Get("/a");
  26268. ASSERT_TRUE(res1);
  26269. EXPECT_EQ("via-proxy", res1->body);
  26270. EXPECT_EQ(1, proxy_hits.load());
  26271. EXPECT_EQ(0, target_hits.load());
  26272. cli.set_no_proxy({"public.example"});
  26273. auto res2 = cli.Get("/b");
  26274. ASSERT_TRUE(res2);
  26275. EXPECT_EQ("direct", res2->body);
  26276. EXPECT_EQ(1, proxy_hits.load());
  26277. EXPECT_EQ(1, target_hits.load());
  26278. }
  26279. // Forward declarations (see the base64_encode note).
  26280. namespace httplib {
  26281. namespace detail {
  26282. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26283. int shutdown_socket(socket_t sock) noexcept;
  26284. } // namespace detail
  26285. } // namespace httplib
  26286. namespace proxy_tunnel_test {
  26287. const char *const kTunnelEstablished =
  26288. "HTTP/1.1 200 Connection established\r\n\r\n";
  26289. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26290. using ConnectReply = std::function<std::string(const std::string &head)>;
  26291. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26292. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26293. class ScopedConnectProxy {
  26294. public:
  26295. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26296. : forward_port_(forward_port), reply_(std::move(reply)) {
  26297. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26298. if (listen_sock_ == INVALID_SOCKET) { return; }
  26299. auto a = loopback(0);
  26300. auto addr = reinterpret_cast<sockaddr *>(&a);
  26301. socklen_t alen = sizeof(a);
  26302. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26303. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26304. ::listen(listen_sock_, 4) != 0) {
  26305. return;
  26306. }
  26307. port_ = ntohs(a.sin_port);
  26308. th_ = std::thread([this] { run(); });
  26309. }
  26310. ~ScopedConnectProxy() {
  26311. if (th_.joinable()) {
  26312. stop_ = true;
  26313. auto wake = connect_to(port_);
  26314. th_.join();
  26315. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26316. }
  26317. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26318. }
  26319. int port() const { return port_; }
  26320. int connect_hits() const { return connect_hits_.load(); }
  26321. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26322. std::string connect_request() const {
  26323. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26324. return connect_request_;
  26325. }
  26326. private:
  26327. static sockaddr_in loopback(int port) {
  26328. sockaddr_in a{};
  26329. a.sin_family = AF_INET;
  26330. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26331. a.sin_port = htons(static_cast<unsigned short>(port));
  26332. return a;
  26333. }
  26334. static socket_t connect_to(int port) {
  26335. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26336. if (sock == INVALID_SOCKET) { return sock; }
  26337. auto a = loopback(port);
  26338. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26339. detail::close_socket(sock);
  26340. return INVALID_SOCKET;
  26341. }
  26342. return sock;
  26343. }
  26344. static bool send_all(socket_t sock, const char *data, size_t size) {
  26345. while (size > 0) {
  26346. auto n = detail::send_socket(sock, data, size, 0);
  26347. if (n <= 0) { return false; }
  26348. data += n;
  26349. size -= static_cast<size_t>(n);
  26350. }
  26351. return true;
  26352. }
  26353. void run() {
  26354. for (;;) {
  26355. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26356. if (stop_) {
  26357. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26358. return;
  26359. }
  26360. if (client == INVALID_SOCKET) { continue; }
  26361. serve(client);
  26362. detail::close_socket(client);
  26363. }
  26364. }
  26365. void serve(socket_t client) {
  26366. std::string head;
  26367. char buf[2048];
  26368. while (head.find("\r\n\r\n") == std::string::npos) {
  26369. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26370. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26371. if (n <= 0) { return; }
  26372. head.append(buf, static_cast<size_t>(n));
  26373. }
  26374. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26375. connect_hits_++;
  26376. {
  26377. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26378. connect_request_ = head;
  26379. }
  26380. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26381. if (!send_all(client, res.data(), res.size()) ||
  26382. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26383. return;
  26384. }
  26385. auto origin = connect_to(forward_port_);
  26386. if (origin == INVALID_SOCKET) { return; }
  26387. // When either side stops, shut both down so the other pump returns too.
  26388. auto pump = [&](socket_t from, socket_t to) {
  26389. char b[8192];
  26390. for (;;) {
  26391. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26392. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26393. }
  26394. detail::shutdown_socket(client);
  26395. detail::shutdown_socket(origin);
  26396. };
  26397. std::thread up([&] { pump(client, origin); });
  26398. pump(origin, client);
  26399. up.join();
  26400. detail::close_socket(origin);
  26401. }
  26402. int forward_port_;
  26403. ConnectReply reply_;
  26404. socket_t listen_sock_ = INVALID_SOCKET;
  26405. int port_ = 0;
  26406. std::thread th_;
  26407. std::atomic<bool> stop_{false};
  26408. std::atomic<int> connect_hits_{0};
  26409. mutable std::mutex connect_request_mutex_;
  26410. std::string connect_request_;
  26411. };
  26412. } // namespace proxy_tunnel_test
  26413. #ifdef CPPHTTPLIB_SSL_ENABLED
  26414. namespace proxy_tunnel_test {
  26415. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26416. class ScopedSSLServer {
  26417. public:
  26418. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26419. port_ = svr_.bind_to_any_port("127.0.0.1");
  26420. }
  26421. ~ScopedSSLServer() {
  26422. svr_.stop();
  26423. if (th_.joinable()) { th_.join(); }
  26424. }
  26425. SSLServer &svr() { return svr_; }
  26426. int port() const { return port_; }
  26427. void listen() {
  26428. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26429. svr_.wait_until_ready();
  26430. }
  26431. private:
  26432. SSLServer svr_;
  26433. std::thread th_;
  26434. int port_ = 0;
  26435. };
  26436. // Sends one request through the CONNECT proxy to the TLS origin with a
  26437. // credential configured for each hop, and checks that each credential reaches
  26438. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26439. // origin's (every header in origin_headers) on the tunnelled request.
  26440. void CredentialsStayWithTheirHop(
  26441. const std::function<void(SSLClient &)> &set_credentials,
  26442. const std::string &scheme,
  26443. const std::vector<std::string> &origin_headers = {"Authorization"},
  26444. bool stream = false) {
  26445. std::atomic<int> origin_hits{0};
  26446. std::atomic<bool> origin_saw_proxy_authz{false};
  26447. std::atomic<bool> origin_saw_headers{false};
  26448. ScopedSSLServer origin;
  26449. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26450. origin_hits++;
  26451. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26452. origin_saw_headers =
  26453. std::all_of(origin_headers.begin(), origin_headers.end(),
  26454. [&](const std::string &h) { return req.has_header(h); });
  26455. res.set_content("ok", "text/plain");
  26456. });
  26457. origin.listen();
  26458. ScopedConnectProxy proxy(origin.port());
  26459. ASSERT_NE(0, proxy.port());
  26460. // Pinned to 127.0.0.1 for the same reason as the test below.
  26461. SSLClient cli("127.0.0.1", origin.port());
  26462. cli.enable_server_certificate_verification(false);
  26463. cli.set_proxy("127.0.0.1", proxy.port());
  26464. set_credentials(cli);
  26465. if (stream) {
  26466. auto handle = cli.open_stream("GET", "/x");
  26467. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26468. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26469. } else {
  26470. auto res = cli.Get("/x");
  26471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26472. EXPECT_EQ(StatusCode::OK_200, res->status);
  26473. }
  26474. EXPECT_EQ(1, origin_hits.load());
  26475. EXPECT_EQ(1, proxy.connect_hits());
  26476. EXPECT_TRUE(origin_saw_headers.load());
  26477. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26478. << "Proxy-Authorization must not be sent inside the tunnel";
  26479. auto connect_req = proxy.connect_request();
  26480. EXPECT_NE(std::string::npos,
  26481. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26482. for (const auto &h : origin_headers) {
  26483. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26484. << h << " must not be sent to the proxy on CONNECT";
  26485. }
  26486. }
  26487. } // namespace proxy_tunnel_test
  26488. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26489. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26490. [](SSLClient &cli) {
  26491. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26492. cli.set_basic_auth("origin-user", "origin-pass");
  26493. },
  26494. "Basic");
  26495. }
  26496. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26497. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26498. [](SSLClient &cli) {
  26499. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26500. cli.set_basic_auth("origin-user", "origin-pass");
  26501. },
  26502. "Basic", {"Authorization"}, true);
  26503. }
  26504. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26505. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26506. [](SSLClient &cli) {
  26507. cli.set_proxy_bearer_token_auth("proxy-token");
  26508. cli.set_bearer_token_auth("origin-token");
  26509. },
  26510. "Bearer");
  26511. }
  26512. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26513. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26514. [](SSLClient &cli) {
  26515. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26516. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26517. {"Cookie", "sid=origin-session"},
  26518. {"X-Api-Key", "origin-key"}});
  26519. },
  26520. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26521. }
  26522. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26523. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26524. // retry; otherwise proxy creds would be sent to the origin.
  26525. std::atomic<int> origin_hits{0};
  26526. std::atomic<bool> origin_saw_proxy_authz{false};
  26527. proxy_tunnel_test::ScopedSSLServer origin;
  26528. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26529. origin_hits++;
  26530. if (req.has_header("Proxy-Authorization")) {
  26531. origin_saw_proxy_authz = true;
  26532. }
  26533. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26534. res.set_header("Proxy-Authenticate",
  26535. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26536. "algorithm=MD5");
  26537. });
  26538. origin.listen();
  26539. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26540. ASSERT_NE(0, proxy.port());
  26541. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26542. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26543. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26544. // and answer with its own status, making this test flaky.
  26545. SSLClient cli("127.0.0.1", origin.port());
  26546. cli.enable_server_certificate_verification(false);
  26547. cli.set_proxy("127.0.0.1", proxy.port());
  26548. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26549. auto res = cli.Get("/x");
  26550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26551. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26552. EXPECT_EQ(1, origin_hits.load());
  26553. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26554. EXPECT_EQ(1, proxy.connect_hits());
  26555. }
  26556. #endif
  26557. namespace proxy_tunnel_test {
  26558. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26559. // anything else gets a 407 with `challenge`.
  26560. ConnectReply require_proxy_auth(const std::string &expected,
  26561. const std::string &challenge) {
  26562. return [=](const std::string &head) -> std::string {
  26563. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26564. std::string::npos) {
  26565. return kTunnelEstablished;
  26566. }
  26567. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26568. "Proxy-Authenticate: " +
  26569. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26570. };
  26571. }
  26572. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26573. // request, then echoes.
  26574. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26575. ws.send(
  26576. "authorization:" + req.get_header_value("Authorization") +
  26577. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26578. std::string msg;
  26579. while (ws.read(msg)) {
  26580. ws.send(msg);
  26581. }
  26582. }
  26583. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26584. class ScopedWebSocketOrigin {
  26585. public:
  26586. ScopedWebSocketOrigin() {
  26587. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26588. server_.listen();
  26589. }
  26590. int port() const { return server_.port(); }
  26591. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26592. std::string url() const {
  26593. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26594. }
  26595. private:
  26596. no_proxy_test::ScopedServer server_;
  26597. };
  26598. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26599. // passed as a constructor header, and checks that each reaches only its hop.
  26600. void WebSocketCredentialsStayWithTheirHop(
  26601. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26602. const std::string &proxy_authz, const std::string &origin_authz) {
  26603. ScopedWebSocketOrigin origin;
  26604. ScopedConnectProxy proxy(
  26605. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26606. ASSERT_NE(0, proxy.port());
  26607. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26608. client.set_proxy("127.0.0.1", proxy.port());
  26609. set_proxy_credentials(client);
  26610. auto res = client.connect();
  26611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26612. std::string msg;
  26613. ASSERT_TRUE(client.read(msg));
  26614. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26615. client.close();
  26616. EXPECT_EQ(1, proxy.connect_hits());
  26617. EXPECT_EQ(std::string::npos,
  26618. proxy.connect_request().find("\r\nAuthorization: "))
  26619. << "origin credentials must not be sent to the proxy";
  26620. }
  26621. } // namespace proxy_tunnel_test
  26622. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26623. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26624. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26625. ASSERT_NE(0, proxy.port());
  26626. ws::WebSocketClient client(origin.url());
  26627. client.set_proxy("127.0.0.1", proxy.port());
  26628. auto res = client.connect();
  26629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26630. std::string msg;
  26631. ASSERT_TRUE(client.read(msg));
  26632. ASSERT_TRUE(client.send("hello"));
  26633. ASSERT_TRUE(client.read(msg));
  26634. EXPECT_EQ("hello", msg);
  26635. client.close();
  26636. EXPECT_EQ(1, proxy.connect_hits());
  26637. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26638. auto connect_req = proxy.connect_request();
  26639. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26640. EXPECT_NE(std::string::npos,
  26641. connect_req.find("\r\nHost: " + target + "\r\n"));
  26642. }
  26643. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26644. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26645. [](ws::WebSocketClient &cli) {
  26646. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26647. },
  26648. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26649. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26650. }
  26651. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26652. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26653. [](ws::WebSocketClient &cli) {
  26654. cli.set_proxy_bearer_token_auth("proxy-token");
  26655. },
  26656. "Bearer proxy-token", "Bearer origin-token");
  26657. }
  26658. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26659. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26660. proxy_tunnel_test::ScopedConnectProxy proxy(
  26661. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26662. "Basic " + detail::base64_encode("proxy-user:"),
  26663. "Basic realm=\"proxy\""));
  26664. ASSERT_NE(0, proxy.port());
  26665. ws::WebSocketClient client(origin.url());
  26666. client.set_proxy("127.0.0.1", proxy.port());
  26667. client.set_proxy_basic_auth("proxy-user", "");
  26668. auto res = client.connect();
  26669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26670. client.close();
  26671. EXPECT_EQ(1, proxy.connect_hits());
  26672. }
  26673. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26674. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26675. proxy_tunnel_test::ScopedConnectProxy proxy(
  26676. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26677. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26678. ASSERT_NE(0, proxy.port());
  26679. ws::WebSocketClient client(origin.url());
  26680. client.set_proxy("127.0.0.1", proxy.port());
  26681. auto res = client.connect();
  26682. EXPECT_FALSE(res);
  26683. EXPECT_EQ(Error::ProxyConnection, res.error());
  26684. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26685. EXPECT_EQ("Basic realm=\"proxy\"",
  26686. res.get_header_value("Proxy-Authenticate"));
  26687. EXPECT_FALSE(client.is_open());
  26688. }
  26689. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26690. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26691. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26692. ASSERT_NE(0, proxy.port());
  26693. ws::WebSocketClient client(origin.url());
  26694. client.set_proxy("127.0.0.1", proxy.port());
  26695. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26696. client.set_no_proxy({"127.0.0.1"});
  26697. auto res = client.connect();
  26698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26699. std::string msg;
  26700. ASSERT_TRUE(client.read(msg));
  26701. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26702. << "proxy credentials must not reach a bypassed origin";
  26703. client.close();
  26704. EXPECT_EQ(0, proxy.connect_hits());
  26705. }
  26706. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26707. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26708. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26709. ASSERT_NE(0, proxy.port());
  26710. ws::WebSocketClient client(origin.url());
  26711. client.set_proxy("127.0.0.1", proxy.port());
  26712. ASSERT_TRUE(client.connect());
  26713. ASSERT_TRUE(client.connect());
  26714. client.close();
  26715. EXPECT_EQ(2, proxy.connect_hits());
  26716. }
  26717. #ifdef CPPHTTPLIB_SSL_ENABLED
  26718. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26719. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26720. proxy_tunnel_test::ScopedConnectProxy proxy(
  26721. origin.port(), [](const std::string &head) -> std::string {
  26722. if (head.find(
  26723. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26724. std::string::npos) {
  26725. return proxy_tunnel_test::kTunnelEstablished;
  26726. }
  26727. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26728. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26729. "nonce=\"abc\", algorithm=MD5\r\n"
  26730. "Content-Length: 0\r\n\r\n";
  26731. });
  26732. ASSERT_NE(0, proxy.port());
  26733. ws::WebSocketClient client(origin.url());
  26734. client.set_proxy("127.0.0.1", proxy.port());
  26735. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26736. auto res = client.connect();
  26737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26738. std::string msg;
  26739. ASSERT_TRUE(client.read(msg));
  26740. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26741. client.close();
  26742. EXPECT_EQ(2, proxy.connect_hits());
  26743. }
  26744. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26745. proxy_tunnel_test::ScopedSSLServer origin;
  26746. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26747. origin.listen();
  26748. proxy_tunnel_test::ScopedConnectProxy proxy(
  26749. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26750. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26751. ASSERT_NE(0, proxy.port());
  26752. ws::WebSocketClient client(
  26753. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26754. client.enable_server_certificate_verification(false);
  26755. client.set_proxy("127.0.0.1", proxy.port());
  26756. client.set_proxy_bearer_token_auth("proxy-token");
  26757. auto res = client.connect();
  26758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26759. std::string msg;
  26760. ASSERT_TRUE(client.read(msg));
  26761. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26762. << "Proxy-Authorization must not be sent inside the tunnel";
  26763. client.close();
  26764. EXPECT_EQ(1, proxy.connect_hits());
  26765. }
  26766. #endif