test.cc 917 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declarations (see the base64_encode note below).
  474. namespace httplib {
  475. namespace detail {
  476. bool parse_status_line(const char *line, std::string &version, int &status,
  477. std::string &reason);
  478. std::string file_extension(const std::string &path);
  479. std::string
  480. find_content_type(const std::string &path,
  481. const std::map<std::string, std::string> &user_data,
  482. const std::string &default_content_type);
  483. bool can_compress_content_type(const std::string &content_type);
  484. bool is_prohibited_header_name(const std::string &name);
  485. } // namespace detail
  486. } // namespace httplib
  487. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  488. struct {
  489. const char *line;
  490. const char *version;
  491. int status;
  492. const char *reason;
  493. } cases[] = {
  494. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  495. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  496. // The reason phrase may be empty, or left out along with its space.
  497. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  498. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  499. };
  500. for (const auto &c : cases) {
  501. std::string version;
  502. int status = 0;
  503. std::string reason = "unset";
  504. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  505. << c.line;
  506. EXPECT_EQ(c.version, version);
  507. EXPECT_EQ(c.status, status);
  508. EXPECT_EQ(c.reason, reason);
  509. }
  510. }
  511. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  512. const char *lines[] = {
  513. "HTTP/2 200 OK\r\n",
  514. "HTTP/1.2 200 OK\r\n",
  515. "HTTP/1.1 20 OK\r\n",
  516. "HTTP/1.1 2000 OK\r\n",
  517. "HTTP/1.1 2x0 OK\r\n",
  518. "HTTP/1.1 200 OK\r\n",
  519. "HTTP/1.1 200OK\r\n",
  520. "HTTP/1.1 200 O\rK\r\n",
  521. "HTTP/1.1 200 OK",
  522. "HTTP/1.1 200 OK\r\nX",
  523. "",
  524. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  525. "HTTP/1.1 200 OK\n",
  526. #endif
  527. };
  528. for (auto line : lines) {
  529. std::string version;
  530. int status = 0;
  531. std::string reason;
  532. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  533. << line;
  534. }
  535. }
  536. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  537. // Long enough to overflow the stack when matched with std::regex.
  538. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  539. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  540. std::string version;
  541. int status = 0;
  542. std::string reason;
  543. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  544. EXPECT_EQ(200, status);
  545. EXPECT_EQ(long_reason, reason);
  546. }
  547. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  548. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  549. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  550. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  551. EXPECT_EQ("", detail::file_extension("noext"));
  552. EXPECT_EQ("", detail::file_extension("a."));
  553. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  554. EXPECT_EQ("", detail::file_extension("a.b-c"));
  555. // Long enough to overflow the stack when matched with std::regex.
  556. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  557. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  558. }
  559. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  560. detail::case_ignore::hash hash;
  561. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  562. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  563. // Long enough to overflow the stack if hashed one call per character.
  564. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  565. }
  566. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  567. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  568. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  569. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  570. // Same 26-bit hash as html, svg and js.
  571. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  572. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  573. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  574. }
  575. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  576. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  577. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  578. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  579. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  580. // Same 26-bit hash as application/json.
  581. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  582. }
  583. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  584. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  585. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  586. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  587. // Same 26-bit hash as REMOTE_ADDR.
  588. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  589. }
  590. // Forward declaration: in split builds split.py strips `inline` and moves the
  591. // definition into httplib.cc, so detail::base64_encode is not visible from the
  592. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  593. // in both header-only and split builds.
  594. namespace httplib {
  595. namespace detail {
  596. std::string base64_encode(const std::string &in);
  597. } // namespace detail
  598. } // namespace httplib
  599. TEST(Base64EncodeTest, KnownAnswers) {
  600. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  601. // where the accumulator's top bit is already set before the next shift.
  602. EXPECT_EQ("", detail::base64_encode(""));
  603. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  604. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  605. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  606. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  607. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  608. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  609. // High bytes keep the top bit set across several rounds.
  610. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  611. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  612. }
  613. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  614. string unescapedCharacters = "-_.!~*'()";
  615. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  616. }
  617. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  618. string reservedCharacters = ";,/?:@&=+$";
  619. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  620. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  621. }
  622. TEST(ClientQueryOrder, PreserveOrder) {
  623. // This test reproduces Issue #2259: client may reorder query parameters
  624. // when sending a GET request. The expected behavior is that the client
  625. // preserves the original query string order when the caller supplied it
  626. // as part of the path.
  627. Server svr;
  628. svr.Get("/", [&](const Request &req, Response &res) {
  629. // Echo back the raw target so the test can assert ordering
  630. res.set_content(req.target, "text/plain");
  631. });
  632. std::thread t{[&] { svr.listen(HOST, PORT); }};
  633. auto se = detail::scope_exit([&] {
  634. svr.stop();
  635. t.join();
  636. ASSERT_FALSE(svr.is_running());
  637. });
  638. svr.wait_until_ready();
  639. Client cli(HOST, PORT);
  640. ASSERT_TRUE(cli.is_valid());
  641. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  642. auto res = cli.Get(original);
  643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  644. // Expect the echoed target to exactly match the original path (order
  645. // preserved)
  646. EXPECT_EQ(res->body, original);
  647. }
  648. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  649. string chineseCharacters = U8("中国語");
  650. string russianCharacters = U8("дом");
  651. string brazilianCharacters = U8("óculos");
  652. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  653. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  654. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  655. "%D0%B4%D0%BE%D0%BC");
  656. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  657. }
  658. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  659. string unescapedCharacters = "-_.!~*'()";
  660. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  661. }
  662. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  663. string reservedCharacters = ";,/?:@&=+$";
  664. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  665. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  666. }
  667. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  668. string chineseCharacters = U8("中国語");
  669. string russianCharacters = U8("дом");
  670. string brazilianCharacters = U8("óculos");
  671. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  672. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  673. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  674. "%D0%B4%D0%BE%D0%BC");
  675. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  676. }
  677. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  678. // Issue #2082 use case: encoding path component with ampersand
  679. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  680. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  681. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  682. }
  683. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  684. string unescapedCharacters = "-_.!~*'()";
  685. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  686. }
  687. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  688. string reservedCharacters = ";,/?:@&=+$#";
  689. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  690. }
  691. TEST(EncodeUriTest, TestUTF8Characters) {
  692. string chineseCharacters = U8("中国語");
  693. string russianCharacters = U8("дом");
  694. string brazilianCharacters = U8("óculos");
  695. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  696. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  697. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  698. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  699. }
  700. TEST(EncodeUriTest, TestCompleteUri) {
  701. string uri =
  702. "https://example.com/path/to/resource?query=value&param=test#fragment";
  703. EXPECT_EQ(
  704. httplib::encode_uri(uri),
  705. "https://example.com/path/to/resource?query=value&param=test#fragment");
  706. }
  707. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  708. string uri =
  709. "https://example.com/path with spaces/file name.html?q=hello world";
  710. EXPECT_EQ(httplib::encode_uri(uri),
  711. "https://example.com/path%20with%20spaces/"
  712. "file%20name.html?q=hello%20world");
  713. }
  714. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  715. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  716. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  717. }
  718. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  723. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  724. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  725. string encodedBrazilian = "%C3%B3culos";
  726. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  727. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  728. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  729. }
  730. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  731. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  732. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  733. "Piri Tommy Villiers - on & on");
  734. }
  735. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  736. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  737. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  738. }
  739. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  740. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  741. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  742. }
  743. TEST(DecodeUriTest, TestUTF8Characters) {
  744. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  745. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  746. string encodedBrazilian = "%C3%B3culos";
  747. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  748. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  749. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  750. }
  751. TEST(DecodeUriTest, TestCompleteUri) {
  752. string encodedUri = "https://example.com/path%20with%20spaces/"
  753. "file%20name.html?q=hello%20world";
  754. EXPECT_EQ(
  755. httplib::decode_uri(encodedUri),
  756. "https://example.com/path with spaces/file name.html?q=hello world");
  757. }
  758. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  759. string original =
  760. "https://example.com/path with spaces/file name.html?q=hello world";
  761. string encoded = httplib::encode_uri(original);
  762. string decoded = httplib::decode_uri(encoded);
  763. EXPECT_EQ(decoded, original);
  764. }
  765. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  766. // decode_uri is the inverse of encode_uri: an escaped reserved character
  767. // stays encoded so it is not promoted into a real delimiter, while
  768. // non-reserved escapes still decode (like JS decodeURI).
  769. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  770. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  771. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  772. "%3F%3A%40%26%3D%2B%24%2C%3B");
  773. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  774. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  775. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  776. "http://example.com/a%2Fb");
  777. // decode_uri_component still decodes the reserved character.
  778. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  779. }
  780. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  781. string original = "Piri Tommy Villiers - on & on";
  782. string encoded = httplib::encode_uri_component(original);
  783. string decoded = httplib::decode_uri_component(encoded);
  784. EXPECT_EQ(decoded, original);
  785. }
  786. TEST(TrimTests, TrimStringTests) {
  787. EXPECT_EQ("abc", detail::trim_copy("abc"));
  788. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  789. EXPECT_TRUE(detail::trim_copy("").empty());
  790. }
  791. TEST(AsciiTest, LocaleIndependentClassification) {
  792. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  793. // which consult the global C locale: std::isalnum(0xC5) can return true
  794. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  795. // helpers must classify every byte by the ASCII grammar alone.
  796. for (int i = 0; i < 256; i++) {
  797. auto c = static_cast<char>(i);
  798. auto is_digit = i >= '0' && i <= '9';
  799. auto is_upper = i >= 'A' && i <= 'Z';
  800. auto is_lower = i >= 'a' && i <= 'z';
  801. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  802. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  803. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  804. << "byte " << i;
  805. }
  806. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  807. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  808. // Non-ASCII bytes must be percent-encoded, never passed through as
  809. // alphanumeric.
  810. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  811. }
  812. TEST(FromCharsTest, Double) {
  813. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  814. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  815. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  816. auto parse = [](const std::string &s, double &v) {
  817. return detail::from_chars(s.data(), s.data() + s.size(), v);
  818. };
  819. double v = -1.0;
  820. // Representative quality values.
  821. EXPECT_EQ(parse("0", v).ec, std::errc{});
  822. EXPECT_DOUBLE_EQ(v, 0.0);
  823. EXPECT_EQ(parse("1", v).ec, std::errc{});
  824. EXPECT_DOUBLE_EQ(v, 1.0);
  825. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  826. EXPECT_DOUBLE_EQ(v, 0.8);
  827. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  828. EXPECT_DOUBLE_EQ(v, 0.001);
  829. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  830. EXPECT_DOUBLE_EQ(v, 1.0);
  831. // A missing integer or fractional part is tolerated.
  832. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  833. EXPECT_DOUBLE_EQ(v, 0.5);
  834. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  835. EXPECT_DOUBLE_EQ(v, 5.0);
  836. // Values outside [0, 1] still parse; the caller range-checks them.
  837. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  838. EXPECT_DOUBLE_EQ(v, 123.456);
  839. // Stops at the first byte that is not part of the number and reports where.
  840. std::string trailing = "0.9, text/html";
  841. auto r = parse(trailing, v);
  842. EXPECT_EQ(r.ec, std::errc{});
  843. EXPECT_DOUBLE_EQ(v, 0.9);
  844. EXPECT_EQ(*r.ptr, ',');
  845. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  846. // outright, and an 'e'/'E' simply ends the number.
  847. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  848. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  849. std::string exp_input = "1.5e3";
  850. r = parse(exp_input, v);
  851. EXPECT_EQ(r.ec, std::errc{});
  852. EXPECT_DOUBLE_EQ(v, 1.5);
  853. EXPECT_EQ(*r.ptr, 'e');
  854. // Invalid inputs.
  855. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  856. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  857. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  858. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  859. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  860. // Pathological but well-formed inputs must stay bounded (no overflow, no
  861. // out-of-bounds table access) and stay within [0, 1] for the caller.
  862. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  863. std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.0);
  865. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  866. std::errc{});
  867. EXPECT_GE(v, 0.0);
  868. EXPECT_LE(v, 1.0);
  869. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  870. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  871. }
  872. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  873. // Simple case without quality values
  874. std::vector<std::string> result1;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "text/html,application/json,text/plain", result1));
  877. EXPECT_EQ(result1.size(), 3U);
  878. EXPECT_EQ(result1[0], "text/html");
  879. EXPECT_EQ(result1[1], "application/json");
  880. EXPECT_EQ(result1[2], "text/plain");
  881. // With quality values
  882. std::vector<std::string> result2;
  883. EXPECT_TRUE(detail::parse_accept_header(
  884. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  885. EXPECT_EQ(result2.size(), 3U);
  886. EXPECT_EQ(result2[0], "application/json"); // highest q value
  887. EXPECT_EQ(result2[1], "text/html");
  888. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  889. }
  890. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  891. // Mixed with and without quality values
  892. std::vector<std::string> result;
  893. EXPECT_TRUE(detail::parse_accept_header(
  894. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  895. EXPECT_EQ(result.size(), 3U);
  896. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  897. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  898. EXPECT_EQ(result[2], "application/json"); // q=0.5
  899. }
  900. TEST(ParseAcceptHeaderTest, EdgeCases) {
  901. // Empty header
  902. std::vector<std::string> empty_result;
  903. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  904. EXPECT_TRUE(empty_result.empty());
  905. // Single type
  906. std::vector<std::string> single_result;
  907. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  908. EXPECT_EQ(single_result.size(), 1U);
  909. EXPECT_EQ(single_result[0], "application/json");
  910. // Wildcard types
  911. std::vector<std::string> wildcard_result;
  912. EXPECT_TRUE(detail::parse_accept_header(
  913. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  914. EXPECT_EQ(wildcard_result.size(), 3U);
  915. EXPECT_EQ(wildcard_result[0], "application/json");
  916. EXPECT_EQ(wildcard_result[1], "text/*");
  917. EXPECT_EQ(wildcard_result[2], "*/*");
  918. }
  919. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  920. // Common browser Accept header
  921. std::vector<std::string> browser_result;
  922. EXPECT_TRUE(
  923. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  924. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  925. browser_result));
  926. EXPECT_EQ(browser_result.size(), 6U);
  927. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  928. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  929. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  930. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  931. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  932. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  933. // API client header
  934. std::vector<std::string> api_result;
  935. EXPECT_TRUE(detail::parse_accept_header(
  936. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  937. api_result));
  938. EXPECT_EQ(api_result.size(), 3U);
  939. EXPECT_EQ(api_result[0], "application/json");
  940. EXPECT_EQ(api_result[1], "application/xml");
  941. EXPECT_EQ(api_result[2], "text/plain");
  942. }
  943. TEST(ParseAcceptHeaderTest, SpecialCases) {
  944. // Quality value with 3 decimal places
  945. std::vector<std::string> decimal_result;
  946. EXPECT_TRUE(detail::parse_accept_header(
  947. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  948. EXPECT_EQ(decimal_result.size(), 2U);
  949. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  950. EXPECT_EQ(decimal_result[1], "text/html");
  951. // Zero quality (should still be included but with lowest priority)
  952. std::vector<std::string> zero_q_result;
  953. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  954. zero_q_result));
  955. EXPECT_EQ(zero_q_result.size(), 2U);
  956. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  957. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  958. // No spaces around commas
  959. std::vector<std::string> no_space_result;
  960. EXPECT_TRUE(detail::parse_accept_header(
  961. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  962. no_space_result));
  963. EXPECT_EQ(no_space_result.size(), 3U);
  964. EXPECT_EQ(no_space_result[0], "text/html");
  965. EXPECT_EQ(no_space_result[1], "application/json");
  966. EXPECT_EQ(no_space_result[2], "text/plain");
  967. }
  968. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  969. // Quality values always use '.' as the decimal separator, so parsing must
  970. // not depend on the process locale. An embedding application may have
  971. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  972. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  973. std::string saved = cur ? cur : "C";
  974. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  975. "fr_FR.UTF-8"};
  976. bool switched = false;
  977. for (const auto loc : comma_locales) {
  978. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  979. std::localeconv()->decimal_point[0] == ',') {
  980. switched = true;
  981. break;
  982. }
  983. }
  984. if (!switched) {
  985. std::setlocale(LC_NUMERIC, saved.c_str());
  986. GTEST_SKIP() << "no comma-decimal locale available on this host";
  987. }
  988. // The higher-weighted type appears later in the list, so a correct parse
  989. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  990. // sensitive parse reads both weights as 0 and leaves the original order.
  991. std::vector<std::string> result;
  992. EXPECT_TRUE(detail::parse_accept_header(
  993. "application/json;q=0.1,text/html;q=0.9", result));
  994. ASSERT_EQ(result.size(), 2U);
  995. EXPECT_EQ(result[0], "text/html");
  996. EXPECT_EQ(result[1], "application/json");
  997. std::setlocale(LC_NUMERIC, saved.c_str());
  998. }
  999. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1000. std::vector<std::string> result;
  1001. // Invalid quality value (> 1.0)
  1002. EXPECT_FALSE(
  1003. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1004. // Invalid quality value (< 0.0)
  1005. EXPECT_FALSE(
  1006. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1007. // Invalid quality value (not a number)
  1008. EXPECT_FALSE(detail::parse_accept_header(
  1009. "text/html;q=invalid,application/json", result));
  1010. // A valid numeric prefix does not make the entire quality value valid.
  1011. EXPECT_FALSE(detail::parse_accept_header(
  1012. "text/html;q=0.5junk,application/json", result));
  1013. // Empty quality value
  1014. EXPECT_FALSE(
  1015. detail::parse_accept_header("text/html;q=,application/json", result));
  1016. // Invalid media type format (no slash and not wildcard)
  1017. EXPECT_FALSE(
  1018. detail::parse_accept_header("invalidtype,application/json", result));
  1019. // Valid cases should still work
  1020. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1021. EXPECT_EQ(result.size(), 1U);
  1022. EXPECT_EQ(result[0], "*/*");
  1023. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1024. EXPECT_EQ(result.size(), 1U);
  1025. EXPECT_EQ(result[0], "*");
  1026. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1027. EXPECT_EQ(result.size(), 1U);
  1028. EXPECT_EQ(result[0], "text/*");
  1029. }
  1030. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1031. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1032. // and must not be answered with 400 Bad Request.
  1033. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1034. struct {
  1035. const char *value;
  1036. std::vector<std::string> expected;
  1037. } cases[] = {
  1038. {",application/json", {"application/json"}},
  1039. {"text/html,", {"text/html"}},
  1040. {"text/html,,*/*", {"text/html", "*/*"}},
  1041. // An empty element may be spelled with whitespace in it
  1042. {"text/html, , application/json", {"text/html", "application/json"}},
  1043. // Nothing but empty elements is an empty list, which means the same
  1044. // thing as no Accept header at all
  1045. {",,,", {}},
  1046. // Quality values still apply across ignored empty elements
  1047. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1048. };
  1049. for (const auto &c : cases) {
  1050. std::vector<std::string> result;
  1051. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1052. << "value: " << c.value;
  1053. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1054. }
  1055. // An invalid entry is still rejected when empty elements surround it
  1056. std::vector<std::string> result;
  1057. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1058. }
  1059. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1060. // or ';' inside one does not end the list element or the parameter. Section
  1061. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1062. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1063. struct {
  1064. const char *value;
  1065. std::vector<std::string> expected;
  1066. } cases[] = {
  1067. {"text/html;profile=\"a,b\",application/json",
  1068. {"text/html", "application/json"}},
  1069. // A "q=" inside a quoted value is not the weight
  1070. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1071. {"text/html", "application/json"}},
  1072. // The weight after a quoted value still applies
  1073. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1074. {"application/json", "text/html"}},
  1075. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1076. {"application/json", "text/html"}},
  1077. {"text/html;profile=\"a\\\"b\",application/json",
  1078. {"text/html", "application/json"}},
  1079. // An escaped backslash does not escape the '"' after it
  1080. {"text/html;profile=\"a\\\\\",application/json",
  1081. {"text/html", "application/json"}},
  1082. };
  1083. for (const auto &c : cases) {
  1084. std::vector<std::string> result;
  1085. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1086. << "value: " << c.value;
  1087. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1088. }
  1089. }
  1090. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1091. Server svr;
  1092. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1093. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1094. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1095. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1096. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1097. res.set_content("ok", "text/plain");
  1098. });
  1099. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1100. EXPECT_TRUE(false);
  1101. res.set_content("bad request", "text/plain");
  1102. });
  1103. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1104. auto se = detail::scope_exit([&] {
  1105. svr.stop();
  1106. listen_thread.join();
  1107. ASSERT_FALSE(svr.is_running());
  1108. });
  1109. svr.wait_until_ready();
  1110. Client cli("localhost", PORT);
  1111. {
  1112. auto res = cli.Get(
  1113. "/accept_ok",
  1114. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1116. EXPECT_EQ(StatusCode::OK_200, res->status);
  1117. }
  1118. {
  1119. auto res = cli.Get("/accept_bad_request",
  1120. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1122. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1123. }
  1124. }
  1125. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1126. Server svr;
  1127. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1128. res.set_content("ok", "text/plain");
  1129. });
  1130. std::atomic<int> start_count{0};
  1131. std::atomic<bool> running_when_called{false};
  1132. svr.set_start_handler([&]() {
  1133. running_when_called = svr.is_running();
  1134. start_count++;
  1135. });
  1136. auto port = svr.bind_to_any_port(HOST);
  1137. std::thread t([&]() { svr.listen_after_bind(); });
  1138. auto se = detail::scope_exit([&] {
  1139. svr.stop();
  1140. t.join();
  1141. ASSERT_FALSE(svr.is_running());
  1142. });
  1143. svr.wait_until_ready();
  1144. // A successful request proves the accept loop is running, which the start
  1145. // handler precedes; so by now the handler must have run exactly once.
  1146. Client cli(HOST, port);
  1147. cli.set_connection_timeout(std::chrono::seconds(5));
  1148. auto res = cli.Get("/");
  1149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1150. EXPECT_EQ(StatusCode::OK_200, res->status);
  1151. EXPECT_EQ(1, start_count.load());
  1152. EXPECT_TRUE(running_when_called.load());
  1153. }
  1154. TEST(DivideTest, DivideStringTests) {
  1155. auto divide = [](const std::string &str, char d) {
  1156. std::string lhs;
  1157. std::string rhs;
  1158. detail::divide(str, d,
  1159. [&](const char *lhs_data, std::size_t lhs_size,
  1160. const char *rhs_data, std::size_t rhs_size) {
  1161. lhs.assign(lhs_data, lhs_size);
  1162. rhs.assign(rhs_data, rhs_size);
  1163. });
  1164. return std::make_pair(std::move(lhs), std::move(rhs));
  1165. };
  1166. {
  1167. const auto res = divide("", '=');
  1168. EXPECT_EQ(res.first, "");
  1169. EXPECT_EQ(res.second, "");
  1170. }
  1171. {
  1172. const auto res = divide("=", '=');
  1173. EXPECT_EQ(res.first, "");
  1174. EXPECT_EQ(res.second, "");
  1175. }
  1176. {
  1177. const auto res = divide(" ", '=');
  1178. EXPECT_EQ(res.first, " ");
  1179. EXPECT_EQ(res.second, "");
  1180. }
  1181. {
  1182. const auto res = divide("a", '=');
  1183. EXPECT_EQ(res.first, "a");
  1184. EXPECT_EQ(res.second, "");
  1185. }
  1186. {
  1187. const auto res = divide("a=", '=');
  1188. EXPECT_EQ(res.first, "a");
  1189. EXPECT_EQ(res.second, "");
  1190. }
  1191. {
  1192. const auto res = divide("=b", '=');
  1193. EXPECT_EQ(res.first, "");
  1194. EXPECT_EQ(res.second, "b");
  1195. }
  1196. {
  1197. const auto res = divide("a=b", '=');
  1198. EXPECT_EQ(res.first, "a");
  1199. EXPECT_EQ(res.second, "b");
  1200. }
  1201. {
  1202. const auto res = divide("a=b=", '=');
  1203. EXPECT_EQ(res.first, "a");
  1204. EXPECT_EQ(res.second, "b=");
  1205. }
  1206. {
  1207. const auto res = divide("a=b=c", '=');
  1208. EXPECT_EQ(res.first, "a");
  1209. EXPECT_EQ(res.second, "b=c");
  1210. }
  1211. }
  1212. TEST(SplitTest, ParseQueryString) {
  1213. string s = "key1=val1&key2=val2&key3=val3";
  1214. Params dic;
  1215. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1216. [&](const char *b, const char *e) {
  1217. string key, val;
  1218. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1219. if (key.empty()) {
  1220. key.assign(b2, e2);
  1221. } else {
  1222. val.assign(b2, e2);
  1223. }
  1224. });
  1225. dic.emplace(key, val);
  1226. });
  1227. EXPECT_EQ("val1", dic.find("key1")->second);
  1228. EXPECT_EQ("val2", dic.find("key2")->second);
  1229. EXPECT_EQ("val3", dic.find("key3")->second);
  1230. }
  1231. TEST(SplitTest, ParseInvalidQueryTests) {
  1232. {
  1233. string s = " ";
  1234. Params dict;
  1235. detail::parse_query_text(s, dict);
  1236. EXPECT_TRUE(dict.empty());
  1237. }
  1238. {
  1239. string s = " = =";
  1240. Params dict;
  1241. detail::parse_query_text(s, dict);
  1242. EXPECT_TRUE(dict.empty());
  1243. }
  1244. }
  1245. TEST(ParseQueryTest, ParseQueryString) {
  1246. {
  1247. std::string s = "key1=val1&key2=val2&key3=val3";
  1248. Params dic;
  1249. detail::parse_query_text(s, dic);
  1250. EXPECT_EQ("val1", dic.find("key1")->second);
  1251. EXPECT_EQ("val2", dic.find("key2")->second);
  1252. EXPECT_EQ("val3", dic.find("key3")->second);
  1253. }
  1254. {
  1255. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1256. Params dic;
  1257. detail::parse_query_text(s, dic);
  1258. EXPECT_EQ("", dic.find("key1")->second);
  1259. EXPECT_EQ("val1", dic.find("key2")->second);
  1260. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1261. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1262. }
  1263. }
  1264. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1265. Params dic;
  1266. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1267. dic.emplace("key1", "val1");
  1268. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1269. dic.emplace("key2", "val2");
  1270. dic.emplace("key3", "val3");
  1271. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1272. }
  1273. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1274. Params params;
  1275. params.emplace("a", "1");
  1276. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1277. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1278. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1279. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1280. // Long enough to overflow the stack when matched with std::regex.
  1281. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1282. EXPECT_EQ("/p?" + long_query + "&a=1",
  1283. append_query_params("/p?" + long_query, params));
  1284. }
  1285. // Joins every entry of a Headers or Params into "key=value " so a whole
  1286. // traversal can be compared in one assertion. Both are instantiations of the
  1287. // same insertion-ordered container, so one helper serves both.
  1288. template <typename Map> static std::string entries_to_string(const Map &m) {
  1289. std::string s;
  1290. for (const auto &entry : m) {
  1291. s += entry.first + "=" + entry.second + " ";
  1292. }
  1293. return s;
  1294. }
  1295. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1296. // Params used to be a std::multimap, which sorted by name and handed the
  1297. // caller's query back alphabetised. A client signing its query string could
  1298. // not reproduce the order it asked for.
  1299. Params dic;
  1300. dic.emplace("zulu", "1");
  1301. dic.emplace("alpha", "2");
  1302. dic.emplace("mike", "3");
  1303. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1304. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1305. }
  1306. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1307. Params dic;
  1308. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1309. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1310. }
  1311. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1312. Request req;
  1313. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1314. req.params);
  1315. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1316. EXPECT_EQ("first", req.get_param_value("tag"));
  1317. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1318. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1319. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1320. EXPECT_EQ("", req.get_param_value("tag", 3));
  1321. }
  1322. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1323. // Params shares its container with Headers, which matches field names
  1324. // case-insensitively. Parameter names must not pick that up.
  1325. Params dic;
  1326. dic.emplace("Key", "upper");
  1327. dic.emplace("key", "lower");
  1328. EXPECT_EQ(2U, dic.size());
  1329. EXPECT_EQ(1U, dic.count("Key"));
  1330. EXPECT_EQ(1U, dic.count("key"));
  1331. EXPECT_EQ("upper", dic.find("Key")->second);
  1332. EXPECT_EQ("lower", dic.find("key")->second);
  1333. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1334. }
  1335. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1336. Server svr;
  1337. std::string order;
  1338. svr.Get("/order", [&](const Request &req, Response &res) {
  1339. order = entries_to_string(req.params);
  1340. res.set_content("ok", "text/plain");
  1341. });
  1342. auto port = svr.bind_to_any_port(HOST);
  1343. thread t = thread([&] { svr.listen_after_bind(); });
  1344. auto se = detail::scope_exit([&] {
  1345. svr.stop();
  1346. t.join();
  1347. ASSERT_FALSE(svr.is_running());
  1348. });
  1349. svr.wait_until_ready();
  1350. Client cli(HOST, port);
  1351. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1352. ASSERT_TRUE(res);
  1353. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1354. }
  1355. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1356. Server svr;
  1357. std::string field_order, file_order;
  1358. svr.Post("/order", [&](const Request &req, Response &res) {
  1359. for (const auto &field : req.form.fields) {
  1360. field_order += field.first + "=" + field.second.content + " ";
  1361. }
  1362. for (const auto &file : req.form.files) {
  1363. file_order += file.first + "=" + file.second.filename + " ";
  1364. }
  1365. res.set_content("ok", "text/plain");
  1366. });
  1367. auto port = svr.bind_to_any_port(HOST);
  1368. thread t = thread([&] { svr.listen_after_bind(); });
  1369. auto se = detail::scope_exit([&] {
  1370. svr.stop();
  1371. t.join();
  1372. ASSERT_FALSE(svr.is_running());
  1373. });
  1374. svr.wait_until_ready();
  1375. UploadFormDataItems items = {
  1376. {"zulu", "1", "", ""},
  1377. {"alpha", "2", "", ""},
  1378. {"mike", "3", "", ""},
  1379. {"zebra", "z", "z.txt", "text/plain"},
  1380. {"apple", "a", "a.txt", "text/plain"},
  1381. };
  1382. Client cli(HOST, port);
  1383. auto res = cli.Post("/order", items);
  1384. ASSERT_TRUE(res);
  1385. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1386. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1387. }
  1388. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1389. Server svr;
  1390. std::vector<std::string> values;
  1391. std::string first, second, out_of_range, order;
  1392. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1393. values = req.form.get_fields("tag");
  1394. first = req.form.get_field("tag", 0);
  1395. second = req.form.get_field("tag", 1);
  1396. out_of_range = req.form.get_field("tag", 2);
  1397. for (const auto &field : req.form.fields) {
  1398. order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1411. // not adjacent in the container.
  1412. UploadFormDataItems items = {
  1413. {"tag", "first", "", ""},
  1414. {"other", "x", "", ""},
  1415. {"tag", "second", "", ""},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/repeated", items);
  1419. ASSERT_TRUE(res);
  1420. ASSERT_EQ(2U, values.size());
  1421. EXPECT_EQ("first", values[0]);
  1422. EXPECT_EQ("second", values[1]);
  1423. EXPECT_EQ("first", first);
  1424. EXPECT_EQ("second", second);
  1425. // std::multimap already kept entries sharing a name in insertion order, so
  1426. // everything above passes without this change too. The whole traversal is
  1427. // what tells the two apart: sorting by name would hoist "other" to the front
  1428. // and the two "tag" parts would end up adjacent.
  1429. EXPECT_EQ("tag=first other=x tag=second ", order);
  1430. // Advancing past the last entry of a name used to run off the container;
  1431. // the container's saturating increment makes it return the default instead.
  1432. EXPECT_EQ("", out_of_range);
  1433. }
  1434. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1435. // Server::read_content() keeps a FormFields::iterator alive across the
  1436. // content callbacks that fill the part it points at. The container is
  1437. // vector-backed, so a later emplace can reallocate and invalidate an older
  1438. // iterator; 64 parts grow the vector through seven reallocations, which
  1439. // checks that every part's content still lands in its own entry.
  1440. const size_t part_count = 64;
  1441. // One formula for both the parts sent and the values expected back, so the
  1442. // two cannot drift apart.
  1443. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1444. auto content_of = [](size_t i) {
  1445. return std::string(64, static_cast<char>('a' + (i % 26)));
  1446. };
  1447. Server svr;
  1448. std::vector<std::pair<std::string, std::string>> received;
  1449. svr.Post("/many", [&](const Request &req, Response &res) {
  1450. for (const auto &field : req.form.fields) {
  1451. received.emplace_back(field.first, field.second.content);
  1452. }
  1453. res.set_content("ok", "text/plain");
  1454. });
  1455. auto port = svr.bind_to_any_port(HOST);
  1456. thread t = thread([&] { svr.listen_after_bind(); });
  1457. auto se = detail::scope_exit([&] {
  1458. svr.stop();
  1459. t.join();
  1460. ASSERT_FALSE(svr.is_running());
  1461. });
  1462. svr.wait_until_ready();
  1463. UploadFormDataItems items;
  1464. for (size_t i = 0; i < part_count; i++) {
  1465. items.push_back({name_of(i), content_of(i), "", ""});
  1466. }
  1467. Client cli(HOST, port);
  1468. auto res = cli.Post("/many", items);
  1469. ASSERT_TRUE(res);
  1470. ASSERT_EQ(part_count, received.size());
  1471. for (size_t i = 0; i < part_count; i++) {
  1472. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1473. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1474. }
  1475. }
  1476. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1477. string content_type = "multipart/form-data; boundary=something";
  1478. string boundary;
  1479. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1480. EXPECT_TRUE(ret);
  1481. EXPECT_EQ(boundary, "something");
  1482. }
  1483. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1484. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1485. string boundary;
  1486. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1487. EXPECT_TRUE(ret);
  1488. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1489. }
  1490. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1491. string content_type =
  1492. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1493. string boundary;
  1494. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1495. EXPECT_TRUE(ret);
  1496. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1497. }
  1498. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1499. string content_type =
  1500. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1501. string boundary;
  1502. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1503. EXPECT_TRUE(ret);
  1504. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1505. }
  1506. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1507. const string boundary(70, 'a');
  1508. string content_type = "multipart/form-data; boundary=" + boundary;
  1509. string parsed;
  1510. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1511. EXPECT_TRUE(ret);
  1512. EXPECT_EQ(parsed, boundary);
  1513. }
  1514. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1515. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1516. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1517. string parsed;
  1518. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1519. EXPECT_FALSE(ret);
  1520. }
  1521. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1522. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1523. // is 72 characters on the wire and still valid.
  1524. const string boundary(70, 'a');
  1525. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1526. string parsed;
  1527. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1528. EXPECT_EQ(parsed, boundary);
  1529. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1530. parsed.clear();
  1531. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1532. }
  1533. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1534. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1535. // The parameter parser must not treat that '=' as the key/value separator.
  1536. string content_type =
  1537. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1538. "charset=UTF-8";
  1539. string parsed;
  1540. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1541. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1542. }
  1543. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1544. // A ';' inside the quoted-string is part of the value, not a parameter
  1545. // separator, so it must not truncate the boundary.
  1546. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1547. string parsed;
  1548. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1549. EXPECT_EQ(parsed, "a;b");
  1550. }
  1551. TEST(ParseDispositionParamsTest, QuotedValues) {
  1552. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1553. // ';' and '=' are ordinary characters inside one.
  1554. struct {
  1555. const char *value;
  1556. std::vector<std::pair<const char *, const char *>> expected;
  1557. } cases[] = {
  1558. {"name=\"file1\"; filename=\"a.txt\"",
  1559. {{"name", "file1"}, {"filename", "a.txt"}}},
  1560. // Whitespace around '=' and ';' is still trimmed
  1561. {"name=\"file2\" ;filename = \"a.html\"",
  1562. {{"name", "file2"}, {"filename", "a.html"}}},
  1563. // '=' inside the value used to leave only the text after the last one
  1564. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1565. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1566. {"name=\"x=y\"", {{"name", "x=y"}}},
  1567. // ';' inside the value used to truncate the pair and leave a bogus one
  1568. {"name=\"file3\"; filename=\"a;b.txt\"",
  1569. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1570. // An unquoted value keeps working, and so does filename*
  1571. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1572. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1573. // A parameter with no key is dropped rather than turned into one whose
  1574. // key is the value
  1575. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1576. };
  1577. for (const auto &c : cases) {
  1578. Params params;
  1579. detail::parse_disposition_params(c.value, params);
  1580. for (const auto &kv : c.expected) {
  1581. auto it = params.find(kv.first);
  1582. ASSERT_NE(it, params.end())
  1583. << "value: " << c.value << ", key: " << kv.first;
  1584. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1585. }
  1586. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1587. }
  1588. }
  1589. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1590. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1591. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1592. Server svr;
  1593. std::string field_value, file_name, file_filename;
  1594. bool has_field = false, has_file = false;
  1595. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1596. has_field = req.form.has_field("x=y");
  1597. field_value = req.form.get_field("x=y");
  1598. has_file = req.form.has_file("file1");
  1599. const auto &file = req.form.get_file("file1");
  1600. file_name = file.name;
  1601. file_filename = file.filename;
  1602. res.set_content("ok", "text/plain");
  1603. });
  1604. auto port = svr.bind_to_any_port(HOST);
  1605. thread t = thread([&] { svr.listen_after_bind(); });
  1606. auto se = detail::scope_exit([&] {
  1607. svr.stop();
  1608. t.join();
  1609. ASSERT_FALSE(svr.is_running());
  1610. });
  1611. svr.wait_until_ready();
  1612. UploadFormDataItems items = {
  1613. {"x=y", "field-value", "", ""},
  1614. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1615. };
  1616. Client cli(HOST, port);
  1617. auto res = cli.Post("/quoted", items);
  1618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1619. ASSERT_EQ(StatusCode::OK_200, res->status);
  1620. EXPECT_TRUE(has_field);
  1621. EXPECT_EQ("field-value", field_value);
  1622. EXPECT_TRUE(has_file);
  1623. EXPECT_EQ("file1", file_name);
  1624. EXPECT_EQ("a;b=report.pdf", file_filename);
  1625. }
  1626. TEST(GetHeaderValueTest, DefaultValue) {
  1627. Headers headers = {{"Dummy", "Dummy"}};
  1628. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1629. EXPECT_STREQ("text/plain", val);
  1630. }
  1631. TEST(GetHeaderValueTest, DefaultValueInt) {
  1632. Headers headers = {{"Dummy", "Dummy"}};
  1633. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1634. EXPECT_EQ(100ull, val);
  1635. }
  1636. TEST(GetHeaderValueTest, RegularValue) {
  1637. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1638. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1639. EXPECT_STREQ("text/html", val);
  1640. }
  1641. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1642. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1643. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1644. EXPECT_STREQ("text/html", val);
  1645. }
  1646. TEST(GetHeaderValueTest, SetContent) {
  1647. Response res;
  1648. res.set_content("html", "text/html");
  1649. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1650. res.set_content("text", "text/plain");
  1651. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1652. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1653. }
  1654. TEST(GetHeaderValueTest, RegularValueInt) {
  1655. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1656. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1657. EXPECT_EQ(100ull, val);
  1658. }
  1659. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1660. Headers headers = {{"Content-Length", "x"}};
  1661. auto is_invalid_value = false;
  1662. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1663. is_invalid_value);
  1664. EXPECT_EQ(0ull, val);
  1665. EXPECT_TRUE(is_invalid_value);
  1666. }
  1667. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1668. // An all-digit value that overflows size_t must be reported as invalid, not
  1669. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1670. // a large length to a small one on 32-bit builds, leaving the framing length
  1671. // wrong while is_invalid_value stayed false.
  1672. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1673. auto is_invalid_value = false;
  1674. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1675. is_invalid_value);
  1676. EXPECT_TRUE(is_invalid_value);
  1677. // A well-formed length is unaffected.
  1678. Headers ok = {{"Content-Length", "1234"}};
  1679. is_invalid_value = false;
  1680. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1681. is_invalid_value);
  1682. EXPECT_EQ(1234ull, val);
  1683. EXPECT_FALSE(is_invalid_value);
  1684. }
  1685. TEST(GetHeaderValueTest, Range) {
  1686. {
  1687. Headers headers = {make_range_header({{1, -1}})};
  1688. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1689. EXPECT_STREQ("bytes=1-", val);
  1690. }
  1691. {
  1692. Headers headers = {make_range_header({{-1, 1}})};
  1693. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1694. EXPECT_STREQ("bytes=-1", val);
  1695. }
  1696. {
  1697. Headers headers = {make_range_header({{1, 10}})};
  1698. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1699. EXPECT_STREQ("bytes=1-10", val);
  1700. }
  1701. {
  1702. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1703. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1704. EXPECT_STREQ("bytes=1-10, 100-", val);
  1705. }
  1706. {
  1707. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1708. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1709. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1710. }
  1711. {
  1712. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1713. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1714. EXPECT_STREQ("bytes=0-0, -1", val);
  1715. }
  1716. }
  1717. TEST(BearerTokenAuthTest, SchemeValidation) {
  1718. // A value shorter than "Bearer " must not throw from the fixed-length
  1719. // substr, and a non-Bearer scheme must not be reported as a token.
  1720. struct {
  1721. const char *value;
  1722. const char *expected;
  1723. } cases[] = {
  1724. {"x", ""},
  1725. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1726. {"Bearer abc123", "abc123"},
  1727. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1728. };
  1729. for (const auto &c : cases) {
  1730. Request req;
  1731. req.set_header("Authorization", c.value);
  1732. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1733. }
  1734. }
  1735. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1736. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1737. // to depend on the standard library (libstdc++ handed back duplicates in
  1738. // reverse insertion order, libc++ in insertion order).
  1739. Request req;
  1740. req.set_header("Accept-Encoding", "gzip");
  1741. req.set_header("Accept-Encoding", "deflate");
  1742. req.set_header("Accept-Encoding", "br");
  1743. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1744. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1745. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1746. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1747. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1748. }
  1749. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1750. Request req;
  1751. req.set_header("X-Test", "only");
  1752. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1753. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1754. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1755. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1756. }
  1757. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1758. Request req;
  1759. req.set_header("X-First", "1");
  1760. req.set_header("X-Test", "2");
  1761. req.params.emplace("first", "1");
  1762. req.params.emplace("test", "2");
  1763. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1764. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1765. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1766. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1767. // The second one is negative when read as a signed value
  1768. const auto max_id = (std::numeric_limits<size_t>::max)();
  1769. for (auto id : {max_id / 2, max_id}) {
  1770. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1771. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1772. EXPECT_EQ("", req.get_param_value("test", id));
  1773. EXPECT_EQ("", req.form.get_field("test", id));
  1774. EXPECT_EQ("", req.form.get_file("test", id).content);
  1775. }
  1776. }
  1777. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1778. Headers headers;
  1779. headers.emplace("Host", "example.com");
  1780. headers.emplace("Accept-Encoding", "gzip");
  1781. headers.emplace("User-Agent", "test");
  1782. headers.emplace("Accept-Encoding", "deflate");
  1783. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1784. "Accept-Encoding=deflate ",
  1785. entries_to_string(headers));
  1786. }
  1787. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1788. Headers headers = {{"Content-Type", "text/html"},
  1789. {"CONTENT-TYPE", "text/xml"}};
  1790. EXPECT_EQ(2U, headers.count("content-type"));
  1791. auto it = headers.find("content-type");
  1792. ASSERT_TRUE(it != headers.end());
  1793. EXPECT_EQ("text/html", it->second);
  1794. }
  1795. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1796. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1797. // drop only those fields and leave everything positioned between them.
  1798. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1799. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1800. auto rng = headers.equal_range("a");
  1801. headers.erase(rng.first, rng.second);
  1802. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1803. }
  1804. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1805. Headers headers = {
  1806. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1807. EXPECT_EQ(3U, headers.erase("A"));
  1808. EXPECT_EQ(0U, headers.count("A"));
  1809. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1810. }
  1811. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1812. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1813. headers.emplace_front("Host", "example.com");
  1814. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1815. entries_to_string(headers));
  1816. }
  1817. TEST(ParseHeaderValueTest, Range) {
  1818. {
  1819. Ranges ranges;
  1820. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1821. EXPECT_TRUE(ret);
  1822. EXPECT_EQ(1u, ranges.size());
  1823. EXPECT_EQ(1u, ranges[0].first);
  1824. EXPECT_EQ(-1, ranges[0].second);
  1825. }
  1826. {
  1827. Ranges ranges;
  1828. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1829. EXPECT_TRUE(ret);
  1830. EXPECT_EQ(1u, ranges.size());
  1831. EXPECT_EQ(-1, ranges[0].first);
  1832. EXPECT_EQ(1u, ranges[0].second);
  1833. }
  1834. {
  1835. Ranges ranges;
  1836. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1837. EXPECT_TRUE(ret);
  1838. EXPECT_EQ(1u, ranges.size());
  1839. EXPECT_EQ(1u, ranges[0].first);
  1840. EXPECT_EQ(10u, ranges[0].second);
  1841. }
  1842. {
  1843. Ranges ranges;
  1844. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1845. EXPECT_FALSE(ret);
  1846. }
  1847. {
  1848. Ranges ranges;
  1849. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1850. EXPECT_TRUE(ret);
  1851. EXPECT_EQ(2u, ranges.size());
  1852. EXPECT_EQ(1u, ranges[0].first);
  1853. EXPECT_EQ(10u, ranges[0].second);
  1854. EXPECT_EQ(100u, ranges[1].first);
  1855. EXPECT_EQ(-1, ranges[1].second);
  1856. }
  1857. {
  1858. Ranges ranges;
  1859. auto ret =
  1860. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1861. EXPECT_TRUE(ret);
  1862. EXPECT_EQ(3u, ranges.size());
  1863. EXPECT_EQ(1u, ranges[0].first);
  1864. EXPECT_EQ(10u, ranges[0].second);
  1865. EXPECT_EQ(100u, ranges[1].first);
  1866. EXPECT_EQ(200u, ranges[1].second);
  1867. EXPECT_EQ(300u, ranges[2].first);
  1868. EXPECT_EQ(400u, ranges[2].second);
  1869. }
  1870. {
  1871. Ranges ranges;
  1872. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1873. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1874. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1875. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1876. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1877. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1878. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1879. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1880. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1881. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1882. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1883. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1884. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1885. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1886. EXPECT_FALSE(
  1887. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1888. EXPECT_TRUE(ranges.empty());
  1889. }
  1890. {
  1891. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1892. // remainder of the representation, so it stays accepted.
  1893. Ranges ranges;
  1894. auto ret =
  1895. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1896. EXPECT_TRUE(ret);
  1897. ASSERT_EQ(1u, ranges.size());
  1898. EXPECT_EQ(0, ranges[0].first);
  1899. EXPECT_EQ(-1, ranges[0].second);
  1900. }
  1901. // RFC 9110 14.1: range unit names are case-insensitive.
  1902. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1903. Ranges ranges;
  1904. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1905. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1906. }
  1907. }
  1908. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1909. Request req;
  1910. req.set_header("Accept-Encoding", "gzip");
  1911. Response res;
  1912. res.set_header("Content-Type", "text/plain");
  1913. auto ret = detail::encoding_type(req, res);
  1914. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1915. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1916. #else
  1917. EXPECT_TRUE(ret == detail::EncodingType::None);
  1918. #endif
  1919. }
  1920. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1921. Request req;
  1922. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1923. Response res;
  1924. res.set_header("Content-Type", "text/plain");
  1925. auto ret = detail::encoding_type(req, res);
  1926. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1927. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1928. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1929. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1930. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1931. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1932. #else
  1933. EXPECT_TRUE(ret == detail::EncodingType::None);
  1934. #endif
  1935. }
  1936. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1937. Request req;
  1938. req.set_header("Accept-Encoding",
  1939. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1940. Response res;
  1941. res.set_header("Content-Type", "text/plain");
  1942. auto ret = detail::encoding_type(req, res);
  1943. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1944. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1945. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1946. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1947. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1948. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1949. #else
  1950. EXPECT_TRUE(ret == detail::EncodingType::None);
  1951. #endif
  1952. }
  1953. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1954. // All supported encodings rejected with q=0 should return None
  1955. Request req;
  1956. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1957. Response res;
  1958. res.set_header("Content-Type", "text/plain");
  1959. auto ret = detail::encoding_type(req, res);
  1960. EXPECT_TRUE(ret == detail::EncodingType::None);
  1961. }
  1962. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1963. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1964. Request req;
  1965. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1966. Response res;
  1967. res.set_header("Content-Type", "text/plain");
  1968. auto ret = detail::encoding_type(req, res);
  1969. EXPECT_TRUE(ret == detail::EncodingType::None);
  1970. }
  1971. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1972. Request req;
  1973. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1974. Response res;
  1975. res.set_header("Content-Type", "text/plain");
  1976. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1977. }
  1978. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1979. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1980. Request req;
  1981. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1982. Response res;
  1983. res.set_header("Content-Type", "text/plain");
  1984. auto ret = detail::encoding_type(req, res);
  1985. EXPECT_TRUE(ret == detail::EncodingType::None);
  1986. }
  1987. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1988. // RFC 7231: Accept-Encoding values are case-insensitive
  1989. Request req;
  1990. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1991. Response res;
  1992. res.set_header("Content-Type", "text/plain");
  1993. auto ret = detail::encoding_type(req, res);
  1994. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1995. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1996. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1997. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1998. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1999. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2000. #else
  2001. EXPECT_TRUE(ret == detail::EncodingType::None);
  2002. #endif
  2003. }
  2004. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2005. // q value should determine priority, not hardcoded order
  2006. Request req;
  2007. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2008. Response res;
  2009. res.set_header("Content-Type", "text/plain");
  2010. auto ret = detail::encoding_type(req, res);
  2011. // gzip has highest q=1.0, so it should be selected even though
  2012. // br and zstd are also supported
  2013. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2014. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2015. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2016. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2017. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2018. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2019. #else
  2020. EXPECT_TRUE(ret == detail::EncodingType::None);
  2021. #endif
  2022. }
  2023. TEST(BufferStreamTest, read) {
  2024. detail::BufferStream strm1;
  2025. Stream &strm = strm1;
  2026. EXPECT_EQ(5, strm.write("hello"));
  2027. char buf[512];
  2028. EXPECT_EQ(2, strm.read(buf, 2));
  2029. EXPECT_EQ('h', buf[0]);
  2030. EXPECT_EQ('e', buf[1]);
  2031. EXPECT_EQ(2, strm.read(buf, 2));
  2032. EXPECT_EQ('l', buf[0]);
  2033. EXPECT_EQ('l', buf[1]);
  2034. EXPECT_EQ(1, strm.read(buf, 1));
  2035. EXPECT_EQ('o', buf[0]);
  2036. EXPECT_EQ(0, strm.read(buf, 1));
  2037. }
  2038. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2039. auto host = "www.httpwatch.com";
  2040. auto ip = hosted_at(host);
  2041. EXPECT_EQ("23.96.13.243", ip);
  2042. std::vector<std::string> addrs;
  2043. hosted_at(host, addrs);
  2044. EXPECT_EQ(1u, addrs.size());
  2045. }
  2046. #if 0 // It depends on each test environment...
  2047. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2048. auto host = "www.youtube.com";
  2049. std::vector<std::string> addrs;
  2050. hosted_at(host, addrs);
  2051. EXPECT_EQ(20u, addrs.size());
  2052. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2053. EXPECT_TRUE(it != addrs.end());
  2054. }
  2055. #endif
  2056. class ChunkedEncodingTest : public ::testing::Test {
  2057. protected:
  2058. ChunkedEncodingTest()
  2059. : cli_(HOST, PORT)
  2060. #ifdef CPPHTTPLIB_SSL_ENABLED
  2061. ,
  2062. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2063. #endif
  2064. {
  2065. cli_.set_connection_timeout(2);
  2066. #ifdef CPPHTTPLIB_SSL_ENABLED
  2067. cli_.enable_server_certificate_verification(false);
  2068. #endif
  2069. }
  2070. virtual void SetUp() {
  2071. read_file("./image.jpg", image_data_);
  2072. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2073. res.set_content("Hello World!", "text/plain");
  2074. });
  2075. svr_.Get(
  2076. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2077. res.set_chunked_content_provider(
  2078. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2079. size_t remaining = image_data_.size() - offset;
  2080. if (remaining == 0) {
  2081. sink.done();
  2082. } else {
  2083. constexpr size_t CHUNK_SIZE = 1024;
  2084. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2085. sink.write(&image_data_[offset], send_size);
  2086. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2087. }
  2088. return true;
  2089. });
  2090. });
  2091. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2092. svr_.wait_until_ready();
  2093. }
  2094. virtual void TearDown() {
  2095. svr_.stop();
  2096. if (!request_threads_.empty()) {
  2097. std::this_thread::sleep_for(std::chrono::seconds(1));
  2098. for (auto &t : request_threads_) {
  2099. t.join();
  2100. }
  2101. }
  2102. t_.join();
  2103. }
  2104. #ifdef CPPHTTPLIB_SSL_ENABLED
  2105. SSLClient cli_;
  2106. SSLServer svr_;
  2107. #else
  2108. Client cli_;
  2109. Server svr_;
  2110. #endif
  2111. thread t_;
  2112. std::vector<thread> request_threads_;
  2113. std::string image_data_;
  2114. };
  2115. TEST_F(ChunkedEncodingTest, NormalGet) {
  2116. auto res = cli_.Get("/chunked");
  2117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2118. std::string out;
  2119. read_file("./image.jpg", out);
  2120. EXPECT_EQ(StatusCode::OK_200, res->status);
  2121. EXPECT_EQ(out, res->body);
  2122. }
  2123. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2124. std::string body;
  2125. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2126. body.append(data, data_length);
  2127. return true;
  2128. });
  2129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2130. std::string out;
  2131. read_file("./image.jpg", out);
  2132. EXPECT_EQ(StatusCode::OK_200, res->status);
  2133. EXPECT_EQ(out, body);
  2134. }
  2135. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2136. std::string body;
  2137. auto res = cli_.Get(
  2138. "/chunked",
  2139. [&](const Response &response) {
  2140. EXPECT_EQ(StatusCode::OK_200, response.status);
  2141. return true;
  2142. },
  2143. [&](const char *data, size_t data_length) {
  2144. body.append(data, data_length);
  2145. return true;
  2146. });
  2147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2148. std::string out;
  2149. read_file("./image.jpg", out);
  2150. EXPECT_EQ(StatusCode::OK_200, res->status);
  2151. EXPECT_EQ(out, body);
  2152. }
  2153. TEST(RangeTest, FromHTTPBin_Online) {
  2154. auto host = "httpbingo.org";
  2155. auto path = std::string{"/range/32"};
  2156. #ifdef CPPHTTPLIB_SSL_ENABLED
  2157. auto port = 443;
  2158. SSLClient cli(host, port);
  2159. #else
  2160. auto port = 80;
  2161. Client cli(host, port);
  2162. #endif
  2163. cli.set_connection_timeout(5);
  2164. {
  2165. auto res = cli.Get(path);
  2166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2167. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2168. EXPECT_EQ(StatusCode::OK_200, res->status);
  2169. }
  2170. {
  2171. Headers headers = {make_range_header({{1, -1}})};
  2172. auto res = cli.Get(path, headers);
  2173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2174. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2175. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2176. }
  2177. {
  2178. Headers headers = {make_range_header({{1, 10}})};
  2179. auto res = cli.Get(path, headers);
  2180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2181. EXPECT_EQ("bcdefghijk", res->body);
  2182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2183. }
  2184. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2185. // entire resource, while the original httpbin returned 200. Both are
  2186. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2187. {
  2188. Headers headers = {make_range_header({{0, 31}})};
  2189. auto res = cli.Get(path, headers);
  2190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2191. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2192. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2193. res->status == StatusCode::PartialContent_206);
  2194. }
  2195. {
  2196. Headers headers = {make_range_header({{0, -1}})};
  2197. auto res = cli.Get(path, headers);
  2198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2199. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2200. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2201. res->status == StatusCode::PartialContent_206);
  2202. }
  2203. // go-httpbin returns 206 with clamped range for over-range requests,
  2204. // while the original httpbin returned 416. Both behaviors are observed
  2205. // in real servers, so we only verify the request succeeds.
  2206. {
  2207. Headers headers = {make_range_header({{0, 32}})};
  2208. auto res = cli.Get(path, headers);
  2209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2210. }
  2211. }
  2212. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2213. auto host = "unresolvableaddress.local";
  2214. auto path = std::string{"/"};
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. auto port = 443;
  2217. SSLClient cli(host, port);
  2218. #else
  2219. auto port = 80;
  2220. Client cli(host, port);
  2221. #endif
  2222. cli.set_connection_timeout(1);
  2223. {
  2224. auto res = cli.Get(path);
  2225. ASSERT_FALSE(res);
  2226. }
  2227. std::this_thread::sleep_for(std::chrono::seconds(8));
  2228. }
  2229. #if defined(__linux__) && defined(__GLIBC__) && \
  2230. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2231. // Forward declaration: in split builds split.py strips `inline` and moves the
  2232. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2233. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2234. // against the symbol in both header-only and split builds.
  2235. namespace httplib {
  2236. namespace detail {
  2237. int getaddrinfo_with_timeout(const char *node, const char *service,
  2238. const struct addrinfo *hints,
  2239. struct addrinfo **res, time_t timeout_sec);
  2240. } // namespace detail
  2241. } // namespace httplib
  2242. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2243. //
  2244. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2245. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2246. // gai_suspend() call hits the connection timeout the function calls
  2247. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2248. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2249. // still alive and still references the now-destroyed stack frame.
  2250. //
  2251. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2252. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2253. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2254. // and runs them in a container.
  2255. namespace {
  2256. bool should_run_issue_2431_tests() {
  2257. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2258. return v && *v && std::string(v) != "0";
  2259. }
  2260. std::string unique_unresolvable_host(int n) {
  2261. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2262. // glibc still asks the configured nameserver — which is exactly the path
  2263. // we want to exercise. A unique label per call avoids the resolver cache.
  2264. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2265. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2266. std::to_string(n) + ".invalid";
  2267. }
  2268. } // namespace
  2269. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2270. if (!should_run_issue_2431_tests()) {
  2271. GTEST_SKIP()
  2272. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2273. }
  2274. for (int i = 0; i < 8; ++i) {
  2275. struct addrinfo hints;
  2276. memset(&hints, 0, sizeof(hints));
  2277. hints.ai_family = AF_UNSPEC;
  2278. hints.ai_socktype = SOCK_STREAM;
  2279. auto host = unique_unresolvable_host(i);
  2280. struct addrinfo *result = nullptr;
  2281. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2282. &result, /*timeout_sec=*/1);
  2283. if (rc == 0 && result) { freeaddrinfo(result); }
  2284. }
  2285. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2286. // stack region they still believe holds their gaicb.
  2287. std::this_thread::sleep_for(std::chrono::seconds(3));
  2288. }
  2289. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2290. if (!should_run_issue_2431_tests()) {
  2291. GTEST_SKIP()
  2292. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2293. }
  2294. std::atomic<bool> stop{false};
  2295. std::vector<std::thread> threads;
  2296. for (int t = 0; t < 8; ++t) {
  2297. threads.emplace_back([t, &stop] {
  2298. int i = 0;
  2299. while (!stop.load(std::memory_order_relaxed)) {
  2300. struct addrinfo hints;
  2301. memset(&hints, 0, sizeof(hints));
  2302. hints.ai_family = AF_UNSPEC;
  2303. hints.ai_socktype = SOCK_STREAM;
  2304. auto host = unique_unresolvable_host(t * 100000 + i++);
  2305. struct addrinfo *result = nullptr;
  2306. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2307. &result, /*timeout_sec=*/1);
  2308. if (rc == 0 && result) { freeaddrinfo(result); }
  2309. }
  2310. });
  2311. }
  2312. std::this_thread::sleep_for(std::chrono::seconds(8));
  2313. stop.store(true, std::memory_order_relaxed);
  2314. for (auto &th : threads) {
  2315. th.join();
  2316. }
  2317. std::this_thread::sleep_for(std::chrono::seconds(3));
  2318. }
  2319. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2320. if (!should_run_issue_2431_tests()) {
  2321. GTEST_SKIP()
  2322. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2323. }
  2324. std::atomic<bool> stop{false};
  2325. std::vector<std::thread> threads;
  2326. for (int t = 0; t < 8; ++t) {
  2327. threads.emplace_back([t, &stop] {
  2328. int i = 0;
  2329. while (!stop.load(std::memory_order_relaxed)) {
  2330. auto host = unique_unresolvable_host(t * 100000 + i++);
  2331. Client cli(host, 80);
  2332. cli.set_connection_timeout(1, 0);
  2333. cli.set_read_timeout(1, 0);
  2334. cli.set_write_timeout(1, 0);
  2335. (void)cli.Get("/");
  2336. }
  2337. });
  2338. }
  2339. std::this_thread::sleep_for(std::chrono::seconds(8));
  2340. stop.store(true, std::memory_order_relaxed);
  2341. for (auto &th : threads) {
  2342. th.join();
  2343. }
  2344. std::this_thread::sleep_for(std::chrono::seconds(3));
  2345. }
  2346. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2347. TEST(ConnectionErrorTest, InvalidHost) {
  2348. auto host = "-abcde.com";
  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(std::chrono::seconds(2));
  2357. auto res = cli.Get("/");
  2358. ASSERT_TRUE(!res);
  2359. EXPECT_EQ(Error::Connection, res.error());
  2360. }
  2361. TEST(ConnectionErrorTest, InvalidHost2) {
  2362. auto host = "httpcan.org/";
  2363. #ifdef CPPHTTPLIB_SSL_ENABLED
  2364. SSLClient cli(host);
  2365. #else
  2366. Client cli(host);
  2367. #endif
  2368. cli.set_connection_timeout(std::chrono::seconds(2));
  2369. auto res = cli.Get("/");
  2370. ASSERT_TRUE(!res);
  2371. EXPECT_EQ(Error::Connection, res.error());
  2372. }
  2373. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2374. auto host = "httpcan.org/";
  2375. #ifdef CPPHTTPLIB_SSL_ENABLED
  2376. SSLClient cli(host);
  2377. #else
  2378. Client cli(host);
  2379. #endif
  2380. cli.set_connection_timeout(std::chrono::seconds(2));
  2381. auto res = cli.Get("/");
  2382. ASSERT_TRUE(!res);
  2383. stringstream s;
  2384. s << "error code: " << res.error();
  2385. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2386. }
  2387. TEST(ConnectionErrorTest, InvalidPort) {
  2388. auto host = "localhost";
  2389. auto port = 44380;
  2390. #ifdef CPPHTTPLIB_SSL_ENABLED
  2391. SSLClient cli(host, port);
  2392. #else
  2393. Client cli(host, port);
  2394. #endif
  2395. cli.set_connection_timeout(std::chrono::seconds(2));
  2396. auto res = cli.Get("/");
  2397. ASSERT_TRUE(!res);
  2398. EXPECT_TRUE(Error::Connection == res.error() ||
  2399. Error::ConnectionTimeout == res.error());
  2400. }
  2401. TEST(ConnectionErrorTest, Timeout_Online) {
  2402. auto host = "google.com";
  2403. #ifdef CPPHTTPLIB_SSL_ENABLED
  2404. auto port = 44380;
  2405. SSLClient cli(host, port);
  2406. #else
  2407. auto port = 8080;
  2408. Client cli(host, port);
  2409. #endif
  2410. cli.set_connection_timeout(std::chrono::seconds(2));
  2411. // only probe one address type so that the error reason
  2412. // correlates to the timed-out IPv4, not the unsupported
  2413. // IPv6 connection attempt
  2414. cli.set_address_family(AF_INET);
  2415. auto res = cli.Get("/");
  2416. ASSERT_TRUE(!res);
  2417. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2418. }
  2419. TEST(CancelTest, NoCancel_Online) {
  2420. auto host = "httpbingo.org";
  2421. auto path = std::string{"/range/32"};
  2422. #ifdef CPPHTTPLIB_SSL_ENABLED
  2423. auto port = 443;
  2424. SSLClient cli(host, port);
  2425. #else
  2426. auto port = 80;
  2427. Client cli(host, port);
  2428. #endif
  2429. cli.set_connection_timeout(std::chrono::seconds(5));
  2430. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2432. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2433. EXPECT_EQ(StatusCode::OK_200, res->status);
  2434. }
  2435. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2436. // Use /bytes with a large payload so that the DownloadProgress callback
  2437. // (which only fires for Content-Length responses) is invoked before the
  2438. // entire body is received, giving cancellation a chance to fire.
  2439. auto host = "httpbingo.org";
  2440. auto path = std::string{"/bytes/524288"};
  2441. #ifdef CPPHTTPLIB_SSL_ENABLED
  2442. auto port = 443;
  2443. SSLClient cli(host, port);
  2444. #else
  2445. auto port = 80;
  2446. Client cli(host, port);
  2447. #endif
  2448. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2449. cli.set_connection_timeout(std::chrono::seconds(5));
  2450. ASSERT_TRUE(!res);
  2451. EXPECT_EQ(Error::Canceled, res.error());
  2452. }
  2453. TEST(CancelTest, WithCancelLargePayload_Online) {
  2454. auto host = "httpbingo.org";
  2455. auto path = std::string{"/bytes/524288"};
  2456. #ifdef CPPHTTPLIB_SSL_ENABLED
  2457. auto port = 443;
  2458. SSLClient cli(host, port);
  2459. #else
  2460. auto port = 80;
  2461. Client cli(host, port);
  2462. #endif
  2463. cli.set_connection_timeout(std::chrono::seconds(5));
  2464. uint32_t count = 0;
  2465. auto res =
  2466. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2467. ASSERT_TRUE(!res);
  2468. EXPECT_EQ(Error::Canceled, res.error());
  2469. }
  2470. TEST(CancelTest, NoCancelPost) {
  2471. Server svr;
  2472. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2473. res.set_content("Hello World!", "text/plain");
  2474. });
  2475. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2476. auto se = detail::scope_exit([&] {
  2477. svr.stop();
  2478. thread.join();
  2479. ASSERT_FALSE(svr.is_running());
  2480. });
  2481. svr.wait_until_ready();
  2482. Client cli(HOST, PORT);
  2483. cli.set_connection_timeout(std::chrono::seconds(5));
  2484. auto res =
  2485. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2486. "application/json", [](uint64_t, uint64_t) { return true; });
  2487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2488. EXPECT_EQ("Hello World!", res->body);
  2489. EXPECT_EQ(StatusCode::OK_200, res->status);
  2490. }
  2491. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2492. Server svr;
  2493. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2494. res.set_content("Hello World!", "text/plain");
  2495. });
  2496. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2497. auto se = detail::scope_exit([&] {
  2498. svr.stop();
  2499. thread.join();
  2500. ASSERT_FALSE(svr.is_running());
  2501. });
  2502. svr.wait_until_ready();
  2503. Client cli(HOST, PORT);
  2504. cli.set_connection_timeout(std::chrono::seconds(5));
  2505. auto res =
  2506. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2507. "application/json", [](uint64_t, uint64_t) { return false; });
  2508. ASSERT_TRUE(!res);
  2509. EXPECT_EQ(Error::Canceled, res.error());
  2510. }
  2511. TEST(CancelTest, WithCancelLargePayloadPost) {
  2512. Server svr;
  2513. svr.set_payload_max_length(200 * 1024 * 1024);
  2514. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2515. res.set_content(LARGE_DATA, "text/plain");
  2516. });
  2517. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2518. auto se = detail::scope_exit([&] {
  2519. svr.stop();
  2520. thread.join();
  2521. ASSERT_FALSE(svr.is_running());
  2522. });
  2523. svr.wait_until_ready();
  2524. Client cli(HOST, PORT);
  2525. cli.set_payload_max_length(200 * 1024 * 1024);
  2526. cli.set_connection_timeout(std::chrono::seconds(5));
  2527. auto res =
  2528. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2529. "application/json", [](uint64_t, uint64_t) { return false; });
  2530. ASSERT_TRUE(!res);
  2531. EXPECT_EQ(Error::Canceled, res.error());
  2532. }
  2533. TEST(CancelTest, NoCancelPut) {
  2534. Server svr;
  2535. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2536. res.set_content("Hello World!", "text/plain");
  2537. });
  2538. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2539. auto se = detail::scope_exit([&] {
  2540. svr.stop();
  2541. thread.join();
  2542. ASSERT_FALSE(svr.is_running());
  2543. });
  2544. svr.wait_until_ready();
  2545. Client cli(HOST, PORT);
  2546. cli.set_connection_timeout(std::chrono::seconds(5));
  2547. auto res =
  2548. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2549. "application/json", [](uint64_t, uint64_t) { return true; });
  2550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2551. EXPECT_EQ("Hello World!", res->body);
  2552. EXPECT_EQ(StatusCode::OK_200, res->status);
  2553. }
  2554. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2555. Server svr;
  2556. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2557. res.set_content("Hello World!", "text/plain");
  2558. });
  2559. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2560. auto se = detail::scope_exit([&] {
  2561. svr.stop();
  2562. thread.join();
  2563. ASSERT_FALSE(svr.is_running());
  2564. });
  2565. svr.wait_until_ready();
  2566. Client cli(HOST, PORT);
  2567. cli.set_connection_timeout(std::chrono::seconds(5));
  2568. auto res =
  2569. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2570. "application/json", [](uint64_t, uint64_t) { return false; });
  2571. ASSERT_TRUE(!res);
  2572. EXPECT_EQ(Error::Canceled, res.error());
  2573. }
  2574. TEST(CancelTest, WithCancelLargePayloadPut) {
  2575. Server svr;
  2576. svr.set_payload_max_length(200 * 1024 * 1024);
  2577. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2578. res.set_content(LARGE_DATA, "text/plain");
  2579. });
  2580. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2581. auto se = detail::scope_exit([&] {
  2582. svr.stop();
  2583. thread.join();
  2584. ASSERT_FALSE(svr.is_running());
  2585. });
  2586. svr.wait_until_ready();
  2587. Client cli(HOST, PORT);
  2588. cli.set_payload_max_length(200 * 1024 * 1024);
  2589. cli.set_connection_timeout(std::chrono::seconds(5));
  2590. auto res =
  2591. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2592. "application/json", [](uint64_t, uint64_t) { return false; });
  2593. ASSERT_TRUE(!res);
  2594. EXPECT_EQ(Error::Canceled, res.error());
  2595. }
  2596. TEST(CancelTest, NoCancelPatch) {
  2597. Server svr;
  2598. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2599. res.set_content("Hello World!", "text/plain");
  2600. });
  2601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2602. auto se = detail::scope_exit([&] {
  2603. svr.stop();
  2604. thread.join();
  2605. ASSERT_FALSE(svr.is_running());
  2606. });
  2607. svr.wait_until_ready();
  2608. Client cli(HOST, PORT);
  2609. cli.set_connection_timeout(std::chrono::seconds(5));
  2610. auto res =
  2611. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2612. "application/json", [](uint64_t, uint64_t) { return true; });
  2613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2614. EXPECT_EQ("Hello World!", res->body);
  2615. EXPECT_EQ(StatusCode::OK_200, res->status);
  2616. }
  2617. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2618. Server svr;
  2619. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2620. res.set_content("Hello World!", "text/plain");
  2621. });
  2622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2623. auto se = detail::scope_exit([&] {
  2624. svr.stop();
  2625. thread.join();
  2626. ASSERT_FALSE(svr.is_running());
  2627. });
  2628. svr.wait_until_ready();
  2629. Client cli(HOST, PORT);
  2630. cli.set_connection_timeout(std::chrono::seconds(5));
  2631. auto res =
  2632. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2633. "application/json", [](uint64_t, uint64_t) { return false; });
  2634. ASSERT_TRUE(!res);
  2635. EXPECT_EQ(Error::Canceled, res.error());
  2636. }
  2637. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2638. Server svr;
  2639. svr.set_payload_max_length(200 * 1024 * 1024);
  2640. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2641. res.set_content(LARGE_DATA, "text/plain");
  2642. });
  2643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2644. auto se = detail::scope_exit([&] {
  2645. svr.stop();
  2646. thread.join();
  2647. ASSERT_FALSE(svr.is_running());
  2648. });
  2649. svr.wait_until_ready();
  2650. Client cli(HOST, PORT);
  2651. cli.set_payload_max_length(200 * 1024 * 1024);
  2652. cli.set_connection_timeout(std::chrono::seconds(5));
  2653. auto res =
  2654. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2655. "application/json", [](uint64_t, uint64_t) { return false; });
  2656. ASSERT_TRUE(!res);
  2657. EXPECT_EQ(Error::Canceled, res.error());
  2658. }
  2659. TEST(CancelTest, NoCancelDelete) {
  2660. Server svr;
  2661. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2662. res.set_content("Hello World!", "text/plain");
  2663. });
  2664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2665. auto se = detail::scope_exit([&] {
  2666. svr.stop();
  2667. thread.join();
  2668. ASSERT_FALSE(svr.is_running());
  2669. });
  2670. svr.wait_until_ready();
  2671. Client cli(HOST, PORT);
  2672. cli.set_connection_timeout(std::chrono::seconds(5));
  2673. auto res =
  2674. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2675. "application/json", [](uint64_t, uint64_t) { return true; });
  2676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2677. EXPECT_EQ("Hello World!", res->body);
  2678. EXPECT_EQ(StatusCode::OK_200, res->status);
  2679. }
  2680. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2681. Server svr;
  2682. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2683. res.set_content("Hello World!", "text/plain");
  2684. });
  2685. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2686. auto se = detail::scope_exit([&] {
  2687. svr.stop();
  2688. thread.join();
  2689. ASSERT_FALSE(svr.is_running());
  2690. });
  2691. svr.wait_until_ready();
  2692. Client cli(HOST, PORT);
  2693. cli.set_connection_timeout(std::chrono::seconds(5));
  2694. auto res =
  2695. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2696. "application/json", [](uint64_t, uint64_t) { return false; });
  2697. ASSERT_TRUE(!res);
  2698. EXPECT_EQ(Error::Canceled, res.error());
  2699. }
  2700. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2701. Server svr;
  2702. svr.set_payload_max_length(200 * 1024 * 1024);
  2703. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2704. res.set_content(LARGE_DATA, "text/plain");
  2705. });
  2706. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2707. auto se = detail::scope_exit([&] {
  2708. svr.stop();
  2709. thread.join();
  2710. ASSERT_FALSE(svr.is_running());
  2711. });
  2712. svr.wait_until_ready();
  2713. Client cli(HOST, PORT);
  2714. cli.set_payload_max_length(200 * 1024 * 1024);
  2715. cli.set_connection_timeout(std::chrono::seconds(5));
  2716. auto res =
  2717. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2718. "application/json", [](uint64_t, uint64_t) { return false; });
  2719. ASSERT_TRUE(!res);
  2720. EXPECT_EQ(Error::Canceled, res.error());
  2721. }
  2722. static std::string remove_whitespace(const std::string &input) {
  2723. std::string output;
  2724. output.reserve(input.size());
  2725. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2726. [](unsigned char c) { return !std::isspace(c); });
  2727. return output;
  2728. }
  2729. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2730. auto host = "httpbingo.org";
  2731. auto path = std::string{"/basic-auth/hello/world"};
  2732. #ifdef CPPHTTPLIB_SSL_ENABLED
  2733. auto port = 443;
  2734. SSLClient cli(host, port);
  2735. #else
  2736. auto port = 80;
  2737. Client cli(host, port);
  2738. #endif
  2739. {
  2740. auto res = cli.Get(path);
  2741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2742. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2743. }
  2744. {
  2745. auto res = cli.Get(
  2746. path, Headers{make_basic_authentication_header("hello", "world")});
  2747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2748. auto body = remove_whitespace(res->body);
  2749. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2750. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2751. EXPECT_EQ(StatusCode::OK_200, res->status);
  2752. }
  2753. {
  2754. cli.set_basic_auth("hello", "world");
  2755. auto res = cli.Get(path);
  2756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2757. auto body = remove_whitespace(res->body);
  2758. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2759. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2760. EXPECT_EQ(StatusCode::OK_200, res->status);
  2761. }
  2762. {
  2763. cli.set_basic_auth("hello", "bad");
  2764. auto res = cli.Get(path);
  2765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2766. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2767. }
  2768. {
  2769. cli.set_basic_auth("bad", "world");
  2770. auto res = cli.Get(path);
  2771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2772. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2773. }
  2774. }
  2775. #ifdef CPPHTTPLIB_SSL_ENABLED
  2776. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2777. auto host = "httpbingo.org";
  2778. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2779. auto paths = std::vector<std::string>{
  2780. "/digest-auth/auth/hello/world/MD5",
  2781. "/digest-auth/auth/hello/world/SHA-256",
  2782. };
  2783. auto port = 443;
  2784. SSLClient cli(host, port);
  2785. {
  2786. auto res = cli.Get(unauth_path);
  2787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2788. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2789. }
  2790. {
  2791. cli.set_digest_auth("hello", "world");
  2792. for (const auto &path : paths) {
  2793. auto res = cli.Get(path.c_str());
  2794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2795. auto body = remove_whitespace(res->body);
  2796. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2797. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2798. EXPECT_EQ(StatusCode::OK_200, res->status);
  2799. }
  2800. cli.set_digest_auth("hello", "bad");
  2801. for (const auto &path : paths) {
  2802. auto res = cli.Get(path.c_str());
  2803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2804. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2805. }
  2806. }
  2807. }
  2808. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2809. // comma-separated list of challenges, and each challenge may itself carry a
  2810. // comma-separated auth-param list, so a server can legally offer Basic
  2811. // before Digest, either as two field lines or packed into one. Runs one 401
  2812. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2813. // value() joins them in receipt order) and checks that the retry carries a
  2814. // well-formed Digest Authorization header naming expected_realm.
  2815. static void
  2816. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2817. const std::string &expected_realm) {
  2818. std::atomic<int> hits{0};
  2819. Server svr;
  2820. svr.Get("/x", [&](const Request &req, Response &res) {
  2821. if (++hits == 1) {
  2822. res.status = StatusCode::Unauthorized_401;
  2823. for (const auto &challenge : challenges) {
  2824. res.set_header("WWW-Authenticate", challenge);
  2825. }
  2826. } else {
  2827. auto authorization = req.get_header_value("Authorization");
  2828. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2829. EXPECT_NE(std::string::npos,
  2830. authorization.find("realm=\"" + expected_realm + "\""));
  2831. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2832. res.set_content("ok", "text/plain");
  2833. }
  2834. });
  2835. auto port = svr.bind_to_any_port(HOST);
  2836. std::thread t([&]() { svr.listen_after_bind(); });
  2837. auto se = detail::scope_exit([&] {
  2838. svr.stop();
  2839. t.join();
  2840. });
  2841. svr.wait_until_ready();
  2842. Client cli(HOST, port);
  2843. cli.set_digest_auth("hello", "world");
  2844. auto res = cli.Get("/x");
  2845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2846. EXPECT_EQ(2, hits.load());
  2847. }
  2848. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2849. static const char *kDigestChallenge =
  2850. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2851. "algorithm=MD5";
  2852. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2853. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2854. "testrealm");
  2855. }
  2856. // Same challenge list with the schemes in the opposite order, to make sure
  2857. // the fix above didn't just special-case "Basic first".
  2858. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2859. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2860. "testrealm");
  2861. }
  2862. // A comma inside a quoted auth-param value must not be mistaken for the
  2863. // separator between two challenges (or two auth-params).
  2864. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2865. run_digest_challenge_list_test(
  2866. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2867. "algorithm=MD5"},
  2868. "test,realm");
  2869. }
  2870. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2871. // make_digest_authentication_header() dereferences both unconditionally, so
  2872. // a server sending a challenge missing either one must not be treated as
  2873. // usable -- doing so used to crash the client with std::out_of_range.
  2874. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2875. Server svr;
  2876. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2877. res.status = StatusCode::Unauthorized_401;
  2878. res.set_header("WWW-Authenticate", challenge);
  2879. });
  2880. auto port = svr.bind_to_any_port(HOST);
  2881. std::thread t([&]() { svr.listen_after_bind(); });
  2882. auto se = detail::scope_exit([&] {
  2883. svr.stop();
  2884. t.join();
  2885. });
  2886. svr.wait_until_ready();
  2887. Client cli(HOST, port);
  2888. cli.set_digest_auth("hello", "world");
  2889. auto res = cli.Get("/x");
  2890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2891. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2892. }
  2893. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2894. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2895. }
  2896. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2897. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2898. }
  2899. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2900. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2901. }
  2902. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2903. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2904. // when storing the values, so the header builder has to re-escape them (and
  2905. // keep algorithm a bare token); otherwise the value breaks out of its
  2906. // quoted-string and injects extra auth-params into the client's Authorization.
  2907. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2908. std::atomic<int> hits{0};
  2909. std::string authorization;
  2910. Server svr;
  2911. svr.Get("/x", [&](const Request &req, Response &res) {
  2912. if (++hits == 1) {
  2913. res.status = StatusCode::Unauthorized_401;
  2914. // On the wire the quotes embedded in the values are backslash-escaped.
  2915. res.set_header("WWW-Authenticate",
  2916. "Digest realm=\"testrealm\", "
  2917. "nonce=\"n\\\"; injected=\\\"x\", "
  2918. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2919. } else {
  2920. authorization = req.get_header_value("Authorization");
  2921. res.set_content("ok", "text/plain");
  2922. }
  2923. });
  2924. auto port = svr.bind_to_any_port(HOST);
  2925. std::thread t([&]() { svr.listen_after_bind(); });
  2926. auto se = detail::scope_exit([&] {
  2927. svr.stop();
  2928. t.join();
  2929. });
  2930. svr.wait_until_ready();
  2931. Client cli(HOST, port);
  2932. cli.set_digest_auth("hello", "world");
  2933. auto res = cli.Get("/x");
  2934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2935. EXPECT_EQ(2, hits.load());
  2936. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2937. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2938. // inside its quoted-string rather than starting an "injected" auth-param.
  2939. EXPECT_NE(std::string::npos,
  2940. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2941. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2942. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2943. }
  2944. #endif
  2945. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2946. auto host = "google.com";
  2947. auto another_host = "example.com";
  2948. auto wrong_ip = "0.0.0.0";
  2949. #ifdef CPPHTTPLIB_SSL_ENABLED
  2950. SSLClient cli(host);
  2951. #else
  2952. Client cli(host);
  2953. #endif
  2954. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2955. auto res = cli.Get("/");
  2956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2957. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2958. }
  2959. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2960. auto host = "google.com";
  2961. auto wrong_ip = "0.0.0.0";
  2962. #ifdef CPPHTTPLIB_SSL_ENABLED
  2963. SSLClient cli(host);
  2964. #else
  2965. Client cli(host);
  2966. #endif
  2967. cli.set_hostname_addr_map({{host, wrong_ip}});
  2968. auto res = cli.Get("/");
  2969. ASSERT_TRUE(!res);
  2970. EXPECT_EQ(Error::Connection, res.error());
  2971. }
  2972. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2973. // A mapped value that is not an IP literal must be resolved. "localhost"
  2974. // resolves from the hosts file, so this test needs no external DNS.
  2975. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2976. auto host = "target.invalid";
  2977. Server svr;
  2978. std::string received_host;
  2979. svr.Get("/hi", [&](const Request &req, Response &res) {
  2980. received_host = req.get_header_value("Host");
  2981. res.set_content("Hello World!", "text/plain");
  2982. });
  2983. auto port = svr.bind_to_any_port(HOST);
  2984. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2985. auto se = detail::scope_exit([&] {
  2986. svr.stop();
  2987. thread.join();
  2988. ASSERT_FALSE(svr.is_running());
  2989. });
  2990. svr.wait_until_ready();
  2991. Client cli(host, port);
  2992. cli.set_hostname_addr_map({{host, HOST}});
  2993. auto res = cli.Get("/hi");
  2994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2995. EXPECT_EQ(StatusCode::OK_200, res->status);
  2996. // The mapping only redirects the connection; the identity stays host_.
  2997. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2998. }
  2999. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3000. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3001. auto host = "target.invalid";
  3002. Server svr;
  3003. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3004. res.set_content("Hello World!", "text/plain");
  3005. });
  3006. auto port = svr.bind_to_any_port("127.0.0.1");
  3007. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3008. auto se = detail::scope_exit([&] {
  3009. svr.stop();
  3010. thread.join();
  3011. ASSERT_FALSE(svr.is_running());
  3012. });
  3013. svr.wait_until_ready();
  3014. Client cli(host, port);
  3015. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3016. auto res = cli.Get("/hi");
  3017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3018. EXPECT_EQ(StatusCode::OK_200, res->status);
  3019. }
  3020. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3021. // An empty mapped value must leave host_ as the connection target. Without
  3022. // that guard the empty value would become the host argument, getaddrinfo
  3023. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3024. // loopback - silently connecting somewhere the caller never asked for.
  3025. // The server listens on loopback, so such a fallback would succeed and is
  3026. // therefore observable as a failure of this test.
  3027. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3028. Server svr;
  3029. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3030. res.set_content("Hello World!", "text/plain");
  3031. });
  3032. auto port = svr.bind_to_any_port(HOST);
  3033. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3034. auto se = detail::scope_exit([&] {
  3035. svr.stop();
  3036. thread.join();
  3037. ASSERT_FALSE(svr.is_running());
  3038. });
  3039. svr.wait_until_ready();
  3040. Client cli(blackhole, port);
  3041. cli.set_hostname_addr_map({{blackhole, ""}});
  3042. cli.set_connection_timeout(1);
  3043. auto res = cli.Get("/hi");
  3044. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3045. }
  3046. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3047. auto host = "httpbingo.org";
  3048. auto path = std::string{"/absolute-redirect/3"};
  3049. #ifdef CPPHTTPLIB_SSL_ENABLED
  3050. SSLClient cli(host);
  3051. #else
  3052. Client cli(host);
  3053. #endif
  3054. cli.set_follow_location(true);
  3055. auto res = cli.Get(path);
  3056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3057. EXPECT_EQ(StatusCode::OK_200, res->status);
  3058. }
  3059. TEST(RedirectTest, Redirect_Online) {
  3060. auto host = "httpbingo.org";
  3061. auto path = std::string{"/redirect/3"};
  3062. #ifdef CPPHTTPLIB_SSL_ENABLED
  3063. SSLClient cli(host);
  3064. #else
  3065. Client cli(host);
  3066. #endif
  3067. cli.set_follow_location(true);
  3068. auto res = cli.Get(path);
  3069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3070. EXPECT_EQ(StatusCode::OK_200, res->status);
  3071. }
  3072. TEST(RelativeRedirectTest, Redirect_Online) {
  3073. auto host = "httpbingo.org";
  3074. auto path = std::string{"/relative-redirect/3"};
  3075. #ifdef CPPHTTPLIB_SSL_ENABLED
  3076. SSLClient cli(host);
  3077. #else
  3078. Client cli(host);
  3079. #endif
  3080. cli.set_follow_location(true);
  3081. auto res = cli.Get(path);
  3082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3083. EXPECT_EQ(StatusCode::OK_200, res->status);
  3084. }
  3085. TEST(TooManyRedirectTest, Redirect_Online) {
  3086. auto host = "httpbingo.org";
  3087. auto path = std::string{"/redirect/21"};
  3088. #ifdef CPPHTTPLIB_SSL_ENABLED
  3089. SSLClient cli(host);
  3090. #else
  3091. Client cli(host);
  3092. #endif
  3093. cli.set_follow_location(true);
  3094. auto res = cli.Get(path);
  3095. ASSERT_TRUE(!res);
  3096. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3097. }
  3098. #ifdef CPPHTTPLIB_SSL_ENABLED
  3099. TEST(YahooRedirectTest, Redirect_Online) {
  3100. Client cli("yahoo.com");
  3101. auto res = cli.Get("/");
  3102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3103. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3104. cli.set_follow_location(true);
  3105. res = cli.Get("/");
  3106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3107. EXPECT_EQ(StatusCode::OK_200, res->status);
  3108. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3109. }
  3110. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3111. #define REDIR_HOST "httpbingo.org"
  3112. #define REDIR_PATH "/redirect-to"
  3113. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3114. SSLClient cli(REDIR_HOST);
  3115. cli.set_follow_location(true);
  3116. auto res =
  3117. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3119. EXPECT_EQ(StatusCode::OK_200, res->status);
  3120. }
  3121. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3122. SSLClient cli(REDIR_HOST);
  3123. cli.set_follow_location(true);
  3124. Params params;
  3125. params.emplace("url", "http://example.com");
  3126. params.emplace("status_code", "302");
  3127. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3129. EXPECT_EQ(StatusCode::OK_200, res->status);
  3130. }
  3131. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3132. SSLClient cli(REDIR_HOST);
  3133. cli.set_follow_location(true);
  3134. Params params;
  3135. params.emplace("url", "http://example.com");
  3136. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ(StatusCode::OK_200, res->status);
  3139. }
  3140. TEST(UrlWithSpace, Redirect_Online) {
  3141. SSLClient cli("edge.forgecdn.net");
  3142. cli.set_follow_location(true);
  3143. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3145. EXPECT_EQ(StatusCode::OK_200, res->status);
  3146. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3147. }
  3148. #endif
  3149. #if !defined(_WIN32) && !defined(_WIN64)
  3150. TEST(ReceiveSignals, Signal) {
  3151. auto setupSignalHandlers = []() {
  3152. struct sigaction act;
  3153. sigemptyset(&act.sa_mask);
  3154. act.sa_flags = SA_SIGINFO;
  3155. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3156. switch (sig) {
  3157. case SIGINT:
  3158. default: break;
  3159. }
  3160. };
  3161. ::sigaction(SIGINT, &act, nullptr);
  3162. };
  3163. Server svr;
  3164. int port = 0;
  3165. auto thread = std::thread([&]() {
  3166. setupSignalHandlers();
  3167. port = svr.bind_to_any_port(HOST);
  3168. svr.listen_after_bind();
  3169. });
  3170. auto se = detail::scope_exit([&] {
  3171. svr.stop();
  3172. thread.join();
  3173. ASSERT_FALSE(svr.is_running());
  3174. });
  3175. svr.wait_until_ready();
  3176. ASSERT_TRUE(svr.is_running());
  3177. pthread_kill(thread.native_handle(), SIGINT);
  3178. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3179. ASSERT_TRUE(svr.is_running());
  3180. }
  3181. #endif
  3182. TEST(RedirectToDifferentPort, Redirect) {
  3183. Server svr1;
  3184. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3185. res.set_content("Hello World!", "text/plain");
  3186. });
  3187. int svr1_port = 0;
  3188. auto thread1 = std::thread([&]() {
  3189. svr1_port = svr1.bind_to_any_port(HOST);
  3190. svr1.listen_after_bind();
  3191. });
  3192. Server svr2;
  3193. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3194. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3195. });
  3196. int svr2_port = 0;
  3197. auto thread2 = std::thread([&]() {
  3198. svr2_port = svr2.bind_to_any_port(HOST);
  3199. svr2.listen_after_bind();
  3200. });
  3201. auto se = detail::scope_exit([&] {
  3202. svr2.stop();
  3203. thread2.join();
  3204. svr1.stop();
  3205. thread1.join();
  3206. ASSERT_FALSE(svr2.is_running());
  3207. ASSERT_FALSE(svr1.is_running());
  3208. });
  3209. svr1.wait_until_ready();
  3210. svr2.wait_until_ready();
  3211. Client cli("localhost", svr2_port);
  3212. cli.set_follow_location(true);
  3213. auto res = cli.Get("/2");
  3214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3215. EXPECT_EQ(StatusCode::OK_200, res->status);
  3216. EXPECT_EQ("Hello World!", res->body);
  3217. }
  3218. // GET /redir on one server redirects to /target on another port, so the
  3219. // client follows it with a new client.
  3220. static Result
  3221. GetThroughRedirectToDifferentPort(Server::Handler target,
  3222. const std::function<void(Client &)> &setup,
  3223. const Headers &headers = Headers()) {
  3224. Server target_svr;
  3225. target_svr.Get("/target", target);
  3226. int target_port = 0;
  3227. auto target_thread = std::thread([&]() {
  3228. target_port = target_svr.bind_to_any_port(HOST);
  3229. target_svr.listen_after_bind();
  3230. });
  3231. Server origin_svr;
  3232. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3233. res.set_redirect(
  3234. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3235. });
  3236. int origin_port = 0;
  3237. auto origin_thread = std::thread([&]() {
  3238. origin_port = origin_svr.bind_to_any_port(HOST);
  3239. origin_svr.listen_after_bind();
  3240. });
  3241. auto se = detail::scope_exit([&] {
  3242. origin_svr.stop();
  3243. origin_thread.join();
  3244. target_svr.stop();
  3245. target_thread.join();
  3246. });
  3247. target_svr.wait_until_ready();
  3248. origin_svr.wait_until_ready();
  3249. Client cli("localhost", origin_port);
  3250. cli.set_follow_location(true);
  3251. setup(cli);
  3252. return cli.Get("/redir", headers);
  3253. }
  3254. static void
  3255. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3256. std::string captured_authorization;
  3257. auto result = GetThroughRedirectToDifferentPort(
  3258. [&](const Request &req, Response &res) {
  3259. captured_authorization = req.get_header_value("Authorization");
  3260. res.set_content("OK", "text/plain");
  3261. },
  3262. set_auth);
  3263. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3264. EXPECT_EQ(StatusCode::OK_200, result->status);
  3265. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3266. EXPECT_TRUE(captured_authorization.empty());
  3267. }
  3268. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3269. TestDoNotForwardCredentialsOnRedirect(
  3270. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3271. }
  3272. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3273. TestDoNotForwardCredentialsOnRedirect(
  3274. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3275. }
  3276. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3277. std::string captured_cookie;
  3278. auto result = GetThroughRedirectToDifferentPort(
  3279. [&](const Request &req, Response &res) {
  3280. captured_cookie = req.get_header_value("Cookie");
  3281. res.set_content("OK", "text/plain");
  3282. },
  3283. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3284. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3285. EXPECT_EQ(StatusCode::OK_200, result->status);
  3286. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3287. EXPECT_TRUE(captured_cookie.empty());
  3288. }
  3289. TEST(RedirectToSamePort, ForwardCookie) {
  3290. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3291. // header so that ordinary session flows keep working.
  3292. Server svr;
  3293. std::string captured_cookie;
  3294. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3295. res.set_redirect("/target", 302);
  3296. });
  3297. svr.Get("/target", [&](const Request &req, Response &res) {
  3298. captured_cookie = req.get_header_value("Cookie");
  3299. res.set_content("OK", "text/plain");
  3300. });
  3301. auto port = svr.bind_to_any_port(HOST);
  3302. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3303. auto se = detail::scope_exit([&] {
  3304. svr.stop();
  3305. thread.join();
  3306. ASSERT_FALSE(svr.is_running());
  3307. });
  3308. svr.wait_until_ready();
  3309. Client cli(HOST, port);
  3310. cli.set_follow_location(true);
  3311. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3312. auto res = cli.Get("/redir", headers);
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(StatusCode::OK_200, res->status);
  3315. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3316. }
  3317. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3318. std::string authorization;
  3319. std::string trace_id;
  3320. auto result = GetThroughRedirectToDifferentPort(
  3321. [&](const Request &req, Response &res) {
  3322. authorization = req.get_header_value("Authorization");
  3323. trace_id = req.get_header_value("X-Trace-Id");
  3324. res.set_content("OK", "text/plain");
  3325. },
  3326. [](Client &cli) {
  3327. cli.set_default_headers(
  3328. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3329. });
  3330. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3331. EXPECT_EQ(StatusCode::OK_200, result->status);
  3332. // Like a header given with the request, a default one goes along unless it
  3333. // carries credentials (RFC 9110 15.4).
  3334. EXPECT_TRUE(authorization.empty());
  3335. EXPECT_EQ("42", trace_id);
  3336. }
  3337. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3338. auto result = GetThroughRedirectToDifferentPort(
  3339. [](const Request &, Response &res) {
  3340. res.set_content(std::string(2048, 'x'), "text/plain");
  3341. },
  3342. [](Client &cli) { cli.set_payload_max_length(1024); });
  3343. EXPECT_FALSE(result);
  3344. }
  3345. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3346. auto result = GetThroughRedirectToDifferentPort(
  3347. [](const Request &req, Response &res) {
  3348. // Answer after a second, or once the client gives up.
  3349. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3350. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3351. }
  3352. res.set_content("late", "text/plain");
  3353. },
  3354. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3355. ASSERT_FALSE(result);
  3356. EXPECT_EQ(Error::Read, result.error());
  3357. }
  3358. #ifdef CPPHTTPLIB_SSL_ENABLED
  3359. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3360. auto result = GetThroughRedirectToDifferentPort(
  3361. [](const Request &, Response &res) {
  3362. res.status = StatusCode::Unauthorized_401;
  3363. res.set_header("WWW-Authenticate",
  3364. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3365. },
  3366. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3367. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3368. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3369. }
  3370. #endif
  3371. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3372. Server svr;
  3373. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3374. // Port number that overflows int — should not crash
  3375. res.set_redirect("http://localhost:99999999999999999999/target");
  3376. });
  3377. auto port = svr.bind_to_any_port(HOST);
  3378. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3379. auto se = detail::scope_exit([&] {
  3380. svr.stop();
  3381. thread.join();
  3382. ASSERT_FALSE(svr.is_running());
  3383. });
  3384. svr.wait_until_ready();
  3385. Client cli(HOST, port);
  3386. cli.set_follow_location(true);
  3387. auto res = cli.Get("/redir");
  3388. // Should fail gracefully, not crash (no valid response due to bad port)
  3389. EXPECT_FALSE(res);
  3390. }
  3391. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3392. Server svr;
  3393. auto port = svr.bind_to_any_port(HOST);
  3394. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3395. // The server's own port followed by junk must not be followed
  3396. res.set_redirect("http://" + std::string(HOST) + ":" +
  3397. std::to_string(port) + "junk/target");
  3398. });
  3399. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3400. res.set_content("target", "text/plain");
  3401. });
  3402. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3403. auto se = detail::scope_exit([&] {
  3404. svr.stop();
  3405. thread.join();
  3406. ASSERT_FALSE(svr.is_running());
  3407. });
  3408. svr.wait_until_ready();
  3409. Client cli(HOST, port);
  3410. cli.set_follow_location(true);
  3411. auto res = cli.Get("/redir");
  3412. EXPECT_FALSE(res);
  3413. }
  3414. TEST(RedirectFromPageWithContent, Redirect) {
  3415. Server svr;
  3416. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3417. res.set_content("___", "text/plain");
  3418. res.set_redirect("/2");
  3419. });
  3420. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3421. res.set_content("Hello World!", "text/plain");
  3422. });
  3423. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3424. auto se = detail::scope_exit([&] {
  3425. svr.stop();
  3426. th.join();
  3427. ASSERT_FALSE(svr.is_running());
  3428. });
  3429. svr.wait_until_ready();
  3430. {
  3431. Client cli("localhost", PORT);
  3432. cli.set_follow_location(true);
  3433. std::string body;
  3434. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3435. body.append(data, data_length);
  3436. return true;
  3437. });
  3438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3439. EXPECT_EQ(StatusCode::OK_200, res->status);
  3440. EXPECT_EQ("Hello World!", body);
  3441. }
  3442. {
  3443. Client cli("localhost", PORT);
  3444. std::string body;
  3445. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3446. body.append(data, data_length);
  3447. return true;
  3448. });
  3449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3450. EXPECT_EQ(StatusCode::Found_302, res->status);
  3451. EXPECT_EQ("___", body);
  3452. }
  3453. }
  3454. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3455. Server svr;
  3456. auto port_str = std::to_string(PORT);
  3457. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3458. auto expected_host = "[::1]:" + port_str;
  3459. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3460. res.set_content("___", "text/plain");
  3461. // res.set_redirect("/2");
  3462. res.set_redirect(redirect_url);
  3463. });
  3464. svr.Get("/2", [&](const Request &req, Response &res) {
  3465. auto host_header = req.headers.find("Host");
  3466. ASSERT_TRUE(host_header != req.headers.end());
  3467. EXPECT_EQ(expected_host, host_header->second);
  3468. res.set_content("Hello World!", "text/plain");
  3469. });
  3470. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3471. auto se = detail::scope_exit([&] {
  3472. svr.stop();
  3473. th.join();
  3474. ASSERT_FALSE(svr.is_running());
  3475. });
  3476. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3477. // actually starts anything, so the condition !svr.is_running() will
  3478. // always remain true, and the loop never stops.
  3479. // This basically counts how many milliseconds have passed since the
  3480. // call to svr.listen(), and if after 5 seconds nothing started yet
  3481. // aborts the test.
  3482. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3483. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3484. ASSERT_LT(milliseconds, 5000U);
  3485. }
  3486. {
  3487. Client cli("::1", PORT);
  3488. cli.set_follow_location(true);
  3489. std::string body;
  3490. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3491. body.append(data, data_length);
  3492. return true;
  3493. });
  3494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3495. EXPECT_EQ(StatusCode::OK_200, res->status);
  3496. EXPECT_EQ("Hello World!", body);
  3497. }
  3498. {
  3499. Client cli("::1", PORT);
  3500. std::string body;
  3501. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3502. body.append(data, data_length);
  3503. return true;
  3504. });
  3505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3506. EXPECT_EQ(StatusCode::Found_302, res->status);
  3507. EXPECT_EQ("___", body);
  3508. }
  3509. }
  3510. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3511. Server svr;
  3512. svr.Get("/foo", [](const Request &req, Response &res) {
  3513. auto a = req.params.find("a");
  3514. if (a != req.params.end()) {
  3515. res.set_content((*a).second, "text/plain");
  3516. res.status = StatusCode::OK_200;
  3517. } else {
  3518. res.status = StatusCode::BadRequest_400;
  3519. }
  3520. });
  3521. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3522. auto se = detail::scope_exit([&] {
  3523. svr.stop();
  3524. thread.join();
  3525. ASSERT_FALSE(svr.is_running());
  3526. });
  3527. svr.wait_until_ready();
  3528. {
  3529. Client cli(HOST, PORT);
  3530. cli.set_path_encode(false);
  3531. auto res = cli.Get("/foo?a=explicitly+encoded");
  3532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3533. EXPECT_EQ(StatusCode::OK_200, res->status);
  3534. // This expects it back with a space, as the `+` won't have been
  3535. // url-encoded, and server-side the params get decoded turning `+`
  3536. // into spaces.
  3537. EXPECT_EQ("explicitly encoded", res->body);
  3538. }
  3539. }
  3540. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3541. // When path encoding is disabled the client must transmit the supplied
  3542. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3543. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3544. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3545. // than a space (0x20). Assert on the raw wire target to catch this.
  3546. Server svr;
  3547. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3548. svr.Get("/foo", [&](const Request &req, Response &res) {
  3549. EXPECT_EQ(expected_target, req.target);
  3550. res.status = StatusCode::OK_200;
  3551. });
  3552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3553. auto se = detail::scope_exit([&] {
  3554. svr.stop();
  3555. thread.join();
  3556. ASSERT_FALSE(svr.is_running());
  3557. });
  3558. svr.wait_until_ready();
  3559. {
  3560. Client cli(HOST, PORT);
  3561. cli.set_path_encode(false);
  3562. auto res = cli.Get(expected_target.c_str());
  3563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3564. EXPECT_EQ(StatusCode::OK_200, res->status);
  3565. }
  3566. }
  3567. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3568. // `open_stream()` used to skip the path encoding that the buffered send
  3569. // path applies, so the same `path` produced different bytes in the request
  3570. // line depending on which API was used. Assert the two agree.
  3571. Server svr;
  3572. std::string target;
  3573. svr.Get(".*", [&](const Request &req, Response &res) {
  3574. target = req.target;
  3575. res.status = StatusCode::OK_200;
  3576. });
  3577. auto port = svr.bind_to_any_port(HOST);
  3578. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3579. auto se = detail::scope_exit([&] {
  3580. svr.stop();
  3581. thread.join();
  3582. ASSERT_FALSE(svr.is_running());
  3583. });
  3584. svr.wait_until_ready();
  3585. struct {
  3586. const char *path;
  3587. const char *expected;
  3588. } cases[] = {
  3589. {"/a b?x=1", "/a%20b?x=1"},
  3590. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3591. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3592. };
  3593. for (const auto &c : cases) {
  3594. Client cli(HOST, port);
  3595. target.clear();
  3596. auto res = cli.Get(c.path);
  3597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3598. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3599. auto buffered_target = target;
  3600. target.clear();
  3601. auto handle = cli.open_stream("GET", c.path);
  3602. EXPECT_TRUE(handle.is_valid())
  3603. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3604. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3605. }
  3606. }
  3607. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3608. // The `set_path_encode(false)` contract — transmit the supplied target
  3609. // verbatim — must hold for the streaming API too.
  3610. Server svr;
  3611. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3612. std::string target;
  3613. svr.Get("/foo", [&](const Request &req, Response &res) {
  3614. target = req.target;
  3615. res.status = StatusCode::OK_200;
  3616. });
  3617. auto port = svr.bind_to_any_port(HOST);
  3618. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3619. auto se = detail::scope_exit([&] {
  3620. svr.stop();
  3621. thread.join();
  3622. ASSERT_FALSE(svr.is_running());
  3623. });
  3624. svr.wait_until_ready();
  3625. {
  3626. Client cli(HOST, port);
  3627. cli.set_path_encode(false);
  3628. auto handle = cli.open_stream("GET", expected_target);
  3629. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3630. EXPECT_EQ(expected_target, target);
  3631. }
  3632. }
  3633. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3634. // With path encoding enabled a CR/LF in the target is percent-encoded
  3635. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3636. // write_request_line still backstops `set_path_encode(false)`, which is
  3637. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3638. Server svr;
  3639. // Captured before routing: the decoded path contains a newline, which a
  3640. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3641. std::string target;
  3642. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3643. target = req.target;
  3644. res.status = StatusCode::OK_200;
  3645. return Server::HandlerResponse::Handled;
  3646. });
  3647. auto port = svr.bind_to_any_port(HOST);
  3648. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3649. auto se = detail::scope_exit([&] {
  3650. svr.stop();
  3651. thread.join();
  3652. ASSERT_FALSE(svr.is_running());
  3653. });
  3654. svr.wait_until_ready();
  3655. {
  3656. Client cli(HOST, port);
  3657. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3658. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3659. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3660. }
  3661. }
  3662. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3663. // Every control character is percent-encoded, not just CR/LF, so the target
  3664. // passes the request-target check in write_request_line.
  3665. Server svr;
  3666. std::string target;
  3667. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3668. target = req.target;
  3669. res.status = StatusCode::OK_200;
  3670. return Server::HandlerResponse::Handled;
  3671. });
  3672. auto port = svr.bind_to_any_port(HOST);
  3673. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3674. auto se = detail::scope_exit([&] {
  3675. svr.stop();
  3676. thread.join();
  3677. ASSERT_FALSE(svr.is_running());
  3678. });
  3679. svr.wait_until_ready();
  3680. {
  3681. Client cli(HOST, port);
  3682. auto res = cli.Get("/a\tb\x1b\x7f");
  3683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3684. EXPECT_EQ("/a%09b%1B%7F", target);
  3685. }
  3686. }
  3687. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3688. // Nothing may reach the wire: a raw CR/LF target would split the request
  3689. // line and inject headers.
  3690. Server svr;
  3691. // Pre-routing so that "not called" means nothing reached the server at all,
  3692. // rather than merely failing to match a handler pattern.
  3693. auto handler_called = false;
  3694. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3695. handler_called = true;
  3696. res.status = StatusCode::OK_200;
  3697. return Server::HandlerResponse::Handled;
  3698. });
  3699. auto port = svr.bind_to_any_port(HOST);
  3700. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3701. auto se = detail::scope_exit([&] {
  3702. svr.stop();
  3703. thread.join();
  3704. ASSERT_FALSE(svr.is_running());
  3705. });
  3706. svr.wait_until_ready();
  3707. {
  3708. Client cli(HOST, port);
  3709. cli.set_path_encode(false);
  3710. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3711. EXPECT_FALSE(handle.is_valid());
  3712. EXPECT_EQ(Error::Write, handle.error);
  3713. EXPECT_FALSE(handler_called);
  3714. }
  3715. }
  3716. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3717. // Which of the two branches runs is decided by whether the query component
  3718. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3719. // an empty query and must still fall back to building one from
  3720. // `req.params`, while a non-empty query must win over `req.params`.
  3721. Server svr;
  3722. std::string target;
  3723. svr.Get("/foo", [&](const Request &req, Response &res) {
  3724. target = req.target;
  3725. res.status = StatusCode::OK_200;
  3726. });
  3727. auto port = svr.bind_to_any_port(HOST);
  3728. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3729. auto se = detail::scope_exit([&] {
  3730. svr.stop();
  3731. thread.join();
  3732. ASSERT_FALSE(svr.is_running());
  3733. });
  3734. svr.wait_until_ready();
  3735. {
  3736. // Trailing `?` -> empty query component -> `req.params` is used.
  3737. Client cli(HOST, port);
  3738. Request req;
  3739. req.method = "GET";
  3740. req.path = "/foo?";
  3741. req.params.emplace("a", "1");
  3742. target.clear();
  3743. auto res = cli.send(req);
  3744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3745. EXPECT_EQ("/foo?a=1", target);
  3746. }
  3747. {
  3748. // Non-empty query in `req.path` -> `req.params` is not appended.
  3749. Client cli(HOST, port);
  3750. Request req;
  3751. req.method = "GET";
  3752. req.path = "/foo?b=2";
  3753. req.params.emplace("a", "1");
  3754. target.clear();
  3755. auto res = cli.send(req);
  3756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3757. EXPECT_EQ("/foo?b=2", target);
  3758. }
  3759. }
  3760. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3761. Server svr;
  3762. svr.Get("/", [](const Request &req, Response &) {
  3763. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3764. });
  3765. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3766. auto se = detail::scope_exit([&] {
  3767. svr.stop();
  3768. thread.join();
  3769. ASSERT_FALSE(svr.is_running());
  3770. });
  3771. svr.wait_until_ready();
  3772. {
  3773. Client cli(HOST, PORT);
  3774. cli.set_path_encode(false);
  3775. auto res = cli.Get("/?something=%0A");
  3776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3777. EXPECT_EQ(StatusCode::OK_200, res->status);
  3778. }
  3779. }
  3780. TEST(BindServerTest, BindDualStack) {
  3781. Server svr;
  3782. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3783. res.set_content("Hello World!", "text/plain");
  3784. });
  3785. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3786. auto se = detail::scope_exit([&] {
  3787. svr.stop();
  3788. thread.join();
  3789. ASSERT_FALSE(svr.is_running());
  3790. });
  3791. svr.wait_until_ready();
  3792. {
  3793. Client cli("127.0.0.1", PORT);
  3794. auto res = cli.Get("/1");
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. EXPECT_EQ("Hello World!", res->body);
  3798. }
  3799. {
  3800. Client cli("::1", PORT);
  3801. auto res = cli.Get("/1");
  3802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3803. EXPECT_EQ(StatusCode::OK_200, res->status);
  3804. EXPECT_EQ("Hello World!", res->body);
  3805. }
  3806. }
  3807. TEST(BindServerTest, BindAndListenSeparately) {
  3808. Server svr;
  3809. int port = svr.bind_to_any_port("0.0.0.0");
  3810. ASSERT_TRUE(svr.is_valid());
  3811. ASSERT_TRUE(port > 0);
  3812. svr.stop();
  3813. }
  3814. // Reports whether anything is still listening on a loopback port. A plain
  3815. // connect() is used instead of a Client request because a socket left bound by
  3816. // mistake accepts the connection into its backlog and never answers, which
  3817. // would hang the test instead of failing it.
  3818. static bool is_loopback_port_accepting(int port) {
  3819. sockaddr_in addr{};
  3820. addr.sin_family = AF_INET;
  3821. addr.sin_port = htons(static_cast<uint16_t>(port));
  3822. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3823. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3824. EXPECT_NE(sock, INVALID_SOCKET);
  3825. if (sock == INVALID_SOCKET) { return false; }
  3826. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3827. static_cast<socklen_t>(sizeof(addr)));
  3828. detail::close_socket(sock);
  3829. return ret == 0;
  3830. }
  3831. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3832. Server svr;
  3833. auto port = svr.bind_to_any_port("127.0.0.1");
  3834. ASSERT_TRUE(port > 0);
  3835. svr.stop();
  3836. // bind_to_any_port() already called listen(2), so until stop() closed the
  3837. // descriptor the port kept accepting connections into the backlog. ASSERT
  3838. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3839. // below blocks forever in the accept loop.
  3840. ASSERT_FALSE(is_loopback_port_accepting(port));
  3841. // Nothing is left to accept on, so listen_after_bind() must report failure
  3842. // instead of returning success without ever serving.
  3843. EXPECT_FALSE(svr.listen_after_bind());
  3844. // The failed listen marks the server decommissioned, so a waiter returns
  3845. // instead of spinning forever.
  3846. svr.wait_until_ready();
  3847. }
  3848. #ifdef CPPHTTPLIB_SSL_ENABLED
  3849. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3851. CLIENT_CA_CERT_DIR);
  3852. int port = svr.bind_to_any_port("0.0.0.0");
  3853. ASSERT_TRUE(svr.is_valid());
  3854. ASSERT_TRUE(port > 0);
  3855. svr.stop();
  3856. }
  3857. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3858. // or a rejected CustomRoute() registration would not stop the server binding.
  3859. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3860. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3861. CLIENT_CA_CERT_DIR);
  3862. ASSERT_TRUE(svr.is_valid());
  3863. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3864. EXPECT_FALSE(svr.is_valid());
  3865. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3866. }
  3867. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3868. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3869. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3870. int port = svr.bind_to_any_port("0.0.0.0");
  3871. ASSERT_TRUE(svr.is_valid());
  3872. ASSERT_TRUE(port > 0);
  3873. svr.stop();
  3874. }
  3875. TEST(BindServerTest, UpdateCertsPem) {
  3876. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3877. int port = svr.bind_to_any_port("0.0.0.0");
  3878. ASSERT_TRUE(svr.is_valid());
  3879. ASSERT_TRUE(port > 0);
  3880. // Read PEM files
  3881. std::string cert_pem, key_pem, ca_pem;
  3882. read_file(SERVER_CERT_FILE, cert_pem);
  3883. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3884. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3885. // Update server certificates using PEM API
  3886. ASSERT_TRUE(
  3887. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3888. ASSERT_TRUE(svr.is_valid());
  3889. svr.stop();
  3890. }
  3891. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3892. // Start server with client CA (enables client auth)
  3893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3894. ASSERT_TRUE(svr.is_valid());
  3895. bool handler_called = false;
  3896. svr.Get("/test", [&](const Request &req, Response &res) {
  3897. handler_called = true;
  3898. // Verify client certificate is present
  3899. auto cert = req.peer_cert();
  3900. EXPECT_TRUE(static_cast<bool>(cert));
  3901. res.set_content("ok", "text/plain");
  3902. });
  3903. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3904. auto se = detail::scope_exit([&] {
  3905. svr.stop();
  3906. t.join();
  3907. ASSERT_FALSE(svr.is_running());
  3908. });
  3909. svr.wait_until_ready();
  3910. // Read PEM files
  3911. std::string cert_pem, key_pem, ca_pem;
  3912. read_file(SERVER_CERT_FILE, cert_pem);
  3913. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3914. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3915. // Update server certificates and client CA using PEM API while server running
  3916. ASSERT_TRUE(
  3917. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3918. // Connect with client certificate
  3919. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3920. cli.enable_server_certificate_verification(false);
  3921. cli.set_connection_timeout(30);
  3922. auto res = cli.Get("/test");
  3923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3924. ASSERT_EQ(StatusCode::OK_200, res->status);
  3925. ASSERT_TRUE(handler_called);
  3926. EXPECT_EQ("ok", res->body);
  3927. }
  3928. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  3929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3930. ASSERT_TRUE(svr.is_valid());
  3931. svr.Get("/test", [](const Request &, Response &res) {
  3932. res.set_content("ok", "text/plain");
  3933. });
  3934. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3935. auto se = detail::scope_exit([&] {
  3936. svr.stop();
  3937. t.join();
  3938. ASSERT_FALSE(svr.is_running());
  3939. });
  3940. svr.wait_until_ready();
  3941. // A connection that sends no ClientHello keeps its handshake in progress,
  3942. // once the server has had a moment to start it.
  3943. auto error = Error::Success;
  3944. auto sock = detail::create_client_socket(
  3945. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3946. /*connection_timeout_sec=*/5, 0,
  3947. /*read_timeout_sec=*/5, 0,
  3948. /*write_timeout_sec=*/5, 0, std::string(), error);
  3949. ASSERT_NE(INVALID_SOCKET, sock);
  3950. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3951. std::string cert_pem, key_pem;
  3952. read_file(SERVER_CERT_FILE, cert_pem);
  3953. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3954. auto update = std::async(std::launch::async, [&]() {
  3955. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  3956. });
  3957. EXPECT_EQ(std::future_status::timeout,
  3958. update.wait_for(std::chrono::milliseconds(200)));
  3959. detail::close_socket(sock);
  3960. EXPECT_TRUE(update.get());
  3961. SSLClient cli(HOST, PORT);
  3962. cli.enable_server_certificate_verification(false);
  3963. auto res = cli.Get("/test");
  3964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3965. EXPECT_EQ(StatusCode::OK_200, res->status);
  3966. }
  3967. #endif
  3968. TEST(ErrorHandlerTest, ContentLength) {
  3969. Server svr;
  3970. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3971. res.status = StatusCode::OK_200;
  3972. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3973. "text/html"); // <= Content-Length still 13
  3974. });
  3975. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3976. res.set_content("Hello World!\n", "text/plain");
  3977. res.status = 524;
  3978. });
  3979. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3980. auto se = detail::scope_exit([&] {
  3981. svr.stop();
  3982. thread.join();
  3983. ASSERT_FALSE(svr.is_running());
  3984. });
  3985. svr.wait_until_ready();
  3986. {
  3987. Client cli(HOST, PORT);
  3988. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3990. EXPECT_EQ(StatusCode::OK_200, res->status);
  3991. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3992. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3993. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3994. }
  3995. }
  3996. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3997. TEST(ExceptionTest, WithoutExceptionHandler) {
  3998. Server svr;
  3999. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4000. throw std::runtime_error("exception...");
  4001. });
  4002. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4003. throw std::runtime_error("exception\r\n...");
  4004. });
  4005. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4006. auto se = detail::scope_exit([&] {
  4007. svr.stop();
  4008. listen_thread.join();
  4009. ASSERT_FALSE(svr.is_running());
  4010. });
  4011. svr.wait_until_ready();
  4012. Client cli("localhost", PORT);
  4013. {
  4014. auto res = cli.Get("/exception");
  4015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4016. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4017. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4018. }
  4019. {
  4020. auto res = cli.Get("/unknown");
  4021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4022. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4023. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4024. }
  4025. }
  4026. TEST(ExceptionTest, WithExceptionHandler) {
  4027. Server svr;
  4028. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4029. std::exception_ptr ep) {
  4030. EXPECT_FALSE(ep == nullptr);
  4031. try {
  4032. std::rethrow_exception(ep);
  4033. } catch (std::exception &e) {
  4034. EXPECT_EQ("abc", std::string(e.what()));
  4035. } catch (...) {}
  4036. res.status = StatusCode::InternalServerError_500;
  4037. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4038. "text/html"); // <= Content-Length still 13 at this point
  4039. });
  4040. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4041. res.set_content("Hello World!\n", "text/plain");
  4042. throw std::runtime_error("abc");
  4043. });
  4044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4045. auto se = detail::scope_exit([&] {
  4046. svr.stop();
  4047. thread.join();
  4048. ASSERT_FALSE(svr.is_running());
  4049. });
  4050. svr.wait_until_ready();
  4051. for (size_t i = 0; i < 10; i++) {
  4052. Client cli(HOST, PORT);
  4053. for (size_t j = 0; j < 100; j++) {
  4054. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4056. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4057. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4058. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4059. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4060. }
  4061. cli.set_keep_alive(true);
  4062. for (size_t j = 0; j < 100; j++) {
  4063. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4065. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4066. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4067. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4068. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4069. }
  4070. }
  4071. }
  4072. TEST(ExceptionTest, AndErrorHandler) {
  4073. Server svr;
  4074. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4075. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4076. });
  4077. svr.set_exception_handler(
  4078. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4079. EXPECT_FALSE(ep == nullptr);
  4080. try {
  4081. std::rethrow_exception(ep);
  4082. } catch (std::exception &e) {
  4083. res.set_content(e.what(), "text/html");
  4084. } catch (...) {}
  4085. res.status = StatusCode::InternalServerError_500;
  4086. });
  4087. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4088. throw std::runtime_error("EXCEPTION");
  4089. });
  4090. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4091. res.set_content("ERROR", "text/html");
  4092. res.status = StatusCode::InternalServerError_500;
  4093. });
  4094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4095. auto se = detail::scope_exit([&] {
  4096. svr.stop();
  4097. thread.join();
  4098. ASSERT_FALSE(svr.is_running());
  4099. });
  4100. svr.wait_until_ready();
  4101. Client cli(HOST, PORT);
  4102. {
  4103. auto res = cli.Get("/exception");
  4104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4105. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4106. EXPECT_EQ("EXCEPTION", res->body);
  4107. }
  4108. {
  4109. auto res = cli.Get("/error");
  4110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4111. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4112. EXPECT_EQ("ERROR", res->body);
  4113. }
  4114. {
  4115. auto res = cli.Get("/invalid");
  4116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4117. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4118. EXPECT_EQ("NOT_FOUND", res->body);
  4119. }
  4120. }
  4121. #endif
  4122. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4123. // process_request() wraps only routing() in a try/catch, so an exception from
  4124. // any other user callback used to unwind into the task queue - which does not
  4125. // catch - and terminate the process. Each test below runs the server on a
  4126. // single worker thread: a guard that catches the exception but still loses the
  4127. // thread would otherwise be hidden by a spare worker serving the follow-up
  4128. // request. Note that a regression here aborts the whole test binary rather
  4129. // than failing one test.
  4130. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4131. Server svr;
  4132. svr.new_task_queue = [] { return new ThreadPool(1); };
  4133. std::atomic<int> reported{0};
  4134. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4135. if (err == Error::UserCallbackException) { reported++; }
  4136. });
  4137. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4138. res.set_content_provider(
  4139. 1024, "text/plain",
  4140. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4141. sink.write("hello", 5);
  4142. throw std::runtime_error("from the content provider");
  4143. });
  4144. });
  4145. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4146. res.set_content("ok", "text/plain");
  4147. });
  4148. auto port = svr.bind_to_any_port(HOST);
  4149. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4150. auto se = detail::scope_exit([&] {
  4151. svr.stop();
  4152. listen_thread.join();
  4153. ASSERT_FALSE(svr.is_running());
  4154. });
  4155. svr.wait_until_ready();
  4156. {
  4157. Client cli(HOST, port);
  4158. cli.set_read_timeout(5, 0);
  4159. EXPECT_FALSE(cli.Get("/throw"));
  4160. }
  4161. EXPECT_TRUE(svr.is_running());
  4162. EXPECT_EQ(1, reported.load());
  4163. // A request on a fresh connection is still served.
  4164. {
  4165. Client cli(HOST, port);
  4166. auto res = cli.Get("/ok");
  4167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4168. EXPECT_EQ(StatusCode::OK_200, res->status);
  4169. EXPECT_EQ("ok", res->body);
  4170. }
  4171. }
  4172. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4173. Server svr;
  4174. svr.new_task_queue = [] { return new ThreadPool(1); };
  4175. std::atomic<bool> should_throw{true};
  4176. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4177. res.set_content("hi", "text/plain");
  4178. });
  4179. svr.set_post_routing_handler(
  4180. [&](const Request & /*req*/, Response & /*res*/) {
  4181. if (should_throw) {
  4182. throw std::runtime_error("from the post-routing handler");
  4183. }
  4184. });
  4185. auto port = svr.bind_to_any_port(HOST);
  4186. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4187. auto se = detail::scope_exit([&] {
  4188. svr.stop();
  4189. listen_thread.join();
  4190. ASSERT_FALSE(svr.is_running());
  4191. });
  4192. svr.wait_until_ready();
  4193. {
  4194. Client cli(HOST, port);
  4195. cli.set_read_timeout(5, 0);
  4196. EXPECT_FALSE(cli.Get("/hi"));
  4197. }
  4198. EXPECT_TRUE(svr.is_running());
  4199. should_throw = false;
  4200. {
  4201. Client cli(HOST, port);
  4202. auto res = cli.Get("/hi");
  4203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4204. EXPECT_EQ(StatusCode::OK_200, res->status);
  4205. EXPECT_EQ("hi", res->body);
  4206. }
  4207. }
  4208. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4209. // The guard reports the caught exception through the error logger, which is
  4210. // a user callback too. A logger that throws has to be contained as well, or
  4211. // the process would terminate from inside the catch.
  4212. Server svr;
  4213. svr.new_task_queue = [] { return new ThreadPool(1); };
  4214. std::atomic<int> reported{0};
  4215. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4216. if (err == Error::UserCallbackException) {
  4217. reported++;
  4218. throw std::runtime_error("from the error logger");
  4219. }
  4220. });
  4221. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4222. res.set_content_provider(
  4223. 1024, "text/plain",
  4224. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4225. sink.write("hello", 5);
  4226. throw std::runtime_error("from the content provider");
  4227. });
  4228. });
  4229. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4230. res.set_content("ok", "text/plain");
  4231. });
  4232. auto port = svr.bind_to_any_port(HOST);
  4233. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4234. auto se = detail::scope_exit([&] {
  4235. svr.stop();
  4236. listen_thread.join();
  4237. ASSERT_FALSE(svr.is_running());
  4238. });
  4239. svr.wait_until_ready();
  4240. {
  4241. Client cli(HOST, port);
  4242. cli.set_read_timeout(5, 0);
  4243. EXPECT_FALSE(cli.Get("/throw"));
  4244. }
  4245. EXPECT_TRUE(svr.is_running());
  4246. EXPECT_EQ(1, reported.load());
  4247. {
  4248. Client cli(HOST, port);
  4249. auto res = cli.Get("/ok");
  4250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4251. EXPECT_EQ(StatusCode::OK_200, res->status);
  4252. EXPECT_EQ("ok", res->body);
  4253. }
  4254. }
  4255. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4256. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4257. // so the exception unwinds through the ws::WebSocket object on its way to
  4258. // the guard. None of the HTTP cases above cross that.
  4259. Server svr;
  4260. svr.new_task_queue = [] { return new ThreadPool(1); };
  4261. std::atomic<int> reported{0};
  4262. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4263. if (err == Error::UserCallbackException) { reported++; }
  4264. });
  4265. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4266. throw std::runtime_error("from the WebSocket handler");
  4267. });
  4268. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4269. res.set_content("ok", "text/plain");
  4270. });
  4271. auto port = svr.bind_to_any_port(HOST);
  4272. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4273. auto se = detail::scope_exit([&] {
  4274. svr.stop();
  4275. listen_thread.join();
  4276. ASSERT_FALSE(svr.is_running());
  4277. });
  4278. svr.wait_until_ready();
  4279. {
  4280. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4281. "/ws");
  4282. auto res = client.connect();
  4283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4284. // The server dropped the connection instead of dying.
  4285. std::string msg;
  4286. EXPECT_FALSE(client.read(msg));
  4287. client.close();
  4288. }
  4289. EXPECT_TRUE(svr.is_running());
  4290. EXPECT_EQ(1, reported.load());
  4291. {
  4292. Client cli(HOST, port);
  4293. auto res = cli.Get("/ok");
  4294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4295. EXPECT_EQ(StatusCode::OK_200, res->status);
  4296. EXPECT_EQ("ok", res->body);
  4297. }
  4298. }
  4299. #ifdef CPPHTTPLIB_SSL_ENABLED
  4300. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4301. // SSLServer::process_and_close_socket() is a separate overload with its own
  4302. // guard, so it is exercised on its own.
  4303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4304. ASSERT_TRUE(svr.is_valid());
  4305. svr.new_task_queue = [] { return new ThreadPool(1); };
  4306. std::atomic<int> reported{0};
  4307. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4308. if (err == Error::UserCallbackException) { reported++; }
  4309. });
  4310. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4311. res.set_content_provider(
  4312. 1024, "text/plain",
  4313. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4314. sink.write("hello", 5);
  4315. throw std::runtime_error("from the content provider");
  4316. });
  4317. });
  4318. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4319. res.set_content("ok", "text/plain");
  4320. });
  4321. auto port = svr.bind_to_any_port(HOST);
  4322. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4323. auto se = detail::scope_exit([&] {
  4324. svr.stop();
  4325. listen_thread.join();
  4326. ASSERT_FALSE(svr.is_running());
  4327. });
  4328. svr.wait_until_ready();
  4329. {
  4330. SSLClient cli(HOST, port);
  4331. cli.enable_server_certificate_verification(false);
  4332. cli.set_read_timeout(5, 0);
  4333. EXPECT_FALSE(cli.Get("/throw"));
  4334. }
  4335. EXPECT_TRUE(svr.is_running());
  4336. EXPECT_EQ(1, reported.load());
  4337. {
  4338. SSLClient cli(HOST, port);
  4339. cli.enable_server_certificate_verification(false);
  4340. auto res = cli.Get("/ok");
  4341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4342. EXPECT_EQ(StatusCode::OK_200, res->status);
  4343. EXPECT_EQ("ok", res->body);
  4344. }
  4345. }
  4346. #endif
  4347. #endif
  4348. TEST(NoContentTest, ContentLength) {
  4349. Server svr;
  4350. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4351. res.status = StatusCode::NoContent_204;
  4352. });
  4353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4354. auto se = detail::scope_exit([&] {
  4355. svr.stop();
  4356. thread.join();
  4357. ASSERT_FALSE(svr.is_running());
  4358. });
  4359. svr.wait_until_ready();
  4360. {
  4361. Client cli(HOST, PORT);
  4362. auto res = cli.Get("/hi");
  4363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4364. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4365. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4366. }
  4367. }
  4368. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4369. #ifdef CPPHTTPLIB_SSL_ENABLED
  4370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4371. ASSERT_TRUE(svr.is_valid());
  4372. #else
  4373. Server svr;
  4374. #endif
  4375. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4376. if (req.path == "/routing_handler") {
  4377. res.set_header("PRE_ROUTING", "on");
  4378. res.set_content("Routing Handler", "text/plain");
  4379. return httplib::Server::HandlerResponse::Handled;
  4380. }
  4381. return httplib::Server::HandlerResponse::Unhandled;
  4382. });
  4383. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4384. res.set_content("Error", "text/html");
  4385. });
  4386. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4387. if (req.path == "/routing_handler") {
  4388. res.set_header("POST_ROUTING", "on");
  4389. }
  4390. });
  4391. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4392. res.set_content("Hello World!\n", "text/plain");
  4393. });
  4394. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4395. auto se = detail::scope_exit([&] {
  4396. svr.stop();
  4397. thread.join();
  4398. ASSERT_FALSE(svr.is_running());
  4399. });
  4400. svr.wait_until_ready();
  4401. {
  4402. #ifdef CPPHTTPLIB_SSL_ENABLED
  4403. SSLClient cli(HOST, PORT);
  4404. cli.enable_server_certificate_verification(false);
  4405. #else
  4406. Client cli(HOST, PORT);
  4407. #endif
  4408. auto res = cli.Get("/routing_handler");
  4409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4410. EXPECT_EQ(StatusCode::OK_200, res->status);
  4411. EXPECT_EQ("Routing Handler", res->body);
  4412. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4413. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4414. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4415. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4416. }
  4417. {
  4418. #ifdef CPPHTTPLIB_SSL_ENABLED
  4419. SSLClient cli(HOST, PORT);
  4420. cli.enable_server_certificate_verification(false);
  4421. #else
  4422. Client cli(HOST, PORT);
  4423. #endif
  4424. auto res = cli.Get("/hi");
  4425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4426. EXPECT_EQ(StatusCode::OK_200, res->status);
  4427. EXPECT_EQ("Hello World!\n", res->body);
  4428. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4429. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4430. }
  4431. {
  4432. #ifdef CPPHTTPLIB_SSL_ENABLED
  4433. SSLClient cli(HOST, PORT);
  4434. cli.enable_server_certificate_verification(false);
  4435. #else
  4436. Client cli(HOST, PORT);
  4437. #endif
  4438. auto res = cli.Get("/aaa");
  4439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4440. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4441. EXPECT_EQ("Error", res->body);
  4442. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4443. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4444. }
  4445. }
  4446. TEST(RequestHandlerTest, PreRequestHandler) {
  4447. auto route_path = "/user/:user";
  4448. Server svr;
  4449. svr.Get("/hi", [](const Request &, Response &res) {
  4450. res.set_content("hi", "text/plain");
  4451. });
  4452. svr.Get(route_path, [](const Request &req, Response &res) {
  4453. res.set_content(req.path_params.at("user"), "text/plain");
  4454. });
  4455. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4456. if (req.matched_route == route_path) {
  4457. auto user = req.path_params.at("user");
  4458. if (user != "john") {
  4459. res.status = StatusCode::Forbidden_403;
  4460. res.set_content("error", "text/html");
  4461. return Server::HandlerResponse::Handled;
  4462. }
  4463. }
  4464. return Server::HandlerResponse::Unhandled;
  4465. });
  4466. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4467. auto se = detail::scope_exit([&] {
  4468. svr.stop();
  4469. thread.join();
  4470. ASSERT_FALSE(svr.is_running());
  4471. });
  4472. svr.wait_until_ready();
  4473. Client cli(HOST, PORT);
  4474. {
  4475. auto res = cli.Get("/hi");
  4476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4477. EXPECT_EQ(StatusCode::OK_200, res->status);
  4478. EXPECT_EQ("hi", res->body);
  4479. }
  4480. {
  4481. auto res = cli.Get("/user/john");
  4482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4483. EXPECT_EQ(StatusCode::OK_200, res->status);
  4484. EXPECT_EQ("john", res->body);
  4485. }
  4486. {
  4487. auto res = cli.Get("/user/invalid-user");
  4488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4489. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4490. EXPECT_EQ("error", res->body);
  4491. }
  4492. }
  4493. // The pre-request handler must run before the request body is read, so a
  4494. // rejected request never forces the server to buffer a (potentially large)
  4495. // body. Here the posted body is larger than the payload limit: if the body
  4496. // were read first the server would answer 413, but because the pre-request
  4497. // handler runs first it answers 403 and the body is never read.
  4498. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4499. Server svr;
  4500. svr.set_payload_max_length(8);
  4501. auto handler_ran = false;
  4502. svr.Post("/reject", [&](const Request &req, Response &res) {
  4503. handler_ran = true;
  4504. res.set_content(req.body, "text/plain");
  4505. });
  4506. svr.Post("/accept", [](const Request &req, Response &res) {
  4507. res.set_content(req.body, "text/plain");
  4508. });
  4509. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4510. if (req.matched_route == "/reject") {
  4511. res.status = StatusCode::Forbidden_403;
  4512. res.set_content("denied", "text/plain");
  4513. return Server::HandlerResponse::Handled;
  4514. }
  4515. return Server::HandlerResponse::Unhandled;
  4516. });
  4517. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4518. auto se = detail::scope_exit([&] {
  4519. svr.stop();
  4520. thread.join();
  4521. ASSERT_FALSE(svr.is_running());
  4522. });
  4523. svr.wait_until_ready();
  4524. Client cli(HOST, PORT);
  4525. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4526. // rejects with 403 before the body is read, so 413 is never reached.
  4527. {
  4528. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4530. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4531. EXPECT_EQ("denied", res->body);
  4532. EXPECT_FALSE(handler_ran);
  4533. }
  4534. // An approved route still reads the body and enforces the payload limit.
  4535. {
  4536. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4538. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4539. }
  4540. }
  4541. TEST(UserDataTest, BasicOperations) {
  4542. httplib::UserData ud;
  4543. // Initially empty
  4544. EXPECT_FALSE(ud.has("key"));
  4545. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4546. // set and get
  4547. ud.set("key", 42);
  4548. EXPECT_TRUE(ud.has("key"));
  4549. auto *p = ud.get<int>("key");
  4550. ASSERT_NE(nullptr, p);
  4551. EXPECT_EQ(42, *p);
  4552. // Type mismatch → nullptr
  4553. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4554. // Overwrite with different type
  4555. ud.set("key", std::string("hello"));
  4556. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4557. auto *s = ud.get<std::string>("key");
  4558. ASSERT_NE(nullptr, s);
  4559. EXPECT_EQ("hello", *s);
  4560. // erase
  4561. ud.erase("key");
  4562. EXPECT_FALSE(ud.has("key"));
  4563. // clear
  4564. ud.set("a", 1);
  4565. ud.set("b", 2);
  4566. ud.clear();
  4567. EXPECT_FALSE(ud.has("a"));
  4568. EXPECT_FALSE(ud.has("b"));
  4569. }
  4570. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4571. struct AuthCtx {
  4572. std::string user_id;
  4573. };
  4574. Server svr;
  4575. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4576. res.user_data.set("auth", AuthCtx{"alice"});
  4577. return Server::HandlerResponse::Unhandled;
  4578. });
  4579. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4580. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4581. ASSERT_NE(nullptr, ctx);
  4582. res.set_content("Hello " + ctx->user_id, "text/plain");
  4583. });
  4584. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4585. auto se = detail::scope_exit([&] {
  4586. svr.stop();
  4587. thread.join();
  4588. ASSERT_FALSE(svr.is_running());
  4589. });
  4590. svr.wait_until_ready();
  4591. Client cli(HOST, PORT);
  4592. auto res = cli.Get("/me");
  4593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4594. EXPECT_EQ(StatusCode::OK_200, res->status);
  4595. EXPECT_EQ("Hello alice", res->body);
  4596. }
  4597. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4598. struct RoleCtx {
  4599. std::string role;
  4600. };
  4601. Server svr;
  4602. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4603. res.user_data.set("role", RoleCtx{"admin"});
  4604. return Server::HandlerResponse::Unhandled;
  4605. });
  4606. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4607. auto *ctx = res.user_data.get<RoleCtx>("role");
  4608. ASSERT_NE(nullptr, ctx);
  4609. res.set_content(ctx->role, "text/plain");
  4610. });
  4611. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4612. auto se = detail::scope_exit([&] {
  4613. svr.stop();
  4614. thread.join();
  4615. ASSERT_FALSE(svr.is_running());
  4616. });
  4617. svr.wait_until_ready();
  4618. Client cli(HOST, PORT);
  4619. auto res = cli.Get("/role");
  4620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4621. EXPECT_EQ(StatusCode::OK_200, res->status);
  4622. EXPECT_EQ("admin", res->body);
  4623. }
  4624. TEST(InvalidFormatTest, StatusCode) {
  4625. Server svr;
  4626. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4627. res.set_content("Hello World!\n", "text/plain");
  4628. res.status = 9999; // Status should be a three-digit code...
  4629. });
  4630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4631. auto se = detail::scope_exit([&] {
  4632. svr.stop();
  4633. thread.join();
  4634. ASSERT_FALSE(svr.is_running());
  4635. });
  4636. svr.wait_until_ready();
  4637. {
  4638. Client cli(HOST, PORT);
  4639. auto res = cli.Get("/hi");
  4640. ASSERT_FALSE(res);
  4641. }
  4642. }
  4643. TEST(URLFragmentTest, WithFragment) {
  4644. Server svr;
  4645. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4646. EXPECT_TRUE(req.target == "/hi");
  4647. });
  4648. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4649. auto se = detail::scope_exit([&] {
  4650. svr.stop();
  4651. thread.join();
  4652. ASSERT_FALSE(svr.is_running());
  4653. });
  4654. svr.wait_until_ready();
  4655. {
  4656. Client cli(HOST, PORT);
  4657. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4658. EXPECT_TRUE(res);
  4659. EXPECT_EQ(StatusCode::OK_200, res->status);
  4660. res = cli.Get("/hi%23key1=val1=key2=val2");
  4661. EXPECT_TRUE(res);
  4662. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4663. }
  4664. }
  4665. TEST(HeaderWriter, SetHeaderWriter) {
  4666. Server svr;
  4667. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4668. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4669. return detail::write_headers(strm, hdrs);
  4670. });
  4671. svr.Get("/hi", [](const Request &req, Response &res) {
  4672. auto it = req.headers.find("CustomClientHeader");
  4673. EXPECT_TRUE(it != req.headers.end());
  4674. EXPECT_EQ(it->second, "CustomClientValue");
  4675. res.set_content("Hello World!\n", "text/plain");
  4676. });
  4677. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4678. auto se = detail::scope_exit([&] {
  4679. svr.stop();
  4680. thread.join();
  4681. ASSERT_FALSE(svr.is_running());
  4682. });
  4683. svr.wait_until_ready();
  4684. {
  4685. Client cli(HOST, PORT);
  4686. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4687. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4688. return detail::write_headers(strm, hdrs);
  4689. });
  4690. auto res = cli.Get("/hi");
  4691. EXPECT_TRUE(res);
  4692. EXPECT_EQ(StatusCode::OK_200, res->status);
  4693. auto it = res->headers.find("CustomServerHeader");
  4694. EXPECT_TRUE(it != res->headers.end());
  4695. EXPECT_EQ(it->second, "CustomServerValue");
  4696. }
  4697. }
  4698. class ServerTest : public ::testing::Test {
  4699. protected:
  4700. ServerTest()
  4701. : cli_(HOST, PORT)
  4702. #ifdef CPPHTTPLIB_SSL_ENABLED
  4703. ,
  4704. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4705. #endif
  4706. {
  4707. #ifdef CPPHTTPLIB_SSL_ENABLED
  4708. cli_.enable_server_certificate_verification(false);
  4709. #endif
  4710. // Allow LARGE_DATA (100MB) responses
  4711. cli_.set_payload_max_length(200 * 1024 * 1024);
  4712. }
  4713. virtual void SetUp() {
  4714. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4715. svr_.set_payload_max_length(200 * 1024 * 1024);
  4716. svr_.set_mount_point("/", "./www");
  4717. svr_.set_mount_point("/mount", "./www2");
  4718. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4719. svr_.Get("/hi",
  4720. [&](const Request & /*req*/, Response &res) {
  4721. res.set_content("Hello World!", "text/plain");
  4722. })
  4723. .Get("/file_content",
  4724. [&](const Request & /*req*/, Response &res) {
  4725. res.set_file_content("./www/dir/test.html");
  4726. })
  4727. .Get("/file_content_with_content_type",
  4728. [&](const Request & /*req*/, Response &res) {
  4729. res.set_file_content("./www/file", "text/plain");
  4730. })
  4731. .Get("/invalid_file_content",
  4732. [&](const Request & /*req*/, Response &res) {
  4733. res.set_file_content("./www/dir/invalid_file_path");
  4734. })
  4735. .Get("/http_response_splitting",
  4736. [&](const Request & /*req*/, Response &res) {
  4737. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4738. EXPECT_EQ(0U, res.headers.size());
  4739. EXPECT_FALSE(res.has_header("a"));
  4740. res.set_header("a", "1\nSet-Cookie: a=1");
  4741. EXPECT_EQ(0U, res.headers.size());
  4742. EXPECT_FALSE(res.has_header("a"));
  4743. res.set_header("a", "1\rSet-Cookie: a=1");
  4744. EXPECT_EQ(0U, res.headers.size());
  4745. EXPECT_FALSE(res.has_header("a"));
  4746. res.set_header("a\r\nb", "0");
  4747. EXPECT_EQ(0U, res.headers.size());
  4748. EXPECT_FALSE(res.has_header("a"));
  4749. res.set_header("a\rb", "0");
  4750. EXPECT_EQ(0U, res.headers.size());
  4751. EXPECT_FALSE(res.has_header("a"));
  4752. res.set_header("a\nb", "0");
  4753. EXPECT_EQ(0U, res.headers.size());
  4754. EXPECT_FALSE(res.has_header("a"));
  4755. res.set_redirect("1\r\nSet-Cookie: a=1");
  4756. EXPECT_EQ(0U, res.headers.size());
  4757. EXPECT_FALSE(res.has_header("Location"));
  4758. })
  4759. .Get("/slow",
  4760. [&](const Request & /*req*/, Response &res) {
  4761. std::this_thread::sleep_for(std::chrono::seconds(4));
  4762. res.set_content("slow", "text/plain");
  4763. })
  4764. #if 0
  4765. .Post("/slowpost",
  4766. [&](const Request & /*req*/, Response &res) {
  4767. std::this_thread::sleep_for(std::chrono::seconds(2));
  4768. res.set_content("slow", "text/plain");
  4769. })
  4770. #endif
  4771. .Get("/remote_addr",
  4772. [&](const Request &req, Response &res) {
  4773. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4774. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4775. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4776. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4777. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4778. #endif
  4779. res.set_content(req.remote_addr, "text/plain");
  4780. })
  4781. .Get("/local_addr",
  4782. [&](const Request &req, Response &res) {
  4783. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4784. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4785. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4786. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4787. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4788. #endif
  4789. auto local_addr = req.local_addr;
  4790. auto local_port = std::to_string(req.local_port);
  4791. res.set_content(local_addr.append(":").append(local_port),
  4792. "text/plain");
  4793. })
  4794. .Get("/endwith%",
  4795. [&](const Request & /*req*/, Response &res) {
  4796. res.set_content("Hello World!", "text/plain");
  4797. })
  4798. .Get("/a\\+\\+b",
  4799. [&](const Request &req, Response &res) {
  4800. ASSERT_TRUE(req.has_param("a +b"));
  4801. auto val = req.get_param_value("a +b");
  4802. res.set_content(val, "text/plain");
  4803. })
  4804. .Get("/", [&](const Request & /*req*/,
  4805. Response &res) { res.set_redirect("/hi"); })
  4806. .Post("/1",
  4807. [](const Request & /*req*/, Response &res) {
  4808. res.set_redirect("/2", StatusCode::SeeOther_303);
  4809. })
  4810. .Get("/2",
  4811. [](const Request & /*req*/, Response &res) {
  4812. res.set_content("redirected.", "text/plain");
  4813. res.status = StatusCode::OK_200;
  4814. })
  4815. .Post("/person",
  4816. [&](const Request &req, Response &res) {
  4817. if (req.has_param("name") && req.has_param("note")) {
  4818. persons_[req.get_param_value("name")] =
  4819. req.get_param_value("note");
  4820. } else {
  4821. res.status = StatusCode::BadRequest_400;
  4822. }
  4823. })
  4824. .Put("/person",
  4825. [&](const Request &req, Response &res) {
  4826. if (req.has_param("name") && req.has_param("note")) {
  4827. persons_[req.get_param_value("name")] =
  4828. req.get_param_value("note");
  4829. } else {
  4830. res.status = StatusCode::BadRequest_400;
  4831. }
  4832. })
  4833. .Get("/person/(.*)",
  4834. [&](const Request &req, Response &res) {
  4835. string name = req.matches[1];
  4836. if (persons_.find(name) != persons_.end()) {
  4837. auto note = persons_[name];
  4838. res.set_content(note, "text/plain");
  4839. } else {
  4840. res.status = StatusCode::NotFound_404;
  4841. }
  4842. })
  4843. .Delete("/person",
  4844. [&](const Request &req, Response &res) {
  4845. if (req.has_param("name")) {
  4846. string name = req.get_param_value("name");
  4847. if (persons_.find(name) != persons_.end()) {
  4848. persons_.erase(name);
  4849. res.set_content("DELETED", "text/plain");
  4850. } else {
  4851. res.status = StatusCode::NotFound_404;
  4852. }
  4853. } else {
  4854. res.status = StatusCode::BadRequest_400;
  4855. }
  4856. })
  4857. .Post("/x-www-form-urlencoded-json",
  4858. [&](const Request &req, Response &res) {
  4859. auto json = req.get_param_value("json");
  4860. ASSERT_EQ(JSON_DATA, json);
  4861. res.set_content(json, "appliation/json");
  4862. res.status = StatusCode::OK_200;
  4863. })
  4864. .Get("/streamed-chunked",
  4865. [&](const Request & /*req*/, Response &res) {
  4866. res.set_chunked_content_provider(
  4867. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4868. sink.os << "123";
  4869. sink.os << "456";
  4870. sink.os << "789";
  4871. sink.done();
  4872. return true;
  4873. });
  4874. })
  4875. .Get("/streamed-chunked-with-prohibited-trailer",
  4876. [&](const Request & /*req*/, Response &res) {
  4877. auto i = new int(0);
  4878. // Declare both a prohibited trailer (Content-Length) and an
  4879. // allowed one
  4880. res.set_header("Trailer", "Content-Length, X-Allowed");
  4881. res.set_chunked_content_provider(
  4882. "text/plain",
  4883. [i](size_t /*offset*/, DataSink &sink) {
  4884. switch (*i) {
  4885. case 0: sink.os << "123"; break;
  4886. case 1: sink.os << "456"; break;
  4887. case 2: sink.os << "789"; break;
  4888. case 3: {
  4889. sink.done_with_trailer(
  4890. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4891. } break;
  4892. }
  4893. (*i)++;
  4894. return true;
  4895. },
  4896. [i](bool success) {
  4897. EXPECT_TRUE(success);
  4898. delete i;
  4899. });
  4900. })
  4901. .Get("/streamed-chunked2",
  4902. [&](const Request & /*req*/, Response &res) {
  4903. auto i = new int(0);
  4904. res.set_chunked_content_provider(
  4905. "text/plain",
  4906. [i](size_t /*offset*/, DataSink &sink) {
  4907. switch (*i) {
  4908. case 0: sink.os << "123"; break;
  4909. case 1: sink.os << "456"; break;
  4910. case 2: sink.os << "789"; break;
  4911. case 3: sink.done(); break;
  4912. }
  4913. (*i)++;
  4914. return true;
  4915. },
  4916. [i](bool success) {
  4917. EXPECT_TRUE(success);
  4918. delete i;
  4919. });
  4920. })
  4921. .Get("/streamed-chunked-with-trailer",
  4922. [&](const Request & /*req*/, Response &res) {
  4923. auto i = new int(0);
  4924. res.set_header("Trailer", "Dummy1, Dummy2");
  4925. res.set_chunked_content_provider(
  4926. "text/plain",
  4927. [i](size_t /*offset*/, DataSink &sink) {
  4928. switch (*i) {
  4929. case 0: sink.os << "123"; break;
  4930. case 1: sink.os << "456"; break;
  4931. case 2: sink.os << "789"; break;
  4932. case 3: {
  4933. sink.done_with_trailer(
  4934. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4935. } break;
  4936. }
  4937. (*i)++;
  4938. return true;
  4939. },
  4940. [i](bool success) {
  4941. EXPECT_TRUE(success);
  4942. delete i;
  4943. });
  4944. })
  4945. .Get("/streamed",
  4946. [&](const Request & /*req*/, Response &res) {
  4947. res.set_content_provider(
  4948. 6, "text/plain",
  4949. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4950. sink.os << (offset < 3 ? "a" : "b");
  4951. return true;
  4952. });
  4953. })
  4954. .Get("/streamed-without-length",
  4955. [&](const Request & /*req*/, Response &res) {
  4956. auto data = new std::string("abcdefg");
  4957. res.set_content_provider(
  4958. "text/plain",
  4959. [data](size_t offset, DataSink &sink) {
  4960. if (offset < data->size()) {
  4961. sink.os << data->substr(offset);
  4962. }
  4963. sink.done();
  4964. return true;
  4965. },
  4966. [data](bool success) {
  4967. EXPECT_TRUE(success);
  4968. delete data;
  4969. });
  4970. })
  4971. .Get("/streamed-with-range",
  4972. [&](const Request &req, Response &res) {
  4973. auto data = new std::string("abcdefg");
  4974. // An explicit status keeps the server from picking the 206 it
  4975. // would otherwise choose for a ranged request, so the response
  4976. // is not a partial representation.
  4977. auto status = req.get_param_value("status");
  4978. if (status == "200") {
  4979. res.status = StatusCode::OK_200;
  4980. } else if (status == "403") {
  4981. res.status = StatusCode::Forbidden_403;
  4982. }
  4983. res.set_content_provider(
  4984. data->size(), "text/plain",
  4985. [data](size_t offset, size_t length, DataSink &sink) {
  4986. size_t DATA_CHUNK_SIZE = 4;
  4987. const auto &d = *data;
  4988. auto out_len =
  4989. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4990. auto ret =
  4991. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4992. EXPECT_TRUE(ret);
  4993. return true;
  4994. },
  4995. [data, &req](bool success) {
  4996. EXPECT_EQ(success, !req.has_param("error"));
  4997. delete data;
  4998. });
  4999. })
  5000. .Get("/streamed-cancel",
  5001. [&](const Request & /*req*/, Response &res) {
  5002. res.set_content_provider(
  5003. size_t(-1), "text/plain",
  5004. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5005. sink.os << "data_chunk";
  5006. return true;
  5007. });
  5008. })
  5009. .Get("/regex-with-delimiter",
  5010. [&](const Request &req, Response & /*res*/) {
  5011. ASSERT_TRUE(req.has_param("key"));
  5012. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5013. })
  5014. .Get("/with-range",
  5015. [&](const Request & /*req*/, Response &res) {
  5016. res.set_content("abcdefg", "text/plain");
  5017. })
  5018. .Get("/test-start-time",
  5019. [&](const Request &req, Response & /*res*/) {
  5020. EXPECT_NE(req.start_time_,
  5021. std::chrono::steady_clock::time_point::min());
  5022. })
  5023. .Get("/with-range-customized-response",
  5024. [&](const Request & /*req*/, Response &res) {
  5025. res.status = StatusCode::BadRequest_400;
  5026. res.set_content(JSON_DATA, "application/json");
  5027. })
  5028. .Post("/chunked",
  5029. [&](const Request &req, Response & /*res*/) {
  5030. EXPECT_EQ(req.body, "dechunked post body");
  5031. })
  5032. .Post("/large-chunked",
  5033. [&](const Request &req, Response & /*res*/) {
  5034. std::string expected(6 * 30 * 1024u, 'a');
  5035. EXPECT_EQ(req.body, expected);
  5036. })
  5037. .Post("/multipart",
  5038. [&](const Request &req, Response & /*res*/) {
  5039. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5040. req.form.get_field_count("text2") +
  5041. req.form.get_field_count("file3") +
  5042. req.form.get_field_count("file4"));
  5043. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5044. req.form.get_file_count("file2"));
  5045. ASSERT_TRUE(!req.form.has_file("???"));
  5046. ASSERT_TRUE(!req.form.has_field("???"));
  5047. ASSERT_TRUE(req.body.empty());
  5048. {
  5049. const auto &text = req.form.get_field("text1");
  5050. EXPECT_EQ("text default", text);
  5051. }
  5052. {
  5053. const auto &text = req.form.get_field("text2");
  5054. EXPECT_EQ("aωb", text);
  5055. }
  5056. {
  5057. const auto &file = req.form.get_file("file1");
  5058. EXPECT_EQ("hello.txt", file.filename);
  5059. EXPECT_EQ("text/plain", file.content_type);
  5060. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5061. }
  5062. {
  5063. const auto &file = req.form.get_file("file2");
  5064. EXPECT_EQ("world.json", file.filename);
  5065. EXPECT_EQ("application/json", file.content_type);
  5066. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5067. }
  5068. {
  5069. const auto &text = req.form.get_field("file3");
  5070. EXPECT_EQ(0u, text.size());
  5071. }
  5072. {
  5073. const auto &text = req.form.get_field("file4");
  5074. EXPECT_EQ(0u, text.size());
  5075. }
  5076. })
  5077. .Post("/multipart/multi_file_values",
  5078. [&](const Request &req, Response & /*res*/) {
  5079. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5080. req.form.get_field_count("multi_text1"));
  5081. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5082. ASSERT_TRUE(!req.form.has_file("???"));
  5083. ASSERT_TRUE(!req.form.has_field("???"));
  5084. ASSERT_TRUE(req.body.empty());
  5085. {
  5086. const auto &text = req.form.get_field("text");
  5087. EXPECT_EQ("default text", text);
  5088. }
  5089. {
  5090. const auto &text1_values = req.form.get_fields("multi_text1");
  5091. EXPECT_EQ(2u, text1_values.size());
  5092. EXPECT_EQ("aaaaa", text1_values[0]);
  5093. EXPECT_EQ("bbbbb", text1_values[1]);
  5094. }
  5095. {
  5096. const auto &file1_values = req.form.get_files("multi_file1");
  5097. EXPECT_EQ(2u, file1_values.size());
  5098. auto file1 = file1_values[0];
  5099. EXPECT_EQ(file1.filename, "hello.txt");
  5100. EXPECT_EQ(file1.content_type, "text/plain");
  5101. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5102. auto file2 = file1_values[1];
  5103. EXPECT_EQ(file2.filename, "world.json");
  5104. EXPECT_EQ(file2.content_type, "application/json");
  5105. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5106. }
  5107. })
  5108. .Post("/empty",
  5109. [&](const Request &req, Response &res) {
  5110. EXPECT_EQ(req.body, "");
  5111. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5112. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5113. res.set_content("empty", "text/plain");
  5114. })
  5115. .Post("/empty-no-content-type",
  5116. [&](const Request &req, Response &res) {
  5117. EXPECT_EQ(req.body, "");
  5118. EXPECT_FALSE(req.has_header("Content-Type"));
  5119. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5120. res.set_content("empty-no-content-type", "text/plain");
  5121. })
  5122. .Post("/path-only",
  5123. [&](const Request &req, Response &res) {
  5124. EXPECT_EQ(req.body, "");
  5125. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5126. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5127. res.set_content("path-only", "text/plain");
  5128. })
  5129. .Post("/path-headers-only",
  5130. [&](const Request &req, Response &res) {
  5131. EXPECT_EQ(req.body, "");
  5132. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5133. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5134. EXPECT_EQ("world", req.get_header_value("hello"));
  5135. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5136. res.set_content("path-headers-only", "text/plain");
  5137. })
  5138. .Post("/post-large",
  5139. [&](const Request &req, Response &res) {
  5140. EXPECT_EQ(req.body, LARGE_DATA);
  5141. res.set_content(req.body, "text/plain");
  5142. })
  5143. .Post("/post-loopback",
  5144. [&](const Request &, Response &res,
  5145. ContentReader const &content_reader) {
  5146. std::string body;
  5147. content_reader([&](const char *data, size_t data_length) {
  5148. body.append(data, data_length);
  5149. return true;
  5150. });
  5151. res.set_content(body, "text/plain");
  5152. })
  5153. .Put("/put-loopback",
  5154. [&](const Request &, Response &res,
  5155. ContentReader const &content_reader) {
  5156. std::string body;
  5157. content_reader([&](const char *data, size_t data_length) {
  5158. body.append(data, data_length);
  5159. return true;
  5160. });
  5161. res.set_content(body, "text/plain");
  5162. })
  5163. .Patch("/patch-loopback",
  5164. [&](const Request &, Response &res,
  5165. ContentReader const &content_reader) {
  5166. std::string body;
  5167. content_reader([&](const char *data, size_t data_length) {
  5168. body.append(data, data_length);
  5169. return true;
  5170. });
  5171. res.set_content(body, "text/plain");
  5172. })
  5173. .Put("/empty-no-content-type",
  5174. [&](const Request &req, Response &res) {
  5175. EXPECT_EQ(req.body, "");
  5176. EXPECT_FALSE(req.has_header("Content-Type"));
  5177. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5178. res.set_content("empty-no-content-type", "text/plain");
  5179. })
  5180. .Put("/put",
  5181. [&](const Request &req, Response &res) {
  5182. EXPECT_EQ(req.body, "PUT");
  5183. res.set_content(req.body, "text/plain");
  5184. })
  5185. .Put("/put-large",
  5186. [&](const Request &req, Response &res) {
  5187. EXPECT_EQ(req.body, LARGE_DATA);
  5188. res.set_content(req.body, "text/plain");
  5189. })
  5190. .Patch("/patch",
  5191. [&](const Request &req, Response &res) {
  5192. EXPECT_EQ(req.body, "PATCH");
  5193. res.set_content(req.body, "text/plain");
  5194. })
  5195. .Delete("/delete",
  5196. [&](const Request & /*req*/, Response &res) {
  5197. res.set_content("DELETE", "text/plain");
  5198. })
  5199. .Delete("/delete-body",
  5200. [&](const Request &req, Response &res) {
  5201. EXPECT_EQ(req.body, "content");
  5202. res.set_content(req.body, "text/plain");
  5203. })
  5204. .Options(R"(\*)",
  5205. [&](const Request & /*req*/, Response &res) {
  5206. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5207. })
  5208. .CustomRoute("PROPFIND", "/dav/:id",
  5209. [&](const Request &req, Response &res) {
  5210. res.set_header("x-body-size",
  5211. std::to_string(req.body.size()));
  5212. res.set_header("x-matched-route", req.matched_route);
  5213. res.set_header("x-dav-id", req.path_params.at("id"));
  5214. res.status = StatusCode::MultiStatus_207;
  5215. res.set_content(req.body, "application/xml");
  5216. })
  5217. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5218. [&](const Request &req, Response &res) {
  5219. res.set_header("x-dav-match", req.matches[1]);
  5220. res.status = StatusCode::MultiStatus_207;
  5221. })
  5222. .CustomRoute("MKCOL", "/dav-mkcol",
  5223. [&](const Request &req, Response &res) {
  5224. EXPECT_TRUE(req.body.empty());
  5225. res.status = StatusCode::Created_201;
  5226. })
  5227. .CustomRoute(
  5228. "REPORT", "/dav-report",
  5229. [&](const Request & /*req*/, Response &res,
  5230. const ContentReader &content_reader) {
  5231. std::string body;
  5232. content_reader([&](const char *data, size_t data_length) {
  5233. body.append(data, data_length);
  5234. return true;
  5235. });
  5236. res.set_header("x-body-size", std::to_string(body.size()));
  5237. res.status = StatusCode::MultiStatus_207;
  5238. res.set_content(body, "application/xml");
  5239. })
  5240. .Get("/request-target",
  5241. [&](const Request &req, Response & /*res*/) {
  5242. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5243. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5244. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5245. })
  5246. .Get("/long-query-value",
  5247. [&](const Request &req, Response & /*res*/) {
  5248. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5249. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5250. })
  5251. .Get("/too-long-query-value",
  5252. [&](const Request &req, Response & /*res*/) {
  5253. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5254. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5255. })
  5256. .Get("/array-param",
  5257. [&](const Request &req, Response & /*res*/) {
  5258. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5259. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5260. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5261. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5262. })
  5263. .Get("/array-param-values",
  5264. [&](const Request &req, Response & /*res*/) {
  5265. auto values = req.get_param_values("array");
  5266. EXPECT_EQ(3u, values.size());
  5267. EXPECT_EQ("value1", values[0]);
  5268. EXPECT_EQ("value2", values[1]);
  5269. EXPECT_EQ("value3", values[2]);
  5270. auto empty = req.get_param_values("nonexistent");
  5271. EXPECT_TRUE(empty.empty());
  5272. })
  5273. .Post("/validate-no-multiple-headers",
  5274. [&](const Request &req, Response & /*res*/) {
  5275. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5276. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5277. })
  5278. .Post("/content_receiver",
  5279. [&](const Request &req, Response &res,
  5280. const ContentReader &content_reader) {
  5281. if (req.is_multipart_form_data()) {
  5282. std::vector<FormData> items;
  5283. content_reader(
  5284. [&](const FormData &file) {
  5285. items.push_back(file);
  5286. return true;
  5287. },
  5288. [&](const char *data, size_t data_length) {
  5289. items.back().content.append(data, data_length);
  5290. return true;
  5291. });
  5292. EXPECT_EQ(5u, items.size());
  5293. {
  5294. const auto &file = get_file_value(items, "text1");
  5295. EXPECT_TRUE(file.filename.empty());
  5296. EXPECT_EQ("text default", file.content);
  5297. }
  5298. {
  5299. const auto &file = get_file_value(items, "text2");
  5300. EXPECT_TRUE(file.filename.empty());
  5301. EXPECT_EQ("aωb", file.content);
  5302. }
  5303. {
  5304. const auto &file = get_file_value(items, "file1");
  5305. EXPECT_EQ("hello.txt", file.filename);
  5306. EXPECT_EQ("text/plain", file.content_type);
  5307. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5308. }
  5309. {
  5310. const auto &file = get_file_value(items, "file2");
  5311. EXPECT_EQ("world.json", file.filename);
  5312. EXPECT_EQ("application/json", file.content_type);
  5313. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5314. }
  5315. {
  5316. const auto &file = get_file_value(items, "file3");
  5317. EXPECT_TRUE(file.filename.empty());
  5318. EXPECT_EQ("application/octet-stream", file.content_type);
  5319. EXPECT_EQ(0u, file.content.size());
  5320. }
  5321. } else {
  5322. std::string body;
  5323. content_reader([&](const char *data, size_t data_length) {
  5324. EXPECT_EQ(7U, data_length);
  5325. body.append(data, data_length);
  5326. return true;
  5327. });
  5328. EXPECT_EQ(body, "content");
  5329. res.set_content(body, "text/plain");
  5330. }
  5331. })
  5332. .Put("/content_receiver",
  5333. [&](const Request & /*req*/, Response &res,
  5334. const ContentReader &content_reader) {
  5335. std::string body;
  5336. content_reader([&](const char *data, size_t data_length) {
  5337. body.append(data, data_length);
  5338. return true;
  5339. });
  5340. EXPECT_EQ(body, "content");
  5341. res.set_content(body, "text/plain");
  5342. })
  5343. .Patch("/content_receiver",
  5344. [&](const Request & /*req*/, Response &res,
  5345. const ContentReader &content_reader) {
  5346. std::string body;
  5347. content_reader([&](const char *data, size_t data_length) {
  5348. body.append(data, data_length);
  5349. return true;
  5350. });
  5351. EXPECT_EQ(body, "content");
  5352. res.set_content(body, "text/plain");
  5353. })
  5354. .Post("/query-string-and-body",
  5355. [&](const Request &req, Response & /*res*/) {
  5356. ASSERT_TRUE(req.has_param("key"));
  5357. EXPECT_EQ(req.get_param_value("key"), "value");
  5358. EXPECT_EQ(req.body, "content");
  5359. })
  5360. .Get("/last-request",
  5361. [&](const Request &req, Response & /*res*/) {
  5362. EXPECT_EQ("close", req.get_header_value("Connection"));
  5363. })
  5364. .Get(R"(/redirect/(\d+))",
  5365. [&](const Request &req, Response &res) {
  5366. auto num = std::stoi(req.matches[1]) + 1;
  5367. std::string url = "/redirect/" + std::to_string(num);
  5368. res.set_redirect(url);
  5369. })
  5370. .Post("/binary",
  5371. [&](const Request &req, Response &res) {
  5372. EXPECT_EQ(4U, req.body.size());
  5373. EXPECT_EQ("application/octet-stream",
  5374. req.get_header_value("Content-Type"));
  5375. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5376. res.set_content(req.body, "application/octet-stream");
  5377. })
  5378. .Put("/binary",
  5379. [&](const Request &req, Response &res) {
  5380. EXPECT_EQ(4U, req.body.size());
  5381. EXPECT_EQ("application/octet-stream",
  5382. req.get_header_value("Content-Type"));
  5383. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5384. res.set_content(req.body, "application/octet-stream");
  5385. })
  5386. .Patch("/binary",
  5387. [&](const Request &req, Response &res) {
  5388. EXPECT_EQ(4U, req.body.size());
  5389. EXPECT_EQ("application/octet-stream",
  5390. req.get_header_value("Content-Type"));
  5391. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5392. res.set_content(req.body, "application/octet-stream");
  5393. })
  5394. .Delete("/binary",
  5395. [&](const Request &req, Response &res) {
  5396. EXPECT_EQ(4U, req.body.size());
  5397. EXPECT_EQ("application/octet-stream",
  5398. req.get_header_value("Content-Type"));
  5399. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5400. res.set_content(req.body, "application/octet-stream");
  5401. })
  5402. .Get("/issue1772",
  5403. [&](const Request & /*req*/, Response &res) {
  5404. res.status = 401;
  5405. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5406. })
  5407. .Delete("/issue609",
  5408. [](const httplib::Request &, httplib::Response &res,
  5409. const httplib::ContentReader &) {
  5410. res.set_content("ok", "text/plain");
  5411. })
  5412. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5413. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5414. .Get("/compress",
  5415. [&](const Request & /*req*/, Response &res) {
  5416. res.set_content(
  5417. "12345678901234567890123456789012345678901234567890123456789"
  5418. "01234567890123456789012345678901234567890",
  5419. "text/plain");
  5420. })
  5421. .Get("/compress-with-charset",
  5422. [&](const Request & /*req*/, Response &res) {
  5423. res.set_content(
  5424. "12345678901234567890123456789012345678901234567890123456789"
  5425. "01234567890123456789012345678901234567890",
  5426. "application/json; charset=utf-8");
  5427. })
  5428. .Get("/nocompress",
  5429. [&](const Request & /*req*/, Response &res) {
  5430. res.set_content(
  5431. "12345678901234567890123456789012345678901234567890123456789"
  5432. "01234567890123456789012345678901234567890",
  5433. "application/octet-stream");
  5434. })
  5435. .Post("/compress-multipart",
  5436. [&](const Request &req, Response & /*res*/) {
  5437. EXPECT_EQ(2u, req.form.fields.size());
  5438. ASSERT_TRUE(!req.form.has_field("???"));
  5439. {
  5440. const auto &text = req.form.get_field("key1");
  5441. EXPECT_EQ("test", text);
  5442. }
  5443. {
  5444. const auto &text = req.form.get_field("key2");
  5445. EXPECT_EQ("--abcdefg123", text);
  5446. }
  5447. })
  5448. #endif
  5449. ;
  5450. persons_["john"] = "programmer";
  5451. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5452. svr_.wait_until_ready();
  5453. }
  5454. virtual void TearDown() {
  5455. svr_.stop();
  5456. if (!request_threads_.empty()) {
  5457. std::this_thread::sleep_for(std::chrono::seconds(1));
  5458. for (auto &t : request_threads_) {
  5459. t.join();
  5460. }
  5461. }
  5462. t_.join();
  5463. }
  5464. map<string, string> persons_;
  5465. #ifdef CPPHTTPLIB_SSL_ENABLED
  5466. SSLClient cli_;
  5467. SSLServer svr_;
  5468. #else
  5469. Client cli_;
  5470. Server svr_;
  5471. #endif
  5472. thread t_;
  5473. std::vector<thread> request_threads_;
  5474. };
  5475. TEST_F(ServerTest, GetMethod200) {
  5476. auto res = cli_.Get("/hi");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ("HTTP/1.1", res->version);
  5479. EXPECT_EQ(StatusCode::OK_200, res->status);
  5480. EXPECT_EQ("OK", res->reason);
  5481. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5482. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5483. EXPECT_EQ("Hello World!", res->body);
  5484. }
  5485. TEST_F(ServerTest, GetEmptyFile) {
  5486. auto res = cli_.Get("/empty_file");
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. EXPECT_EQ(StatusCode::OK_200, res->status);
  5489. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5490. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5491. EXPECT_EQ("", res->body);
  5492. }
  5493. TEST_F(ServerTest, GetFileContent) {
  5494. auto res = cli_.Get("/file_content");
  5495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5496. EXPECT_EQ(StatusCode::OK_200, res->status);
  5497. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5498. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5499. EXPECT_EQ("test.html", res->body);
  5500. }
  5501. TEST_F(ServerTest, GetFileContentWithRange) {
  5502. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5504. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5505. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5506. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5507. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5508. EXPECT_EQ("est", res->body);
  5509. }
  5510. TEST_F(ServerTest, GetFileContentWithContentType) {
  5511. auto res = cli_.Get("/file_content_with_content_type");
  5512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5513. EXPECT_EQ(StatusCode::OK_200, res->status);
  5514. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5515. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5516. EXPECT_EQ("file\n", res->body);
  5517. }
  5518. TEST_F(ServerTest, GetInvalidFileContent) {
  5519. auto res = cli_.Get("/invalid_file_content");
  5520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5521. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5522. }
  5523. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5524. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5526. EXPECT_EQ("HTTP/1.1", res->version);
  5527. EXPECT_EQ(StatusCode::OK_200, res->status);
  5528. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5529. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5530. EXPECT_EQ("Hello World!", res->body);
  5531. }
  5532. TEST_F(ServerTest, GetMethod302) {
  5533. auto res = cli_.Get("/");
  5534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5535. EXPECT_EQ(StatusCode::Found_302, res->status);
  5536. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5537. }
  5538. TEST_F(ServerTest, GetMethod302Redirect) {
  5539. cli_.set_follow_location(true);
  5540. auto res = cli_.Get("/");
  5541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5542. EXPECT_EQ(StatusCode::OK_200, res->status);
  5543. EXPECT_EQ("Hello World!", res->body);
  5544. EXPECT_EQ("/hi", res->location);
  5545. }
  5546. TEST_F(ServerTest, GetMethod404) {
  5547. auto res = cli_.Get("/invalid");
  5548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5549. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5550. }
  5551. TEST_F(ServerTest, HeadMethod200) {
  5552. auto res = cli_.Head("/hi");
  5553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5554. EXPECT_EQ(StatusCode::OK_200, res->status);
  5555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5556. EXPECT_TRUE(res->body.empty());
  5557. }
  5558. TEST_F(ServerTest, HeadMethod200Static) {
  5559. auto res = cli_.Head("/mount/dir/index.html");
  5560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5561. EXPECT_EQ(StatusCode::OK_200, res->status);
  5562. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5563. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5564. EXPECT_TRUE(res->body.empty());
  5565. }
  5566. TEST_F(ServerTest, HeadMethod404) {
  5567. auto res = cli_.Head("/invalid");
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5570. EXPECT_TRUE(res->body.empty());
  5571. }
  5572. TEST_F(ServerTest, GetMethodPersonJohn) {
  5573. auto res = cli_.Get("/person/john");
  5574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5575. EXPECT_EQ(StatusCode::OK_200, res->status);
  5576. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5577. EXPECT_EQ("programmer", res->body);
  5578. }
  5579. TEST_F(ServerTest, PostMethod1) {
  5580. auto res = cli_.Get("/person/john1");
  5581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5582. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5583. res = cli_.Post("/person", "name=john1&note=coder",
  5584. "application/x-www-form-urlencoded");
  5585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5586. ASSERT_EQ(StatusCode::OK_200, res->status);
  5587. res = cli_.Get("/person/john1");
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. ASSERT_EQ(StatusCode::OK_200, res->status);
  5590. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5591. ASSERT_EQ("coder", res->body);
  5592. }
  5593. TEST_F(ServerTest, PostMethod2) {
  5594. auto res = cli_.Get("/person/john2");
  5595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5596. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5597. Params params;
  5598. params.emplace("name", "john2");
  5599. params.emplace("note", "coder");
  5600. res = cli_.Post("/person", params);
  5601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5602. ASSERT_EQ(StatusCode::OK_200, res->status);
  5603. res = cli_.Get("/person/john2");
  5604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5605. ASSERT_EQ(StatusCode::OK_200, res->status);
  5606. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5607. ASSERT_EQ("coder", res->body);
  5608. }
  5609. TEST_F(ServerTest, PutMethod3) {
  5610. auto res = cli_.Get("/person/john3");
  5611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5612. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5613. Params params;
  5614. params.emplace("name", "john3");
  5615. params.emplace("note", "coder");
  5616. res = cli_.Put("/person", params);
  5617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5618. ASSERT_EQ(StatusCode::OK_200, res->status);
  5619. res = cli_.Get("/person/john3");
  5620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5621. ASSERT_EQ(StatusCode::OK_200, res->status);
  5622. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5623. ASSERT_EQ("coder", res->body);
  5624. }
  5625. TEST_F(ServerTest, DeleteMethod1) {
  5626. auto res = cli_.Get("/person/john4");
  5627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5628. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5629. Params params;
  5630. params.emplace("name", "john4");
  5631. params.emplace("note", "coder");
  5632. res = cli_.Post("/person", params);
  5633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5634. ASSERT_EQ(StatusCode::OK_200, res->status);
  5635. res = cli_.Get("/person/john4");
  5636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5637. ASSERT_EQ(StatusCode::OK_200, res->status);
  5638. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5639. ASSERT_EQ("coder", res->body);
  5640. Params delete_params;
  5641. delete_params.emplace("name", "john4");
  5642. res = cli_.Delete("/person", delete_params);
  5643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5644. ASSERT_EQ(StatusCode::OK_200, res->status);
  5645. ASSERT_EQ("DELETED", res->body);
  5646. res = cli_.Get("/person/john4");
  5647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5648. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5649. }
  5650. TEST_F(ServerTest, DeleteMethod2) {
  5651. auto res = cli_.Get("/person/john5");
  5652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5653. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5654. Params params;
  5655. params.emplace("name", "john5");
  5656. params.emplace("note", "developer");
  5657. res = cli_.Post("/person", params);
  5658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5659. ASSERT_EQ(StatusCode::OK_200, res->status);
  5660. res = cli_.Get("/person/john5");
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. ASSERT_EQ(StatusCode::OK_200, res->status);
  5663. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5664. ASSERT_EQ("developer", res->body);
  5665. Params delete_params;
  5666. delete_params.emplace("name", "john5");
  5667. Headers headers;
  5668. headers.emplace("Custom-Header", "test-value");
  5669. res = cli_.Delete("/person", headers, delete_params);
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. ASSERT_EQ(StatusCode::OK_200, res->status);
  5672. ASSERT_EQ("DELETED", res->body);
  5673. res = cli_.Get("/person/john5");
  5674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5675. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5676. }
  5677. TEST_F(ServerTest, DeleteMethod3) {
  5678. auto res = cli_.Get("/person/john6");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5681. Params params;
  5682. params.emplace("name", "john6");
  5683. params.emplace("note", "tester");
  5684. res = cli_.Post("/person", params);
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. ASSERT_EQ(StatusCode::OK_200, res->status);
  5687. res = cli_.Get("/person/john6");
  5688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5689. ASSERT_EQ(StatusCode::OK_200, res->status);
  5690. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5691. ASSERT_EQ("tester", res->body);
  5692. Params delete_params;
  5693. delete_params.emplace("name", "john6");
  5694. Headers headers;
  5695. headers.emplace("Custom-Header", "test-value");
  5696. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5698. ASSERT_EQ(StatusCode::OK_200, res->status);
  5699. ASSERT_EQ("DELETED", res->body);
  5700. res = cli_.Get("/person/john6");
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5703. }
  5704. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5705. Params params;
  5706. params.emplace("json", JSON_DATA);
  5707. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5709. ASSERT_EQ(StatusCode::OK_200, res->status);
  5710. ASSERT_EQ(JSON_DATA, res->body);
  5711. }
  5712. TEST_F(ServerTest, PostEmptyContent) {
  5713. auto res = cli_.Post("/empty", "", "text/plain");
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. ASSERT_EQ(StatusCode::OK_200, res->status);
  5716. ASSERT_EQ("empty", res->body);
  5717. }
  5718. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5719. auto res = cli_.Post("/empty-no-content-type");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. ASSERT_EQ(StatusCode::OK_200, res->status);
  5722. ASSERT_EQ("empty-no-content-type", res->body);
  5723. }
  5724. TEST_F(ServerTest, PostPathOnly) {
  5725. auto res = cli_.Post("/path-only");
  5726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5727. ASSERT_EQ(StatusCode::OK_200, res->status);
  5728. ASSERT_EQ("path-only", res->body);
  5729. }
  5730. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5731. auto res = cli_.Post("/path-headers-only",
  5732. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5734. ASSERT_EQ(StatusCode::OK_200, res->status);
  5735. ASSERT_EQ("path-headers-only", res->body);
  5736. }
  5737. TEST_F(ServerTest, PostLarge) {
  5738. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5740. ASSERT_EQ(StatusCode::OK_200, res->status);
  5741. EXPECT_EQ(LARGE_DATA, res->body);
  5742. }
  5743. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5744. auto res = cli_.Put("/empty-no-content-type");
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. ASSERT_EQ(StatusCode::OK_200, res->status);
  5747. ASSERT_EQ("empty-no-content-type", res->body);
  5748. }
  5749. TEST_F(ServerTest, GetMethodDir) {
  5750. auto res = cli_.Get("/dir/");
  5751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5752. EXPECT_EQ(StatusCode::OK_200, res->status);
  5753. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5754. auto body = R"(<html>
  5755. <head>
  5756. </head>
  5757. <body>
  5758. <a href="/dir/test.html">Test</a>
  5759. <a href="/hi">hi</a>
  5760. </body>
  5761. </html>
  5762. )";
  5763. EXPECT_EQ(body, res->body);
  5764. }
  5765. TEST_F(ServerTest, GetMethodDirTest) {
  5766. auto res = cli_.Get("/dir/test.html");
  5767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5768. EXPECT_EQ(StatusCode::OK_200, res->status);
  5769. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5770. EXPECT_EQ("test.html", res->body);
  5771. }
  5772. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5773. auto res = cli_.Get("/dir/../dir/test.html");
  5774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5775. EXPECT_EQ(StatusCode::OK_200, res->status);
  5776. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5777. EXPECT_EQ("test.html", res->body);
  5778. }
  5779. TEST_F(ServerTest, GetMethodInvalidPath) {
  5780. auto res = cli_.Get("/dir/../test.html");
  5781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5782. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5783. }
  5784. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5785. auto res = cli_.Get("/../www/dir/test.html");
  5786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5787. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5788. }
  5789. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5790. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5793. }
  5794. TEST_F(ServerTest, GetMethodDirMountTest) {
  5795. auto res = cli_.Get("/mount/dir/test.html");
  5796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5797. EXPECT_EQ(StatusCode::OK_200, res->status);
  5798. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5799. EXPECT_EQ("test.html", res->body);
  5800. }
  5801. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5802. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5804. EXPECT_EQ(StatusCode::OK_200, res->status);
  5805. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5806. EXPECT_EQ("test.html", res->body);
  5807. }
  5808. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5809. auto res = cli_.Get("/mount/dir/../test.html");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5812. }
  5813. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5814. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5817. }
  5818. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5819. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5822. }
  5823. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5824. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5827. }
  5828. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5829. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5831. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5832. }
  5833. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5834. auto res = cli_.Get("/mount/dir");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5837. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5838. }
  5839. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5840. auto res = cli_.Get("//dir");
  5841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5842. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5843. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5844. }
  5845. TEST_F(ServerTest, PostMethod303) {
  5846. auto res = cli_.Post("/1", "body", "text/plain");
  5847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5848. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5849. EXPECT_EQ("/2", res->get_header_value("Location"));
  5850. }
  5851. TEST_F(ServerTest, PostMethod303Redirect) {
  5852. cli_.set_follow_location(true);
  5853. auto res = cli_.Post("/1", "body", "text/plain");
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. EXPECT_EQ("redirected.", res->body);
  5857. EXPECT_EQ("/2", res->location);
  5858. }
  5859. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5860. auto res = cli_.Get("/dir/test.abcde");
  5861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5862. EXPECT_EQ(StatusCode::OK_200, res->status);
  5863. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5864. EXPECT_EQ("abcde", res->body);
  5865. }
  5866. TEST_F(ServerTest, StaticFileRange) {
  5867. auto res =
  5868. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5870. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5871. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5872. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5873. EXPECT_EQ(true, res->has_header("Content-Range"));
  5874. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5875. EXPECT_EQ(std::string("cd"), res->body);
  5876. }
  5877. TEST_F(ServerTest, StaticFileRanges) {
  5878. auto res = cli_.Get("/dir/test.abcde",
  5879. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5881. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5882. EXPECT_TRUE(
  5883. res->get_header_value("Content-Type")
  5884. .find(
  5885. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5886. 0);
  5887. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5888. }
  5889. TEST_F(ServerTest, StaticFileRangeHead) {
  5890. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5892. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5893. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5894. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5895. EXPECT_EQ(true, res->has_header("Content-Range"));
  5896. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5897. }
  5898. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5899. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5902. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5903. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5904. EXPECT_EQ(true, res->has_header("Content-Range"));
  5905. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5906. res->get_header_value("Content-Range"));
  5907. EXPECT_EQ("LAST\n", res->body);
  5908. }
  5909. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5910. auto res =
  5911. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5913. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5914. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5915. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5916. EXPECT_EQ(true, res->has_header("Content-Range"));
  5917. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5918. }
  5919. TEST_F(ServerTest, StaticFileBigFile) {
  5920. auto res = cli_.Get("/dir/1MB.txt");
  5921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5922. EXPECT_EQ(StatusCode::OK_200, res->status);
  5923. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5924. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5925. }
  5926. TEST_F(ServerTest, InvalidBaseDirMount) {
  5927. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5928. }
  5929. TEST_F(ServerTest, Binary) {
  5930. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5931. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5932. "application/octet-stream");
  5933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5934. ASSERT_EQ(StatusCode::OK_200, res->status);
  5935. ASSERT_EQ(4U, res->body.size());
  5936. res = cli_.Put("/binary", binary.data(), binary.size(),
  5937. "application/octet-stream");
  5938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5939. ASSERT_EQ(StatusCode::OK_200, res->status);
  5940. ASSERT_EQ(4U, res->body.size());
  5941. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5942. "application/octet-stream");
  5943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5944. ASSERT_EQ(StatusCode::OK_200, res->status);
  5945. ASSERT_EQ(4U, res->body.size());
  5946. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5947. "application/octet-stream");
  5948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5949. ASSERT_EQ(StatusCode::OK_200, res->status);
  5950. ASSERT_EQ(4U, res->body.size());
  5951. }
  5952. TEST_F(ServerTest, BinaryString) {
  5953. auto binary = std::string("\x00\x01\x02\x03", 4);
  5954. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5956. ASSERT_EQ(StatusCode::OK_200, res->status);
  5957. ASSERT_EQ(4U, res->body.size());
  5958. res = cli_.Put("/binary", binary, "application/octet-stream");
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. ASSERT_EQ(StatusCode::OK_200, res->status);
  5961. ASSERT_EQ(4U, res->body.size());
  5962. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5964. ASSERT_EQ(StatusCode::OK_200, res->status);
  5965. ASSERT_EQ(4U, res->body.size());
  5966. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. ASSERT_EQ(StatusCode::OK_200, res->status);
  5969. ASSERT_EQ(4U, res->body.size());
  5970. }
  5971. TEST_F(ServerTest, EmptyRequest) {
  5972. auto res = cli_.Get("");
  5973. ASSERT_TRUE(!res);
  5974. EXPECT_EQ(Error::Connection, res.error());
  5975. }
  5976. TEST_F(ServerTest, LongRequest) {
  5977. std::string request;
  5978. for (size_t i = 0; i < 545; i++) {
  5979. request += "/TooLongRequest";
  5980. }
  5981. request += "OK";
  5982. auto res = cli_.Get(request.c_str());
  5983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5984. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5985. }
  5986. TEST_F(ServerTest, TooLongRequest) {
  5987. std::string request;
  5988. for (size_t i = 0; i < 546; i++) {
  5989. request += "/TooLongRequest";
  5990. }
  5991. request += "_NG";
  5992. auto start = std::chrono::high_resolution_clock::now();
  5993. cli_.set_keep_alive(true);
  5994. auto res = cli_.Get(request.c_str());
  5995. auto end = std::chrono::high_resolution_clock::now();
  5996. auto elapsed =
  5997. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5998. .count();
  5999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6000. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6001. EXPECT_LE(elapsed, 1000);
  6002. EXPECT_EQ("close", res->get_header_value("Connection"));
  6003. EXPECT_FALSE(cli_.is_socket_open());
  6004. }
  6005. TEST_F(ServerTest, AlmostTooLongRequest) {
  6006. // test for #2046 - URI length check shouldn't include other content on req
  6007. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6008. // leading /, space, HTTP/1.1)
  6009. std::string request =
  6010. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6011. auto res = cli_.Get(request.c_str());
  6012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6013. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6014. }
  6015. TEST_F(ServerTest, LongHeader) {
  6016. Request req;
  6017. req.method = "GET";
  6018. req.path = "/hi";
  6019. std::string host_and_port;
  6020. host_and_port += HOST;
  6021. host_and_port += ":";
  6022. host_and_port += std::to_string(PORT);
  6023. req.headers.emplace("Host", host_and_port.c_str());
  6024. req.headers.emplace("Accept", "*/*");
  6025. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6026. req.headers.emplace(
  6027. "Header-Name",
  6028. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6056. "@@@@@@@@@@@@@@@@");
  6057. auto res = std::make_shared<Response>();
  6058. auto error = Error::Success;
  6059. auto ret = cli_.send(req, *res, error);
  6060. ASSERT_TRUE(ret);
  6061. EXPECT_EQ(StatusCode::OK_200, res->status);
  6062. }
  6063. TEST_F(ServerTest, LongQueryValue) {
  6064. auto start = std::chrono::high_resolution_clock::now();
  6065. cli_.set_keep_alive(true);
  6066. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6067. auto end = std::chrono::high_resolution_clock::now();
  6068. auto elapsed =
  6069. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6070. .count();
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6073. EXPECT_LE(elapsed, 1000);
  6074. EXPECT_EQ("close", res->get_header_value("Connection"));
  6075. EXPECT_FALSE(cli_.is_socket_open());
  6076. }
  6077. TEST_F(ServerTest, TooLongQueryValue) {
  6078. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6079. ASSERT_FALSE(res);
  6080. EXPECT_EQ(Error::Read, res.error());
  6081. }
  6082. TEST_F(ServerTest, TooLongHeader) {
  6083. Request req;
  6084. req.method = "GET";
  6085. req.path = "/hi";
  6086. std::string host_and_port;
  6087. host_and_port += HOST;
  6088. host_and_port += ":";
  6089. host_and_port += std::to_string(PORT);
  6090. req.headers.emplace("Host", host_and_port.c_str());
  6091. req.headers.emplace("Accept", "*/*");
  6092. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6093. req.headers.emplace(
  6094. "Header-Name",
  6095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6104. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6105. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6106. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6114. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6115. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6116. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6117. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6118. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6119. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6120. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6121. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6122. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6123. "@@@@@@@@@@@@@@@@@");
  6124. auto res = std::make_shared<Response>();
  6125. auto error = Error::Success;
  6126. auto ret = cli_.send(req, *res, error);
  6127. ASSERT_TRUE(ret);
  6128. EXPECT_EQ(StatusCode::OK_200, res->status);
  6129. }
  6130. TEST_F(ServerTest, HeaderCountAtLimit) {
  6131. // Test with headers just under the 100 limit
  6132. httplib::Headers headers;
  6133. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6134. // This should keep us just under the 100 header limit
  6135. for (int i = 0; i < 95; i++) {
  6136. std::string name = "X-Test-Header-" + std::to_string(i);
  6137. std::string value = "value" + std::to_string(i);
  6138. headers.emplace(name, value);
  6139. }
  6140. // This should work fine as we're under the limit
  6141. auto res = cli_.Get("/hi", headers);
  6142. EXPECT_TRUE(res);
  6143. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6144. }
  6145. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6146. // Test with many headers to exceed the 100 limit
  6147. httplib::Headers headers;
  6148. // Add 150 headers to definitely exceed the 100 limit
  6149. for (int i = 0; i < 150; i++) {
  6150. std::string name = "X-Test-Header-" + std::to_string(i);
  6151. std::string value = "value" + std::to_string(i);
  6152. headers.emplace(name, value);
  6153. }
  6154. // This should fail due to exceeding header count limit
  6155. cli_.set_keep_alive(true);
  6156. auto res = cli_.Get("/hi", headers);
  6157. // The server should respond with 400 Bad Request
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6160. EXPECT_EQ("close", res->get_header_value("Connection"));
  6161. EXPECT_FALSE(cli_.is_socket_open());
  6162. }
  6163. TEST_F(ServerTest, PercentEncoding) {
  6164. auto res = cli_.Get("/e%6edwith%");
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. EXPECT_EQ(StatusCode::OK_200, res->status);
  6167. }
  6168. TEST_F(ServerTest, PercentEncodingUnicode) {
  6169. auto res = cli_.Get("/e%u006edwith%");
  6170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6171. EXPECT_EQ(StatusCode::OK_200, res->status);
  6172. }
  6173. TEST_F(ServerTest, InvalidPercentEncoding) {
  6174. auto res = cli_.Get("/%endwith%");
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6177. }
  6178. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6179. auto res = cli_.Get("/%uendwith%");
  6180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6181. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6182. }
  6183. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6184. auto res = cli_.Get("/hello?aaa=bbb%");
  6185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6186. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6187. }
  6188. TEST_F(ServerTest, PlusSignEncoding) {
  6189. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. EXPECT_EQ(StatusCode::OK_200, res->status);
  6192. EXPECT_EQ("a +b", res->body);
  6193. }
  6194. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6195. // This test simulates a potential DoS attack using many headers
  6196. // to verify our security fix prevents memory exhaustion
  6197. httplib::Headers attack_headers;
  6198. // Attempt to add many headers like an attacker would (200 headers to far
  6199. // exceed limit)
  6200. for (int i = 0; i < 200; i++) {
  6201. std::string name = "X-Attack-Header-" + std::to_string(i);
  6202. std::string value = "attack_payload_" + std::to_string(i);
  6203. attack_headers.emplace(name, value);
  6204. }
  6205. // Try to POST with excessive headers
  6206. cli_.set_keep_alive(true);
  6207. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6208. // Should either fail or return 400 Bad Request due to security limit
  6209. if (res) {
  6210. // If we get a response, it should be 400 Bad Request
  6211. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6212. EXPECT_EQ("close", res->get_header_value("Connection"));
  6213. }
  6214. EXPECT_FALSE(cli_.is_socket_open());
  6215. }
  6216. TEST_F(ServerTest, MultipartFormData) {
  6217. UploadFormDataItems items = {
  6218. {"text1", "text default", "", ""},
  6219. {"text2", "aωb", "", ""},
  6220. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6221. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6222. {"file3", "", "", "application/octet-stream"},
  6223. {"file4", "", "", " application/json tmp-string "}};
  6224. auto res = cli_.Post("/multipart", items);
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. EXPECT_EQ(StatusCode::OK_200, res->status);
  6227. }
  6228. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6229. UploadFormDataItems items = {
  6230. {"text", "default text", "", ""},
  6231. {"multi_text1", "aaaaa", "", ""},
  6232. {"multi_text1", "bbbbb", "", ""},
  6233. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6234. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6235. "application/json"},
  6236. };
  6237. auto res = cli_.Post("/multipart/multi_file_values", items);
  6238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6239. EXPECT_EQ(StatusCode::OK_200, res->status);
  6240. }
  6241. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6242. auto res = cli_.Get("/hi");
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. EXPECT_EQ(StatusCode::OK_200, res->status);
  6245. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6246. EXPECT_EQ("Hello World!", res->body);
  6247. }
  6248. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6249. Request req;
  6250. req.method = "POST";
  6251. req.path = "/chunked";
  6252. std::string host_and_port;
  6253. host_and_port += HOST;
  6254. host_and_port += ":";
  6255. host_and_port += std::to_string(PORT);
  6256. req.headers.emplace("Host", host_and_port.c_str());
  6257. req.headers.emplace("Accept", "*/*");
  6258. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6259. req.headers.emplace("Content-Type", "text/plain");
  6260. req.headers.emplace("Content-Length", "0");
  6261. req.headers.emplace(
  6262. "Transfer-Encoding",
  6263. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6264. // Client does not chunk, so make a chunked body manually.
  6265. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6266. auto res = std::make_shared<Response>();
  6267. auto error = Error::Success;
  6268. auto ret = cli_.send(req, *res, error);
  6269. ASSERT_TRUE(ret);
  6270. EXPECT_EQ(StatusCode::OK_200, res->status);
  6271. }
  6272. template <typename ClientT>
  6273. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6274. int expected_status) {
  6275. Request req;
  6276. req.method = "POST";
  6277. req.path = "/chunked";
  6278. std::string host_and_port;
  6279. host_and_port += HOST;
  6280. host_and_port += ":";
  6281. host_and_port += std::to_string(PORT);
  6282. req.headers.emplace("Host", host_and_port.c_str());
  6283. req.headers.emplace("Content-Length", "0");
  6284. req.headers.emplace("Transfer-Encoding", "chunked");
  6285. req.body = body;
  6286. auto res = std::make_shared<Response>();
  6287. auto error = Error::Success;
  6288. ASSERT_TRUE(cli.send(req, *res, error));
  6289. EXPECT_EQ(expected_status, res->status);
  6290. }
  6291. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6292. // rather than treat them as valid lengths.
  6293. template <typename ClientT>
  6294. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6295. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6296. }
  6297. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6298. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6299. }
  6300. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6301. expect_chunked_body_rejected(
  6302. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6303. }
  6304. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6305. // chunk-size line carries no CR, LF or other control character ahead of its
  6306. // terminator. Such a line must be refused rather than read as extension text.
  6307. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6308. expect_chunked_body_rejected(
  6309. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6310. }
  6311. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6312. expect_chunked_body_rejected(
  6313. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6314. }
  6315. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6316. expect_chunked_body_rejected(
  6317. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6318. }
  6319. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6320. // The literal stays split: a hex escape consumes every hex digit that
  6321. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6322. expect_chunked_body_rejected(
  6323. cli_, "4;a\x01"
  6324. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6325. }
  6326. TEST_F(ServerTest, AcceptsChunkExtension) {
  6327. expect_chunked_body_status(cli_,
  6328. "4;name=value\r\ndech\r\n"
  6329. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6330. "0;last\r\n\r\n",
  6331. StatusCode::OK_200);
  6332. }
  6333. TEST_F(ServerTest, GetStreamed2) {
  6334. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6336. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6337. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6338. EXPECT_EQ(true, res->has_header("Content-Range"));
  6339. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6340. EXPECT_EQ(std::string("ab"), res->body);
  6341. }
  6342. TEST_F(ServerTest, GetStreamed) {
  6343. auto res = cli_.Get("/streamed");
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::OK_200, res->status);
  6346. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6347. EXPECT_EQ(std::string("aaabbb"), res->body);
  6348. }
  6349. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6350. auto res = cli_.Get("/streamed-without-length",
  6351. Headers{make_range_header({{0, -1}})});
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. EXPECT_EQ(StatusCode::OK_200, res->status);
  6354. EXPECT_EQ(false, res->has_header("Content-Length"));
  6355. EXPECT_EQ(false, res->has_header("Content-Range"));
  6356. EXPECT_EQ(std::string("abcdefg"), res->body);
  6357. }
  6358. TEST_F(ServerTest, GetStreamedWithRange1) {
  6359. auto res =
  6360. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6362. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6363. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6364. EXPECT_EQ(true, res->has_header("Content-Range"));
  6365. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6366. EXPECT_EQ(std::string("def"), res->body);
  6367. }
  6368. TEST_F(ServerTest, GetStreamedWithRange2) {
  6369. auto res =
  6370. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6372. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6373. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6374. EXPECT_EQ(true, res->has_header("Content-Range"));
  6375. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6376. EXPECT_EQ(std::string("bcdefg"), res->body);
  6377. }
  6378. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6379. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6382. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6383. EXPECT_EQ(true, res->has_header("Content-Range"));
  6384. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6385. EXPECT_EQ(std::string("efg"), res->body);
  6386. }
  6387. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6388. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6389. // the entire representation.
  6390. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6391. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6394. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6395. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6396. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6397. }
  6398. }
  6399. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6400. auto res =
  6401. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6404. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6405. EXPECT_EQ(false, res->has_header("Content-Range"));
  6406. EXPECT_EQ(0U, res->body.size());
  6407. }
  6408. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6409. // Only a 206 is served as a partial representation. Under any other status
  6410. // `apply_ranges()` reported the full content length, so the body must match
  6411. // that header, and the content provider must never be asked for an offset
  6412. // outside the representation.
  6413. auto check = [&](int status, const char *range) {
  6414. auto path =
  6415. std::string("/streamed-with-range?status=") + std::to_string(status);
  6416. auto ctx = path + " Range: " + range;
  6417. auto res = cli_.Get(path, Headers{{"Range", range}});
  6418. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6419. EXPECT_EQ(status, res->status) << ctx;
  6420. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6422. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6423. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6424. };
  6425. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6426. check(403, "bytes=3-5");
  6427. // The offset is far past the representation.
  6428. check(403, "bytes=100000-100200");
  6429. // `first_pos` is still -1 here, and the bounds asserts in
  6430. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6431. check(403, "bytes=-3");
  6432. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6433. // multipart branch would have written one that is empty.
  6434. check(403, "bytes=1-2, 4-5");
  6435. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6436. // covers the whole representation.
  6437. check(200, "bytes=3-5");
  6438. check(200, "bytes=1-2, 4-5");
  6439. }
  6440. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6441. auto res =
  6442. cli_.Get("/streamed-with-range",
  6443. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6444. "92233720368547758079223372036854775807"}});
  6445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6446. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6447. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6448. EXPECT_EQ(false, res->has_header("Content-Range"));
  6449. EXPECT_EQ(0U, res->body.size());
  6450. }
  6451. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6452. auto res = cli_.Get(
  6453. "/with-range",
  6454. Headers{{"Range",
  6455. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6456. {"Accept-Encoding", ""}});
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6459. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6460. EXPECT_EQ(true, res->has_header("Content-Range"));
  6461. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6462. EXPECT_EQ(std::string("abcdefg"), res->body);
  6463. }
  6464. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6465. auto res = cli_.Get("/with-range", Headers{
  6466. {"Range", "bytes=0-"},
  6467. {"Accept-Encoding", ""},
  6468. });
  6469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6470. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6471. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6472. EXPECT_EQ(true, res->has_header("Content-Range"));
  6473. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6474. EXPECT_EQ(std::string("abcdefg"), res->body);
  6475. }
  6476. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6477. auto res = cli_.Get("/streamed-with-range",
  6478. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6480. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6481. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6482. EXPECT_EQ(false, res->has_header("Content-Range"));
  6483. EXPECT_EQ(267U, res->body.size());
  6484. // Check that both range contents are present
  6485. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6486. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6487. // Check that Content-Range headers are present for both ranges
  6488. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6489. std::string::npos);
  6490. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6491. std::string::npos);
  6492. }
  6493. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6494. Ranges ranges;
  6495. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6496. ranges.emplace_back(0, -1);
  6497. }
  6498. auto res = cli_.Get("/streamed-with-range?error",
  6499. Headers{{make_range_header(ranges)}});
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6502. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6503. EXPECT_EQ(false, res->has_header("Content-Range"));
  6504. EXPECT_EQ(0U, res->body.size());
  6505. }
  6506. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6507. auto res = cli_.Get("/streamed-with-range",
  6508. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6510. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6511. EXPECT_EQ(5U, res->body.size());
  6512. // Check that overlapping ranges are coalesced into a single range
  6513. EXPECT_EQ("bcdef", res->body);
  6514. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6515. // Should be single range, not multipart
  6516. EXPECT_TRUE(res->has_header("Content-Range"));
  6517. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6518. }
  6519. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6520. auto res = cli_.Get("/streamed-with-range",
  6521. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6523. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6524. EXPECT_EQ(268U, res->body.size());
  6525. // Check that both range contents are present
  6526. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6527. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6528. // Check that Content-Range headers are present for both ranges
  6529. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6530. std::string::npos);
  6531. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6532. std::string::npos);
  6533. }
  6534. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6535. auto res = cli_.Get("/streamed-with-range",
  6536. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6538. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6539. EXPECT_EQ(269U, res->body.size());
  6540. // Check that both duplicate range contents are present
  6541. size_t first_abc = res->body.find("abc\r\n");
  6542. EXPECT_TRUE(first_abc != std::string::npos);
  6543. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6544. EXPECT_TRUE(second_abc != std::string::npos);
  6545. // Check that Content-Range headers are present for both ranges
  6546. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6547. EXPECT_TRUE(first_range != std::string::npos);
  6548. size_t second_range =
  6549. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6550. EXPECT_TRUE(second_range != std::string::npos);
  6551. }
  6552. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6553. auto res =
  6554. cli_.Get("/streamed-with-range?error",
  6555. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6557. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6558. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6559. EXPECT_EQ(false, res->has_header("Content-Range"));
  6560. EXPECT_EQ(0U, res->body.size());
  6561. }
  6562. TEST_F(ServerTest, GetStreamedEndless) {
  6563. uint64_t offset = 0;
  6564. auto res = cli_.Get("/streamed-cancel",
  6565. [&](const char * /*data*/, uint64_t data_length) {
  6566. if (offset < 100) {
  6567. offset += data_length;
  6568. return true;
  6569. }
  6570. return false;
  6571. });
  6572. ASSERT_TRUE(!res);
  6573. EXPECT_EQ(Error::Canceled, res.error());
  6574. }
  6575. TEST_F(ServerTest, ClientStop) {
  6576. std::atomic_size_t count{4};
  6577. std::vector<std::thread> threads;
  6578. for (auto i = count.load(); i != 0; --i) {
  6579. threads.emplace_back([&]() {
  6580. auto res = cli_.Get("/streamed-cancel",
  6581. [&](const char *, uint64_t) { return true; });
  6582. --count;
  6583. ASSERT_TRUE(!res);
  6584. EXPECT_TRUE(res.error() == Error::Canceled ||
  6585. res.error() == Error::Read || res.error() == Error::Write);
  6586. });
  6587. }
  6588. std::this_thread::sleep_for(std::chrono::seconds(2));
  6589. while (count != 0) {
  6590. cli_.stop();
  6591. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6592. }
  6593. for (auto &t : threads) {
  6594. t.join();
  6595. }
  6596. }
  6597. TEST_F(ServerTest, GetWithRange1) {
  6598. auto res = cli_.Get("/with-range", Headers{
  6599. make_range_header({{3, 5}}),
  6600. {"Accept-Encoding", ""},
  6601. });
  6602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6604. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6605. EXPECT_EQ(true, res->has_header("Content-Range"));
  6606. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6607. EXPECT_EQ(std::string("def"), res->body);
  6608. }
  6609. TEST_F(ServerTest, GetWithRange2) {
  6610. auto res = cli_.Get("/with-range", Headers{
  6611. make_range_header({{1, -1}}),
  6612. {"Accept-Encoding", ""},
  6613. });
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6616. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6617. EXPECT_EQ(true, res->has_header("Content-Range"));
  6618. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6619. EXPECT_EQ(std::string("bcdefg"), res->body);
  6620. }
  6621. TEST_F(ServerTest, GetWithRange3) {
  6622. auto res = cli_.Get("/with-range", Headers{
  6623. make_range_header({{0, 0}}),
  6624. {"Accept-Encoding", ""},
  6625. });
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6628. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6629. EXPECT_EQ(true, res->has_header("Content-Range"));
  6630. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6631. EXPECT_EQ(std::string("a"), res->body);
  6632. }
  6633. TEST_F(ServerTest, GetWithRange4) {
  6634. auto res = cli_.Get("/with-range", Headers{
  6635. make_range_header({{-1, 2}}),
  6636. {"Accept-Encoding", ""},
  6637. });
  6638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6640. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6641. EXPECT_EQ(true, res->has_header("Content-Range"));
  6642. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6643. EXPECT_EQ(std::string("fg"), res->body);
  6644. }
  6645. TEST_F(ServerTest, GetWithRange5) {
  6646. auto res = cli_.Get("/with-range", Headers{
  6647. make_range_header({{0, 5}}),
  6648. {"Accept-Encoding", ""},
  6649. });
  6650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6651. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6652. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6653. EXPECT_EQ(true, res->has_header("Content-Range"));
  6654. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6655. EXPECT_EQ(std::string("abcdef"), res->body);
  6656. }
  6657. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6658. auto res =
  6659. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6662. }
  6663. TEST_F(ServerTest, GetWithRangeMultipart) {
  6664. auto res =
  6665. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6667. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6668. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6669. EXPECT_EQ(false, res->has_header("Content-Range"));
  6670. EXPECT_EQ(267U, res->body.size());
  6671. }
  6672. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6673. auto res = cli_.Get("/with-range",
  6674. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6676. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6677. }
  6678. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6679. auto res = cli_.Get("/with-range-customized-response",
  6680. Headers{{make_range_header({{1, 2}})}});
  6681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6682. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6683. EXPECT_EQ(true, res->has_header("Content-Length"));
  6684. EXPECT_EQ(false, res->has_header("Content-Range"));
  6685. EXPECT_EQ(JSON_DATA, res->body);
  6686. }
  6687. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6688. auto res = cli_.Get("/with-range-customized-response",
  6689. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6691. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6692. EXPECT_EQ(true, res->has_header("Content-Length"));
  6693. EXPECT_EQ(false, res->has_header("Content-Range"));
  6694. EXPECT_EQ(JSON_DATA, res->body);
  6695. }
  6696. TEST_F(ServerTest, Issue1772) {
  6697. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6699. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6700. }
  6701. TEST_F(ServerTest, Issue609) {
  6702. auto res = cli_.Delete("/issue609");
  6703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6704. EXPECT_EQ(StatusCode::OK_200, res->status);
  6705. EXPECT_EQ(std::string("ok"), res->body);
  6706. }
  6707. TEST_F(ServerTest, GetStreamedChunked) {
  6708. auto res = cli_.Get("/streamed-chunked");
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. EXPECT_EQ(std::string("123456789"), res->body);
  6712. }
  6713. TEST_F(ServerTest, GetStreamedChunked2) {
  6714. auto res = cli_.Get("/streamed-chunked2");
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. EXPECT_EQ(StatusCode::OK_200, res->status);
  6717. EXPECT_EQ(std::string("123456789"), res->body);
  6718. }
  6719. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6720. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::OK_200, res->status);
  6723. EXPECT_EQ(std::string("123456789"), res->body);
  6724. EXPECT_TRUE(res->has_header("Trailer"));
  6725. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6726. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6727. // Trailers are now stored separately from headers (security fix)
  6728. EXPECT_EQ(2U, res->trailers.size());
  6729. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6730. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6731. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6732. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6733. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6734. // Verify trailers are NOT in headers (security verification)
  6735. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6736. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6737. }
  6738. TEST_F(ServerTest, LargeChunkedPost) {
  6739. Request req;
  6740. req.method = "POST";
  6741. req.path = "/large-chunked";
  6742. std::string host_and_port;
  6743. host_and_port += HOST;
  6744. host_and_port += ":";
  6745. host_and_port += std::to_string(PORT);
  6746. req.headers.emplace("Host", host_and_port.c_str());
  6747. req.headers.emplace("Accept", "*/*");
  6748. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6749. req.headers.emplace("Content-Type", "text/plain");
  6750. req.headers.emplace("Content-Length", "0");
  6751. req.headers.emplace("Transfer-Encoding", "chunked");
  6752. std::string long_string(30 * 1024u, 'a');
  6753. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6754. // Attempt to make a large enough post to exceed OS buffers, to test that
  6755. // the server handles short reads if the full chunk data isn't available.
  6756. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6757. auto res = std::make_shared<Response>();
  6758. auto error = Error::Success;
  6759. auto ret = cli_.send(req, *res, error);
  6760. ASSERT_TRUE(ret);
  6761. EXPECT_EQ(StatusCode::OK_200, res->status);
  6762. }
  6763. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6764. auto res = cli_.Get("/remote_addr");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6768. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6769. }
  6770. TEST_F(ServerTest, GetMethodLocalAddr) {
  6771. auto res = cli_.Get("/local_addr");
  6772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6773. EXPECT_EQ(StatusCode::OK_200, res->status);
  6774. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6775. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6776. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6777. }
  6778. TEST_F(ServerTest, HTTPResponseSplitting) {
  6779. auto res = cli_.Get("/http_response_splitting");
  6780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6781. EXPECT_EQ(StatusCode::OK_200, res->status);
  6782. }
  6783. TEST_F(ServerTest, SlowRequest) {
  6784. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6785. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6786. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6787. }
  6788. #if 0
  6789. TEST_F(ServerTest, SlowPost) {
  6790. char buffer[64 * 1024];
  6791. memset(buffer, 0x42, sizeof(buffer));
  6792. auto res = cli_.Post(
  6793. "/slowpost", 64 * 1024 * 1024,
  6794. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6795. auto ret = sink.write(buffer, sizeof(buffer));
  6796. EXPECT_TRUE(ret);
  6797. return true;
  6798. },
  6799. "text/plain");
  6800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. }
  6803. TEST_F(ServerTest, SlowPostFail) {
  6804. char buffer[64 * 1024];
  6805. memset(buffer, 0x42, sizeof(buffer));
  6806. cli_.set_write_timeout(std::chrono::seconds(0));
  6807. auto res = cli_.Post(
  6808. "/slowpost", 64 * 1024 * 1024,
  6809. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6810. sink.write(buffer, sizeof(buffer));
  6811. return true;
  6812. },
  6813. "text/plain");
  6814. ASSERT_TRUE(!res);
  6815. EXPECT_EQ(Error::Write, res.error());
  6816. }
  6817. #endif
  6818. TEST_F(ServerTest, Put) {
  6819. auto res = cli_.Put("/put", "PUT", "text/plain");
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. EXPECT_EQ("PUT", res->body);
  6823. }
  6824. TEST_F(ServerTest, PutWithContentProvider) {
  6825. auto res = cli_.Put(
  6826. "/put", 3,
  6827. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6828. sink.os << "PUT";
  6829. return true;
  6830. },
  6831. "text/plain");
  6832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6833. EXPECT_EQ(StatusCode::OK_200, res->status);
  6834. EXPECT_EQ("PUT", res->body);
  6835. }
  6836. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6837. auto res = cli_.Post(
  6838. "/post", 42,
  6839. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6840. return false;
  6841. },
  6842. "text/plain");
  6843. ASSERT_TRUE(!res);
  6844. EXPECT_EQ(Error::Canceled, res.error());
  6845. }
  6846. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6847. auto res = cli_.Put(
  6848. "/put",
  6849. [](size_t /*offset*/, DataSink &sink) {
  6850. sink.os << "PUT";
  6851. sink.done();
  6852. return true;
  6853. },
  6854. "text/plain");
  6855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6856. EXPECT_EQ(StatusCode::OK_200, res->status);
  6857. EXPECT_EQ("PUT", res->body);
  6858. }
  6859. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6860. auto res = cli_.Post(
  6861. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6862. "text/plain");
  6863. ASSERT_TRUE(!res);
  6864. EXPECT_EQ(Error::Canceled, res.error());
  6865. }
  6866. TEST_F(ServerTest, PostLoopBack) {
  6867. std::string body;
  6868. auto res = cli_.Post(
  6869. "/post-loopback", 9,
  6870. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6871. EXPECT_EQ(9u, length);
  6872. sink.write("123", 3);
  6873. sink.write("456", 3);
  6874. sink.write("789", 3);
  6875. return true;
  6876. },
  6877. "text/plain",
  6878. [&body](const char *data, size_t data_length) {
  6879. body.append(data, data_length);
  6880. return true;
  6881. });
  6882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6883. EXPECT_EQ(StatusCode::OK_200, res->status);
  6884. EXPECT_EQ("123456789", body);
  6885. }
  6886. TEST_F(ServerTest, PutLoopBack) {
  6887. std::string body;
  6888. auto res = cli_.Put(
  6889. "/put-loopback", 9,
  6890. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6891. EXPECT_EQ(9u, length);
  6892. sink.write("123", 3);
  6893. sink.write("456", 3);
  6894. sink.write("789", 3);
  6895. return true;
  6896. },
  6897. "text/plain",
  6898. [&body](const char *data, size_t data_length) {
  6899. body.append(data, data_length);
  6900. return true;
  6901. });
  6902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6903. EXPECT_EQ(StatusCode::OK_200, res->status);
  6904. EXPECT_EQ("123456789", body);
  6905. }
  6906. TEST_F(ServerTest, PatchLoopBack) {
  6907. std::string body;
  6908. auto res = cli_.Patch(
  6909. "/patch-loopback", 9,
  6910. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6911. EXPECT_EQ(9u, length);
  6912. sink.write("123", 3);
  6913. sink.write("456", 3);
  6914. sink.write("789", 3);
  6915. return true;
  6916. },
  6917. "text/plain",
  6918. [&body](const char *data, size_t data_length) {
  6919. body.append(data, data_length);
  6920. return true;
  6921. });
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. EXPECT_EQ("123456789", body);
  6925. }
  6926. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6927. std::string body;
  6928. auto res = cli_.Post(
  6929. "/post-loopback",
  6930. [](size_t /*offset*/, DataSink &sink) {
  6931. sink.write("123", 3);
  6932. sink.write("456", 3);
  6933. sink.write("789", 3);
  6934. sink.done();
  6935. return true;
  6936. },
  6937. "text/plain",
  6938. [&body](const char *data, size_t data_length) {
  6939. body.append(data, data_length);
  6940. return true;
  6941. });
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_EQ(StatusCode::OK_200, res->status);
  6944. EXPECT_EQ("123456789", body);
  6945. }
  6946. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6947. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6948. cli_.set_compress(true);
  6949. auto res = cli_.Put(
  6950. "/put", 3,
  6951. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6952. sink.os << "PUT";
  6953. return true;
  6954. },
  6955. "text/plain");
  6956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6957. EXPECT_EQ(StatusCode::OK_200, res->status);
  6958. EXPECT_EQ("PUT", res->body);
  6959. }
  6960. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6961. cli_.set_compress(true);
  6962. auto res = cli_.Post(
  6963. "/post", 42,
  6964. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6965. return false;
  6966. },
  6967. "text/plain");
  6968. ASSERT_TRUE(!res);
  6969. EXPECT_EQ(Error::Canceled, res.error());
  6970. }
  6971. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6972. cli_.set_compress(true);
  6973. auto res = cli_.Put(
  6974. "/put",
  6975. [](size_t /*offset*/, DataSink &sink) {
  6976. sink.os << "PUT";
  6977. sink.done();
  6978. return true;
  6979. },
  6980. "text/plain");
  6981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6982. EXPECT_EQ(StatusCode::OK_200, res->status);
  6983. EXPECT_EQ("PUT", res->body);
  6984. }
  6985. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6986. cli_.set_compress(true);
  6987. auto res = cli_.Post(
  6988. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6989. "text/plain");
  6990. ASSERT_TRUE(!res);
  6991. EXPECT_EQ(Error::Canceled, res.error());
  6992. }
  6993. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6994. cli_.set_compress(true);
  6995. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. EXPECT_EQ(StatusCode::OK_200, res->status);
  6998. EXPECT_EQ(LARGE_DATA, res->body);
  6999. }
  7000. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7001. #ifdef CPPHTTPLIB_SSL_ENABLED
  7002. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7003. Client cli(s.c_str());
  7004. cli.enable_server_certificate_verification(false);
  7005. #else
  7006. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7007. Client cli(s.c_str());
  7008. #endif
  7009. cli.set_compress(true);
  7010. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. EXPECT_EQ(LARGE_DATA, res->body);
  7014. // The compressed size should be less than a 10th of the original. May vary
  7015. // depending on the zlib library.
  7016. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7017. static_cast<uint64_t>(10 * 1024 * 1024));
  7018. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7019. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7020. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7021. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7022. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7023. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7024. #endif
  7025. }
  7026. TEST_F(ServerTest, PutContentWithDeflate) {
  7027. cli_.set_compress(false);
  7028. Headers headers;
  7029. headers.emplace("Content-Encoding", "deflate");
  7030. // PUT in deflate format:
  7031. auto res = cli_.Put("/put", headers,
  7032. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7034. EXPECT_EQ(StatusCode::OK_200, res->status);
  7035. EXPECT_EQ("PUT", res->body);
  7036. }
  7037. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7038. Headers headers;
  7039. headers.emplace("Accept-Encoding", "gzip, deflate");
  7040. auto res = cli_.Get("/streamed-chunked", headers);
  7041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7042. EXPECT_EQ(StatusCode::OK_200, res->status);
  7043. EXPECT_EQ(std::string("123456789"), res->body);
  7044. }
  7045. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7046. Headers headers;
  7047. headers.emplace("Accept-Encoding", "gzip, deflate");
  7048. auto res = cli_.Get("/streamed-chunked2", headers);
  7049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7050. EXPECT_EQ(StatusCode::OK_200, res->status);
  7051. EXPECT_EQ(std::string("123456789"), res->body);
  7052. }
  7053. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7054. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7056. EXPECT_EQ(StatusCode::OK_200, res->status);
  7057. }
  7058. TEST(GzipDecompressor, ChunkedDecompression) {
  7059. std::string data;
  7060. for (size_t i = 0; i < 32 * 1024; ++i) {
  7061. data.push_back(static_cast<char>('a' + i % 26));
  7062. }
  7063. std::string compressed_data;
  7064. {
  7065. httplib::detail::gzip_compressor compressor;
  7066. bool result = compressor.compress(
  7067. data.data(), data.size(),
  7068. /*last=*/true,
  7069. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7070. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7071. compressed_data_size);
  7072. return true;
  7073. });
  7074. ASSERT_TRUE(result);
  7075. }
  7076. std::string decompressed_data;
  7077. {
  7078. httplib::detail::gzip_decompressor decompressor;
  7079. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7080. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7081. size_t chunk_size = 130;
  7082. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7083. chunk_begin += chunk_size) {
  7084. size_t current_chunk_size =
  7085. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7086. bool result = decompressor.decompress(
  7087. compressed_data.data() + chunk_begin, current_chunk_size,
  7088. [&](const char *decompressed_data_chunk,
  7089. size_t decompressed_data_chunk_size) {
  7090. decompressed_data.insert(decompressed_data.size(),
  7091. decompressed_data_chunk,
  7092. decompressed_data_chunk_size);
  7093. return true;
  7094. });
  7095. ASSERT_TRUE(result);
  7096. }
  7097. }
  7098. ASSERT_EQ(data, decompressed_data);
  7099. }
  7100. TEST(GzipDecompressor, DeflateDecompression) {
  7101. std::string original_text = "Raw deflate without gzip";
  7102. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7103. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7104. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7105. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7106. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7107. std::string decompressed_data;
  7108. {
  7109. httplib::detail::gzip_decompressor decompressor;
  7110. bool result = decompressor.decompress(
  7111. compressed_data.data(), compressed_data.size(),
  7112. [&](const char *decompressed_data_chunk,
  7113. size_t decompressed_data_chunk_size) {
  7114. decompressed_data.insert(decompressed_data.size(),
  7115. decompressed_data_chunk,
  7116. decompressed_data_chunk_size);
  7117. return true;
  7118. });
  7119. ASSERT_TRUE(result);
  7120. }
  7121. ASSERT_EQ(original_text, decompressed_data);
  7122. }
  7123. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7124. std::string original_text = "Raw deflate without gzip";
  7125. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7126. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7127. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7128. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7129. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7130. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7131. std::string decompressed_data;
  7132. {
  7133. httplib::detail::gzip_decompressor decompressor;
  7134. bool result = decompressor.decompress(
  7135. compressed_data.data(), compressed_data.size(),
  7136. [&](const char *decompressed_data_chunk,
  7137. size_t decompressed_data_chunk_size) {
  7138. decompressed_data.insert(decompressed_data.size(),
  7139. decompressed_data_chunk,
  7140. decompressed_data_chunk_size);
  7141. return true;
  7142. });
  7143. ASSERT_TRUE(result);
  7144. }
  7145. ASSERT_EQ(original_text, decompressed_data);
  7146. }
  7147. #endif
  7148. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7149. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7150. Headers headers;
  7151. headers.emplace("Accept-Encoding", "br");
  7152. auto res = cli_.Get("/streamed-chunked", headers);
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::OK_200, res->status);
  7155. EXPECT_EQ(std::string("123456789"), res->body);
  7156. }
  7157. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7158. Headers headers;
  7159. headers.emplace("Accept-Encoding", "br");
  7160. auto res = cli_.Get("/streamed-chunked2", headers);
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::OK_200, res->status);
  7163. EXPECT_EQ(std::string("123456789"), res->body);
  7164. }
  7165. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7166. cli_.set_compress(true);
  7167. auto res = cli_.Put(
  7168. "/put", 3,
  7169. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7170. sink.os << "PUT";
  7171. return true;
  7172. },
  7173. "text/plain");
  7174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7175. EXPECT_EQ(StatusCode::OK_200, res->status);
  7176. EXPECT_EQ("PUT", res->body);
  7177. }
  7178. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7179. cli_.set_compress(true);
  7180. auto res = cli_.Put(
  7181. "/put",
  7182. [](size_t /*offset*/, DataSink &sink) {
  7183. sink.os << "PUT";
  7184. sink.done();
  7185. return true;
  7186. },
  7187. "text/plain");
  7188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7189. EXPECT_EQ(StatusCode::OK_200, res->status);
  7190. EXPECT_EQ("PUT", res->body);
  7191. }
  7192. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7193. cli_.set_compress(true);
  7194. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::OK_200, res->status);
  7197. EXPECT_EQ(LARGE_DATA, res->body);
  7198. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7199. }
  7200. #endif
  7201. TEST_F(ServerTest, Patch) {
  7202. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7204. EXPECT_EQ(StatusCode::OK_200, res->status);
  7205. EXPECT_EQ("PATCH", res->body);
  7206. }
  7207. TEST_F(ServerTest, Delete) {
  7208. auto res = cli_.Delete("/delete");
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. EXPECT_EQ(StatusCode::OK_200, res->status);
  7211. EXPECT_EQ("DELETE", res->body);
  7212. }
  7213. TEST_F(ServerTest, DeleteContentReceiver) {
  7214. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7216. EXPECT_EQ(StatusCode::OK_200, res->status);
  7217. EXPECT_EQ("content", res->body);
  7218. }
  7219. TEST_F(ServerTest, Options) {
  7220. auto res = cli_.Options("*");
  7221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7222. EXPECT_EQ(StatusCode::OK_200, res->status);
  7223. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7224. EXPECT_TRUE(res->body.empty());
  7225. }
  7226. TEST_F(ServerTest, URL) {
  7227. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7229. EXPECT_EQ(StatusCode::OK_200, res->status);
  7230. }
  7231. TEST_F(ServerTest, ArrayParam) {
  7232. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7234. EXPECT_EQ(StatusCode::OK_200, res->status);
  7235. }
  7236. TEST_F(ServerTest, ArrayParamValues) {
  7237. auto res =
  7238. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7240. EXPECT_EQ(StatusCode::OK_200, res->status);
  7241. }
  7242. TEST_F(ServerTest, NoMultipleHeaders) {
  7243. Headers headers = {{"Content-Length", "5"}};
  7244. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7245. "text/plain");
  7246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7247. EXPECT_EQ(StatusCode::OK_200, res->status);
  7248. }
  7249. TEST_F(ServerTest, PostContentReceiver) {
  7250. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7252. ASSERT_EQ(StatusCode::OK_200, res->status);
  7253. ASSERT_EQ("content", res->body);
  7254. }
  7255. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7256. UploadFormDataItems items = {
  7257. {"text1", "text default", "", ""},
  7258. {"text2", "aωb", "", ""},
  7259. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7260. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7261. {"file3", "", "", "application/octet-stream"},
  7262. };
  7263. auto res = cli_.Post("/content_receiver", items);
  7264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7265. EXPECT_EQ(StatusCode::OK_200, res->status);
  7266. }
  7267. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7268. UploadFormDataItems items = {
  7269. {"text1", "text default", "", ""},
  7270. {"text2", "aωb", "", ""},
  7271. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7272. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7273. {"file3", "", "", "application/octet-stream"},
  7274. };
  7275. auto boundary = std::string("+++++");
  7276. std::string body;
  7277. for (const auto &item : items) {
  7278. body += "--" + boundary + "\r\n";
  7279. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7280. if (!item.filename.empty()) {
  7281. body += "; filename=\"" + item.filename + "\"";
  7282. }
  7283. body += "\r\n";
  7284. if (!item.content_type.empty()) {
  7285. body += "Content-Type: " + item.content_type + "\r\n";
  7286. }
  7287. body += "\r\n";
  7288. body += item.content + "\r\n";
  7289. }
  7290. body += "--" + boundary + "--\r\n";
  7291. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7292. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ(StatusCode::OK_200, res->status);
  7295. }
  7296. TEST(MultipartFormDataTest, FieldEscaping) {
  7297. Server svr;
  7298. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7299. const ContentReader &content_reader) {
  7300. ASSERT_TRUE(req.is_multipart_form_data());
  7301. std::vector<FormData> received;
  7302. content_reader(
  7303. [&](const FormData &file) {
  7304. received.push_back(file);
  7305. return true;
  7306. },
  7307. [&](const char *data, size_t data_length) {
  7308. received.back().content.append(data, data_length);
  7309. return true;
  7310. });
  7311. // '"', CR and LF in names and filenames are escaped following the
  7312. // WHATWG HTML standard, so each part still parses as a single part
  7313. // with no injected headers. Content types get CR/LF escaped too,
  7314. // while '"' (legal there, e.g. quoted charset) is preserved.
  7315. ASSERT_EQ(4U, received.size());
  7316. EXPECT_EQ("na%22me", received[0].name);
  7317. EXPECT_EQ("quoted name", received[0].content);
  7318. EXPECT_EQ("file", received[1].name);
  7319. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7320. received[1].filename);
  7321. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7322. EXPECT_EQ("injected", received[1].content);
  7323. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7324. EXPECT_EQ("my%22file.txt", received[2].filename);
  7325. EXPECT_EQ("cr lf name", received[2].content);
  7326. EXPECT_EQ("typed", received[3].name);
  7327. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7328. received[3].content_type);
  7329. EXPECT_EQ("typed content", received[3].content);
  7330. });
  7331. auto port = svr.bind_to_any_port("localhost");
  7332. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7333. auto se = detail::scope_exit([&] {
  7334. svr.stop();
  7335. t.join();
  7336. ASSERT_FALSE(svr.is_running());
  7337. });
  7338. svr.wait_until_ready();
  7339. Client cli("localhost", port);
  7340. UploadFormDataItems items = {
  7341. {"na\"me", "quoted name", "", ""},
  7342. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7343. "application/octet-stream"},
  7344. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7345. {"typed", "typed content", "",
  7346. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7347. };
  7348. auto res = cli.Post("/post", items);
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. EXPECT_EQ(StatusCode::OK_200, res->status);
  7351. }
  7352. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7353. const UploadFormDataItems items = {
  7354. {"name1", "Content 1", "", ""},
  7355. {"name2", "Content 2", "file2.txt", "text/plain"},
  7356. };
  7357. Server svr;
  7358. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7359. const ContentReader &content_reader) {
  7360. ASSERT_TRUE(req.is_multipart_form_data());
  7361. std::vector<FormData> received;
  7362. content_reader(
  7363. [&](const FormData &file) {
  7364. received.push_back(file);
  7365. return true;
  7366. },
  7367. [&](const char *data, size_t data_length) {
  7368. received.back().content.append(data, data_length);
  7369. return true;
  7370. });
  7371. ASSERT_EQ(2U, received.size());
  7372. EXPECT_EQ("name1", received[0].name);
  7373. EXPECT_EQ("Content 1", received[0].content);
  7374. EXPECT_EQ("name2", received[1].name);
  7375. EXPECT_EQ("Content 2", received[1].content);
  7376. EXPECT_EQ("file2.txt", received[1].filename);
  7377. EXPECT_EQ("text/plain", received[1].content_type);
  7378. });
  7379. auto port = svr.bind_to_any_port("localhost");
  7380. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7381. auto se = detail::scope_exit([&] {
  7382. svr.stop();
  7383. t.join();
  7384. ASSERT_FALSE(svr.is_running());
  7385. });
  7386. svr.wait_until_ready();
  7387. Client cli("localhost", port);
  7388. // Whole-body serialization with a generated boundary
  7389. {
  7390. MultipartFormDataWriter writer;
  7391. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7392. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7393. writer.content_type());
  7394. auto body = writer.serialize(items);
  7395. EXPECT_EQ(body.size(), writer.content_length(items));
  7396. auto res = cli.Post("/post", body, writer.content_type());
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::OK_200, res->status);
  7399. }
  7400. // Per-part framing with a custom boundary via a content provider
  7401. {
  7402. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7403. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7404. MultipartFormDataWriter writer("custom-boundary_123");
  7405. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7406. std::string body;
  7407. for (const auto &item : items) {
  7408. body += writer.item_begin(item);
  7409. body += item.content;
  7410. body += MultipartFormDataWriter::item_end();
  7411. }
  7412. body += writer.finish();
  7413. EXPECT_EQ(body.size(), writer.content_length(items));
  7414. auto res = cli.Post(
  7415. "/post", body.size(),
  7416. [&](size_t offset, size_t length, DataSink &sink) {
  7417. sink.write(body.data() + offset, length);
  7418. return true;
  7419. },
  7420. writer.content_type());
  7421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7422. EXPECT_EQ(StatusCode::OK_200, res->status);
  7423. }
  7424. }
  7425. TEST_F(ServerTest, PostContentReceiverGzip) {
  7426. cli_.set_compress(true);
  7427. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7429. ASSERT_EQ(StatusCode::OK_200, res->status);
  7430. ASSERT_EQ("content", res->body);
  7431. }
  7432. TEST_F(ServerTest, PutContentReceiver) {
  7433. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7435. ASSERT_EQ(StatusCode::OK_200, res->status);
  7436. ASSERT_EQ("content", res->body);
  7437. }
  7438. TEST_F(ServerTest, PatchContentReceiver) {
  7439. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7441. ASSERT_EQ(StatusCode::OK_200, res->status);
  7442. ASSERT_EQ("content", res->body);
  7443. }
  7444. template <typename ClientType>
  7445. void TestWithHeadersAndContentReceiver(
  7446. ClientType &cli,
  7447. std::function<Result(ClientType &, const std::string &, const Headers &,
  7448. const std::string &, const std::string &,
  7449. ContentReceiver, DownloadProgress)>
  7450. request_func) {
  7451. Headers headers;
  7452. headers.emplace("X-Custom-Header", "test-value");
  7453. std::string received_body;
  7454. auto res = request_func(
  7455. cli, "/content_receiver", headers, "content", "application/json",
  7456. [&](const char *data, size_t data_length) {
  7457. received_body.append(data, data_length);
  7458. return true;
  7459. },
  7460. nullptr);
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::OK_200, res->status);
  7463. EXPECT_EQ("content", received_body);
  7464. }
  7465. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7466. #ifdef CPPHTTPLIB_SSL_ENABLED
  7467. using ClientT = SSLClient;
  7468. #else
  7469. using ClientT = Client;
  7470. #endif
  7471. TestWithHeadersAndContentReceiver<ClientT>(
  7472. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7473. const std::string &body, const std::string &content_type,
  7474. ContentReceiver receiver, DownloadProgress progress) {
  7475. return cli.Post(path, headers, body, content_type, receiver, progress);
  7476. });
  7477. }
  7478. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7479. #ifdef CPPHTTPLIB_SSL_ENABLED
  7480. using ClientT = SSLClient;
  7481. #else
  7482. using ClientT = Client;
  7483. #endif
  7484. TestWithHeadersAndContentReceiver<ClientT>(
  7485. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7486. const std::string &body, const std::string &content_type,
  7487. ContentReceiver receiver, DownloadProgress progress) {
  7488. return cli.Put(path, headers, body, content_type, receiver, progress);
  7489. });
  7490. }
  7491. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7492. #ifdef CPPHTTPLIB_SSL_ENABLED
  7493. using ClientT = SSLClient;
  7494. #else
  7495. using ClientT = Client;
  7496. #endif
  7497. TestWithHeadersAndContentReceiver<ClientT>(
  7498. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7499. const std::string &body, const std::string &content_type,
  7500. ContentReceiver receiver, DownloadProgress progress) {
  7501. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7502. });
  7503. }
  7504. template <typename ClientType>
  7505. void TestWithHeadersAndContentReceiverWithProgress(
  7506. ClientType &cli,
  7507. std::function<Result(ClientType &, const std::string &, const Headers &,
  7508. const std::string &, const std::string &,
  7509. ContentReceiver, DownloadProgress)>
  7510. request_func) {
  7511. Headers headers;
  7512. headers.emplace("X-Test-Header", "progress-test");
  7513. std::string received_body;
  7514. auto progress_called = false;
  7515. auto res = request_func(
  7516. cli, "/content_receiver", headers, "content", "text/plain",
  7517. [&](const char *data, size_t data_length) {
  7518. received_body.append(data, data_length);
  7519. return true;
  7520. },
  7521. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7522. progress_called = true;
  7523. return true;
  7524. });
  7525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7526. EXPECT_EQ(StatusCode::OK_200, res->status);
  7527. EXPECT_EQ("content", received_body);
  7528. EXPECT_TRUE(progress_called);
  7529. }
  7530. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7531. #ifdef CPPHTTPLIB_SSL_ENABLED
  7532. using ClientT = SSLClient;
  7533. #else
  7534. using ClientT = Client;
  7535. #endif
  7536. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7537. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7538. const std::string &body, const std::string &content_type,
  7539. ContentReceiver receiver, DownloadProgress progress) {
  7540. return cli.Post(path, headers, body, content_type, receiver, progress);
  7541. });
  7542. }
  7543. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7544. #ifdef CPPHTTPLIB_SSL_ENABLED
  7545. using ClientT = SSLClient;
  7546. #else
  7547. using ClientT = Client;
  7548. #endif
  7549. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7550. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7551. const std::string &body, const std::string &content_type,
  7552. ContentReceiver receiver, DownloadProgress progress) {
  7553. return cli.Put(path, headers, body, content_type, receiver, progress);
  7554. });
  7555. }
  7556. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7557. #ifdef CPPHTTPLIB_SSL_ENABLED
  7558. using ClientT = SSLClient;
  7559. #else
  7560. using ClientT = Client;
  7561. #endif
  7562. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7563. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7564. const std::string &body, const std::string &content_type,
  7565. ContentReceiver receiver, DownloadProgress progress) {
  7566. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7567. });
  7568. }
  7569. template <typename ClientType>
  7570. void TestWithHeadersAndContentReceiverError(
  7571. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7572. const Headers &, const std::string &,
  7573. const std::string &, ContentReceiver)>
  7574. request_func) {
  7575. Headers headers;
  7576. headers.emplace("X-Error-Test", "true");
  7577. std::string received_body;
  7578. auto receiver_failed = false;
  7579. auto res =
  7580. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7581. [&](const char *data, size_t data_length) {
  7582. received_body.append(data, data_length);
  7583. receiver_failed = true;
  7584. return false;
  7585. });
  7586. ASSERT_FALSE(res);
  7587. EXPECT_TRUE(receiver_failed);
  7588. }
  7589. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7590. #ifdef CPPHTTPLIB_SSL_ENABLED
  7591. using ClientT = SSLClient;
  7592. #else
  7593. using ClientT = Client;
  7594. #endif
  7595. TestWithHeadersAndContentReceiverError<ClientT>(
  7596. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7597. const std::string &body, const std::string &content_type,
  7598. ContentReceiver receiver) {
  7599. return cli.Post(path, headers, body, content_type, receiver);
  7600. });
  7601. }
  7602. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7603. #ifdef CPPHTTPLIB_SSL_ENABLED
  7604. using ClientT = SSLClient;
  7605. #else
  7606. using ClientT = Client;
  7607. #endif
  7608. TestWithHeadersAndContentReceiverError<ClientT>(
  7609. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7610. const std::string &body, const std::string &content_type,
  7611. ContentReceiver receiver) {
  7612. return cli.Put(path, headers, body, content_type, receiver);
  7613. });
  7614. }
  7615. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7616. #ifdef CPPHTTPLIB_SSL_ENABLED
  7617. using ClientT = SSLClient;
  7618. #else
  7619. using ClientT = Client;
  7620. #endif
  7621. TestWithHeadersAndContentReceiverError<ClientT>(
  7622. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7623. const std::string &body, const std::string &content_type,
  7624. ContentReceiver receiver) {
  7625. return cli.Patch(path, headers, body, content_type, receiver);
  7626. });
  7627. }
  7628. TEST_F(ServerTest, PostQueryStringAndBody) {
  7629. auto res =
  7630. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7632. ASSERT_EQ(StatusCode::OK_200, res->status);
  7633. }
  7634. TEST_F(ServerTest, HTTP2Magic) {
  7635. Request req;
  7636. req.method = "PRI";
  7637. req.path = "*";
  7638. req.body = "SM";
  7639. auto res = std::make_shared<Response>();
  7640. auto error = Error::Success;
  7641. auto ret = cli_.send(req, *res, error);
  7642. ASSERT_TRUE(ret);
  7643. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7644. }
  7645. TEST_F(ServerTest, KeepAlive) {
  7646. auto res = cli_.Get("/hi");
  7647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7648. EXPECT_EQ(StatusCode::OK_200, res->status);
  7649. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7650. EXPECT_EQ("Hello World!", res->body);
  7651. res = cli_.Get("/hi");
  7652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7653. EXPECT_EQ(StatusCode::OK_200, res->status);
  7654. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7655. EXPECT_EQ("Hello World!", res->body);
  7656. res = cli_.Get("/hi");
  7657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7658. EXPECT_EQ(StatusCode::OK_200, res->status);
  7659. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7660. EXPECT_EQ("Hello World!", res->body);
  7661. res = cli_.Get("/not-exist");
  7662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7663. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7664. res = cli_.Post("/empty", "", "text/plain");
  7665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7666. EXPECT_EQ(StatusCode::OK_200, res->status);
  7667. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7668. EXPECT_EQ("empty", res->body);
  7669. EXPECT_EQ("close", res->get_header_value("Connection"));
  7670. res = cli_.Post(
  7671. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7672. "text/plain");
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7676. EXPECT_EQ("empty", res->body);
  7677. cli_.set_keep_alive(false);
  7678. res = cli_.Get("/last-request");
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. EXPECT_EQ(StatusCode::OK_200, res->status);
  7681. EXPECT_EQ("close", res->get_header_value("Connection"));
  7682. }
  7683. TEST_F(ServerTest, TooManyRedirect) {
  7684. cli_.set_follow_location(true);
  7685. auto res = cli_.Get("/redirect/0");
  7686. ASSERT_TRUE(!res);
  7687. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7688. }
  7689. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7690. Request req;
  7691. req.method = "FOOBAR";
  7692. req.path = "/hi";
  7693. cli_.set_keep_alive(true);
  7694. auto res = cli_.send(req);
  7695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7696. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7697. EXPECT_EQ("close", res->get_header_value("Connection"));
  7698. EXPECT_FALSE(cli_.is_socket_open());
  7699. }
  7700. TEST_F(ServerTest, CustomRouteReadsBody) {
  7701. const std::string xml =
  7702. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7703. Request req;
  7704. req.method = "PROPFIND";
  7705. req.path = "/dav/dir";
  7706. req.set_header("Depth", "1");
  7707. req.body = xml;
  7708. auto res = cli_.send(req);
  7709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7710. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7711. EXPECT_EQ(xml, res->body);
  7712. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7713. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7714. }
  7715. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7716. Request req;
  7717. req.method = "PROPFIND";
  7718. req.path = "/dav/42";
  7719. auto res = cli_.send(req);
  7720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7721. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7722. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7723. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7724. }
  7725. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7726. Request req;
  7727. req.method = "PROPFIND";
  7728. req.path = "/dav-re/123";
  7729. auto res = cli_.send(req);
  7730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7731. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7732. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7733. }
  7734. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7735. Request req;
  7736. req.method = "MKCOL";
  7737. req.path = "/dav-mkcol";
  7738. auto res = cli_.send(req);
  7739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7740. EXPECT_EQ(StatusCode::Created_201, res->status);
  7741. }
  7742. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7743. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7744. Request req;
  7745. req.method = "REPORT";
  7746. req.path = "/dav-report";
  7747. req.body = xml;
  7748. auto res = cli_.send(req);
  7749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7750. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7751. EXPECT_EQ(xml, res->body);
  7752. }
  7753. // A content reader route must fire even when the request carries no body,
  7754. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7755. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7756. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7757. Request req;
  7758. req.method = "REPORT";
  7759. req.path = "/dav-report";
  7760. auto res = cli_.send(req);
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7763. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7764. }
  7765. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7766. Request req;
  7767. req.method = "PROPFIND";
  7768. req.path = "/not-dav";
  7769. auto res = cli_.send(req);
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7772. }
  7773. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7774. Request req;
  7775. req.method = "UNLOCK";
  7776. req.path = "/dav/dir";
  7777. cli_.set_keep_alive(true);
  7778. auto res = cli_.send(req);
  7779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7780. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7781. EXPECT_EQ("close", res->get_header_value("Connection"));
  7782. EXPECT_FALSE(cli_.is_socket_open());
  7783. }
  7784. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7785. // The mount point serves this path, but only for GET and HEAD.
  7786. auto get_res = cli_.Get("/dir/index.html");
  7787. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7788. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7789. Request req;
  7790. req.method = "PROPFIND";
  7791. req.path = "/dir/index.html";
  7792. auto res = cli_.send(req);
  7793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7794. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7795. }
  7796. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7797. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7798. cli_.set_keep_alive(true);
  7799. for (auto i = 0; i < 2; i++) {
  7800. Request req;
  7801. req.method = "PROPFIND";
  7802. req.path = "/dav/dir";
  7803. req.body = xml;
  7804. auto res = cli_.send(req);
  7805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7806. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7807. EXPECT_EQ(xml, res->body);
  7808. EXPECT_TRUE(cli_.is_socket_open());
  7809. }
  7810. // A built-in method must still be served on the same connection.
  7811. cli_.set_keep_alive(false);
  7812. auto res = cli_.Get("/hi");
  7813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7814. EXPECT_EQ(StatusCode::OK_200, res->status);
  7815. EXPECT_EQ("close", res->get_header_value("Connection"));
  7816. }
  7817. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7818. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7819. Request req;
  7820. req.method = "PROPFIND";
  7821. req.path = "/dav/dir";
  7822. req.set_header("Expect", "100-continue");
  7823. req.body = xml;
  7824. auto res = cli_.send(req);
  7825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7826. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7827. EXPECT_EQ(xml, res->body);
  7828. }
  7829. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7830. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7831. TEST_F(ServerTest, Gzip) {
  7832. Headers headers;
  7833. headers.emplace("Accept-Encoding", "gzip, deflate");
  7834. auto res = cli_.Get("/compress", headers);
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7837. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7838. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7839. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7840. "7890123456789012345678901234567890",
  7841. res->body);
  7842. EXPECT_EQ(StatusCode::OK_200, res->status);
  7843. }
  7844. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7845. Headers headers;
  7846. headers.emplace("Accept-Encoding", "gzip, deflate");
  7847. auto res = cli_.Get("/compress-with-charset", headers);
  7848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7849. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7850. EXPECT_EQ("application/json; charset=utf-8",
  7851. res->get_header_value("Content-Type"));
  7852. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7853. "7890123456789012345678901234567890",
  7854. res->body);
  7855. EXPECT_EQ(StatusCode::OK_200, res->status);
  7856. }
  7857. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7858. Headers headers;
  7859. headers.emplace("Accept-Encoding", "");
  7860. auto res = cli_.Get("/compress", headers);
  7861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7862. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7863. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7864. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7865. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7866. "7890123456789012345678901234567890",
  7867. res->body);
  7868. EXPECT_EQ(StatusCode::OK_200, res->status);
  7869. }
  7870. TEST_F(ServerTest, GzipWithContentReceiver) {
  7871. Headers headers;
  7872. headers.emplace("Accept-Encoding", "gzip, deflate");
  7873. std::string body;
  7874. auto res = cli_.Get("/compress", headers,
  7875. [&](const char *data, uint64_t data_length) {
  7876. EXPECT_EQ(100U, data_length);
  7877. body.append(data, data_length);
  7878. return true;
  7879. });
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7882. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7883. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7884. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7885. "7890123456789012345678901234567890",
  7886. body);
  7887. EXPECT_EQ(StatusCode::OK_200, res->status);
  7888. }
  7889. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7890. Headers headers;
  7891. headers.emplace("Accept-Encoding", "gzip, deflate");
  7892. cli_.set_decompress(false);
  7893. auto res = cli_.Get("/compress", headers);
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7896. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7897. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7898. EXPECT_EQ(33U, res->body.size());
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. }
  7901. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7902. Headers headers;
  7903. headers.emplace("Accept-Encoding", "");
  7904. std::string body;
  7905. auto res = cli_.Get("/compress", headers,
  7906. [&](const char *data, uint64_t data_length) {
  7907. EXPECT_EQ(100U, data_length);
  7908. body.append(data, data_length);
  7909. return true;
  7910. });
  7911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7912. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7913. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7914. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7915. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7916. "7890123456789012345678901234567890",
  7917. body);
  7918. EXPECT_EQ(StatusCode::OK_200, res->status);
  7919. }
  7920. TEST_F(ServerTest, NoGzip) {
  7921. Headers headers;
  7922. headers.emplace("Accept-Encoding", "gzip, deflate");
  7923. auto res = cli_.Get("/nocompress", headers);
  7924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7925. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7926. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7927. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7928. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7929. "7890123456789012345678901234567890",
  7930. res->body);
  7931. EXPECT_EQ(StatusCode::OK_200, res->status);
  7932. }
  7933. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7934. Headers headers;
  7935. headers.emplace("Accept-Encoding", "gzip, deflate");
  7936. std::string body;
  7937. auto res = cli_.Get("/nocompress", headers,
  7938. [&](const char *data, uint64_t data_length) {
  7939. EXPECT_EQ(100U, data_length);
  7940. body.append(data, data_length);
  7941. return true;
  7942. });
  7943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7944. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7945. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7946. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7947. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7948. "7890123456789012345678901234567890",
  7949. body);
  7950. EXPECT_EQ(StatusCode::OK_200, res->status);
  7951. }
  7952. TEST_F(ServerTest, MultipartFormDataGzip) {
  7953. UploadFormDataItems items = {
  7954. {"key1", "test", "", ""},
  7955. {"key2", "--abcdefg123", "", ""},
  7956. };
  7957. cli_.set_compress(true);
  7958. auto res = cli_.Post("/compress-multipart", items);
  7959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7960. EXPECT_EQ(StatusCode::OK_200, res->status);
  7961. }
  7962. #endif
  7963. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7964. // Static file compression is opt-in, so these run their own server rather than
  7965. // flipping it on for the shared ServerTest fixture, which would silently
  7966. // rewrite what every other static file test is asserting.
  7967. class StaticFileCompressionTest : public ::testing::Test {
  7968. protected:
  7969. void TearDown() override {
  7970. if (t_.joinable()) {
  7971. svr_.stop();
  7972. t_.join();
  7973. }
  7974. }
  7975. int start(const std::function<void(Server &)> &configure = nullptr) {
  7976. // Serves the same tree as a directory of build-time compressed assets
  7977. // would be served: the mount point names the coding the files are already
  7978. // stored in. Registered before "/" so it is the one that matches.
  7979. svr_.set_mount_point("/pre-encoded", "./www",
  7980. {{"Content-Encoding", "gzip"}});
  7981. svr_.set_mount_point("/", "./www");
  7982. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7983. res.set_file_content("./www/dir/index.html", "text/html");
  7984. });
  7985. svr_.Get("/pre-encoded-file-content",
  7986. [](const Request & /*req*/, Response &res) {
  7987. res.set_header("Content-Encoding", "gzip");
  7988. res.set_file_content("./www/dir/index.html", "text/html");
  7989. });
  7990. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7991. res.set_content_provider(
  7992. 6, "text/plain",
  7993. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7994. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7995. return true;
  7996. });
  7997. });
  7998. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7999. res.set_content_provider(
  8000. 1000, "text/plain",
  8001. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8002. if (offset < 100) {
  8003. std::string data(100, 'A');
  8004. sink.write(data.data(), data.size());
  8005. return true;
  8006. }
  8007. std::this_thread::sleep_for(std::chrono::seconds(2));
  8008. std::string data(900, 'B');
  8009. sink.write(data.data(), data.size());
  8010. return true;
  8011. });
  8012. });
  8013. if (configure) { configure(svr_); }
  8014. auto port = svr_.bind_to_any_port(HOST);
  8015. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8016. svr_.wait_until_ready();
  8017. return port;
  8018. }
  8019. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8020. // Every file under ./www except 1MB.txt is smaller than the default
  8021. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8022. // it out of the way.
  8023. static void enable_without_floor(Server &svr) {
  8024. svr.set_static_file_compression(true);
  8025. svr.set_static_file_compression_min_length(0);
  8026. }
  8027. Server svr_;
  8028. std::thread t_;
  8029. };
  8030. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8031. auto port = start();
  8032. Client cli(HOST, port);
  8033. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8035. EXPECT_EQ(StatusCode::OK_200, res->status);
  8036. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8037. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8038. EXPECT_EQ(1048576U, res->body.size());
  8039. }
  8040. TEST_F(StaticFileCompressionTest, MountPoint) {
  8041. auto port = start(enable);
  8042. Client cli(HOST, port);
  8043. cli.set_decompress(false);
  8044. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8046. EXPECT_EQ(StatusCode::OK_200, res->status);
  8047. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8048. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8049. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8050. // The response stays self-delimiting: a length, not a chunked body.
  8051. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8052. EXPECT_EQ(std::to_string(res->body.size()),
  8053. res->get_header_value("Content-Length"));
  8054. EXPECT_LT(res->body.size(), 1048576U);
  8055. EXPECT_FALSE(res->body.empty());
  8056. }
  8057. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8058. auto port = start(enable);
  8059. Client cli(HOST, port);
  8060. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8062. EXPECT_EQ(StatusCode::OK_200, res->status);
  8063. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8064. EXPECT_EQ(1048576U, res->body.size());
  8065. }
  8066. TEST_F(StaticFileCompressionTest, FileContent) {
  8067. auto port = start(enable_without_floor);
  8068. Client cli(HOST, port);
  8069. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8071. EXPECT_EQ(StatusCode::OK_200, res->status);
  8072. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8073. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8074. EXPECT_EQ(104U, res->body.size());
  8075. }
  8076. // A handler that serves an already-encoded file names the coding itself. The
  8077. // file-backed path decided its coding from Accept-Encoding and the content
  8078. // type alone, so it compressed the stored bytes a second time and appended a
  8079. // second Content-Encoding field line.
  8080. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8081. auto port = start(enable_without_floor);
  8082. Client cli(HOST, port);
  8083. cli.set_decompress(false);
  8084. auto res = cli.Get("/pre-encoded-file-content",
  8085. Headers{{"Accept-Encoding", "gzip"}});
  8086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8087. EXPECT_EQ(StatusCode::OK_200, res->status);
  8088. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8089. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8090. // Vary belongs to a coding the server chose, and it chose none here.
  8091. EXPECT_FALSE(res->has_header("Vary"));
  8092. // The file travels exactly as it is stored on disk.
  8093. EXPECT_EQ(104U, res->body.size());
  8094. }
  8095. // The 1MB file clears the default floor, so this one runs the configuration a
  8096. // deployment would actually have.
  8097. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8098. auto port = start(enable);
  8099. Client cli(HOST, port);
  8100. cli.set_decompress(false);
  8101. auto res =
  8102. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8104. EXPECT_EQ(StatusCode::OK_200, res->status);
  8105. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8106. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8107. EXPECT_FALSE(res->has_header("Vary"));
  8108. EXPECT_EQ(1048576U, res->body.size());
  8109. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8110. }
  8111. TEST_F(StaticFileCompressionTest, Head) {
  8112. auto port = start(enable);
  8113. Client cli(HOST, port);
  8114. cli.set_decompress(false);
  8115. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8116. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8117. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8119. EXPECT_EQ(StatusCode::OK_200, res->status);
  8120. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8121. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8122. // HEAD still reports the size a GET would return.
  8123. EXPECT_EQ(get->get_header_value("Content-Length"),
  8124. res->get_header_value("Content-Length"));
  8125. EXPECT_TRUE(res->body.empty());
  8126. }
  8127. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8128. auto port = start(enable);
  8129. Client cli(HOST, port);
  8130. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8131. {"Accept-Encoding", "gzip"}});
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8134. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8135. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8136. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8137. EXPECT_EQ("cd", res->body);
  8138. }
  8139. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8140. auto port = start(enable);
  8141. Client cli(HOST, port);
  8142. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8146. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8147. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8148. }
  8149. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8150. auto port = start(enable);
  8151. Client cli(HOST, port);
  8152. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8154. EXPECT_EQ(StatusCode::OK_200, res->status);
  8155. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8156. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8157. EXPECT_TRUE(res->body.empty());
  8158. }
  8159. TEST_F(StaticFileCompressionTest, MinLength) {
  8160. auto port = start(enable);
  8161. Client cli(HOST, port);
  8162. // 104 bytes, well under the default floor. Compressing it would add the
  8163. // gzip header and trailer to a body that already fits in one packet.
  8164. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8166. EXPECT_EQ(StatusCode::OK_200, res->status);
  8167. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8168. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8169. }
  8170. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8171. auto port = start([](Server &svr) {
  8172. svr.set_static_file_compression(true);
  8173. svr.set_static_file_compression_min_length(1);
  8174. });
  8175. Client cli(HOST, port);
  8176. cli.set_decompress(false);
  8177. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8179. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8180. // A 9-byte file comes back larger than it went in, because gzip's header and
  8181. // trailer outweigh anything deflate can save. That is the end of the range
  8182. // the floor exists to keep out.
  8183. EXPECT_GT(res->body.size(), 9U);
  8184. }
  8185. TEST_F(StaticFileCompressionTest, MaxLength) {
  8186. auto port = start([](Server &svr) {
  8187. svr.set_static_file_compression(true);
  8188. svr.set_static_file_compression_min_length(0);
  8189. svr.set_static_file_compression_max_length(1024);
  8190. });
  8191. Client cli(HOST, port);
  8192. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8193. // defines `small` as a macro on Windows.
  8194. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8195. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8196. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8197. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8198. // Under it: compressed.
  8199. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8200. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8201. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8202. }
  8203. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8204. auto port = start(enable_without_floor);
  8205. Client cli(HOST, port);
  8206. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8207. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8208. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8209. auto identity_etag = identity->get_header_value("ETag");
  8210. ASSERT_FALSE(identity_etag.empty());
  8211. auto gzipped =
  8212. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8213. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8214. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8215. auto gzip_etag = gzipped->get_header_value("ETag");
  8216. ASSERT_FALSE(gzip_etag.empty());
  8217. // Two representations, two validators.
  8218. EXPECT_NE(identity_etag, gzip_etag);
  8219. // Each one revalidates against the request that would produce it...
  8220. auto fresh =
  8221. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8222. {"If-None-Match", gzip_etag}});
  8223. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8224. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8225. auto fresh_identity =
  8226. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8227. {"If-None-Match", identity_etag}});
  8228. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8229. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8230. // ...and not against the other representation.
  8231. auto crossed =
  8232. cli.Get("/dir/index.html",
  8233. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8234. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8235. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8236. }
  8237. // The opt-in covers responses the server reads off disk itself. A caller's own
  8238. // known-length provider keeps its Content-Length and, more importantly, keeps
  8239. // delivering incrementally: routing it through a compressor would hold every
  8240. // write back until zlib's window filled.
  8241. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8242. auto port = start(enable);
  8243. Client cli(HOST, port);
  8244. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8246. EXPECT_EQ(StatusCode::OK_200, res->status);
  8247. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8248. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8249. EXPECT_EQ("aaabbb", res->body);
  8250. }
  8251. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8252. auto port = start(enable);
  8253. Client cli(HOST, port);
  8254. cli.set_read_timeout(1, 0);
  8255. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8256. Headers{{"Accept-Encoding", "gzip"}});
  8257. ASSERT_TRUE(handle.is_valid());
  8258. // The provider writes 100 bytes and then stalls for longer than the read
  8259. // timeout. Those first bytes have to arrive anyway: run the response through
  8260. // a compressor and zlib holds them until its window fills, so the read would
  8261. // come back empty instead.
  8262. char buf[256];
  8263. auto n = handle.read(buf, sizeof(buf));
  8264. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8265. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8266. }
  8267. #endif
  8268. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8269. TEST_F(ServerTest, Brotli) {
  8270. Headers headers;
  8271. headers.emplace("Accept-Encoding", "br");
  8272. auto res = cli_.Get("/compress", headers);
  8273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8274. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8275. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8276. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8277. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8278. "7890123456789012345678901234567890",
  8279. res->body);
  8280. EXPECT_EQ(StatusCode::OK_200, res->status);
  8281. }
  8282. #endif
  8283. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8284. TEST_F(ServerTest, Zstd) {
  8285. Headers headers;
  8286. headers.emplace("Accept-Encoding", "zstd");
  8287. auto res = cli_.Get("/compress", headers);
  8288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8289. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8290. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8291. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8292. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8293. "7890123456789012345678901234567890",
  8294. res->body);
  8295. EXPECT_EQ(StatusCode::OK_200, res->status);
  8296. }
  8297. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8298. Headers headers;
  8299. headers.emplace("Accept-Encoding", "");
  8300. auto res = cli_.Get("/compress", headers);
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8304. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8305. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8306. "7890123456789012345678901234567890",
  8307. res->body);
  8308. EXPECT_EQ(StatusCode::OK_200, res->status);
  8309. }
  8310. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8311. Headers headers;
  8312. headers.emplace("Accept-Encoding", "zstd");
  8313. std::string body;
  8314. auto res = cli_.Get("/compress", headers,
  8315. [&](const char *data, uint64_t data_length) {
  8316. EXPECT_EQ(100U, data_length);
  8317. body.append(data, data_length);
  8318. return true;
  8319. });
  8320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8321. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8322. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8323. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8324. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8325. "7890123456789012345678901234567890",
  8326. body);
  8327. EXPECT_EQ(StatusCode::OK_200, res->status);
  8328. }
  8329. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8330. Headers headers;
  8331. headers.emplace("Accept-Encoding", "zstd");
  8332. cli_.set_decompress(false);
  8333. auto res = cli_.Get("/compress", headers);
  8334. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8335. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8336. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8337. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8339. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8340. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8341. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8342. EXPECT_EQ(StatusCode::OK_200, res->status);
  8343. ASSERT_EQ(26U, res->body.size());
  8344. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8345. 0);
  8346. }
  8347. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8348. Headers headers;
  8349. headers.emplace("Accept-Encoding", "");
  8350. std::string body;
  8351. auto res = cli_.Get("/compress", headers,
  8352. [&](const char *data, uint64_t data_length) {
  8353. EXPECT_EQ(100U, data_length);
  8354. body.append(data, data_length);
  8355. return true;
  8356. });
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8359. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8360. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8361. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8362. "7890123456789012345678901234567890",
  8363. body);
  8364. EXPECT_EQ(StatusCode::OK_200, res->status);
  8365. }
  8366. TEST_F(ServerTest, NoZstd) {
  8367. Headers headers;
  8368. headers.emplace("Accept-Encoding", "zstd");
  8369. auto res = cli_.Get("/nocompress", headers);
  8370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8371. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8372. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8373. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8374. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8375. "7890123456789012345678901234567890",
  8376. res->body);
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. }
  8379. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8380. Headers headers;
  8381. headers.emplace("Accept-Encoding", "zstd");
  8382. std::string body;
  8383. auto res = cli_.Get("/nocompress", headers,
  8384. [&](const char *data, uint64_t data_length) {
  8385. EXPECT_EQ(100U, data_length);
  8386. body.append(data, data_length);
  8387. return true;
  8388. });
  8389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8390. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8391. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8392. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8393. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8394. "7890123456789012345678901234567890",
  8395. body);
  8396. EXPECT_EQ(StatusCode::OK_200, res->status);
  8397. }
  8398. // TODO: How to enable zstd ??
  8399. TEST_F(ServerTest, MultipartFormDataZstd) {
  8400. UploadFormDataItems items = {
  8401. {"key1", "test", "", ""},
  8402. {"key2", "--abcdefg123", "", ""},
  8403. };
  8404. Headers headers;
  8405. headers.emplace("Accept-Encoding", "zstd");
  8406. cli_.set_compress(true);
  8407. auto res = cli_.Post("/compress-multipart", headers, items);
  8408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8409. EXPECT_EQ(StatusCode::OK_200, res->status);
  8410. }
  8411. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8412. Headers headers;
  8413. headers.emplace("Accept-Encoding", "zstd");
  8414. cli_.set_compress(true);
  8415. auto res = cli_.Put(
  8416. "/put", headers, 3,
  8417. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8418. sink.os << "PUT";
  8419. return true;
  8420. },
  8421. "text/plain");
  8422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8423. EXPECT_EQ(StatusCode::OK_200, res->status);
  8424. EXPECT_EQ("PUT", res->body);
  8425. }
  8426. // Pre-compression logging tests
  8427. TEST_F(ServerTest, PreCompressionLogging) {
  8428. // Test data for compression (matches the actual /compress endpoint content)
  8429. const std::string test_content =
  8430. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8431. "3456789012345678901234567890";
  8432. // Variables to capture logging data
  8433. std::string pre_compression_body;
  8434. std::string pre_compression_content_type;
  8435. std::string pre_compression_content_encoding;
  8436. std::string post_compression_body;
  8437. std::string post_compression_content_type;
  8438. std::string post_compression_content_encoding;
  8439. // Set up pre-compression logger
  8440. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8441. const Response &res) {
  8442. pre_compression_body = res.body;
  8443. pre_compression_content_type = res.get_header_value("Content-Type");
  8444. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8445. });
  8446. // Set up post-compression logger
  8447. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8448. post_compression_body = res.body;
  8449. post_compression_content_type = res.get_header_value("Content-Type");
  8450. post_compression_content_encoding =
  8451. res.get_header_value("Content-Encoding");
  8452. });
  8453. // Test with gzip compression
  8454. Headers headers;
  8455. headers.emplace("Accept-Encoding", "gzip");
  8456. auto res = cli_.Get("/compress", headers);
  8457. // Verify response was compressed
  8458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8459. EXPECT_EQ(StatusCode::OK_200, res->status);
  8460. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8461. // Verify pre-compression logger captured uncompressed content
  8462. EXPECT_EQ(test_content, pre_compression_body);
  8463. EXPECT_EQ("text/plain", pre_compression_content_type);
  8464. EXPECT_TRUE(pre_compression_content_encoding
  8465. .empty()); // No encoding header before compression
  8466. // Verify post-compression logger captured compressed content
  8467. EXPECT_NE(test_content,
  8468. post_compression_body); // Should be different after compression
  8469. EXPECT_EQ("text/plain", post_compression_content_type);
  8470. EXPECT_EQ("gzip", post_compression_content_encoding);
  8471. // Verify compressed content is smaller
  8472. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8473. }
  8474. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8475. const std::string test_content =
  8476. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8477. "3456789012345678901234567890";
  8478. std::string pre_compression_body;
  8479. std::string post_compression_body;
  8480. svr_.set_pre_compression_logger(
  8481. [&](const Request & /*req*/, const Response &res) {
  8482. pre_compression_body = res.body;
  8483. });
  8484. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8485. post_compression_body = res.body;
  8486. });
  8487. Headers headers;
  8488. headers.emplace("Accept-Encoding", "br");
  8489. auto res = cli_.Get("/compress", headers);
  8490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8491. EXPECT_EQ(StatusCode::OK_200, res->status);
  8492. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8493. // Verify pre-compression content is uncompressed
  8494. EXPECT_EQ(test_content, pre_compression_body);
  8495. // Verify post-compression content is compressed
  8496. EXPECT_NE(test_content, post_compression_body);
  8497. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8498. }
  8499. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8500. const std::string test_content =
  8501. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8502. "3456789012345678901234567890";
  8503. std::string pre_compression_body;
  8504. std::string post_compression_body;
  8505. svr_.set_pre_compression_logger(
  8506. [&](const Request & /*req*/, const Response &res) {
  8507. pre_compression_body = res.body;
  8508. });
  8509. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8510. post_compression_body = res.body;
  8511. });
  8512. // Request without compression (use /nocompress endpoint)
  8513. Headers headers;
  8514. auto res = cli_.Get("/nocompress", headers);
  8515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8516. EXPECT_EQ(StatusCode::OK_200, res->status);
  8517. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8518. // Pre-compression logger should not be called when no compression is applied
  8519. EXPECT_TRUE(
  8520. pre_compression_body.empty()); // Pre-compression logger not called
  8521. EXPECT_EQ(
  8522. test_content,
  8523. post_compression_body); // Post-compression logger captures final content
  8524. }
  8525. TEST_F(ServerTest, LoggerSeesContentLength) {
  8526. size_t logged_content_length = 0;
  8527. std::string logged_content_length_header;
  8528. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8529. logged_content_length = res.content_length_;
  8530. logged_content_length_header = res.get_header_value("Content-Length");
  8531. });
  8532. auto res = cli_.Get("/nocompress");
  8533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8534. EXPECT_EQ(StatusCode::OK_200, res->status);
  8535. EXPECT_EQ(res->body.size(), logged_content_length);
  8536. EXPECT_EQ(std::to_string(logged_content_length),
  8537. logged_content_length_header);
  8538. }
  8539. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8540. const std::string test_content =
  8541. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8542. "3456789012345678901234567890";
  8543. std::string pre_compression_body;
  8544. bool pre_logger_called = false;
  8545. // Set only pre-compression logger
  8546. svr_.set_pre_compression_logger(
  8547. [&](const Request & /*req*/, const Response &res) {
  8548. pre_compression_body = res.body;
  8549. pre_logger_called = true;
  8550. });
  8551. Headers headers;
  8552. headers.emplace("Accept-Encoding", "gzip");
  8553. auto res = cli_.Get("/compress", headers);
  8554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8555. EXPECT_EQ(StatusCode::OK_200, res->status);
  8556. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8557. // Verify pre-compression logger was called
  8558. EXPECT_TRUE(pre_logger_called);
  8559. EXPECT_EQ(test_content, pre_compression_body);
  8560. }
  8561. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8562. {
  8563. // Test with Expect: 100-continue header - success case
  8564. // Server returns 100 Continue, client sends body, server returns 200 OK
  8565. Request req;
  8566. req.method = "POST";
  8567. req.path = "/post-large";
  8568. req.set_header("Expect", "100-continue");
  8569. req.body = LARGE_DATA;
  8570. Response res;
  8571. auto error = Error::Success;
  8572. cli_.set_keep_alive(true);
  8573. auto ret = cli_.send(req, res, error);
  8574. EXPECT_TRUE(ret);
  8575. EXPECT_EQ(StatusCode::OK_200, res.status);
  8576. EXPECT_EQ(LARGE_DATA, res.body);
  8577. }
  8578. {
  8579. // Test with Expect: 100-continue header - error case
  8580. // Client should not send the body when server returns an error
  8581. Request req;
  8582. req.method = "POST";
  8583. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8584. req.set_header("Expect", "100-continue");
  8585. req.body = LARGE_DATA;
  8586. Response res;
  8587. auto error = Error::Success;
  8588. auto start = std::chrono::high_resolution_clock::now();
  8589. cli_.set_keep_alive(true);
  8590. auto ret = cli_.send(req, res, error);
  8591. auto end = std::chrono::high_resolution_clock::now();
  8592. auto elapsed =
  8593. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8594. .count();
  8595. // With Expect: 100-continue, request completes successfully but with error
  8596. EXPECT_TRUE(ret);
  8597. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8598. EXPECT_EQ("close", res.get_header_value("Connection"));
  8599. EXPECT_FALSE(cli_.is_socket_open());
  8600. EXPECT_LE(elapsed, 2000);
  8601. }
  8602. {
  8603. // Send an extra GET request to ensure error recovery without hanging
  8604. Request req;
  8605. req.method = "GET";
  8606. req.path = "/hi";
  8607. auto start = std::chrono::high_resolution_clock::now();
  8608. auto res = cli_.send(req);
  8609. auto end = std::chrono::high_resolution_clock::now();
  8610. auto elapsed =
  8611. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8612. .count();
  8613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8614. EXPECT_EQ(StatusCode::OK_200, res->status);
  8615. EXPECT_EQ("Hello World!", res->body);
  8616. EXPECT_LE(elapsed, 500);
  8617. }
  8618. }
  8619. TEST(ZstdDecompressor, ChunkedDecompression) {
  8620. std::string data;
  8621. for (size_t i = 0; i < 32 * 1024; ++i) {
  8622. data.push_back(static_cast<char>('a' + i % 26));
  8623. }
  8624. std::string compressed_data;
  8625. {
  8626. httplib::detail::zstd_compressor compressor;
  8627. bool result = compressor.compress(
  8628. data.data(), data.size(),
  8629. /*last=*/true,
  8630. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8631. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8632. compressed_data_size);
  8633. return true;
  8634. });
  8635. ASSERT_TRUE(result);
  8636. }
  8637. std::string decompressed_data;
  8638. {
  8639. httplib::detail::zstd_decompressor decompressor;
  8640. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8641. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8642. size_t chunk_size = 130;
  8643. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8644. chunk_begin += chunk_size) {
  8645. size_t current_chunk_size =
  8646. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8647. bool result = decompressor.decompress(
  8648. compressed_data.data() + chunk_begin, current_chunk_size,
  8649. [&](const char *decompressed_data_chunk,
  8650. size_t decompressed_data_chunk_size) {
  8651. decompressed_data.insert(decompressed_data.size(),
  8652. decompressed_data_chunk,
  8653. decompressed_data_chunk_size);
  8654. return true;
  8655. });
  8656. ASSERT_TRUE(result);
  8657. }
  8658. }
  8659. ASSERT_EQ(data, decompressed_data);
  8660. }
  8661. TEST(ZstdDecompressor, Decompress) {
  8662. std::string original_text = "Compressed with ZSTD";
  8663. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8664. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8665. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8666. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8667. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8668. std::string decompressed_data;
  8669. {
  8670. httplib::detail::zstd_decompressor decompressor;
  8671. bool result = decompressor.decompress(
  8672. compressed_data.data(), compressed_data.size(),
  8673. [&](const char *decompressed_data_chunk,
  8674. size_t decompressed_data_chunk_size) {
  8675. decompressed_data.insert(decompressed_data.size(),
  8676. decompressed_data_chunk,
  8677. decompressed_data_chunk_size);
  8678. return true;
  8679. });
  8680. ASSERT_TRUE(result);
  8681. }
  8682. ASSERT_EQ(original_text, decompressed_data);
  8683. }
  8684. #endif
  8685. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8686. // separate chunks so that the server sees each part in its own read(). Used to
  8687. // place a read boundary at a specific offset of a request body.
  8688. static bool send_request_in_parts(time_t read_timeout_sec,
  8689. const std::vector<std::string> &parts,
  8690. std::string *resp = nullptr,
  8691. int port = PORT) {
  8692. auto error = Error::Success;
  8693. auto client_sock = detail::create_client_socket(
  8694. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8695. /*connection_timeout_sec=*/5, 0,
  8696. /*read_timeout_sec=*/5, 0,
  8697. /*write_timeout_sec=*/5, 0, std::string(), error);
  8698. if (client_sock == INVALID_SOCKET) { return false; }
  8699. auto ret = detail::process_client_socket(
  8700. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8701. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8702. for (size_t i = 0; i < parts.size(); i++) {
  8703. const auto &part = parts[i];
  8704. if (part.size() !=
  8705. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8706. return false;
  8707. }
  8708. if (i + 1 < parts.size()) {
  8709. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8710. }
  8711. }
  8712. char buf[512];
  8713. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8714. while (line_reader.getline()) {
  8715. if (resp) { *resp += line_reader.ptr(); }
  8716. }
  8717. return true;
  8718. });
  8719. detail::close_socket(client_sock);
  8720. return ret;
  8721. }
  8722. // Sends a raw request to a server listening at HOST:PORT.
  8723. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8724. std::string *resp = nullptr, int port = PORT) {
  8725. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8726. }
  8727. #ifdef CPPHTTPLIB_SSL_ENABLED
  8728. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8729. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8730. ASSERT_TRUE(svr.is_valid());
  8731. svr.set_read_timeout(1, 0);
  8732. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8733. auto se = detail::scope_exit([&] {
  8734. svr.stop();
  8735. t.join();
  8736. ASSERT_FALSE(svr.is_running());
  8737. });
  8738. svr.wait_until_ready();
  8739. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8740. // keeps each wait well within the read timeout. The server gives up a
  8741. // second in, so the bytes sent after that fail.
  8742. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8743. parts.resize(26, std::string(1, '\0'));
  8744. EXPECT_FALSE(send_request_in_parts(5, parts));
  8745. }
  8746. #endif
  8747. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8748. Server svr;
  8749. std::string header_value;
  8750. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8751. header_value = req.get_header_value("foo");
  8752. res.set_content("ok", "text/plain");
  8753. });
  8754. thread t = thread([&] { svr.listen(HOST, PORT); });
  8755. auto se = detail::scope_exit([&] {
  8756. svr.stop();
  8757. t.join();
  8758. ASSERT_FALSE(svr.is_running());
  8759. });
  8760. svr.wait_until_ready();
  8761. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8762. // like characters are not treated the same - use vertical tab and escape.
  8763. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8764. "foo: \t \v bar \x1B\t \r\n"
  8765. "Connection: close\r\n"
  8766. "\r\n";
  8767. std::string res;
  8768. ASSERT_TRUE(send_request(5, req, &res));
  8769. EXPECT_EQ(header_value, "");
  8770. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8771. }
  8772. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8773. Server svr;
  8774. std::string received;
  8775. svr.Get("/order", [&](const Request &req, Response &res) {
  8776. received = entries_to_string(req.headers);
  8777. res.set_content("ok", "text/plain");
  8778. });
  8779. auto port = svr.bind_to_any_port(HOST);
  8780. thread t = thread([&] { svr.listen_after_bind(); });
  8781. auto se = detail::scope_exit([&] {
  8782. svr.stop();
  8783. t.join();
  8784. ASSERT_FALSE(svr.is_running());
  8785. });
  8786. svr.wait_until_ready();
  8787. const std::string req = "GET /order HTTP/1.1\r\n"
  8788. "X-First: 1\r\n"
  8789. "X-Dup: a\r\n"
  8790. "X-Second: 2\r\n"
  8791. "X-Dup: b\r\n"
  8792. "Connection: close\r\n"
  8793. "\r\n";
  8794. std::string res;
  8795. ASSERT_TRUE(send_request(5, req, &res, port));
  8796. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8797. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8798. }
  8799. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8800. Server svr;
  8801. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8802. res.set_header("Set-Cookie", "first=1");
  8803. res.set_header("X-Between", "y");
  8804. res.set_header("Set-Cookie", "second=2");
  8805. res.set_content("ok", "text/plain");
  8806. });
  8807. auto port = svr.bind_to_any_port(HOST);
  8808. thread t = thread([&] { svr.listen_after_bind(); });
  8809. auto se = detail::scope_exit([&] {
  8810. svr.stop();
  8811. t.join();
  8812. ASSERT_FALSE(svr.is_running());
  8813. });
  8814. svr.wait_until_ready();
  8815. Client cli(HOST, port);
  8816. auto res = cli.Get("/cookies");
  8817. ASSERT_TRUE(res);
  8818. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8819. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8820. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8821. }
  8822. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8823. Server svr;
  8824. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8825. auto i = new int(0);
  8826. res.set_header("Trailer", "X-Safe, X-Reflected");
  8827. res.set_chunked_content_provider(
  8828. "text/plain",
  8829. [i](size_t /*offset*/, DataSink &sink) {
  8830. if (*i == 0) {
  8831. sink.os << "body";
  8832. } else {
  8833. Headers trailer;
  8834. // A valid trailer that must survive.
  8835. trailer.emplace("X-Safe", "safe");
  8836. // Attacker-controlled value carrying CR/LF (response splitting).
  8837. trailer.emplace("X-Reflected",
  8838. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8839. // Attacker-controlled name carrying CR/LF.
  8840. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8841. sink.done_with_trailer(trailer);
  8842. }
  8843. (*i)++;
  8844. return true;
  8845. },
  8846. [i](bool /*success*/) { delete i; });
  8847. });
  8848. thread t = thread([&] { svr.listen(HOST, PORT); });
  8849. auto se = detail::scope_exit([&] {
  8850. svr.stop();
  8851. t.join();
  8852. ASSERT_FALSE(svr.is_running());
  8853. });
  8854. svr.wait_until_ready();
  8855. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8856. "Host: " + HOST +
  8857. "\r\n"
  8858. "Connection: close\r\n"
  8859. "\r\n";
  8860. std::string res;
  8861. ASSERT_TRUE(send_request(5, req, &res));
  8862. // The injected fields must not appear anywhere in the raw response.
  8863. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8864. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8865. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8866. // Invalid trailers are dropped entirely, matching set_header().
  8867. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8868. // The valid trailer still passes through.
  8869. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8870. }
  8871. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8872. Server svr;
  8873. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8874. // res.headers is a public field an application can populate directly,
  8875. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8876. // A valid header that must survive.
  8877. res.headers.emplace("X-Safe", "safe");
  8878. // Attacker-controlled value carrying CR/LF (response splitting).
  8879. res.headers.emplace("X-Reflected",
  8880. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8881. // Attacker-controlled name carrying CR/LF.
  8882. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8883. res.set_content("body", "text/plain");
  8884. });
  8885. thread t = thread([&] { svr.listen(HOST, PORT); });
  8886. auto se = detail::scope_exit([&] {
  8887. svr.stop();
  8888. t.join();
  8889. ASSERT_FALSE(svr.is_running());
  8890. });
  8891. svr.wait_until_ready();
  8892. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8893. "Host: " + HOST +
  8894. "\r\n"
  8895. "Connection: close\r\n"
  8896. "\r\n";
  8897. std::string res;
  8898. ASSERT_TRUE(send_request(5, req, &res));
  8899. // The injected fields must not appear anywhere in the raw response.
  8900. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8901. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8902. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8903. // Invalid headers are dropped entirely, matching set_header().
  8904. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8905. // The valid header still passes through.
  8906. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8907. }
  8908. // Forward declaration: in split builds split.py strips `inline` and moves the
  8909. // definition into httplib.cc, so detail::write_request_line is not visible from
  8910. // the public httplib.h. Re-declaring it here lets the tests link against the
  8911. // symbol in both header-only and split builds.
  8912. namespace httplib {
  8913. namespace detail {
  8914. ssize_t write_request_line(Stream &strm, const std::string &method,
  8915. const std::string &path);
  8916. } // namespace detail
  8917. } // namespace httplib
  8918. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8919. // A well-formed target is written verbatim.
  8920. {
  8921. detail::BufferStream strm;
  8922. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8923. EXPECT_GT(n, 0);
  8924. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8925. }
  8926. // A target carrying CR/LF, SP or other control octets must be rejected
  8927. // before anything reaches the wire, otherwise it splits the request line and
  8928. // injects a header or a whole request.
  8929. const std::string evil_targets[] = {
  8930. "/a\r\nInjected: pwned",
  8931. "/a\rInjected",
  8932. "/a\nInjected",
  8933. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8934. "/a b",
  8935. "/a\tb",
  8936. "/a\x7f",
  8937. };
  8938. for (const auto &evil : evil_targets) {
  8939. detail::BufferStream strm;
  8940. auto n = detail::write_request_line(strm, "GET", evil);
  8941. EXPECT_LT(n, 0);
  8942. EXPECT_TRUE(strm.get_buffer().empty());
  8943. }
  8944. }
  8945. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8946. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8947. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8948. // target reaches write_request. The client must fail cleanly with
  8949. // Error::Write instead of putting a request-line-less, header-injecting
  8950. // request on the wire.
  8951. Server svr;
  8952. svr.Get("/a", [](const Request &, Response &res) {
  8953. res.set_content("ok", "text/plain");
  8954. });
  8955. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8956. auto se = detail::scope_exit([&] {
  8957. svr.stop();
  8958. thread.join();
  8959. ASSERT_FALSE(svr.is_running());
  8960. });
  8961. svr.wait_until_ready();
  8962. {
  8963. Client cli(HOST, PORT);
  8964. cli.set_path_encode(false);
  8965. // The request is rejected before anything is written, so the connection
  8966. // stays silent and the subsequent response read would otherwise block for
  8967. // the full default read timeout. Shorten it -- the assertion is on the
  8968. // error, not the timeout.
  8969. cli.set_read_timeout(1, 0);
  8970. auto res = cli.Get("/a\r\nInjected: pwned");
  8971. EXPECT_FALSE(res);
  8972. EXPECT_EQ(Error::Write, res.error());
  8973. }
  8974. }
  8975. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8976. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8977. // including extension methods.
  8978. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8979. for (const auto &method : good_methods) {
  8980. detail::BufferStream strm;
  8981. auto n = detail::write_request_line(strm, method, "/");
  8982. EXPECT_GT(n, 0);
  8983. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8984. }
  8985. // A method carrying CR/LF would split the request line and smuggle a whole
  8986. // request ahead of the real one. A space or an empty method corrupts the
  8987. // request line. All must be rejected before anything reaches the wire.
  8988. const std::string evil_methods[] = {
  8989. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8990. "GET\r\nInjected: pwned",
  8991. "GET\r",
  8992. "GET\n",
  8993. "GE T",
  8994. "",
  8995. };
  8996. for (const auto &evil : evil_methods) {
  8997. detail::BufferStream strm;
  8998. auto n = detail::write_request_line(strm, evil, "/");
  8999. EXPECT_LT(n, 0);
  9000. EXPECT_TRUE(strm.get_buffer().empty());
  9001. }
  9002. }
  9003. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9004. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9005. // through Client::send must fail with Error::Write and no request, neither
  9006. // the smuggled one nor the real one, may reach the server.
  9007. Server svr;
  9008. std::atomic<int> request_count(0);
  9009. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9010. request_count++;
  9011. res.status = StatusCode::OK_200;
  9012. return Server::HandlerResponse::Handled;
  9013. });
  9014. auto port = svr.bind_to_any_port(HOST);
  9015. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9016. auto se = detail::scope_exit([&] {
  9017. svr.stop();
  9018. thread.join();
  9019. ASSERT_FALSE(svr.is_running());
  9020. });
  9021. svr.wait_until_ready();
  9022. {
  9023. Client cli(HOST, port);
  9024. const std::string evil_methods[] = {
  9025. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9026. "GE T",
  9027. "",
  9028. };
  9029. for (const auto &evil : evil_methods) {
  9030. Request req;
  9031. req.method = evil;
  9032. req.path = "/";
  9033. auto res = cli.send(req);
  9034. EXPECT_FALSE(res);
  9035. EXPECT_EQ(Error::Write, res.error());
  9036. }
  9037. auto handle =
  9038. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9039. EXPECT_FALSE(handle.is_valid());
  9040. EXPECT_EQ(Error::Write, handle.error);
  9041. // A valid request on the same client still goes through.
  9042. auto res = cli.Get("/");
  9043. ASSERT_TRUE(res);
  9044. EXPECT_EQ(StatusCode::OK_200, res->status);
  9045. }
  9046. EXPECT_EQ(1, request_count.load());
  9047. }
  9048. // Sends a raw request and verifies that there isn't a crash or exception.
  9049. static void test_raw_request(const std::string &req,
  9050. std::string *out = nullptr) {
  9051. Server svr;
  9052. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9053. res.set_content("ok", "text/plain");
  9054. });
  9055. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9056. res.set_content("ok", "text/plain");
  9057. });
  9058. svr.Get("/header_field_value_check",
  9059. [&](const Request & /*req*/, Response &res) {
  9060. res.set_content("ok", "text/plain");
  9061. });
  9062. svr.CustomRoute("PROPFIND", "/dav",
  9063. [&](const Request & /*req*/, Response &res) {
  9064. res.status = StatusCode::MultiStatus_207;
  9065. });
  9066. // Server read timeout must be longer than the client read timeout for the
  9067. // bug to reproduce, probably to force the server to process a request
  9068. // without a trailing blank line.
  9069. const time_t client_read_timeout_sec = 1;
  9070. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9071. bool listen_thread_ok = false;
  9072. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9073. auto se = detail::scope_exit([&] {
  9074. svr.stop();
  9075. t.join();
  9076. ASSERT_FALSE(svr.is_running());
  9077. EXPECT_TRUE(listen_thread_ok);
  9078. });
  9079. svr.wait_until_ready();
  9080. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9081. }
  9082. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9083. // A certain header line causes an exception if the header property is parsed
  9084. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9085. test_raw_request(
  9086. "GET /hi HTTP/1.1\r\n"
  9087. " : "
  9088. " "
  9089. " ");
  9090. }
  9091. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9092. // A certain header line causes an exception if the header property *name* is
  9093. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9094. // greedy matcher and requires backtracking when there are a lot of ":"
  9095. // characters.
  9096. // This occurs with libc++ but not libstdc++.
  9097. test_raw_request(
  9098. "GET /hi HTTP/1.1\r\n"
  9099. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9100. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9101. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9102. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9103. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9104. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9105. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9106. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9107. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9108. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9109. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9110. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9111. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9112. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9113. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9114. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9115. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9116. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9117. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9118. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9119. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9120. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9121. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9122. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9123. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9124. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9125. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9126. "&&&%%%");
  9127. }
  9128. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9129. // Make sure this doesn't crash the server.
  9130. // In a previous version of the header line regex, the "\r" rendered the line
  9131. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9132. // a new position where the leading white space ended and the field value
  9133. // began.
  9134. // The crash occurs with libc++ but not libstdc++.
  9135. test_raw_request("GET /hi HTTP/1.1\r\n"
  9136. "a:" +
  9137. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9138. "\r\n"
  9139. "\r\n");
  9140. }
  9141. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9142. std::string out;
  9143. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9144. "Content-Type: text/plain\r\n"
  9145. "Transfer-Encoding: chunked\r\n"
  9146. "\r\n"
  9147. "nothex\r\n",
  9148. &out);
  9149. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9150. }
  9151. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9152. std::string out;
  9153. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9154. "Content-Type: text/plain\r\n"
  9155. "Transfer-Encoding: chunked\r\n"
  9156. "\r\n"
  9157. "3\r\n"
  9158. "xyz\r\n"
  9159. "NaN\r\n",
  9160. &out);
  9161. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9162. }
  9163. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9164. std::string out;
  9165. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9166. "Content-Type: text/plain\r\n"
  9167. "Transfer-Encoding: chunked\r\n"
  9168. "\r\n"
  9169. // Length is too large for 64 bits.
  9170. "1ffffffffffffffff\r\n"
  9171. "xyz\r\n",
  9172. &out);
  9173. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9174. }
  9175. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9176. test_raw_request("GET /hi HTTP/1.1\r\n"
  9177. "Content-Type: text/plain\r\n\r");
  9178. }
  9179. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9180. std::string out;
  9181. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9182. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9183. }
  9184. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9185. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9186. std::string out;
  9187. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9188. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9189. }
  9190. }
  9191. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9192. std::string out;
  9193. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9194. "Connection: close\r\n\r\n",
  9195. &out);
  9196. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9197. }
  9198. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9199. Server svr;
  9200. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9201. EXPECT_TRUE(!req.remote_addr.empty());
  9202. });
  9203. thread t = thread([&] { svr.listen(HOST, PORT); });
  9204. auto se = detail::scope_exit([&] {
  9205. svr.stop();
  9206. t.join();
  9207. ASSERT_FALSE(svr.is_running());
  9208. });
  9209. svr.wait_until_ready();
  9210. // Send an invalid request line to trigger Bad Request
  9211. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9212. std::string out;
  9213. ASSERT_TRUE(send_request(5, bad_req, &out));
  9214. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9215. }
  9216. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9217. // answered right away rather than blocking on a read that waits for EOF.
  9218. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9219. std::string out;
  9220. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9221. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9222. }
  9223. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9224. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9225. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9226. for (const auto *method : methods) {
  9227. Server svr;
  9228. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9229. EXPECT_FALSE(svr.is_valid()) << method;
  9230. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9231. }
  9232. }
  9233. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9234. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9235. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9236. for (const auto *method : methods) {
  9237. Server svr;
  9238. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9239. EXPECT_FALSE(svr.is_valid()) << method;
  9240. }
  9241. }
  9242. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9243. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9244. "COPY", "MOVE", "LOCK",
  9245. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9246. Server svr;
  9247. for (const auto *method : methods) {
  9248. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9249. }
  9250. EXPECT_TRUE(svr.is_valid());
  9251. }
  9252. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9253. Server svr;
  9254. svr.CustomRoute("POST", "/x",
  9255. [](const Request &, Response &, const ContentReader &) {});
  9256. EXPECT_FALSE(svr.is_valid());
  9257. }
  9258. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9259. Server svr;
  9260. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9261. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9262. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9263. EXPECT_FALSE(svr.is_valid());
  9264. }
  9265. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9266. Server svr;
  9267. auto captured = Error::Success;
  9268. svr.set_error_logger(
  9269. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9270. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9271. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9272. }
  9273. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9274. std::string out;
  9275. std::string request(
  9276. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9277. test_raw_request(request, &out);
  9278. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9279. }
  9280. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9281. std::string out;
  9282. std::string request(
  9283. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9284. test_raw_request(request, &out);
  9285. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9286. }
  9287. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9288. std::string out;
  9289. std::string request(
  9290. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9291. test_raw_request(request, &out);
  9292. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9293. }
  9294. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9295. std::string out;
  9296. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9297. "Test: \r\n\r\n",
  9298. &out);
  9299. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9300. }
  9301. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9302. Server svr;
  9303. std::string x_custom;
  9304. std::string cookie;
  9305. std::string xff;
  9306. std::string x_unicode;
  9307. std::string x_iis;
  9308. svr.Get("/check", [&](const Request &req, Response &res) {
  9309. x_custom = req.get_header_value("X-Custom");
  9310. cookie = req.get_header_value("Cookie");
  9311. xff = req.get_header_value("X-Forwarded-For");
  9312. x_unicode = req.get_header_value("X-Unicode");
  9313. x_iis = req.get_header_value("X-IIS");
  9314. res.set_content("ok", "text/plain");
  9315. });
  9316. thread t = thread([&] { svr.listen(HOST, PORT); });
  9317. auto se = detail::scope_exit([&] {
  9318. svr.stop();
  9319. t.join();
  9320. ASSERT_FALSE(svr.is_running());
  9321. });
  9322. svr.wait_until_ready();
  9323. const std::string req = "GET /check HTTP/1.1\r\n"
  9324. "Host: localhost\r\n"
  9325. "X-Custom: a%0D%0AInjected: b\r\n"
  9326. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9327. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9328. "X-Unicode: %E3%81%82\r\n"
  9329. "X-IIS: %u00E9\r\n"
  9330. "Connection: close\r\n"
  9331. "\r\n";
  9332. std::string res;
  9333. ASSERT_TRUE(send_request(5, req, &res));
  9334. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9335. // Every value must be returned verbatim (wire form), with no decoding.
  9336. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9337. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9338. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9339. EXPECT_EQ("%E3%81%82", x_unicode);
  9340. EXPECT_EQ("%u00E9", x_iis);
  9341. }
  9342. // Applications that previously relied on automatic percent-decoding can
  9343. // reproduce the old behavior by explicitly calling decode_path_component()
  9344. // or, for RFC 3986 conformance, decode_uri_component().
  9345. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9346. Server svr;
  9347. std::string decoded;
  9348. svr.Get("/check", [&](const Request &req, Response &res) {
  9349. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9350. res.set_content("ok", "text/plain");
  9351. });
  9352. thread t = thread([&] { svr.listen(HOST, PORT); });
  9353. auto se = detail::scope_exit([&] {
  9354. svr.stop();
  9355. t.join();
  9356. ASSERT_FALSE(svr.is_running());
  9357. });
  9358. svr.wait_until_ready();
  9359. const std::string req = "GET /check HTTP/1.1\r\n"
  9360. "Host: localhost\r\n"
  9361. "X-Custom: hello%20world\r\n"
  9362. "Connection: close\r\n"
  9363. "\r\n";
  9364. std::string res;
  9365. ASSERT_TRUE(send_request(5, req, &res));
  9366. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9367. EXPECT_EQ("hello world", decoded);
  9368. }
  9369. // Regression test for #2033. Browsers send Referer values that include
  9370. // percent-encoded characters such as %0A inside the URL. Decoding the
  9371. // header value would either trip the post-decode CR/LF/NUL guard (the
  9372. // original bug, returning 400) or, after that guard was relaxed, silently
  9373. // store a literal LF — both unacceptable. The wire form must round-trip.
  9374. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9375. Server svr;
  9376. std::string referer;
  9377. svr.Get("/check", [&](const Request &req, Response &res) {
  9378. referer = req.get_header_value("Referer");
  9379. res.set_content("ok", "text/plain");
  9380. });
  9381. thread t = thread([&] { svr.listen(HOST, PORT); });
  9382. auto se = detail::scope_exit([&] {
  9383. svr.stop();
  9384. t.join();
  9385. ASSERT_FALSE(svr.is_running());
  9386. });
  9387. svr.wait_until_ready();
  9388. const std::string req = "GET /check HTTP/1.1\r\n"
  9389. "Host: localhost\r\n"
  9390. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9391. "Connection: close\r\n"
  9392. "\r\n";
  9393. std::string res;
  9394. ASSERT_TRUE(send_request(5, req, &res));
  9395. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9396. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9397. }
  9398. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9399. Server svr;
  9400. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9401. res.set_header("Cache-Control", "no-cache");
  9402. res.set_chunked_content_provider(
  9403. "text/event-stream", [](size_t offset, DataSink &sink) {
  9404. std::string s = "data:";
  9405. s += std::to_string(offset);
  9406. s += "\n\n";
  9407. auto ret = sink.write(s.data(), s.size());
  9408. EXPECT_TRUE(ret);
  9409. std::this_thread::sleep_for(std::chrono::seconds(1));
  9410. return true;
  9411. });
  9412. });
  9413. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9414. svr.wait_until_ready();
  9415. Client client(HOST, PORT);
  9416. const Headers headers = {{"Accept", "text/event-stream"}};
  9417. auto get_thread = std::thread([&client, &headers]() {
  9418. auto res = client.Get(
  9419. "/events", headers,
  9420. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9421. });
  9422. auto se = detail::scope_exit([&] {
  9423. svr.stop();
  9424. get_thread.join();
  9425. listen_thread.join();
  9426. ASSERT_FALSE(svr.is_running());
  9427. });
  9428. // Give GET time to get a few messages.
  9429. std::this_thread::sleep_for(std::chrono::seconds(2));
  9430. }
  9431. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9432. httplib::Server svr;
  9433. svr.Post("/hi",
  9434. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9435. res.status = StatusCode::OK_200;
  9436. });
  9437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9438. svr.wait_until_ready();
  9439. Client cli(HOST, PORT);
  9440. auto res = cli.Post("/hi", "data", "text/plain");
  9441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9442. EXPECT_EQ(StatusCode::OK_200, res->status);
  9443. svr.stop();
  9444. thread.join();
  9445. ASSERT_FALSE(svr.is_running());
  9446. res = cli.Post("/hi", "data", "text/plain");
  9447. ASSERT_FALSE(res);
  9448. }
  9449. TEST(ServerStopTest, ListenFailure) {
  9450. Server svr;
  9451. auto t = thread([&]() {
  9452. auto ret = svr.listen("????", PORT);
  9453. EXPECT_FALSE(ret);
  9454. });
  9455. svr.wait_until_ready();
  9456. svr.stop();
  9457. t.join();
  9458. }
  9459. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9460. TEST(ServerStopTest, Decommision) {
  9461. Server svr;
  9462. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9463. for (int i = 0; i < 4; i++) {
  9464. auto is_even = !(i % 2);
  9465. std::thread t{[&] {
  9466. try {
  9467. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9468. if (is_even) {
  9469. throw std::runtime_error("Some thing that happens to go wrong.");
  9470. }
  9471. svr.listen(HOST, PORT);
  9472. } catch (...) { svr.decommission(); }
  9473. }};
  9474. svr.wait_until_ready();
  9475. // Server is up
  9476. {
  9477. Client cli(HOST, PORT);
  9478. auto res = cli.Get("/hi");
  9479. if (is_even) {
  9480. EXPECT_FALSE(res);
  9481. } else {
  9482. EXPECT_TRUE(res);
  9483. EXPECT_EQ("hi...", res->body);
  9484. }
  9485. }
  9486. svr.stop();
  9487. t.join();
  9488. // Server is down...
  9489. {
  9490. Client cli(HOST, PORT);
  9491. auto res = cli.Get("/hi");
  9492. EXPECT_FALSE(res);
  9493. }
  9494. }
  9495. }
  9496. #endif
  9497. // Helper function for string body upload progress tests
  9498. template <typename SetupHandler, typename ClientCall>
  9499. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9500. ClientCall &&client_call,
  9501. const string &body) {
  9502. Server svr;
  9503. setup_handler(svr);
  9504. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9505. auto se = detail::scope_exit([&] {
  9506. svr.stop();
  9507. t.join();
  9508. });
  9509. svr.wait_until_ready();
  9510. Client cli(HOST, PORT);
  9511. vector<uint64_t> progress_values;
  9512. bool progress_called = false;
  9513. auto res =
  9514. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9515. progress_values.push_back(current);
  9516. progress_called = true;
  9517. return true;
  9518. });
  9519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9520. EXPECT_EQ(200, res->status);
  9521. EXPECT_TRUE(progress_called);
  9522. }
  9523. TEST(UploadProgressTest, PostStringBodyBasic) {
  9524. TestStringBodyUploadProgress(
  9525. [](Server &svr) {
  9526. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9527. res.set_content("received", "text/plain");
  9528. });
  9529. },
  9530. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9531. return cli.Post("/test", body, "text/plain", progress_callback);
  9532. },
  9533. "test data for upload progress");
  9534. }
  9535. TEST(UploadProgressTest, PutStringBodyBasic) {
  9536. TestStringBodyUploadProgress(
  9537. [](Server &svr) {
  9538. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9539. res.set_content("put received", "text/plain");
  9540. });
  9541. },
  9542. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9543. return cli.Put("/test", body, "text/plain", progress_callback);
  9544. },
  9545. "put test data for upload progress");
  9546. }
  9547. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9548. TestStringBodyUploadProgress(
  9549. [](Server &svr) {
  9550. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9551. res.set_content("patch received", "text/plain");
  9552. });
  9553. },
  9554. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9555. return cli.Patch("/test", body, "text/plain", progress_callback);
  9556. },
  9557. "patch test data for upload progress");
  9558. }
  9559. // Helper function for content provider upload progress tests
  9560. template <typename SetupHandler, typename ClientCall>
  9561. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9562. ClientCall &&client_call) {
  9563. Server svr;
  9564. setup_handler(svr);
  9565. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9566. auto se = detail::scope_exit([&] {
  9567. svr.stop();
  9568. t.join();
  9569. });
  9570. svr.wait_until_ready();
  9571. Client cli(HOST, PORT);
  9572. vector<uint64_t> progress_values;
  9573. auto res =
  9574. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9575. progress_values.push_back(current);
  9576. return true;
  9577. });
  9578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9579. EXPECT_EQ(200, res->status);
  9580. EXPECT_FALSE(progress_values.empty());
  9581. }
  9582. TEST(UploadProgressTest, PostContentProviderProgress) {
  9583. TestContentProviderUploadProgress(
  9584. [](Server &svr) {
  9585. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9586. res.set_content("provider received", "text/plain");
  9587. });
  9588. },
  9589. [](Client &cli, UploadProgress progress_callback) {
  9590. return cli.Post(
  9591. "/test", 10,
  9592. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9593. sink.os << "test data";
  9594. return true;
  9595. },
  9596. "text/plain", progress_callback);
  9597. });
  9598. }
  9599. // Helper function for multipart upload progress tests
  9600. template <typename SetupHandler, typename ClientCall>
  9601. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9602. ClientCall &&client_call,
  9603. const string &endpoint) {
  9604. Server svr;
  9605. setup_handler(svr);
  9606. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9607. auto se = detail::scope_exit([&] {
  9608. svr.stop();
  9609. t.join();
  9610. });
  9611. svr.wait_until_ready();
  9612. Client cli(HOST, PORT);
  9613. vector<uint64_t> progress_values;
  9614. UploadFormDataItems items = {
  9615. {"field1", "value1", "", ""},
  9616. {"field2", "longer value for progress tracking test", "", ""},
  9617. {"file1", "file content data for upload progress", "test.txt",
  9618. "text/plain"}};
  9619. auto res = client_call(cli, endpoint, items,
  9620. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9621. progress_values.push_back(current);
  9622. return true;
  9623. });
  9624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9625. EXPECT_EQ(200, res->status);
  9626. EXPECT_FALSE(progress_values.empty());
  9627. }
  9628. TEST(UploadProgressTest, PostMultipartProgress) {
  9629. TestMultipartUploadProgress(
  9630. [](Server &svr) {
  9631. svr.Post("/multipart", [](const Request &req, Response &res) {
  9632. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9633. res.set_content("multipart received", "text/plain");
  9634. });
  9635. },
  9636. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9637. UploadProgress progress_callback) {
  9638. return cli.Post(endpoint, items, progress_callback);
  9639. },
  9640. "/multipart");
  9641. }
  9642. // Helper function for basic download progress tests
  9643. template <typename SetupHandler, typename ClientCall>
  9644. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9645. ClientCall &&client_call, const string &endpoint,
  9646. size_t expected_content_size) {
  9647. Server svr;
  9648. setup_handler(svr);
  9649. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9650. auto se = detail::scope_exit([&] {
  9651. svr.stop();
  9652. t.join();
  9653. });
  9654. svr.wait_until_ready();
  9655. Client cli(HOST, PORT);
  9656. vector<uint64_t> progress_values;
  9657. auto res = client_call(cli, endpoint,
  9658. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9659. progress_values.push_back(current);
  9660. return true;
  9661. });
  9662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9663. EXPECT_EQ(200, res->status);
  9664. EXPECT_FALSE(progress_values.empty());
  9665. EXPECT_EQ(expected_content_size, res->body.size());
  9666. }
  9667. TEST(DownloadProgressTest, GetBasic) {
  9668. TestBasicDownloadProgress(
  9669. [](Server &svr) {
  9670. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9671. string content(1000, 'D');
  9672. res.set_content(content, "text/plain");
  9673. });
  9674. },
  9675. [](Client &cli, const string &endpoint,
  9676. DownloadProgress progress_callback) {
  9677. return cli.Get(endpoint, progress_callback);
  9678. },
  9679. "/download", 1000u);
  9680. }
  9681. // Helper function for content receiver download progress tests
  9682. template <typename SetupHandler, typename ClientCall>
  9683. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9684. ClientCall &&client_call,
  9685. const string &endpoint,
  9686. size_t expected_content_size) {
  9687. Server svr;
  9688. setup_handler(svr);
  9689. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9690. auto se = detail::scope_exit([&] {
  9691. svr.stop();
  9692. t.join();
  9693. });
  9694. svr.wait_until_ready();
  9695. Client cli(HOST, PORT);
  9696. vector<uint64_t> progress_values;
  9697. string received_body;
  9698. auto res = client_call(
  9699. cli, endpoint,
  9700. [&](const char *data, size_t data_length) -> bool {
  9701. received_body.append(data, data_length);
  9702. return true;
  9703. },
  9704. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9705. progress_values.push_back(current);
  9706. return true;
  9707. });
  9708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9709. EXPECT_EQ(200, res->status);
  9710. EXPECT_FALSE(progress_values.empty());
  9711. EXPECT_EQ(expected_content_size, received_body.size());
  9712. EXPECT_TRUE(res->body.empty());
  9713. }
  9714. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9715. TestContentReceiverDownloadProgress(
  9716. [](Server &svr) {
  9717. svr.Get("/download-receiver",
  9718. [](const Request & /*req*/, Response &res) {
  9719. string content(2000, 'R');
  9720. res.set_content(content, "text/plain");
  9721. });
  9722. },
  9723. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9724. DownloadProgress progress_callback) {
  9725. return cli.Get(endpoint, content_receiver, progress_callback);
  9726. },
  9727. "/download-receiver", 2000u);
  9728. }
  9729. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9730. // A provider reaching a pass with nothing to hand over - an empty buffer
  9731. // popped off a queue, say - must not be taken to mean the body is finished.
  9732. // It used to end the loop with the terminating chunk unwritten while the
  9733. // server still considered the response complete, so the peer waited for an
  9734. // end that never arrived.
  9735. Server svr;
  9736. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9737. auto step = std::make_shared<int>(0);
  9738. res.set_chunked_content_provider("text/plain",
  9739. [step](size_t /*offset*/, DataSink &sink) {
  9740. switch ((*step)++) {
  9741. case 0: sink.write("", 0); break;
  9742. case 1: sink.write("hello", 5); break;
  9743. default: sink.done(); break;
  9744. }
  9745. return true;
  9746. });
  9747. });
  9748. auto port = svr.bind_to_any_port(HOST);
  9749. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9750. auto listen_se = detail::scope_exit([&] {
  9751. svr.stop();
  9752. listen_thread.join();
  9753. ASSERT_FALSE(svr.is_running());
  9754. });
  9755. svr.wait_until_ready();
  9756. Client cli(HOST, port);
  9757. // Without the fix the body is never terminated, so bound the wait rather
  9758. // than letting the test hang on the default read timeout.
  9759. cli.set_read_timeout(5, 0);
  9760. auto res = cli.Get("/stream");
  9761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9762. EXPECT_EQ(StatusCode::OK_200, res->status);
  9763. EXPECT_EQ("hello", res->body);
  9764. }
  9765. TEST(StreamingTest, NoContentLengthStreaming) {
  9766. Server svr;
  9767. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9768. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9769. if (offset < 6) {
  9770. sink.os << (offset < 3 ? "a" : "b");
  9771. } else {
  9772. sink.done();
  9773. }
  9774. return true;
  9775. });
  9776. });
  9777. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9778. auto listen_se = detail::scope_exit([&] {
  9779. svr.stop();
  9780. listen_thread.join();
  9781. ASSERT_FALSE(svr.is_running());
  9782. });
  9783. svr.wait_until_ready();
  9784. Client client(HOST, PORT);
  9785. auto get_thread = std::thread([&client]() {
  9786. std::string s;
  9787. auto res =
  9788. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9789. s += std::string(data, len);
  9790. return true;
  9791. });
  9792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9793. EXPECT_EQ(StatusCode::OK_200, res->status);
  9794. EXPECT_EQ("aaabbb", s);
  9795. });
  9796. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9797. // Give GET time to get a few messages.
  9798. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9799. }
  9800. TEST(MountTest, Unmount) {
  9801. Server svr;
  9802. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9803. auto se = detail::scope_exit([&] {
  9804. svr.stop();
  9805. listen_thread.join();
  9806. ASSERT_FALSE(svr.is_running());
  9807. });
  9808. svr.wait_until_ready();
  9809. Client cli("localhost", PORT);
  9810. svr.set_mount_point("/mount2", "./www2");
  9811. auto res = cli.Get("/");
  9812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9813. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9814. res = cli.Get("/mount2/dir/test.html");
  9815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9816. EXPECT_EQ(StatusCode::OK_200, res->status);
  9817. svr.set_mount_point("/", "./www");
  9818. res = cli.Get("/dir/");
  9819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9820. EXPECT_EQ(StatusCode::OK_200, res->status);
  9821. svr.remove_mount_point("/");
  9822. res = cli.Get("/dir/");
  9823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9824. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9825. svr.remove_mount_point("/mount2");
  9826. res = cli.Get("/mount2/dir/test.html");
  9827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9828. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9829. }
  9830. TEST(MountTest, PathSegmentBoundary) {
  9831. Server svr;
  9832. svr.set_mount_point("/mount2", "./www2");
  9833. svr.set_mount_point("/", "./www");
  9834. auto port = svr.bind_to_any_port(HOST);
  9835. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9836. auto se = detail::scope_exit([&] {
  9837. svr.stop();
  9838. listen_thread.join();
  9839. ASSERT_FALSE(svr.is_running());
  9840. });
  9841. svr.wait_until_ready();
  9842. Client cli(HOST, port);
  9843. auto res = cli.Get("/mount2/dir/test.html");
  9844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9845. EXPECT_EQ(StatusCode::OK_200, res->status);
  9846. // "/mount2" must not match part-way through a path segment.
  9847. res = cli.Get("/mount2dir/test.html");
  9848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9850. // A mount point ending in '/' keeps matching every path below it.
  9851. res = cli.Get("/dir/test.html");
  9852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9853. EXPECT_EQ(StatusCode::OK_200, res->status);
  9854. }
  9855. TEST(MountTest, Redicect) {
  9856. Server svr;
  9857. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9858. auto se = detail::scope_exit([&] {
  9859. svr.stop();
  9860. listen_thread.join();
  9861. ASSERT_FALSE(svr.is_running());
  9862. });
  9863. svr.set_mount_point("/", "./www");
  9864. svr.wait_until_ready();
  9865. Client cli("localhost", PORT);
  9866. auto res = cli.Get("/dir/");
  9867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9868. EXPECT_EQ(StatusCode::OK_200, res->status);
  9869. res = cli.Get("/dir");
  9870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9871. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9872. res = cli.Get("/file");
  9873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9874. EXPECT_EQ(StatusCode::OK_200, res->status);
  9875. res = cli.Get("/file/");
  9876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9877. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9878. cli.set_follow_location(true);
  9879. res = cli.Get("/dir");
  9880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9881. EXPECT_EQ(StatusCode::OK_200, res->status);
  9882. }
  9883. TEST(MountTest, MultibytesPathName) {
  9884. Server svr;
  9885. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9886. auto se = detail::scope_exit([&] {
  9887. svr.stop();
  9888. listen_thread.join();
  9889. ASSERT_FALSE(svr.is_running());
  9890. });
  9891. svr.set_mount_point("/", "./www");
  9892. svr.wait_until_ready();
  9893. Client cli("localhost", PORT);
  9894. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9896. EXPECT_EQ(StatusCode::OK_200, res->status);
  9897. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9898. }
  9899. #ifdef _WIN32
  9900. // Issue #2435: mmap::open() must succeed even when another handle holds
  9901. // the file open for writing (e.g. an active log file).
  9902. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9903. const char *path = "mmap_concurrent_writer_test.txt";
  9904. const char *content = "hello";
  9905. {
  9906. std::ofstream f(path, std::ios::binary);
  9907. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9908. }
  9909. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9910. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9911. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9912. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9913. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9914. detail::mmap m(path);
  9915. ASSERT_TRUE(m.is_open());
  9916. EXPECT_EQ(strlen(content), m.size());
  9917. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9918. }
  9919. #endif
  9920. #ifndef _WIN32
  9921. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9922. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9923. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9924. TEST(MmapTest, FailedMappingIsNotOpen) {
  9925. const char *path = "./mmap_failed_mapping_test_dir";
  9926. ASSERT_EQ(0, ::mkdir(path, 0755));
  9927. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9928. detail::mmap m(path);
  9929. EXPECT_FALSE(m.is_open());
  9930. EXPECT_EQ(0U, m.size());
  9931. EXPECT_NE(static_cast<const void *>(m.data()),
  9932. static_cast<const void *>(MAP_FAILED));
  9933. }
  9934. #endif
  9935. TEST(KeepAliveTest, ReadTimeout) {
  9936. Server svr;
  9937. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9938. std::this_thread::sleep_for(std::chrono::seconds(2));
  9939. res.set_content("a", "text/plain");
  9940. });
  9941. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9942. res.set_content("b", "text/plain");
  9943. });
  9944. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9945. auto se = detail::scope_exit([&] {
  9946. svr.stop();
  9947. listen_thread.join();
  9948. ASSERT_FALSE(svr.is_running());
  9949. });
  9950. svr.wait_until_ready();
  9951. Client cli("localhost", PORT);
  9952. cli.set_keep_alive(true);
  9953. cli.set_read_timeout(std::chrono::seconds(1));
  9954. auto resa = cli.Get("/a");
  9955. ASSERT_FALSE(resa);
  9956. EXPECT_EQ(Error::Read, resa.error());
  9957. auto resb = cli.Get("/b");
  9958. ASSERT_TRUE(resb);
  9959. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9960. EXPECT_EQ("b", resb->body);
  9961. }
  9962. TEST(KeepAliveTest, MaxCount) {
  9963. size_t keep_alive_max_count = 3;
  9964. Server svr;
  9965. svr.set_keep_alive_max_count(keep_alive_max_count);
  9966. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9967. res.set_content("Hello World!", "text/plain");
  9968. });
  9969. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9970. auto se = detail::scope_exit([&] {
  9971. svr.stop();
  9972. listen_thread.join();
  9973. ASSERT_FALSE(svr.is_running());
  9974. });
  9975. svr.wait_until_ready();
  9976. Client cli(HOST, PORT);
  9977. cli.set_keep_alive(true);
  9978. for (size_t i = 0; i < 5; i++) {
  9979. auto result = cli.Get("/hi");
  9980. ASSERT_TRUE(result);
  9981. EXPECT_EQ(StatusCode::OK_200, result->status);
  9982. if (i == keep_alive_max_count - 1) {
  9983. EXPECT_EQ("close", result->get_header_value("Connection"));
  9984. } else {
  9985. EXPECT_FALSE(result->has_header("Connection"));
  9986. }
  9987. }
  9988. }
  9989. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9990. // can pull the next one into the server's buffer. The server must serve it
  9991. // without waiting for the socket to become readable again. The keep-alive
  9992. // timeout outlasts the client's read timeout, so a request left waiting for it
  9993. // shows up as a missing response.
  9994. static void serve_pipelining_routes(Server &svr,
  9995. const std::function<void(int)> &client) {
  9996. svr.set_keep_alive_timeout(5);
  9997. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9998. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9999. });
  10000. svr.Post("/echo", [](const Request &req, Response &res) {
  10001. res.set_content("echo " + req.body, "text/plain");
  10002. });
  10003. auto port = svr.bind_to_any_port(HOST);
  10004. thread t = thread([&] { svr.listen_after_bind(); });
  10005. auto se = detail::scope_exit([&] {
  10006. svr.stop();
  10007. t.join();
  10008. });
  10009. svr.wait_until_ready();
  10010. client(port);
  10011. }
  10012. static std::string
  10013. send_pipelined_requests(const std::vector<std::string> &parts) {
  10014. Server svr;
  10015. std::string res;
  10016. serve_pipelining_routes(svr, [&](int port) {
  10017. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10018. });
  10019. return res;
  10020. }
  10021. static void expect_in_order(const std::string &res,
  10022. const std::vector<std::string> &bodies) {
  10023. size_t pos = 0;
  10024. for (const auto &body : bodies) {
  10025. pos = res.find(body, pos);
  10026. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10027. pos += body.size();
  10028. }
  10029. }
  10030. TEST(KeepAliveTest, PipelinedRequests) {
  10031. auto res = send_pipelined_requests(
  10032. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10033. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10034. "Content-Length: 4\r\n\r\nbody"
  10035. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10036. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10037. }
  10038. // The second request starts in the server's buffer and ends on the socket.
  10039. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10040. auto res =
  10041. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10042. "GET /hi/2 HTTP/1.1\r\nHo",
  10043. "st: localhost\r\nConnection: close\r\n\r\n"});
  10044. expect_in_order(res, {"hi 1", "hi 2"});
  10045. }
  10046. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10047. // CRLF after a body does not turn into a 400 for the next request.
  10048. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10049. auto res = send_pipelined_requests(
  10050. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10051. "Content-Length: 4\r\n\r\nbody\r\n"
  10052. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10053. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10054. expect_in_order(res, {"echo body", "hi 2"});
  10055. }
  10056. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10057. // must not be served as the next request.
  10058. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10059. auto res = send_pipelined_requests(
  10060. {"INVALID REQUEST LINE\r\n\r\n"
  10061. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10062. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10063. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10064. }
  10065. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10066. // Over TLS, the next request is held by the TLS library as already decrypted
  10067. // data rather than on the socket.
  10068. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10069. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10070. std::string res;
  10071. serve_pipelining_routes(svr, [&](int port) {
  10072. auto error = Error::Success;
  10073. auto sock = detail::create_client_socket(
  10074. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10075. /*connection_timeout_sec=*/5, 0,
  10076. /*read_timeout_sec=*/2, 0,
  10077. /*write_timeout_sec=*/5, 0, std::string(), error);
  10078. ASSERT_NE(INVALID_SOCKET, sock);
  10079. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10080. auto ctx = SSL_CTX_new(TLS_client_method());
  10081. auto ssl = SSL_new(ctx);
  10082. auto ssl_se = detail::scope_exit([&] {
  10083. SSL_free(ssl);
  10084. SSL_CTX_free(ctx);
  10085. });
  10086. SSL_set_fd(ssl, static_cast<int>(sock));
  10087. ASSERT_EQ(1, SSL_connect(ssl));
  10088. // One write, so all three requests arrive in one TLS record
  10089. const std::string req =
  10090. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10091. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10092. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10093. ASSERT_EQ(static_cast<int>(req.size()),
  10094. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10095. char buf[512];
  10096. int n;
  10097. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10098. res.append(buf, static_cast<size_t>(n));
  10099. }
  10100. });
  10101. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10102. }
  10103. #endif
  10104. TEST(KeepAliveTest, Issue1041) {
  10105. Server svr;
  10106. svr.set_keep_alive_timeout(3);
  10107. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10108. res.set_content("Hello World!", "text/plain");
  10109. });
  10110. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10111. auto se = detail::scope_exit([&] {
  10112. svr.stop();
  10113. listen_thread.join();
  10114. ASSERT_FALSE(svr.is_running());
  10115. });
  10116. svr.wait_until_ready();
  10117. Client cli(HOST, PORT);
  10118. cli.set_keep_alive(true);
  10119. auto result = cli.Get("/hi");
  10120. ASSERT_TRUE(result);
  10121. EXPECT_EQ(StatusCode::OK_200, result->status);
  10122. std::this_thread::sleep_for(std::chrono::seconds(5));
  10123. result = cli.Get("/hi");
  10124. ASSERT_TRUE(result);
  10125. EXPECT_EQ(StatusCode::OK_200, result->status);
  10126. }
  10127. TEST(KeepAliveTest, Issue1959) {
  10128. Server svr;
  10129. svr.set_keep_alive_timeout(5);
  10130. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10131. res.set_content("a", "text/plain");
  10132. });
  10133. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10134. auto se = detail::scope_exit([&] {
  10135. if (!svr.is_running()) return;
  10136. svr.stop();
  10137. listen_thread.join();
  10138. ASSERT_FALSE(svr.is_running());
  10139. });
  10140. svr.wait_until_ready();
  10141. Client cli("localhost", PORT);
  10142. cli.set_keep_alive(true);
  10143. using namespace std::chrono;
  10144. auto start = steady_clock::now();
  10145. cli.Get("/a");
  10146. svr.stop();
  10147. listen_thread.join();
  10148. auto end = steady_clock::now();
  10149. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10150. EXPECT_LT(elapsed, 5000);
  10151. }
  10152. #ifdef CPPHTTPLIB_SSL_ENABLED
  10153. TEST(KeepAliveTest, SSLClientReconnection) {
  10154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10155. ASSERT_TRUE(svr.is_valid());
  10156. svr.set_keep_alive_timeout(1);
  10157. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10158. res.set_content("Hello World!", "text/plain");
  10159. });
  10160. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10161. auto se = detail::scope_exit([&] {
  10162. svr.stop();
  10163. listen_thread.join();
  10164. ASSERT_FALSE(svr.is_running());
  10165. });
  10166. svr.wait_until_ready();
  10167. SSLClient cli(HOST, PORT);
  10168. cli.enable_server_certificate_verification(false);
  10169. cli.set_keep_alive(true);
  10170. auto result = cli.Get("/hi");
  10171. ASSERT_TRUE(result);
  10172. EXPECT_EQ(StatusCode::OK_200, result->status);
  10173. result = cli.Get("/hi");
  10174. ASSERT_TRUE(result);
  10175. EXPECT_EQ(StatusCode::OK_200, result->status);
  10176. std::this_thread::sleep_for(std::chrono::seconds(2));
  10177. // Recoonect
  10178. result = cli.Get("/hi");
  10179. ASSERT_TRUE(result);
  10180. EXPECT_EQ(StatusCode::OK_200, result->status);
  10181. result = cli.Get("/hi");
  10182. ASSERT_TRUE(result);
  10183. EXPECT_EQ(StatusCode::OK_200, result->status);
  10184. }
  10185. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10186. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10187. ASSERT_TRUE(svr.is_valid());
  10188. svr.set_keep_alive_timeout(1);
  10189. std::string content = "reconnect";
  10190. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10191. res.set_content("Hello World!", "text/plain");
  10192. });
  10193. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10194. auto se = detail::scope_exit([&] {
  10195. svr.stop();
  10196. listen_thread.join();
  10197. ASSERT_FALSE(svr.is_running());
  10198. });
  10199. svr.wait_until_ready();
  10200. SSLClient cli(HOST, PORT);
  10201. cli.enable_server_certificate_verification(false);
  10202. cli.set_keep_alive(true);
  10203. auto result = cli.Post(
  10204. "/hi", content.size(),
  10205. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10206. sink.write(content.c_str(), content.size());
  10207. return true;
  10208. },
  10209. "text/plain");
  10210. ASSERT_TRUE(result);
  10211. EXPECT_EQ(200, result->status);
  10212. std::this_thread::sleep_for(std::chrono::seconds(2));
  10213. // Recoonect
  10214. result = cli.Post(
  10215. "/hi", content.size(),
  10216. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10217. sink.write(content.c_str(), content.size());
  10218. return true;
  10219. },
  10220. "text/plain");
  10221. ASSERT_TRUE(result);
  10222. EXPECT_EQ(200, result->status);
  10223. result = cli.Post(
  10224. "/hi", content.size(),
  10225. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10226. sink.write(content.c_str(), content.size());
  10227. return true;
  10228. },
  10229. "text/plain");
  10230. ASSERT_TRUE(result);
  10231. EXPECT_EQ(200, result->status);
  10232. }
  10233. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10234. using namespace httplib::tls;
  10235. {
  10236. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10237. ASSERT_TRUE(svr.is_valid());
  10238. svr.Get("/sni", [&](const Request &req, Response &res) {
  10239. std::string expected = req.sni();
  10240. EXPECT_EQ(expected, req.get_param_value("expected"));
  10241. res.set_content("ok", "text/plain");
  10242. });
  10243. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10244. auto se = detail::scope_exit([&] {
  10245. svr.stop();
  10246. listen_thread.join();
  10247. ASSERT_FALSE(svr.is_running());
  10248. });
  10249. svr.wait_until_ready();
  10250. {
  10251. SSLClient cli("localhost", PORT);
  10252. cli.enable_server_certificate_verification(false);
  10253. auto res = cli.Get("/sni?expected=localhost");
  10254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10255. }
  10256. {
  10257. SSLClient cli("::1", PORT);
  10258. cli.enable_server_certificate_verification(false);
  10259. auto res = cli.Get("/sni?expected=");
  10260. // NOTE: This may fail if the server is listening on IPv4 only
  10261. // (e.g., when localhost resolves to 127.0.0.1 only)
  10262. if (res) {
  10263. EXPECT_EQ(StatusCode::OK_200, res->status);
  10264. } else {
  10265. EXPECT_EQ(Error::Connection, res.error());
  10266. }
  10267. }
  10268. }
  10269. }
  10270. #endif
  10271. TEST(ClientProblemDetectionTest, ContentProvider) {
  10272. Server svr;
  10273. size_t content_length = 1024 * 1024;
  10274. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10275. res.set_content_provider(
  10276. content_length, "text/plain",
  10277. [&](size_t offset, size_t length, DataSink &sink) {
  10278. auto out_len = std::min(length, static_cast<size_t>(1024));
  10279. std::string out(out_len, '@');
  10280. sink.write(out.data(), out_len);
  10281. return offset < 4096;
  10282. },
  10283. [](bool success) { ASSERT_FALSE(success); });
  10284. });
  10285. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10286. res.set_content_provider(
  10287. 0, "text/plain",
  10288. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10289. EXPECT_TRUE(false);
  10290. return true;
  10291. },
  10292. [](bool success) { ASSERT_FALSE(success); });
  10293. });
  10294. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10295. auto se = detail::scope_exit([&] {
  10296. svr.stop();
  10297. listen_thread.join();
  10298. ASSERT_FALSE(svr.is_running());
  10299. });
  10300. svr.wait_until_ready();
  10301. Client cli("localhost", PORT);
  10302. {
  10303. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10304. size_t /*data_length*/) { return false; });
  10305. ASSERT_FALSE(res);
  10306. }
  10307. {
  10308. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10309. size_t /*data_length*/) { return false; });
  10310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10311. }
  10312. }
  10313. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10314. // A provider that reports success without writing anything and without
  10315. // calling done() used to be handed the same offset and length again on every
  10316. // pass, so it spun for as long as the peer stayed connected.
  10317. Server svr;
  10318. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10319. res.set_content("ok", "text/plain");
  10320. });
  10321. auto port = svr.bind_to_any_port(HOST);
  10322. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10323. auto se = detail::scope_exit([&] {
  10324. svr.stop();
  10325. listen_thread.join();
  10326. ASSERT_FALSE(svr.is_running());
  10327. });
  10328. svr.wait_until_ready();
  10329. std::atomic<int> call_count{0};
  10330. Client cli(HOST, port);
  10331. auto res = cli.Post(
  10332. "/", 1024,
  10333. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10334. // Give up after enough passes to show the spin, so that losing the
  10335. // check below fails this test instead of hanging it.
  10336. return ++call_count < 100;
  10337. },
  10338. "text/plain");
  10339. ASSERT_FALSE(res);
  10340. EXPECT_EQ(Error::Write, res.error());
  10341. EXPECT_EQ(1, call_count.load());
  10342. }
  10343. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10344. // A writer only has to assign `write`. The other three used to be left as
  10345. // empty std::functions, so a provider calling one threw
  10346. // std::bad_function_call out of the thread running it and took the whole
  10347. // process down.
  10348. DataSink sink;
  10349. std::string written;
  10350. sink.write = [&](const char *data, size_t data_len) {
  10351. written.append(data, data_len);
  10352. return true;
  10353. };
  10354. EXPECT_TRUE(sink.is_writable());
  10355. sink.done();
  10356. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10357. EXPECT_TRUE(written.empty());
  10358. }
  10359. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10360. // A sink that cannot carry trailers still has to finish.
  10361. DataSink sink;
  10362. auto done_count = 0;
  10363. sink.done = [&]() { done_count++; };
  10364. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10365. EXPECT_EQ(1, done_count);
  10366. }
  10367. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10368. Server svr;
  10369. const std::string body(4096, 'x');
  10370. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10371. res.set_content_provider(body.size(), "text/plain",
  10372. [&](size_t offset, size_t length, DataSink &sink) {
  10373. sink.write(body.data() + offset, length);
  10374. sink.done();
  10375. return true;
  10376. });
  10377. });
  10378. auto port = svr.bind_to_any_port(HOST);
  10379. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10380. auto se = detail::scope_exit([&] {
  10381. svr.stop();
  10382. listen_thread.join();
  10383. ASSERT_FALSE(svr.is_running());
  10384. });
  10385. svr.wait_until_ready();
  10386. Client cli(HOST, port);
  10387. auto res = cli.Get("/");
  10388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10389. EXPECT_EQ(StatusCode::OK_200, res->status);
  10390. EXPECT_EQ(body, res->body);
  10391. }
  10392. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10393. Server svr;
  10394. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10395. res.set_content_provider(
  10396. 1024, "text/plain",
  10397. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10398. sink.write("hello", 5);
  10399. sink.done(); // short of the 1024 bytes the response promised
  10400. return true;
  10401. });
  10402. });
  10403. auto port = svr.bind_to_any_port(HOST);
  10404. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10405. auto se = detail::scope_exit([&] {
  10406. svr.stop();
  10407. listen_thread.join();
  10408. ASSERT_FALSE(svr.is_running());
  10409. });
  10410. svr.wait_until_ready();
  10411. Client cli(HOST, port);
  10412. cli.set_read_timeout(5, 0);
  10413. // The response is short of its Content-Length, so the client cannot read a
  10414. // complete body. What matters is that this returns at all: a no-op done()
  10415. // would leave the writer looping over a provider that never makes progress.
  10416. auto res = cli.Get("/");
  10417. EXPECT_FALSE(res);
  10418. }
  10419. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10420. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10421. // The compressed path builds the whole body before connecting, so this
  10422. // fails client-side and never reaches a server.
  10423. Client cli(HOST, PORT);
  10424. cli.set_compress(true);
  10425. auto res = cli.Post(
  10426. "/", 1024,
  10427. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10428. sink.write("hello", 5);
  10429. sink.done(); // short of the 1024 bytes the request announced
  10430. return true;
  10431. },
  10432. "text/plain");
  10433. ASSERT_FALSE(res);
  10434. EXPECT_EQ(Error::Write, res.error());
  10435. }
  10436. #endif
  10437. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10438. Server svr;
  10439. svr.set_error_handler([](Request const &, Response &res) -> void {
  10440. res.set_chunked_content_provider(
  10441. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10442. sink.os << "hello";
  10443. sink.os << "world";
  10444. sink.done();
  10445. return true;
  10446. });
  10447. });
  10448. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10449. auto se = detail::scope_exit([&] {
  10450. svr.stop();
  10451. listen_thread.join();
  10452. ASSERT_FALSE(svr.is_running());
  10453. });
  10454. svr.wait_until_ready();
  10455. Client cli("localhost", PORT);
  10456. auto res = cli.Get("/");
  10457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10459. EXPECT_EQ("helloworld", res->body);
  10460. }
  10461. // A body set after a content provider must replace it, not be sent through it.
  10462. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10463. Server svr;
  10464. svr.set_mount_point("/", "./www");
  10465. svr.set_file_request_handler([](const Request &req, Response &res) {
  10466. if (req.path == "/dir/test.html") {
  10467. res.status = StatusCode::Forbidden_403;
  10468. res.set_content(std::string(5000, 'D'), "text/plain");
  10469. } else if (req.path == "/file") {
  10470. res.status = StatusCode::Forbidden_403;
  10471. res.body = "Denied";
  10472. }
  10473. });
  10474. auto port = svr.bind_to_any_port(HOST);
  10475. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10476. auto se = detail::scope_exit([&] {
  10477. svr.stop();
  10478. t.join();
  10479. ASSERT_FALSE(svr.is_running());
  10480. });
  10481. svr.wait_until_ready();
  10482. Client cli(HOST, port);
  10483. {
  10484. auto res = cli.Get("/dir/test.html");
  10485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10486. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10487. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10488. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10489. }
  10490. {
  10491. auto res = cli.Get("/file");
  10492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10493. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10494. EXPECT_EQ("Denied", res->body);
  10495. }
  10496. {
  10497. auto res = cli.Get("/dir/index.html");
  10498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10499. EXPECT_EQ(StatusCode::OK_200, res->status);
  10500. EXPECT_EQ(0U, res->body.find("<html>"));
  10501. }
  10502. }
  10503. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10504. Server svr;
  10505. std::vector<bool> released;
  10506. std::mutex released_mutex;
  10507. auto releaser = [&](bool success) {
  10508. std::lock_guard<std::mutex> guard(released_mutex);
  10509. released.push_back(success);
  10510. };
  10511. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10512. return sink.write(&"hello"[offset], length);
  10513. };
  10514. svr.Get("/sized", [&](const Request &, Response &res) {
  10515. res.status = StatusCode::NotFound_404;
  10516. res.set_content_provider(5, "text/plain", provider, releaser);
  10517. });
  10518. svr.Get("/chunked", [&](const Request &, Response &res) {
  10519. res.status = StatusCode::ServiceUnavailable_503;
  10520. res.set_chunked_content_provider(
  10521. "text/plain",
  10522. [](size_t, DataSink &sink) {
  10523. sink.os << "chunk";
  10524. sink.done();
  10525. return true;
  10526. },
  10527. releaser);
  10528. });
  10529. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10530. res.set_content_provider(5, "text/plain", provider, releaser);
  10531. throw std::runtime_error("after the provider");
  10532. });
  10533. svr.set_error_handler([](const Request &req, Response &res) {
  10534. // Leave the exception handler's content to it.
  10535. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10536. res.set_content(std::string(1000, 'E'), "text/html");
  10537. return Server::HandlerResponse::Handled;
  10538. });
  10539. svr.set_exception_handler(
  10540. [](const Request &, Response &res, std::exception_ptr) {
  10541. res.status = StatusCode::InternalServerError_500;
  10542. res.set_content(std::string(1000, 'X'), "text/html");
  10543. });
  10544. auto port = svr.bind_to_any_port(HOST);
  10545. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10546. auto se = detail::scope_exit([&] {
  10547. svr.stop();
  10548. t.join();
  10549. ASSERT_FALSE(svr.is_running());
  10550. });
  10551. svr.wait_until_ready();
  10552. Client cli(HOST, port);
  10553. {
  10554. auto res = cli.Get("/sized");
  10555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10556. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10557. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10558. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10559. }
  10560. {
  10561. auto res = cli.Get("/chunked");
  10562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10563. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10564. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10565. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10566. }
  10567. {
  10568. auto res = cli.Get("/throw");
  10569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10570. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10571. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10572. }
  10573. std::lock_guard<std::mutex> guard(released_mutex);
  10574. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10575. }
  10576. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10577. Server svr;
  10578. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10579. return sink.write(&"abc"[offset], length);
  10580. };
  10581. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10582. res.set_file_content("./www/dir/test.html");
  10583. res.set_content("body", "text/plain");
  10584. });
  10585. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10586. res.set_content(std::string(100, 'B'), "text/plain");
  10587. res.set_file_content("./www/dir/test.html");
  10588. });
  10589. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10590. res.set_content(std::string(100, 'B'), "text/plain");
  10591. res.set_content_provider(3, "text/plain", abc);
  10592. });
  10593. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10594. res.set_content_provider(3, "text/plain", abc);
  10595. res.set_content(std::string(100, 'B'), "text/plain");
  10596. });
  10597. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10598. res.set_content_provider(3, "text/plain", abc);
  10599. res.body = "direct";
  10600. });
  10601. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10602. res.set_file_content("./www/dir/test.html");
  10603. res.body = "direct";
  10604. });
  10605. auto port = svr.bind_to_any_port(HOST);
  10606. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10607. auto se = detail::scope_exit([&] {
  10608. svr.stop();
  10609. t.join();
  10610. ASSERT_FALSE(svr.is_running());
  10611. });
  10612. svr.wait_until_ready();
  10613. Client cli(HOST, port);
  10614. auto expect_body = [&](const char *path, const std::string &body) {
  10615. // Uncompressed, so Content-Length can be compared with the body.
  10616. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10617. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10618. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10619. EXPECT_EQ(body, res->body) << path;
  10620. EXPECT_EQ(std::to_string(body.size()),
  10621. res->get_header_value("Content-Length"))
  10622. << path;
  10623. };
  10624. expect_body("/file-then-body", "body");
  10625. expect_body("/body-then-file", "test.html");
  10626. expect_body("/body-then-provider", "abc");
  10627. expect_body("/provider-then-body", std::string(100, 'B'));
  10628. expect_body("/provider-then-direct-body", "direct");
  10629. expect_body("/file-then-direct-body", "direct");
  10630. // Ranges are checked against the body, not the dropped provider.
  10631. {
  10632. auto res = cli.Get("/provider-then-direct-body",
  10633. Headers{{make_range_header({{1, 2}})}});
  10634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10635. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10636. EXPECT_EQ("ir", res->body);
  10637. }
  10638. {
  10639. auto res = cli.Get("/file-then-direct-body",
  10640. Headers{{make_range_header({{7, 8}})}});
  10641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10642. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10643. }
  10644. }
  10645. // Forward declaration (see the base64_encode note).
  10646. namespace httplib {
  10647. namespace detail {
  10648. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10649. const std::string &content_type,
  10650. EncodingType encoding);
  10651. } // namespace detail
  10652. } // namespace httplib
  10653. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10654. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10655. ASSERT_TRUE(mm->is_open());
  10656. Response res;
  10657. detail::set_file_content_provider(res, mm, "text/html",
  10658. detail::EncodingType::None);
  10659. std::string out;
  10660. DataSink sink;
  10661. sink.write = [&](const char *d, size_t l) {
  10662. out.append(d, l);
  10663. return true;
  10664. };
  10665. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10666. EXPECT_EQ("test.html", out);
  10667. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10668. EXPECT_EQ("test.html", out);
  10669. }
  10670. TEST(LongPollingTest, ClientCloseDetection) {
  10671. Server svr;
  10672. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10673. res.set_chunked_content_provider(
  10674. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10675. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10676. sink.os << "hello";
  10677. auto count = 10;
  10678. while (count > 0 && sink.is_writable()) {
  10679. this_thread::sleep_for(chrono::milliseconds(10));
  10680. count--;
  10681. }
  10682. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10683. return true;
  10684. });
  10685. });
  10686. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10687. auto se = detail::scope_exit([&] {
  10688. svr.stop();
  10689. listen_thread.join();
  10690. ASSERT_FALSE(svr.is_running());
  10691. });
  10692. svr.wait_until_ready();
  10693. Client cli("localhost", PORT);
  10694. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10695. EXPECT_EQ("hello", string(data, data_length));
  10696. return false; // close the socket immediately.
  10697. });
  10698. ASSERT_FALSE(res);
  10699. }
  10700. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10701. Server svr;
  10702. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10703. res.set_chunked_content_provider(
  10704. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10705. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10706. sink.os << "hello";
  10707. EXPECT_TRUE(sink.os.good());
  10708. // Wait for the client to close the connection
  10709. auto count = 10;
  10710. while (count > 0 && sink.is_writable()) {
  10711. this_thread::sleep_for(chrono::milliseconds(10));
  10712. count--;
  10713. }
  10714. // After client disconnect, write repeatedly until the socket
  10715. // write actually fails (small writes may be absorbed by the
  10716. // kernel buffer)
  10717. std::string chunk(1024, 'x');
  10718. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10719. sink.os << chunk;
  10720. }
  10721. EXPECT_TRUE(sink.os.fail());
  10722. return true;
  10723. });
  10724. });
  10725. auto port = svr.bind_to_any_port("localhost");
  10726. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10727. auto se = detail::scope_exit([&] {
  10728. svr.stop();
  10729. listen_thread.join();
  10730. ASSERT_FALSE(svr.is_running());
  10731. });
  10732. svr.wait_until_ready();
  10733. Client cli("localhost", port);
  10734. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10735. EXPECT_EQ("hello", string(data, data_length));
  10736. return false; // close the socket immediately.
  10737. });
  10738. ASSERT_FALSE(res);
  10739. }
  10740. TEST(GetWithParametersTest, GetWithParameters) {
  10741. Server svr;
  10742. svr.Get("/", [&](const Request &req, Response &) {
  10743. EXPECT_EQ("world", req.get_param_value("hello"));
  10744. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10745. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10746. });
  10747. svr.Get("/params", [&](const Request &req, Response &) {
  10748. EXPECT_EQ("world", req.get_param_value("hello"));
  10749. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10750. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10751. });
  10752. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10753. EXPECT_EQ("resource-id", req.matches[1]);
  10754. EXPECT_EQ("foo", req.get_param_value("param1"));
  10755. EXPECT_EQ("bar", req.get_param_value("param2"));
  10756. });
  10757. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10758. EXPECT_EQ("user-id", req.path_params.at("id"));
  10759. EXPECT_EQ("foo", req.get_param_value("param1"));
  10760. EXPECT_EQ("bar", req.get_param_value("param2"));
  10761. });
  10762. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10763. auto se = detail::scope_exit([&] {
  10764. svr.stop();
  10765. listen_thread.join();
  10766. ASSERT_FALSE(svr.is_running());
  10767. });
  10768. svr.wait_until_ready();
  10769. {
  10770. Client cli(HOST, PORT);
  10771. Params params;
  10772. params.emplace("hello", "world");
  10773. params.emplace("hello2", "world2");
  10774. params.emplace("hello3", "world3");
  10775. auto res = cli.Get("/", params, Headers{});
  10776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10777. EXPECT_EQ(StatusCode::OK_200, res->status);
  10778. }
  10779. {
  10780. Client cli(HOST, PORT);
  10781. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10783. EXPECT_EQ(StatusCode::OK_200, res->status);
  10784. }
  10785. {
  10786. Client cli(HOST, PORT);
  10787. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10789. EXPECT_EQ(StatusCode::OK_200, res->status);
  10790. }
  10791. {
  10792. Client cli(HOST, PORT);
  10793. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10795. EXPECT_EQ(StatusCode::OK_200, res->status);
  10796. }
  10797. }
  10798. TEST(GetWithParametersTest, GetWithParameters2) {
  10799. Server svr;
  10800. svr.Get("/", [&](const Request &req, Response &res) {
  10801. auto text = req.get_param_value("hello");
  10802. res.set_content(text, "text/plain");
  10803. });
  10804. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10805. auto se = detail::scope_exit([&] {
  10806. svr.stop();
  10807. listen_thread.join();
  10808. ASSERT_FALSE(svr.is_running());
  10809. });
  10810. svr.wait_until_ready();
  10811. Client cli("localhost", PORT);
  10812. Params params;
  10813. params.emplace("hello", "world");
  10814. std::string body;
  10815. auto res = cli.Get("/", params, Headers{},
  10816. [&](const char *data, size_t data_length) {
  10817. body.append(data, data_length);
  10818. return true;
  10819. });
  10820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10821. EXPECT_EQ(StatusCode::OK_200, res->status);
  10822. EXPECT_EQ("world", body);
  10823. }
  10824. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10825. Server svr;
  10826. svr.Get("/search", [&](const Request &req, Response &res) {
  10827. auto q = req.get_param_value("q");
  10828. res.set_content(q, "text/plain");
  10829. });
  10830. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10831. auto se = detail::scope_exit([&] {
  10832. svr.stop();
  10833. listen_thread.join();
  10834. ASSERT_FALSE(svr.is_running());
  10835. });
  10836. svr.wait_until_ready();
  10837. Client cli("localhost", PORT);
  10838. // Verify that Get(path, params) works without requiring Headers argument
  10839. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10841. EXPECT_EQ(StatusCode::OK_200, res->status);
  10842. EXPECT_EQ("cpp-httplib", res->body);
  10843. }
  10844. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10845. auto host = "httpbingo.org";
  10846. auto path = std::string{"/range/32"};
  10847. #ifdef CPPHTTPLIB_SSL_ENABLED
  10848. SSLClient cli(host);
  10849. #else
  10850. Client cli(host);
  10851. #endif
  10852. cli.set_default_headers({make_range_header({{1, 10}})});
  10853. cli.set_connection_timeout(5);
  10854. {
  10855. auto res = cli.Get(path);
  10856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10857. EXPECT_EQ("bcdefghijk", res->body);
  10858. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10859. }
  10860. {
  10861. auto res = cli.Get(path);
  10862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10863. EXPECT_EQ("bcdefghijk", res->body);
  10864. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10865. }
  10866. }
  10867. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10868. Server svr;
  10869. svr.set_default_headers({{"Hello", "World"}});
  10870. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10871. res.set_content("ok", "text/plain");
  10872. });
  10873. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10874. auto se = detail::scope_exit([&] {
  10875. svr.stop();
  10876. listen_thread.join();
  10877. ASSERT_FALSE(svr.is_running());
  10878. });
  10879. svr.wait_until_ready();
  10880. Client cli("localhost", PORT);
  10881. auto res = cli.Get("/");
  10882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10883. EXPECT_EQ(StatusCode::OK_200, res->status);
  10884. EXPECT_EQ("ok", res->body);
  10885. EXPECT_EQ("World", res->get_header_value("Hello"));
  10886. }
  10887. #ifdef CPPHTTPLIB_SSL_ENABLED
  10888. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10889. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10890. ASSERT_TRUE(svr.is_valid());
  10891. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10892. std::this_thread::sleep_for(std::chrono::seconds(2));
  10893. res.set_content("a", "text/plain");
  10894. });
  10895. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10896. res.set_content("b", "text/plain");
  10897. });
  10898. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10899. auto se = detail::scope_exit([&] {
  10900. svr.stop();
  10901. listen_thread.join();
  10902. ASSERT_FALSE(svr.is_running());
  10903. });
  10904. svr.wait_until_ready();
  10905. SSLClient cli("localhost", PORT);
  10906. cli.enable_server_certificate_verification(false);
  10907. cli.set_keep_alive(true);
  10908. cli.set_read_timeout(std::chrono::seconds(1));
  10909. auto resa = cli.Get("/a");
  10910. ASSERT_TRUE(!resa);
  10911. EXPECT_EQ(Error::Read, resa.error());
  10912. auto resb = cli.Get("/b");
  10913. ASSERT_TRUE(resb);
  10914. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10915. EXPECT_EQ("b", resb->body);
  10916. }
  10917. // Closing an idle keep-alive connection sends close_notify and returns. The
  10918. // server must not wait for the client's close_notify: an idle client never
  10919. // sends one, so the worker would be held until the read timeout expires, and
  10920. // stop() would wait for it.
  10921. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10923. ASSERT_TRUE(svr.is_valid());
  10924. svr.set_keep_alive_timeout(1);
  10925. svr.set_read_timeout(10, 0);
  10926. svr.Get("/", [](const Request &, Response &res) {
  10927. res.set_content("ok", "text/plain");
  10928. });
  10929. auto port = svr.bind_to_any_port(HOST);
  10930. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10931. auto se = detail::scope_exit([&] {
  10932. if (listen_thread.joinable()) {
  10933. svr.stop();
  10934. listen_thread.join();
  10935. }
  10936. });
  10937. svr.wait_until_ready();
  10938. SSLClient cli(HOST, port);
  10939. cli.enable_server_certificate_verification(false);
  10940. cli.set_keep_alive(true);
  10941. auto res = cli.Get("/");
  10942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10943. EXPECT_EQ(StatusCode::OK_200, res->status);
  10944. // Stay idle past the keep-alive timeout so the server closes the connection.
  10945. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10946. auto start = std::chrono::steady_clock::now();
  10947. svr.stop();
  10948. listen_thread.join();
  10949. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10950. std::chrono::steady_clock::now() - start)
  10951. .count();
  10952. EXPECT_LT(elapsed, 3000);
  10953. }
  10954. #endif
  10955. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10956. protected:
  10957. ServerTestWithAI_PASSIVE()
  10958. : cli_(HOST, PORT)
  10959. #ifdef CPPHTTPLIB_SSL_ENABLED
  10960. ,
  10961. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10962. #endif
  10963. {
  10964. #ifdef CPPHTTPLIB_SSL_ENABLED
  10965. cli_.enable_server_certificate_verification(false);
  10966. #endif
  10967. }
  10968. virtual void SetUp() {
  10969. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10970. res.set_content("Hello World!", "text/plain");
  10971. });
  10972. t_ = thread(
  10973. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10974. svr_.wait_until_ready();
  10975. }
  10976. virtual void TearDown() {
  10977. svr_.stop();
  10978. t_.join();
  10979. }
  10980. #ifdef CPPHTTPLIB_SSL_ENABLED
  10981. SSLClient cli_;
  10982. SSLServer svr_;
  10983. #else
  10984. Client cli_;
  10985. Server svr_;
  10986. #endif
  10987. thread t_;
  10988. };
  10989. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10990. auto res = cli_.Get("/hi");
  10991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10992. EXPECT_EQ(StatusCode::OK_200, res->status);
  10993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10994. EXPECT_EQ("Hello World!", res->body);
  10995. }
  10996. class ServerUpDownTest : public ::testing::Test {
  10997. protected:
  10998. ServerUpDownTest() : cli_(HOST, PORT) {}
  10999. virtual void SetUp() {
  11000. t_ = thread([&]() {
  11001. svr_.bind_to_any_port(HOST);
  11002. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11003. ASSERT_TRUE(svr_.listen_after_bind());
  11004. });
  11005. svr_.wait_until_ready();
  11006. }
  11007. virtual void TearDown() {
  11008. svr_.stop();
  11009. t_.join();
  11010. }
  11011. Client cli_;
  11012. Server svr_;
  11013. thread t_;
  11014. };
  11015. TEST_F(ServerUpDownTest, QuickStartStop) {
  11016. // Should not crash, especially when run with
  11017. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11018. }
  11019. class PayloadMaxLengthTest : public ::testing::Test {
  11020. protected:
  11021. PayloadMaxLengthTest()
  11022. : cli_(HOST, PORT)
  11023. #ifdef CPPHTTPLIB_SSL_ENABLED
  11024. ,
  11025. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11026. #endif
  11027. {
  11028. #ifdef CPPHTTPLIB_SSL_ENABLED
  11029. cli_.enable_server_certificate_verification(false);
  11030. #endif
  11031. }
  11032. virtual void SetUp() {
  11033. svr_.set_payload_max_length(8);
  11034. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11035. res.set_content("test", "text/plain");
  11036. });
  11037. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11038. svr_.wait_until_ready();
  11039. }
  11040. virtual void TearDown() {
  11041. svr_.stop();
  11042. t_.join();
  11043. }
  11044. #ifdef CPPHTTPLIB_SSL_ENABLED
  11045. SSLClient cli_;
  11046. SSLServer svr_;
  11047. #else
  11048. Client cli_;
  11049. Server svr_;
  11050. #endif
  11051. thread t_;
  11052. };
  11053. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11054. auto res = cli_.Post("/test", "123456789", "text/plain");
  11055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11056. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11057. res = cli_.Post("/test", "12345678", "text/plain");
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. EXPECT_EQ(StatusCode::OK_200, res->status);
  11060. }
  11061. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11062. // Test chunked encoding with payload exceeding the 8-byte limit
  11063. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11064. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11066. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11067. }
  11068. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11069. // Test chunked encoding with payload within the 8-byte limit
  11070. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11071. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11073. EXPECT_EQ(StatusCode::OK_200, res->status);
  11074. }
  11075. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11076. // Test using send_request to send chunked data exceeding payload limit
  11077. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11078. "Host: " +
  11079. std::string(HOST) + ":" + std::to_string(PORT) +
  11080. "\r\n"
  11081. "Transfer-Encoding: chunked\r\n"
  11082. "Connection: close\r\n"
  11083. "\r\n"
  11084. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11085. "0123456789\r\n"
  11086. "0\r\n" // End chunk
  11087. "\r\n";
  11088. std::string response;
  11089. bool result = send_request(1, chunked_request, &response);
  11090. if (!result) {
  11091. // If send_request fails, it might be because the server closed the
  11092. // connection due to payload limit enforcement, which is acceptable
  11093. SUCCEED()
  11094. << "Server rejected oversized chunked request (connection closed)";
  11095. } else {
  11096. // If we got a response, check if it's an error response or connection was
  11097. // closed early Short response length indicates connection was closed due to
  11098. // payload limit
  11099. if (response.length() <= 10) {
  11100. SUCCEED() << "Server closed connection for oversized chunked request";
  11101. } else {
  11102. // Check for error status codes
  11103. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11104. response.find("Payload Too Large") != std::string::npos ||
  11105. response.find("400") != std::string::npos);
  11106. }
  11107. }
  11108. }
  11109. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11110. // Test request without Content-Length header exceeding payload limit
  11111. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11112. "Host: " +
  11113. std::string(HOST) + ":" +
  11114. std::to_string(PORT) +
  11115. "\r\n"
  11116. "Connection: close\r\n"
  11117. "\r\n";
  11118. // Add payload exceeding the 8-byte limit
  11119. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11120. request_without_content_length += large_payload;
  11121. std::string response;
  11122. bool result = send_request(1, request_without_content_length, &response);
  11123. if (!result) {
  11124. // If send_request fails, server likely closed connection due to payload
  11125. // limit
  11126. SUCCEED() << "Server rejected oversized request without Content-Length "
  11127. "(connection closed)";
  11128. } else {
  11129. // Check if server responded with error or closed connection early
  11130. if (response.length() <= 10) {
  11131. SUCCEED() << "Server closed connection for oversized request without "
  11132. "Content-Length";
  11133. } else {
  11134. // Check for error status codes
  11135. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11136. response.find("Payload Too Large") != std::string::npos ||
  11137. response.find("400") != std::string::npos);
  11138. }
  11139. }
  11140. }
  11141. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11142. // Test request without Content-Length header within payload limit
  11143. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11144. "Host: " +
  11145. std::string(HOST) + ":" +
  11146. std::to_string(PORT) +
  11147. "\r\n"
  11148. "Connection: close\r\n"
  11149. "\r\n";
  11150. // Add payload within the 8-byte limit
  11151. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11152. request_without_content_length += small_payload;
  11153. std::string response;
  11154. bool result = send_request(1, request_without_content_length, &response);
  11155. // For requests without Content-Length, the server may have different behavior
  11156. // The key is that it should not reject due to payload limit for small
  11157. // payloads
  11158. if (result) {
  11159. // Check for any HTTP response (success or error, but not connection closed)
  11160. if (response.length() > 10) {
  11161. SUCCEED()
  11162. << "Server processed request without Content-Length within limit";
  11163. } else {
  11164. // Short response might indicate connection closed, which is acceptable
  11165. SUCCEED() << "Server closed connection for request without "
  11166. "Content-Length (acceptable behavior)";
  11167. }
  11168. } else {
  11169. // Connection failure might be due to protocol requirements
  11170. SUCCEED() << "Connection issue with request without Content-Length "
  11171. "(environment-specific)";
  11172. }
  11173. }
  11174. class LargePayloadMaxLengthTest : public ::testing::Test {
  11175. protected:
  11176. LargePayloadMaxLengthTest()
  11177. : cli_(HOST, PORT)
  11178. #ifdef CPPHTTPLIB_SSL_ENABLED
  11179. ,
  11180. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11181. #endif
  11182. {
  11183. #ifdef CPPHTTPLIB_SSL_ENABLED
  11184. cli_.enable_server_certificate_verification(false);
  11185. #endif
  11186. }
  11187. virtual void SetUp() {
  11188. // Set 10MB payload limit
  11189. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11190. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11191. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11192. res.set_content("Large payload test", "text/plain");
  11193. });
  11194. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11195. svr_.wait_until_ready();
  11196. }
  11197. virtual void TearDown() {
  11198. svr_.stop();
  11199. t_.join();
  11200. }
  11201. #ifdef CPPHTTPLIB_SSL_ENABLED
  11202. SSLClient cli_;
  11203. SSLServer svr_;
  11204. #else
  11205. Client cli_;
  11206. Server svr_;
  11207. #endif
  11208. thread t_;
  11209. };
  11210. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11211. // Test chunked encoding with payload within 10MB limit
  11212. std::string medium_payload(5 * 1024 * 1024,
  11213. 'A'); // 5MB payload, within 10MB limit
  11214. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11216. EXPECT_EQ(StatusCode::OK_200, res->status);
  11217. }
  11218. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11219. // Test chunked encoding with payload exceeding 10MB limit
  11220. std::string large_payload(12 * 1024 * 1024,
  11221. 'B'); // 12MB payload, exceeds 10MB limit
  11222. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11223. // Server may either return 413 or close the connection
  11224. if (res) {
  11225. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11226. } else {
  11227. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11228. }
  11229. }
  11230. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11231. // Test request without Content-Length header within 10MB limit
  11232. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11233. "Host: " +
  11234. std::string(HOST) + ":" +
  11235. std::to_string(PORT) +
  11236. "\r\n"
  11237. "Connection: close\r\n"
  11238. "\r\n";
  11239. // Add 1MB payload (within 10MB limit)
  11240. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11241. request_without_content_length += medium_payload;
  11242. std::string response;
  11243. bool result = send_request(5, request_without_content_length, &response);
  11244. if (result) {
  11245. // Should get a proper HTTP response for payloads within limit
  11246. if (response.length() > 10) {
  11247. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11248. "10MB limit";
  11249. } else {
  11250. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11251. "Content-Length)";
  11252. }
  11253. } else {
  11254. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11255. }
  11256. }
  11257. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11258. // Test request without Content-Length header exceeding 10MB limit
  11259. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11260. "Host: " +
  11261. std::string(HOST) + ":" +
  11262. std::to_string(PORT) +
  11263. "\r\n"
  11264. "Connection: close\r\n"
  11265. "\r\n";
  11266. // Add 12MB payload (exceeds 10MB limit)
  11267. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11268. request_without_content_length += large_payload;
  11269. std::string response;
  11270. bool result = send_request(10, request_without_content_length, &response);
  11271. if (!result) {
  11272. // Server should close connection due to payload limit
  11273. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11274. "(connection closed)";
  11275. } else {
  11276. // Check for error response
  11277. if (response.length() <= 10) {
  11278. SUCCEED()
  11279. << "Server closed connection for 12MB request exceeding 10MB limit";
  11280. } else {
  11281. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11282. response.find("Payload Too Large") != std::string::npos ||
  11283. response.find("400") != std::string::npos);
  11284. }
  11285. }
  11286. }
  11287. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11288. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11289. // path.
  11290. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11291. Server svr;
  11292. const size_t LIMIT = 64 * 1024; // 64KB
  11293. svr.set_payload_max_length(LIMIT);
  11294. size_t total = 0;
  11295. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11296. const ContentReader &content_reader) {
  11297. content_reader([&](const char * /*data*/, size_t len) {
  11298. total += len;
  11299. return true;
  11300. });
  11301. res.status = 200;
  11302. res.set_content("stream_ok", "text/plain");
  11303. });
  11304. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11305. auto se = detail::scope_exit([&] {
  11306. svr.stop();
  11307. thread.join();
  11308. ASSERT_FALSE(svr.is_running());
  11309. });
  11310. svr.wait_until_ready();
  11311. // Prepare 256KB raw data and gzip-compress it
  11312. std::string raw(256 * 1024, 'A');
  11313. std::string gz;
  11314. {
  11315. z_stream zs{};
  11316. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11317. Z_DEFAULT_STRATEGY);
  11318. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11319. zs.avail_in = static_cast<uInt>(raw.size());
  11320. char outbuf[4096];
  11321. int ret;
  11322. do {
  11323. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11324. zs.avail_out = sizeof(outbuf);
  11325. ret = deflate(&zs, Z_FINISH);
  11326. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11327. } while (ret != Z_STREAM_END);
  11328. deflateEnd(&zs);
  11329. }
  11330. Client cli(HOST, PORT);
  11331. cli.set_connection_timeout(std::chrono::seconds(5));
  11332. Headers headers = {{"Content-Encoding", "gzip"}};
  11333. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11334. "application/octet-stream");
  11335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11336. // Server must reject oversized decompressed payloads with 413.
  11337. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11338. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11339. EXPECT_LE(total, LIMIT);
  11340. }
  11341. #ifndef CPPHTTPLIB_SSL_ENABLED
  11342. // For a request with neither Content-Length nor Transfer-Encoding, the
  11343. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11344. // compressed wire bytes straight to the ContentReader without ever routing
  11345. // them through the decompressor, so payload_max_length_ only bounded the
  11346. // compressed size on the wire, not the decompressed size.
  11347. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11348. Server svr;
  11349. const size_t LIMIT = 64 * 1024; // 64KB
  11350. svr.set_payload_max_length(LIMIT);
  11351. size_t total = 0;
  11352. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11353. const ContentReader &content_reader) {
  11354. content_reader([&](const char * /*data*/, size_t len) {
  11355. total += len;
  11356. return true;
  11357. });
  11358. res.status = 200;
  11359. res.set_content("stream_ok", "text/plain");
  11360. });
  11361. auto port = svr.bind_to_any_port(HOST);
  11362. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11363. auto se = detail::scope_exit([&] {
  11364. svr.stop();
  11365. thread.join();
  11366. ASSERT_FALSE(svr.is_running());
  11367. });
  11368. svr.wait_until_ready();
  11369. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11370. // StreamingGzipDecompression test above.
  11371. std::string raw(256 * 1024, 'A');
  11372. std::string gz;
  11373. {
  11374. httplib::detail::gzip_compressor compressor;
  11375. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11376. [&](const char *chunk, size_t len) {
  11377. gz.append(chunk, len);
  11378. return true;
  11379. });
  11380. ASSERT_TRUE(result);
  11381. }
  11382. // Send the gzip body over raw TCP with neither Content-Length nor
  11383. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11384. // kicks in.
  11385. std::string req = "POST /stream HTTP/1.1\r\n"
  11386. "Host: " +
  11387. std::string(HOST) + ":" + std::to_string(port) +
  11388. "\r\n"
  11389. "Content-Encoding: gzip\r\n"
  11390. "Connection: close\r\n"
  11391. "\r\n" +
  11392. gz;
  11393. std::string response;
  11394. ASSERT_TRUE(send_request(5, req, &response, port));
  11395. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11396. EXPECT_LE(total, LIMIT);
  11397. }
  11398. #endif
  11399. #endif
  11400. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11401. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11402. // the payload must be passed through untouched instead of being rejected.
  11403. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11404. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11405. Server svr;
  11406. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11407. res.set_content(body, "image/jpeg");
  11408. res.set_header("Content-Encoding", "UTF-8");
  11409. });
  11410. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11411. res.set_content(body, "image/jpeg");
  11412. res.set_header("Content-Encoding", "identity");
  11413. });
  11414. svr.Post("/echo", [](const Request &req, Response &res) {
  11415. res.set_content(req.body, "image/jpeg");
  11416. });
  11417. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11418. auto se = detail::scope_exit([&] {
  11419. svr.stop();
  11420. t.join();
  11421. ASSERT_FALSE(svr.is_running());
  11422. });
  11423. svr.wait_until_ready();
  11424. Client cli(HOST, PORT);
  11425. {
  11426. auto res = cli.Get("/image");
  11427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11428. EXPECT_EQ(StatusCode::OK_200, res->status);
  11429. EXPECT_EQ(body, res->body);
  11430. }
  11431. {
  11432. auto res = cli.Get("/identity");
  11433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11434. EXPECT_EQ(StatusCode::OK_200, res->status);
  11435. EXPECT_EQ(body, res->body);
  11436. }
  11437. {
  11438. // The same applies to a request body reaching the server.
  11439. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11440. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11442. EXPECT_EQ(StatusCode::OK_200, res->status);
  11443. EXPECT_EQ(body, res->body);
  11444. }
  11445. }
  11446. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11447. // gzip-encoded response even when the build has no zlib support.
  11448. static const char GZIPPED_HELLO_WORLD[] = {
  11449. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11450. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11451. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11452. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11453. // A content coding is a whole token, not something the field value merely
  11454. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11455. // as "fibre" look like Brotli, and turned a multi-coding value like
  11456. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11457. // it was never meant to see.
  11458. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11459. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11460. Server svr;
  11461. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11462. res.set_content(body, "image/jpeg");
  11463. res.set_header("Content-Encoding", "fibre");
  11464. });
  11465. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11466. res.set_content(body, "image/jpeg");
  11467. res.set_header("Content-Encoding", "gzip, br");
  11468. });
  11469. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11470. res.set_content(body, "image/jpeg");
  11471. res.set_header("Content-Encoding", "x-zstd-ish");
  11472. });
  11473. auto port = svr.bind_to_any_port(HOST);
  11474. thread t = thread([&]() { svr.listen_after_bind(); });
  11475. auto se = detail::scope_exit([&] {
  11476. svr.stop();
  11477. t.join();
  11478. ASSERT_FALSE(svr.is_running());
  11479. });
  11480. svr.wait_until_ready();
  11481. Client cli(HOST, port);
  11482. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11483. auto res = cli.Get(path);
  11484. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11485. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11486. // Not a coding we recognize, so the payload comes back untouched
  11487. EXPECT_EQ(body, res->body) << path;
  11488. }
  11489. }
  11490. // A content coding cpp-httplib recognizes but was not built with must be
  11491. // reported as such. Handing the still-compressed payload back to the caller
  11492. // would silently corrupt it.
  11493. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11494. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11495. Server svr;
  11496. // "image/jpeg" keeps the server from applying a content coding of its own,
  11497. // so the hand-crafted Content-Encoding below survives.
  11498. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11499. res.set_content(gzipped, "image/jpeg");
  11500. res.set_header("Content-Encoding", "gzip");
  11501. });
  11502. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11503. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11504. res.set_content(gzipped, "image/jpeg");
  11505. res.set_header("Content-Encoding", "GZIP");
  11506. });
  11507. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11508. auto se = detail::scope_exit([&] {
  11509. svr.stop();
  11510. t.join();
  11511. ASSERT_FALSE(svr.is_running());
  11512. });
  11513. svr.wait_until_ready();
  11514. Client cli(HOST, PORT);
  11515. {
  11516. auto res = cli.Get("/gzipped");
  11517. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11519. EXPECT_EQ("Hello World!", res->body);
  11520. #else
  11521. ASSERT_FALSE(res);
  11522. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11523. #endif
  11524. }
  11525. {
  11526. // open_stream() must behave the same way.
  11527. auto handle = cli.open_stream("GET", "/gzipped");
  11528. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11529. ASSERT_TRUE(handle.is_valid());
  11530. std::string received;
  11531. char buf[256];
  11532. ssize_t n;
  11533. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11534. received.append(buf, static_cast<size_t>(n));
  11535. }
  11536. EXPECT_EQ("Hello World!", received);
  11537. #else
  11538. EXPECT_FALSE(handle.is_valid());
  11539. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11540. #endif
  11541. }
  11542. {
  11543. // A differently-cased coding must not be mistaken for an unknown one, or
  11544. // the body would be handed back still compressed.
  11545. auto res = cli.Get("/gzipped-uppercase");
  11546. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11548. EXPECT_EQ("Hello World!", res->body);
  11549. #else
  11550. ASSERT_FALSE(res);
  11551. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11552. #endif
  11553. }
  11554. }
  11555. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11556. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11557. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11558. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11559. // body a second time and appending a second Content-Encoding field line, so
  11560. // clients that decode one coding per listed value handed back raw gzip bytes.
  11561. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11562. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11563. Server svr;
  11564. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11565. // keeps the server from applying a coding of its own.
  11566. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11567. res.set_content(gzipped, "text/plain");
  11568. res.set_header("Content-Encoding", "gzip");
  11569. });
  11570. auto port = svr.bind_to_any_port(HOST);
  11571. thread t = thread([&]() { svr.listen_after_bind(); });
  11572. auto se = detail::scope_exit([&] {
  11573. svr.stop();
  11574. t.join();
  11575. ASSERT_FALSE(svr.is_running());
  11576. });
  11577. svr.wait_until_ready();
  11578. Client cli(HOST, port);
  11579. Headers headers = {{"Accept-Encoding", "gzip"}};
  11580. auto res = cli.Get("/pre-gzipped", headers);
  11581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11582. EXPECT_EQ(StatusCode::OK_200, res->status);
  11583. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11584. EXPECT_EQ("Hello World!", res->body);
  11585. }
  11586. // A chunked provider settles its coding where the headers are written and
  11587. // reuses it at write time. Both ends of that have to hold: a handler's own
  11588. // Content-Encoding suppresses the coding, and a response without one is still
  11589. // compressed as it always was.
  11590. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11591. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11592. const std::string plain = "Hello World! Hello World! Hello World!";
  11593. Server svr;
  11594. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11595. res.set_header("Content-Encoding", "gzip");
  11596. res.set_chunked_content_provider(
  11597. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11598. sink.write(gzipped.data(), gzipped.size());
  11599. sink.done();
  11600. return true;
  11601. });
  11602. });
  11603. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11604. res.set_chunked_content_provider(
  11605. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11606. sink.write(plain.data(), plain.size());
  11607. sink.done();
  11608. return true;
  11609. });
  11610. });
  11611. auto port = svr.bind_to_any_port(HOST);
  11612. thread t = thread([&]() { svr.listen_after_bind(); });
  11613. auto se = detail::scope_exit([&] {
  11614. svr.stop();
  11615. t.join();
  11616. ASSERT_FALSE(svr.is_running());
  11617. });
  11618. svr.wait_until_ready();
  11619. Client cli(HOST, port);
  11620. Headers headers = {{"Accept-Encoding", "gzip"}};
  11621. {
  11622. auto res = cli.Get("/pre-gzipped", headers);
  11623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11624. EXPECT_EQ(StatusCode::OK_200, res->status);
  11625. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11626. EXPECT_EQ("Hello World!", res->body);
  11627. }
  11628. {
  11629. auto res = cli.Get("/negotiated", headers);
  11630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11631. EXPECT_EQ(StatusCode::OK_200, res->status);
  11632. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11633. EXPECT_EQ(plain, res->body);
  11634. }
  11635. }
  11636. #endif
  11637. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11638. // the same message as the comma-joined one, so both have to be read the same
  11639. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11640. // single gzip coding, and a body the sender says was encoded twice was handed
  11641. // back after one pass, still compressed but presented as decoded.
  11642. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11643. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11644. Server svr;
  11645. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11646. res.set_content(body, "image/jpeg");
  11647. res.headers.emplace("Content-Encoding", "gzip");
  11648. res.headers.emplace("Content-Encoding", "gzip");
  11649. });
  11650. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11651. res.set_content(body, "image/jpeg");
  11652. res.set_header("Content-Encoding", "gzip, gzip");
  11653. });
  11654. auto port = svr.bind_to_any_port(HOST);
  11655. thread t = thread([&]() { svr.listen_after_bind(); });
  11656. auto se = detail::scope_exit([&] {
  11657. svr.stop();
  11658. t.join();
  11659. ASSERT_FALSE(svr.is_running());
  11660. });
  11661. svr.wait_until_ready();
  11662. Client cli(HOST, port);
  11663. // Two codings is not something cpp-httplib decodes, so both representations
  11664. // take the pass-through path rather than one of them being gunzipped once.
  11665. for (const char *path : {"/split", "/joined"}) {
  11666. auto res = cli.Get(path);
  11667. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11668. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11669. EXPECT_EQ(body, res->body) << path;
  11670. }
  11671. }
  11672. // Regression test for DoS vulnerability: a malicious server sending a response
  11673. // without Content-Length header must not cause unbounded memory consumption on
  11674. // the client side. The client should stop reading after a reasonable limit,
  11675. // similar to the server-side set_payload_max_length protection.
  11676. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11677. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11678. #ifndef _WIN32
  11679. signal(SIGPIPE, SIG_IGN);
  11680. #endif
  11681. auto server_thread = std::thread([] {
  11682. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11683. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11684. default_socket_options(srv);
  11685. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11686. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11687. sockaddr_in addr{};
  11688. addr.sin_family = AF_INET;
  11689. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11690. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11691. int opt = 1;
  11692. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11693. #ifdef _WIN32
  11694. reinterpret_cast<const char *>(&opt),
  11695. #else
  11696. &opt,
  11697. #endif
  11698. sizeof(opt));
  11699. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11700. ::listen(srv, 1);
  11701. sockaddr_in cli_addr{};
  11702. socklen_t cli_len = sizeof(cli_addr);
  11703. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11704. if (cli != INVALID_SOCKET) {
  11705. char buf[4096];
  11706. ::recv(cli, buf, sizeof(buf), 0);
  11707. // Malicious response: no Content-Length, no chunked encoding
  11708. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11709. "Connection: close\r\n"
  11710. "\r\n";
  11711. ::send(cli,
  11712. #ifdef _WIN32
  11713. static_cast<const char *>(response_header.c_str()),
  11714. static_cast<int>(response_header.size()),
  11715. #else
  11716. response_header.c_str(), response_header.size(),
  11717. #endif
  11718. 0);
  11719. // Send 10MB of data
  11720. std::string chunk(64 * 1024, 'A');
  11721. size_t total_sent = 0;
  11722. while (total_sent < MALICIOUS_DATA_SIZE) {
  11723. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11724. auto sent = ::send(cli,
  11725. #ifdef _WIN32
  11726. static_cast<const char *>(chunk.c_str()),
  11727. static_cast<int>(to_send),
  11728. #else
  11729. chunk.c_str(), to_send,
  11730. #endif
  11731. 0);
  11732. if (sent <= 0) break;
  11733. total_sent += static_cast<size_t>(sent);
  11734. }
  11735. detail::close_socket(cli);
  11736. }
  11737. detail::close_socket(srv);
  11738. });
  11739. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11740. size_t total_read = 0;
  11741. {
  11742. Client cli("127.0.0.1", PORT + 2);
  11743. cli.set_read_timeout(5, 0);
  11744. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11745. auto stream = cli.open_stream("GET", "/malicious");
  11746. ASSERT_TRUE(stream.is_valid());
  11747. char buffer[64 * 1024];
  11748. ssize_t n;
  11749. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11750. total_read += static_cast<size_t>(n);
  11751. }
  11752. } // StreamHandle and Client destroyed here, closing the socket
  11753. server_thread.join();
  11754. // With set_payload_max_length, the client must stop reading before consuming
  11755. // all 10MB. The read loop should be cut off at or near the configured limit.
  11756. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11757. << "Client read " << total_read << " bytes, exceeding the configured "
  11758. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11759. }
  11760. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11761. // the entire response body without truncation.
  11762. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11763. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11764. #ifndef _WIN32
  11765. signal(SIGPIPE, SIG_IGN);
  11766. #endif
  11767. auto server_thread = std::thread([] {
  11768. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11769. default_socket_options(srv);
  11770. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11771. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11772. sockaddr_in addr{};
  11773. addr.sin_family = AF_INET;
  11774. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11775. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11776. int opt = 1;
  11777. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11778. #ifdef _WIN32
  11779. reinterpret_cast<const char *>(&opt),
  11780. #else
  11781. &opt,
  11782. #endif
  11783. sizeof(opt));
  11784. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11785. ::listen(srv, 1);
  11786. sockaddr_in cli_addr{};
  11787. socklen_t cli_len = sizeof(cli_addr);
  11788. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11789. if (cli != INVALID_SOCKET) {
  11790. char buf[4096];
  11791. ::recv(cli, buf, sizeof(buf), 0);
  11792. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11793. "Connection: close\r\n"
  11794. "\r\n";
  11795. ::send(cli,
  11796. #ifdef _WIN32
  11797. static_cast<const char *>(response_header.c_str()),
  11798. static_cast<int>(response_header.size()),
  11799. #else
  11800. response_header.c_str(), response_header.size(),
  11801. #endif
  11802. 0);
  11803. std::string chunk(64 * 1024, 'A');
  11804. size_t total_sent = 0;
  11805. while (total_sent < DATA_SIZE) {
  11806. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11807. auto sent = ::send(cli,
  11808. #ifdef _WIN32
  11809. static_cast<const char *>(chunk.c_str()),
  11810. static_cast<int>(to_send),
  11811. #else
  11812. chunk.c_str(), to_send,
  11813. #endif
  11814. 0);
  11815. if (sent <= 0) break;
  11816. total_sent += static_cast<size_t>(sent);
  11817. }
  11818. #ifdef _WIN32
  11819. ::shutdown(cli, SD_SEND);
  11820. #else
  11821. ::shutdown(cli, SHUT_WR);
  11822. #endif
  11823. // Drain until the client closes its end, ensuring all data is delivered
  11824. char drain[1024];
  11825. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11826. detail::close_socket(cli);
  11827. }
  11828. detail::close_socket(srv);
  11829. });
  11830. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11831. size_t total_read = 0;
  11832. {
  11833. Client cli("127.0.0.1", PORT + 2);
  11834. cli.set_read_timeout(5, 0);
  11835. cli.set_payload_max_length(0); // 0 means no limit
  11836. auto stream = cli.open_stream("GET", "/data");
  11837. ASSERT_TRUE(stream.is_valid());
  11838. char buffer[64 * 1024];
  11839. ssize_t n;
  11840. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11841. total_read += static_cast<size_t>(n);
  11842. }
  11843. }
  11844. server_thread.join();
  11845. EXPECT_EQ(total_read, DATA_SIZE)
  11846. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11847. << " bytes without truncation, but only read " << total_read << " bytes.";
  11848. }
  11849. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11850. // enormous Content-Length must not cause the client to pre-allocate a huge
  11851. // response body buffer. The reservation is capped at payload_max_length_, and
  11852. // the read itself fails when the body exceeds the limit.
  11853. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11854. #ifndef _WIN32
  11855. signal(SIGPIPE, SIG_IGN);
  11856. #endif
  11857. auto server_thread = std::thread([] {
  11858. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11859. default_socket_options(srv);
  11860. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11861. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11862. sockaddr_in addr{};
  11863. addr.sin_family = AF_INET;
  11864. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11865. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11866. int opt = 1;
  11867. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11868. #ifdef _WIN32
  11869. reinterpret_cast<const char *>(&opt),
  11870. #else
  11871. &opt,
  11872. #endif
  11873. sizeof(opt));
  11874. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11875. ::listen(srv, 1);
  11876. sockaddr_in cli_addr{};
  11877. socklen_t cli_len = sizeof(cli_addr);
  11878. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11879. if (cli != INVALID_SOCKET) {
  11880. char buf[4096];
  11881. ::recv(cli, buf, sizeof(buf), 0);
  11882. // Malicious response: claim a 20GB body but send only a tiny payload.
  11883. std::string response = "HTTP/1.1 200 OK\r\n"
  11884. "Content-Length: 20000000000\r\n"
  11885. "\r\n"
  11886. "abc";
  11887. ::send(cli,
  11888. #ifdef _WIN32
  11889. static_cast<const char *>(response.c_str()),
  11890. static_cast<int>(response.size()),
  11891. #else
  11892. response.c_str(), response.size(),
  11893. #endif
  11894. 0);
  11895. detail::close_socket(cli);
  11896. }
  11897. detail::close_socket(srv);
  11898. });
  11899. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11900. {
  11901. Client cli("127.0.0.1", PORT + 2);
  11902. cli.set_read_timeout(5, 0);
  11903. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11904. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11905. // (server claims more bytes than payload_max_length permits), but it must
  11906. // not exhaust memory before getting there.
  11907. auto res = cli.Get("/malicious");
  11908. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11909. }
  11910. server_thread.join();
  11911. }
  11912. // Verify that content_receiver bypasses the default payload_max_length,
  11913. // allowing streaming downloads larger than 100MB without requiring an explicit
  11914. // set_payload_max_length call.
  11915. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11916. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11917. #ifndef _WIN32
  11918. signal(SIGPIPE, SIG_IGN);
  11919. #endif
  11920. auto server_thread = std::thread([] {
  11921. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11922. default_socket_options(srv);
  11923. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11924. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11925. sockaddr_in addr{};
  11926. addr.sin_family = AF_INET;
  11927. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11928. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11929. int opt = 1;
  11930. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11931. #ifdef _WIN32
  11932. reinterpret_cast<const char *>(&opt),
  11933. #else
  11934. &opt,
  11935. #endif
  11936. sizeof(opt));
  11937. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11938. ::listen(srv, 1);
  11939. sockaddr_in cli_addr{};
  11940. socklen_t cli_len = sizeof(cli_addr);
  11941. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11942. if (cli != INVALID_SOCKET) {
  11943. char buf[4096];
  11944. ::recv(cli, buf, sizeof(buf), 0);
  11945. // Response with Content-Length larger than default 100MB limit
  11946. auto content_length = std::to_string(DATA_SIZE);
  11947. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11948. "Content-Length: " +
  11949. content_length +
  11950. "\r\n"
  11951. "Connection: close\r\n"
  11952. "\r\n";
  11953. ::send(cli,
  11954. #ifdef _WIN32
  11955. static_cast<const char *>(response_header.c_str()),
  11956. static_cast<int>(response_header.size()),
  11957. #else
  11958. response_header.c_str(), response_header.size(),
  11959. #endif
  11960. 0);
  11961. std::string chunk(64 * 1024, 'A');
  11962. size_t total_sent = 0;
  11963. while (total_sent < DATA_SIZE) {
  11964. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11965. auto sent = ::send(cli,
  11966. #ifdef _WIN32
  11967. static_cast<const char *>(chunk.c_str()),
  11968. static_cast<int>(to_send),
  11969. #else
  11970. chunk.c_str(), to_send,
  11971. #endif
  11972. 0);
  11973. if (sent <= 0) break;
  11974. total_sent += static_cast<size_t>(sent);
  11975. }
  11976. detail::close_socket(cli);
  11977. }
  11978. detail::close_socket(srv);
  11979. });
  11980. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11981. size_t total_received = 0;
  11982. {
  11983. Client cli("127.0.0.1", PORT + 2);
  11984. cli.set_read_timeout(10, 0);
  11985. // Do NOT call set_payload_max_length — use the default 100MB limit
  11986. auto res =
  11987. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11988. total_received += data_length;
  11989. return true;
  11990. });
  11991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11992. EXPECT_EQ(StatusCode::OK_200, res->status);
  11993. }
  11994. server_thread.join();
  11995. EXPECT_EQ(total_received, DATA_SIZE)
  11996. << "With content_receiver, the client should read all " << DATA_SIZE
  11997. << " bytes despite the default 100MB payload_max_length, but only read "
  11998. << total_received << " bytes.";
  11999. }
  12000. // Verify that an explicit set_payload_max_length smaller than the response is
  12001. // enforced even when a content_receiver is used.
  12002. TEST(ClientVulnerabilityTest,
  12003. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12004. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12005. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12006. #ifndef _WIN32
  12007. signal(SIGPIPE, SIG_IGN);
  12008. #endif
  12009. auto server_thread = std::thread([] {
  12010. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12011. default_socket_options(srv);
  12012. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12013. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12014. sockaddr_in addr{};
  12015. addr.sin_family = AF_INET;
  12016. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12017. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12018. int opt = 1;
  12019. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12020. #ifdef _WIN32
  12021. reinterpret_cast<const char *>(&opt),
  12022. #else
  12023. &opt,
  12024. #endif
  12025. sizeof(opt));
  12026. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12027. ::listen(srv, 1);
  12028. sockaddr_in cli_addr{};
  12029. socklen_t cli_len = sizeof(cli_addr);
  12030. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12031. if (cli != INVALID_SOCKET) {
  12032. char buf[4096];
  12033. ::recv(cli, buf, sizeof(buf), 0);
  12034. auto content_length = std::to_string(DATA_SIZE);
  12035. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12036. "Content-Length: " +
  12037. content_length +
  12038. "\r\n"
  12039. "Connection: close\r\n"
  12040. "\r\n";
  12041. ::send(cli,
  12042. #ifdef _WIN32
  12043. static_cast<const char *>(response_header.c_str()),
  12044. static_cast<int>(response_header.size()),
  12045. #else
  12046. response_header.c_str(), response_header.size(),
  12047. #endif
  12048. 0);
  12049. std::string chunk(64 * 1024, 'A');
  12050. size_t total_sent = 0;
  12051. while (total_sent < DATA_SIZE) {
  12052. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12053. auto sent = ::send(cli,
  12054. #ifdef _WIN32
  12055. static_cast<const char *>(chunk.c_str()),
  12056. static_cast<int>(to_send),
  12057. #else
  12058. chunk.c_str(), to_send,
  12059. #endif
  12060. 0);
  12061. if (sent <= 0) break;
  12062. total_sent += static_cast<size_t>(sent);
  12063. }
  12064. detail::close_socket(cli);
  12065. }
  12066. detail::close_socket(srv);
  12067. });
  12068. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12069. size_t total_received = 0;
  12070. {
  12071. Client cli("127.0.0.1", PORT + 2);
  12072. cli.set_read_timeout(10, 0);
  12073. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12074. auto res =
  12075. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12076. total_received += data_length;
  12077. return true;
  12078. });
  12079. // Should fail because 200MB exceeds the explicit 150MB limit
  12080. EXPECT_FALSE(res);
  12081. }
  12082. server_thread.join();
  12083. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12084. << "Client with content_receiver should respect the explicit "
  12085. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12086. << total_received << " bytes.";
  12087. }
  12088. // Verify that an explicit set_payload_max_length larger than the response
  12089. // allows the content_receiver to read all data successfully.
  12090. TEST(ClientVulnerabilityTest,
  12091. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12092. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12093. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12094. #ifndef _WIN32
  12095. signal(SIGPIPE, SIG_IGN);
  12096. #endif
  12097. auto server_thread = std::thread([] {
  12098. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12099. default_socket_options(srv);
  12100. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12101. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12102. sockaddr_in addr{};
  12103. addr.sin_family = AF_INET;
  12104. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12105. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12106. int opt = 1;
  12107. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12108. #ifdef _WIN32
  12109. reinterpret_cast<const char *>(&opt),
  12110. #else
  12111. &opt,
  12112. #endif
  12113. sizeof(opt));
  12114. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12115. ::listen(srv, 1);
  12116. sockaddr_in cli_addr{};
  12117. socklen_t cli_len = sizeof(cli_addr);
  12118. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12119. if (cli != INVALID_SOCKET) {
  12120. char buf[4096];
  12121. ::recv(cli, buf, sizeof(buf), 0);
  12122. auto content_length = std::to_string(DATA_SIZE);
  12123. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12124. "Content-Length: " +
  12125. content_length +
  12126. "\r\n"
  12127. "Connection: close\r\n"
  12128. "\r\n";
  12129. ::send(cli,
  12130. #ifdef _WIN32
  12131. static_cast<const char *>(response_header.c_str()),
  12132. static_cast<int>(response_header.size()),
  12133. #else
  12134. response_header.c_str(), response_header.size(),
  12135. #endif
  12136. 0);
  12137. std::string chunk(64 * 1024, 'A');
  12138. size_t total_sent = 0;
  12139. while (total_sent < DATA_SIZE) {
  12140. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12141. auto sent = ::send(cli,
  12142. #ifdef _WIN32
  12143. static_cast<const char *>(chunk.c_str()),
  12144. static_cast<int>(to_send),
  12145. #else
  12146. chunk.c_str(), to_send,
  12147. #endif
  12148. 0);
  12149. if (sent <= 0) break;
  12150. total_sent += static_cast<size_t>(sent);
  12151. }
  12152. #ifdef _WIN32
  12153. ::shutdown(cli, SD_SEND);
  12154. #else
  12155. ::shutdown(cli, SHUT_WR);
  12156. #endif
  12157. char drain[1024];
  12158. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12159. detail::close_socket(cli);
  12160. }
  12161. detail::close_socket(srv);
  12162. });
  12163. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12164. size_t total_received = 0;
  12165. {
  12166. Client cli("127.0.0.1", PORT + 2);
  12167. cli.set_read_timeout(10, 0);
  12168. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12169. auto res =
  12170. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12171. total_received += data_length;
  12172. return true;
  12173. });
  12174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12175. EXPECT_EQ(StatusCode::OK_200, res->status);
  12176. }
  12177. server_thread.join();
  12178. EXPECT_EQ(total_received, DATA_SIZE)
  12179. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12180. << " bytes (larger than " << DATA_SIZE
  12181. << " bytes response), content_receiver should read all data, but only "
  12182. "read "
  12183. << total_received << " bytes.";
  12184. }
  12185. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12186. // Regression test for "zip bomb" attack on the client side: a malicious server
  12187. // sends a small gzip-compressed response that decompresses to a huge payload.
  12188. // The client must enforce payload_max_length on the decompressed size.
  12189. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12190. constexpr size_t DECOMPRESSED_SIZE =
  12191. 10 * 1024 * 1024; // 10MB after decompression
  12192. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12193. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12194. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12195. std::string compressed;
  12196. {
  12197. httplib::detail::gzip_compressor compressor;
  12198. bool ok =
  12199. compressor.compress(uncompressed.data(), uncompressed.size(),
  12200. /*last=*/true, [&](const char *buf, size_t len) {
  12201. compressed.append(buf, len);
  12202. return true;
  12203. });
  12204. ASSERT_TRUE(ok);
  12205. }
  12206. // Sanity: compressed data should be much smaller than the decompressed size
  12207. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12208. #ifndef _WIN32
  12209. signal(SIGPIPE, SIG_IGN);
  12210. #endif
  12211. // Set up the listening socket in the main thread so the server is guaranteed
  12212. // to be ready before the client connects (eliminates race condition).
  12213. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12214. default_socket_options(srv);
  12215. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12216. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12217. sockaddr_in addr{};
  12218. addr.sin_family = AF_INET;
  12219. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12220. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12221. int opt = 1;
  12222. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12223. #ifdef _WIN32
  12224. reinterpret_cast<const char *>(&opt),
  12225. #else
  12226. &opt,
  12227. #endif
  12228. sizeof(opt));
  12229. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12230. ASSERT_EQ(0, ::listen(srv, 1));
  12231. auto server_thread = std::thread([&compressed, srv] {
  12232. sockaddr_in cli_addr{};
  12233. socklen_t cli_len = sizeof(cli_addr);
  12234. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12235. if (cli != INVALID_SOCKET) {
  12236. // Read the full HTTP request (until \r\n\r\n)
  12237. char buf[4096];
  12238. size_t total = 0;
  12239. while (total < sizeof(buf)) {
  12240. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12241. if (n <= 0) break;
  12242. total += static_cast<size_t>(n);
  12243. // Check for end of headers
  12244. if (total >= 4) {
  12245. std::string req(buf, total);
  12246. if (req.find("\r\n\r\n") != std::string::npos) break;
  12247. }
  12248. }
  12249. // Malicious response: gzip-compressed body, no Content-Length
  12250. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12251. "Content-Encoding: gzip\r\n"
  12252. "Connection: close\r\n"
  12253. "\r\n";
  12254. ::send(cli,
  12255. #ifdef _WIN32
  12256. static_cast<const char *>(response_header.c_str()),
  12257. static_cast<int>(response_header.size()),
  12258. #else
  12259. response_header.c_str(), response_header.size(),
  12260. #endif
  12261. 0);
  12262. // Send the compressed payload (small on the wire, huge when decompressed)
  12263. size_t total_sent = 0;
  12264. while (total_sent < compressed.size()) {
  12265. auto to_send = std::min(compressed.size() - total_sent,
  12266. static_cast<size_t>(64 * 1024));
  12267. auto sent =
  12268. ::send(cli,
  12269. #ifdef _WIN32
  12270. static_cast<const char *>(compressed.c_str() + total_sent),
  12271. static_cast<int>(to_send),
  12272. #else
  12273. compressed.c_str() + total_sent, to_send,
  12274. #endif
  12275. 0);
  12276. if (sent <= 0) break;
  12277. total_sent += static_cast<size_t>(sent);
  12278. }
  12279. detail::close_socket(cli);
  12280. }
  12281. });
  12282. auto se = detail::scope_exit([&] {
  12283. detail::close_socket(srv);
  12284. server_thread.join();
  12285. });
  12286. size_t total_decompressed = 0;
  12287. {
  12288. Client cli("127.0.0.1", PORT + 3);
  12289. cli.set_read_timeout(5, 0);
  12290. cli.set_decompress(true);
  12291. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12292. auto stream = cli.open_stream("GET", "/zipbomb");
  12293. ASSERT_TRUE(stream.is_valid());
  12294. char buffer[64 * 1024];
  12295. ssize_t n;
  12296. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12297. total_decompressed += static_cast<size_t>(n);
  12298. }
  12299. }
  12300. // The decompressed size must be capped by payload_max_length. Without
  12301. // protection, the client would decompress the full 10MB from a tiny
  12302. // compressed payload, enabling a zip bomb DoS attack.
  12303. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12304. << "Client decompressed " << total_decompressed
  12305. << " bytes from a gzip response. The decompressed size should be "
  12306. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12307. }
  12308. #endif
  12309. TEST(HostAndPortPropertiesTest, NoSSL) {
  12310. httplib::Client cli("www.google.com", 1234);
  12311. ASSERT_EQ("www.google.com", cli.host());
  12312. ASSERT_EQ(1234, cli.port());
  12313. }
  12314. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12315. httplib::Client cli("www.google.com:1234");
  12316. ASSERT_EQ("www.google.com", cli.host());
  12317. ASSERT_EQ(1234, cli.port());
  12318. }
  12319. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12320. // Port number that overflows int — should not crash, client becomes invalid
  12321. httplib::Client cli("http://www.google.com:99999999999999999999");
  12322. ASSERT_FALSE(cli.is_valid());
  12323. }
  12324. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12325. // Port 99999 exceeds valid range (1-65535) — should not crash
  12326. httplib::Client cli("http://www.google.com:99999");
  12327. ASSERT_FALSE(cli.is_valid());
  12328. }
  12329. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12330. httplib::Client cli("http://www.google.com:80abc");
  12331. ASSERT_FALSE(cli.is_valid());
  12332. }
  12333. #ifdef CPPHTTPLIB_SSL_ENABLED
  12334. TEST(HostAndPortPropertiesTest, SSL) {
  12335. httplib::SSLClient cli("www.google.com");
  12336. ASSERT_EQ("www.google.com", cli.host());
  12337. ASSERT_EQ(443, cli.port());
  12338. }
  12339. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12340. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12341. std::string cert;
  12342. read_file(CA_CERT_FILE, cert);
  12343. httplib::SSLClient httplib_client("www.google.com");
  12344. // Load CA store first time
  12345. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12346. // Load CA store second time (update)
  12347. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12348. // Verify client is still valid and can make connections
  12349. httplib_client.enable_server_certificate_verification(true);
  12350. auto res = httplib_client.Get("/");
  12351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12352. // Google may return 200 or 301 depending on various factors
  12353. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12354. res->status == StatusCode::MovedPermanently_301);
  12355. }
  12356. TEST(SSLClientTest, ServerNameIndication_Online) {
  12357. auto host = "httpbingo.org";
  12358. auto path = std::string{"/get"};
  12359. SSLClient cli(host, 443);
  12360. auto res = cli.Get(path);
  12361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12362. ASSERT_EQ(StatusCode::OK_200, res->status);
  12363. }
  12364. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12365. // Use a site that will cause SSL verification failure due to self-signed cert
  12366. SSLClient cli("self-signed.badssl.com", 443);
  12367. cli.enable_server_certificate_verification(true);
  12368. auto res = cli.Get("/");
  12369. ASSERT_TRUE(!res);
  12370. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12371. // Verify backend error is captured for SSLServerVerification
  12372. // This occurs when certificate verification fails
  12373. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12374. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12375. EXPECT_NE(0UL, res.ssl_backend_error());
  12376. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12377. // For OpenSSL, ssl_error is 0 for verification errors
  12378. EXPECT_EQ(0, res.ssl_error());
  12379. #if !defined(_WIN32) || \
  12380. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12381. // On non-Windows or when Windows Schannel is disabled, the error comes
  12382. // from OpenSSL's verification
  12383. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12384. res.ssl_backend_error());
  12385. #endif
  12386. #endif
  12387. }
  12388. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12389. // Use a site where hostname doesn't match the certificate
  12390. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12391. SSLClient cli("wrong.host.badssl.com", 443);
  12392. cli.enable_server_certificate_verification(true);
  12393. cli.enable_server_hostname_verification(true);
  12394. auto res = cli.Get("/");
  12395. ASSERT_TRUE(!res);
  12396. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12397. // Verify backend error is captured for hostname verification failure
  12398. EXPECT_NE(0UL, res.ssl_backend_error());
  12399. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12400. // For OpenSSL, ssl_error is 0 for verification errors
  12401. EXPECT_EQ(0, res.ssl_error());
  12402. #if !defined(_WIN32) || \
  12403. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12404. // On non-Windows or when Windows Schannel is disabled, the error comes
  12405. // from OpenSSL's hostname verification
  12406. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12407. res.ssl_backend_error());
  12408. #endif
  12409. #endif
  12410. }
  12411. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12412. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12413. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12414. SSLClient cli("www.google.com", 443);
  12415. cli.enable_server_certificate_verification(true);
  12416. auto res = cli.Get("/");
  12417. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12418. }
  12419. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12420. SSLClient cli("www.google.com", 443);
  12421. cli.enable_server_certificate_verification(true);
  12422. cli.enable_windows_certificate_verification(false);
  12423. auto res = cli.Get("/");
  12424. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12425. }
  12426. // The server sends an intermediate cross-signed by a root Windows trusts,
  12427. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12428. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12429. SSLClient cli("accounts.spotify.com", 443);
  12430. auto res = cli.Get("/");
  12431. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12432. << " ssl_backend_error=" << res.ssl_backend_error();
  12433. }
  12434. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12435. // policy status, which no backend reports for a self-signed certificate.
  12436. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12437. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12438. ASSERT_TRUE(svr.is_valid());
  12439. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12440. auto se = detail::scope_exit([&] {
  12441. svr.stop();
  12442. t.join();
  12443. ASSERT_FALSE(svr.is_running());
  12444. });
  12445. svr.wait_until_ready();
  12446. SSLClient cli("127.0.0.1", PORT);
  12447. cli.set_connection_timeout(30);
  12448. auto res = cli.Get("/");
  12449. ASSERT_FALSE(res);
  12450. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12451. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12452. }
  12453. #endif
  12454. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12455. Client cli("https://google.com");
  12456. auto res = cli.Get("/");
  12457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12458. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12459. }
  12460. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12461. SSLClient cli("google.com");
  12462. cli.set_ca_cert_path(CA_CERT_FILE);
  12463. auto res = cli.Get("/");
  12464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12465. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12466. }
  12467. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12468. SSLClient cli("google.com");
  12469. cli.enable_server_certificate_verification(true);
  12470. cli.set_ca_cert_path("hello");
  12471. auto res = cli.Get("/");
  12472. ASSERT_TRUE(!res);
  12473. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12474. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12475. // should be set
  12476. EXPECT_EQ(0, res.ssl_error());
  12477. // Verify backend error is captured for SSLLoadingCerts
  12478. // This error occurs when loading CA certificates fails
  12479. EXPECT_NE(0UL, res.ssl_backend_error());
  12480. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12481. // OpenSSL specific error codes:
  12482. // > openssl errstr 0x80000002
  12483. // error:80000002:system library::No such file or directory
  12484. // > openssl errstr 0xA000126
  12485. // error:0A000126:SSL routines::unexpected eof while reading
  12486. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12487. res.ssl_backend_error() == 0xA000126);
  12488. #endif
  12489. }
  12490. TEST(SSLClientTest, ServerCertificateVerification4) {
  12491. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12492. ASSERT_TRUE(svr.is_valid());
  12493. svr.Get("/test", [&](const Request &, Response &res) {
  12494. res.set_content("test", "text/plain");
  12495. svr.stop();
  12496. ASSERT_TRUE(true);
  12497. });
  12498. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12499. auto se = detail::scope_exit([&] {
  12500. t.join();
  12501. ASSERT_FALSE(svr.is_running());
  12502. });
  12503. svr.wait_until_ready();
  12504. SSLClient cli("127.0.0.1", PORT);
  12505. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12506. cli.enable_server_certificate_verification(true);
  12507. cli.set_connection_timeout(30);
  12508. auto res = cli.Get("/test");
  12509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12510. ASSERT_EQ(StatusCode::OK_200, res->status);
  12511. }
  12512. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12513. std::string cert;
  12514. read_file(CA_CERT_FILE, cert);
  12515. SSLClient cli("google.com");
  12516. cli.load_ca_cert_store(cert.data(), cert.size());
  12517. const auto res = cli.Get("/");
  12518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12519. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12520. }
  12521. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12522. // clang-format off
  12523. static constexpr char cert[] =
  12524. "GlobalSign Root CA\n"
  12525. "==================\n"
  12526. "-----BEGIN CERTIFICATE-----\n"
  12527. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12528. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12529. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12530. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12531. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12532. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12533. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12534. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12535. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12536. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12537. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12538. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12539. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12540. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12541. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12542. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12543. "-----END CERTIFICATE-----\n";
  12544. // clang-format on
  12545. SSLClient cli("google.com");
  12546. cli.load_ca_cert_store(cert, sizeof(cert));
  12547. const auto res = cli.Get("/");
  12548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12549. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12550. }
  12551. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12552. SSLClient cli("www.youtube.com");
  12553. cli.set_ca_cert_path(CA_CERT_FILE);
  12554. cli.enable_server_certificate_verification(true);
  12555. cli.set_follow_location(true);
  12556. auto res = cli.Get("/");
  12557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12558. ASSERT_EQ(StatusCode::OK_200, res->status);
  12559. }
  12560. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12561. SSLClient cli("wWw.YouTube.Com");
  12562. cli.set_ca_cert_path(CA_CERT_FILE);
  12563. cli.enable_server_certificate_verification(true);
  12564. cli.enable_server_hostname_verification(true);
  12565. cli.set_follow_location(true);
  12566. auto res = cli.Get("/");
  12567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12568. ASSERT_EQ(StatusCode::OK_200, res->status);
  12569. }
  12570. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12571. SSLClient cli("gOoGlE.COm");
  12572. cli.enable_server_certificate_verification(true);
  12573. cli.enable_server_hostname_verification(true);
  12574. cli.set_follow_location(true);
  12575. auto res = cli.Get("/");
  12576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12577. ASSERT_EQ(StatusCode::OK_200, res->status);
  12578. }
  12579. TEST(SSLClientTest, Issue2004_Online) {
  12580. Client client("https://google.com");
  12581. client.set_follow_location(true);
  12582. auto res = client.Get("/");
  12583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12584. ASSERT_EQ(StatusCode::OK_200, res->status);
  12585. auto body = res->body;
  12586. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12587. }
  12588. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12589. // Create SSLClient with invalid cert/key to make is_valid() return false
  12590. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12591. "nonexistent_key.pem");
  12592. // is_valid() should be false due to cert loading failure
  12593. ASSERT_FALSE(cli.is_valid());
  12594. auto res = cli.Get("/");
  12595. ASSERT_FALSE(res);
  12596. EXPECT_EQ(Error::SSLConnection, res.error());
  12597. }
  12598. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12599. // Test for Issue #2251: SSL error not properly reported when client cert
  12600. // and key paths are swapped or mismatched
  12601. // This simulates the scenario where user accidentally swaps the cert and key
  12602. // files
  12603. // Using client cert file as private key and vice versa (completely wrong)
  12604. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12605. // Should fail validation due to cert/key mismatch
  12606. ASSERT_FALSE(cli.is_valid());
  12607. // Attempt to make a request should fail with proper error
  12608. auto res = cli.Get("/");
  12609. ASSERT_FALSE(res);
  12610. EXPECT_EQ(Error::SSLConnection, res.error());
  12611. // SSL error should be recorded in the Result object (this is the key fix for
  12612. // Issue #2251)
  12613. auto backend_error = res.ssl_backend_error();
  12614. EXPECT_NE(0u, backend_error);
  12615. }
  12616. // Tests cert/key mismatch detection at the TLS context level
  12617. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12618. // Test that using mismatched cert/key causes connection failure.
  12619. // We verify this at the SSLClient level rather than through internal
  12620. // TLS API functions.
  12621. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12622. cli.enable_server_certificate_verification(false);
  12623. cli.set_connection_timeout(2);
  12624. // The mismatch should cause a connection or handshake error
  12625. auto res = cli.Get("/test");
  12626. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12627. // Either way, the request should fail
  12628. EXPECT_FALSE(res);
  12629. }
  12630. #endif
  12631. #if 0
  12632. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12633. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12634. ASSERT_TRUE(cli != nullptr);
  12635. cli->set_address_family(AF_INET6);
  12636. cli->set_interface("en0");
  12637. auto res = cli->Get("/get");
  12638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12639. ASSERT_EQ(StatusCode::OK_200, res->status);
  12640. }
  12641. #endif
  12642. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12643. #ifdef CPPHTTPLIB_SSL_ENABLED
  12644. void ClientCertPresent(
  12645. const std::string &client_cert_file,
  12646. const std::string &client_private_key_file,
  12647. const std::string &client_encrypted_private_key_pass = std::string()) {
  12648. using namespace httplib::tls;
  12649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12650. CLIENT_CA_CERT_DIR);
  12651. ASSERT_TRUE(svr.is_valid());
  12652. svr.Get("/test", [&](const Request &req, Response &res) {
  12653. res.set_content("test", "text/plain");
  12654. auto cert = req.peer_cert();
  12655. ASSERT_TRUE(static_cast<bool>(cert));
  12656. std::string common_name = cert.subject_cn();
  12657. EXPECT_EQ("Common Name", common_name);
  12658. });
  12659. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12660. auto se = detail::scope_exit([&] {
  12661. svr.stop();
  12662. t.join();
  12663. ASSERT_FALSE(svr.is_running());
  12664. });
  12665. svr.wait_until_ready();
  12666. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12667. client_encrypted_private_key_pass);
  12668. cli.enable_server_certificate_verification(false);
  12669. cli.set_connection_timeout(30);
  12670. auto res = cli.Get("/test");
  12671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12672. ASSERT_EQ(StatusCode::OK_200, res->status);
  12673. }
  12674. TEST(SSLClientServerTest, ClientCertPresent) {
  12675. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12676. }
  12677. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12678. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12679. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12680. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12681. }
  12682. // PEM memory-based constructor tests (works with all TLS backends)
  12683. void PemMemoryClientCertPresent(
  12684. const std::string &client_cert_file,
  12685. const std::string &client_private_key_file,
  12686. const std::string &client_encrypted_private_key_pass = std::string()) {
  12687. // Read PEM files into memory
  12688. std::string server_cert_pem, server_key_pem;
  12689. std::string client_ca_pem;
  12690. std::string client_cert_pem, client_key_pem;
  12691. read_file(SERVER_CERT_FILE, server_cert_pem);
  12692. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12693. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12694. read_file(client_cert_file, client_cert_pem);
  12695. read_file(client_private_key_file, client_key_pem);
  12696. // Create server with PEM memory
  12697. SSLServer::PemMemory server_pem = {
  12698. server_cert_pem.c_str(),
  12699. server_cert_pem.size(),
  12700. server_key_pem.c_str(),
  12701. server_key_pem.size(),
  12702. client_ca_pem.c_str(),
  12703. client_ca_pem.size(),
  12704. nullptr // no password for server key
  12705. };
  12706. SSLServer svr(server_pem);
  12707. ASSERT_TRUE(svr.is_valid());
  12708. svr.Get("/test", [&](const Request &, Response &res) {
  12709. res.set_content("test", "text/plain");
  12710. });
  12711. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12712. auto se = detail::scope_exit([&] {
  12713. svr.stop();
  12714. t.join();
  12715. ASSERT_FALSE(svr.is_running());
  12716. });
  12717. svr.wait_until_ready();
  12718. // Create client with PEM memory
  12719. const char *password = client_encrypted_private_key_pass.empty()
  12720. ? nullptr
  12721. : client_encrypted_private_key_pass.c_str();
  12722. SSLClient::PemMemory client_pem = {
  12723. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12724. client_key_pem.size(), password};
  12725. SSLClient cli(HOST, PORT, client_pem);
  12726. cli.enable_server_certificate_verification(false);
  12727. cli.set_connection_timeout(30);
  12728. auto res = cli.Get("/test");
  12729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12730. ASSERT_EQ(StatusCode::OK_200, res->status);
  12731. }
  12732. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12733. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12734. }
  12735. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12736. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12737. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12738. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12739. }
  12740. TEST(SSLClientServerTest, ClientCertMissing) {
  12741. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12742. CLIENT_CA_CERT_DIR);
  12743. ASSERT_TRUE(svr.is_valid());
  12744. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12745. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12746. auto se = detail::scope_exit([&] {
  12747. svr.stop();
  12748. t.join();
  12749. ASSERT_FALSE(svr.is_running());
  12750. });
  12751. svr.wait_until_ready();
  12752. SSLClient cli(HOST, PORT);
  12753. cli.set_connection_timeout(30);
  12754. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12755. // the chain check on Windows, so the result does not depend on the order.
  12756. cli.enable_server_hostname_verification(false);
  12757. auto res = cli.Get("/test");
  12758. ASSERT_TRUE(!res);
  12759. // When client cert is missing and server requires it, connection fails
  12760. // Error type depends on backend implementation
  12761. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12762. res.error() == Error::SSLConnection);
  12763. // Verify backend error is captured
  12764. // Note: This test may have different error codes depending on the exact
  12765. // verification failure
  12766. EXPECT_NE(0UL, res.ssl_backend_error());
  12767. }
  12768. TEST(SSLClientServerTest, TrustDirOptional) {
  12769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12770. ASSERT_TRUE(svr.is_valid());
  12771. svr.Get("/test", [&](const Request &, Response &res) {
  12772. res.set_content("test", "text/plain");
  12773. });
  12774. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12775. auto se = detail::scope_exit([&] {
  12776. svr.stop();
  12777. t.join();
  12778. ASSERT_FALSE(svr.is_running());
  12779. });
  12780. svr.wait_until_ready();
  12781. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12782. cli.enable_server_certificate_verification(false);
  12783. cli.set_connection_timeout(30);
  12784. auto res = cli.Get("/test");
  12785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12786. ASSERT_EQ(StatusCode::OK_200, res->status);
  12787. }
  12788. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12789. class NoListenSSLServer : public SSLServer {
  12790. public:
  12791. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12792. const char *client_ca_cert_file_path,
  12793. const char *client_ca_cert_dir_path = nullptr)
  12794. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12795. client_ca_cert_dir_path),
  12796. stop_(false) {}
  12797. std::atomic_bool stop_;
  12798. private:
  12799. bool process_and_close_socket(socket_t /*sock*/) override {
  12800. // Don't create SSL context
  12801. while (!stop_.load()) {
  12802. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12803. }
  12804. return true;
  12805. }
  12806. };
  12807. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12808. CLIENT_CA_CERT_FILE);
  12809. ASSERT_TRUE(svr.is_valid());
  12810. svr.Get("/test", [&](const Request &, Response &res) {
  12811. res.set_content("test", "text/plain");
  12812. });
  12813. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12814. auto se = detail::scope_exit([&] {
  12815. svr.stop_ = true;
  12816. svr.stop();
  12817. t.join();
  12818. ASSERT_FALSE(svr.is_running());
  12819. });
  12820. svr.wait_until_ready();
  12821. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12822. cli.enable_server_certificate_verification(false);
  12823. cli.set_connection_timeout(1);
  12824. auto res = cli.Get("/test");
  12825. ASSERT_TRUE(!res);
  12826. EXPECT_EQ(Error::SSLConnection, res.error());
  12827. // Timeout results in WantRead error code (maps to backend-specific value)
  12828. EXPECT_NE(0, res.ssl_error());
  12829. }
  12830. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12831. // Test SSLServer with client certificate verification using the standard
  12832. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12834. CLIENT_CA_CERT_DIR);
  12835. ASSERT_TRUE(svr.is_valid());
  12836. svr.Get("/test", [&](const Request &req, Response &res) {
  12837. res.set_content("test", "text/plain");
  12838. auto cert = req.peer_cert();
  12839. ASSERT_TRUE(static_cast<bool>(cert));
  12840. auto common_name = cert.subject_cn();
  12841. EXPECT_EQ("Common Name", common_name);
  12842. });
  12843. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12844. auto se = detail::scope_exit([&] {
  12845. svr.stop();
  12846. t.join();
  12847. ASSERT_FALSE(svr.is_running());
  12848. });
  12849. svr.wait_until_ready();
  12850. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12851. cli.enable_server_certificate_verification(false);
  12852. cli.set_connection_timeout(30);
  12853. auto res = cli.Get("/test");
  12854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12855. ASSERT_EQ(StatusCode::OK_200, res->status);
  12856. }
  12857. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12858. // Verifies that wildcard matching and exact matching work consistently
  12859. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12860. using namespace httplib::tls;
  12861. // We need a running server to test against
  12862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12863. ASSERT_TRUE(svr.is_valid());
  12864. svr.Get("/test", [](const Request &, Response &res) {
  12865. res.set_content("ok", "text/plain");
  12866. });
  12867. thread t([&]() { svr.listen(HOST, PORT); });
  12868. auto se = detail::scope_exit([&] {
  12869. svr.stop();
  12870. t.join();
  12871. });
  12872. svr.wait_until_ready();
  12873. bool verify_callback_called = false;
  12874. bool verify_result_wrong = false;
  12875. SSLClient cli(HOST, PORT);
  12876. cli.enable_server_certificate_verification(true);
  12877. cli.set_ca_cert_path(CA_CERT_FILE);
  12878. cli.set_connection_timeout(5);
  12879. // Note: Test certificate has CN="Common Name", not "localhost"
  12880. bool verify_result_cn = false;
  12881. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12882. verify_callback_called = true;
  12883. if (!ctx.cert) return false;
  12884. // Test 1: "Common Name" should match (our test server cert CN)
  12885. verify_result_cn = ctx.check_hostname("Common Name");
  12886. // Test 2: wrong hostname should not match
  12887. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12888. return true; // Accept for the purpose of this test
  12889. });
  12890. auto res = cli.Get("/test");
  12891. // The request may succeed or fail depending on cert configuration
  12892. // but the callback should have been called
  12893. ASSERT_TRUE(verify_callback_called)
  12894. << "Verify callback should have been called";
  12895. // CN="Common Name" should match our test certificate
  12896. //
  12897. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12898. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12899. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12900. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12901. // <openssl/base.h>, which is included transitively when
  12902. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12903. #if defined(OPENSSL_IS_BORINGSSL)
  12904. EXPECT_FALSE(verify_result_cn)
  12905. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12906. #else
  12907. EXPECT_TRUE(verify_result_cn)
  12908. << "verify_hostname should match 'Common Name' (certificate CN)";
  12909. #endif
  12910. // Wrong hostname should not match
  12911. EXPECT_FALSE(verify_result_wrong)
  12912. << "verify_hostname should not match 'wronghost.example.com'";
  12913. }
  12914. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12915. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12916. // X509_check_ip behavior and must hold for every backend.
  12917. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12918. using namespace httplib::tls;
  12919. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12920. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12921. ASSERT_TRUE(svr.is_valid());
  12922. svr.Get("/test", [](const Request &, Response &res) {
  12923. res.set_content("ok", "text/plain");
  12924. });
  12925. thread t([&]() { svr.listen(HOST, PORT); });
  12926. auto se = detail::scope_exit([&] {
  12927. svr.stop();
  12928. t.join();
  12929. });
  12930. svr.wait_until_ready();
  12931. bool verify_callback_called = false;
  12932. bool ip_matched_via_cn = true;
  12933. SSLClient cli(HOST, PORT);
  12934. cli.enable_server_certificate_verification(true);
  12935. cli.set_ca_cert_path(CA_CERT_FILE);
  12936. cli.set_connection_timeout(5);
  12937. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12938. verify_callback_called = true;
  12939. if (!ctx.cert) return false;
  12940. // The IP appears only in the CN, so it must NOT be accepted.
  12941. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12942. return true; // Accept for the purpose of this test
  12943. });
  12944. cli.Get("/test");
  12945. ASSERT_TRUE(verify_callback_called)
  12946. << "Verify callback should have been called";
  12947. EXPECT_FALSE(ip_matched_via_cn)
  12948. << "An IP host must not be authenticated via the certificate CN";
  12949. }
  12950. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12951. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12952. using namespace httplib::tls;
  12953. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12954. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12955. ASSERT_TRUE(svr.is_valid());
  12956. svr.Get("/test", [](const Request &, Response &res) {
  12957. res.set_content("ok", "text/plain");
  12958. });
  12959. thread t([&]() { svr.listen(HOST, PORT); });
  12960. auto se = detail::scope_exit([&] {
  12961. svr.stop();
  12962. t.join();
  12963. });
  12964. svr.wait_until_ready();
  12965. bool verify_callback_called = false;
  12966. bool san_matched = false;
  12967. bool wrong_ipv6_matched = true;
  12968. bool cn_ipv6_matched = true;
  12969. SSLClient cli(HOST, PORT);
  12970. cli.enable_server_certificate_verification(true);
  12971. cli.set_ca_cert_path(CA_CERT_FILE);
  12972. cli.set_connection_timeout(5);
  12973. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12974. verify_callback_called = true;
  12975. if (!ctx.cert) return false;
  12976. // Matches the IPv6 iPAddress SAN.
  12977. san_matched = ctx.check_hostname("2001:db8::1");
  12978. // A different IPv6 address must not match.
  12979. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12980. // "::1" lives only in the CN, so it must not be accepted.
  12981. cn_ipv6_matched = ctx.check_hostname("::1");
  12982. return true; // Accept for the purpose of this test
  12983. });
  12984. cli.Get("/test");
  12985. ASSERT_TRUE(verify_callback_called)
  12986. << "Verify callback should have been called";
  12987. EXPECT_TRUE(san_matched)
  12988. << "verify_hostname should match an IPv6 iPAddress SAN";
  12989. EXPECT_FALSE(wrong_ipv6_matched)
  12990. << "verify_hostname should not match a non-matching IPv6 address";
  12991. EXPECT_FALSE(cn_ipv6_matched)
  12992. << "An IPv6 host must not be authenticated via the certificate CN";
  12993. }
  12994. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12995. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12996. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12997. using namespace httplib::tls;
  12998. // SANs: DNS:a.zz, IP:42.46.122.122
  12999. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13000. ASSERT_TRUE(svr.is_valid());
  13001. svr.Get("/test", [](const Request &, Response &res) {
  13002. res.set_content("ok", "text/plain");
  13003. });
  13004. auto port = svr.bind_to_any_port(HOST);
  13005. thread t([&]() { svr.listen_after_bind(); });
  13006. auto se = detail::scope_exit([&] {
  13007. svr.stop();
  13008. t.join();
  13009. });
  13010. svr.wait_until_ready();
  13011. bool verify_callback_called = false;
  13012. bool dns_san_matched = false;
  13013. bool ip_san_matched = false;
  13014. bool ip_matched_via_dns_san = true;
  13015. bool dns_matched_via_ip_san = true;
  13016. SSLClient cli(HOST, port);
  13017. cli.enable_server_certificate_verification(true);
  13018. cli.set_ca_cert_path(CA_CERT_FILE);
  13019. cli.set_connection_timeout(5);
  13020. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13021. verify_callback_called = true;
  13022. if (!ctx.cert) return false;
  13023. dns_san_matched = ctx.check_hostname("a.zz");
  13024. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13025. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13026. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13027. return true; // Accept for the purpose of this test
  13028. });
  13029. cli.Get("/test");
  13030. ASSERT_TRUE(verify_callback_called)
  13031. << "Verify callback should have been called";
  13032. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13033. EXPECT_TRUE(ip_san_matched)
  13034. << "verify_hostname should match an iPAddress SAN";
  13035. EXPECT_FALSE(ip_matched_via_dns_san)
  13036. << "An IP host must not be authenticated via a dNSName SAN";
  13037. EXPECT_FALSE(dns_matched_via_ip_san)
  13038. << "A DNS host must not be authenticated via an iPAddress SAN";
  13039. }
  13040. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13041. // "www.*.example.test" names one host and not every host under example.test.
  13042. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13043. using namespace httplib::tls;
  13044. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13045. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13046. ASSERT_TRUE(svr.is_valid());
  13047. svr.Get("/test", [](const Request &, Response &res) {
  13048. res.set_content("ok", "text/plain");
  13049. });
  13050. auto port = svr.bind_to_any_port(HOST);
  13051. thread t([&]() { svr.listen_after_bind(); });
  13052. auto se = detail::scope_exit([&] {
  13053. svr.stop();
  13054. t.join();
  13055. });
  13056. svr.wait_until_ready();
  13057. bool verify_callback_called = false;
  13058. bool leftmost_wildcard_matched = false;
  13059. bool wildcard_spanned_labels = true;
  13060. bool inner_wildcard_matched = true;
  13061. SSLClient cli(HOST, port);
  13062. cli.enable_server_certificate_verification(true);
  13063. cli.set_ca_cert_path(CA_CERT_FILE);
  13064. cli.set_connection_timeout(5);
  13065. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13066. verify_callback_called = true;
  13067. if (!ctx.cert) return false;
  13068. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13069. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13070. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13071. return true; // Accept for the purpose of this test
  13072. });
  13073. cli.Get("/test");
  13074. ASSERT_TRUE(verify_callback_called)
  13075. << "Verify callback should have been called";
  13076. EXPECT_TRUE(leftmost_wildcard_matched)
  13077. << "A leftmost wildcard should match a single label";
  13078. EXPECT_FALSE(wildcard_spanned_labels)
  13079. << "A wildcard label must not match more than one label";
  13080. EXPECT_FALSE(inner_wildcard_matched)
  13081. << "A wildcard outside the leftmost label must not be honoured";
  13082. }
  13083. // sans() must report each SAN entry under its own type.
  13084. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13085. using namespace httplib::tls;
  13086. // SANs: DNS:a.zz, IP:42.46.122.122
  13087. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13088. ASSERT_TRUE(svr.is_valid());
  13089. svr.Get("/test", [](const Request &, Response &res) {
  13090. res.set_content("ok", "text/plain");
  13091. });
  13092. auto port = svr.bind_to_any_port(HOST);
  13093. thread t([&]() { svr.listen_after_bind(); });
  13094. auto se = detail::scope_exit([&] {
  13095. svr.stop();
  13096. t.join();
  13097. });
  13098. svr.wait_until_ready();
  13099. bool verify_callback_called = false;
  13100. std::vector<SanEntry> sans;
  13101. SSLClient cli(HOST, port);
  13102. cli.enable_server_certificate_verification(true);
  13103. cli.set_ca_cert_path(CA_CERT_FILE);
  13104. cli.set_connection_timeout(5);
  13105. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13106. verify_callback_called = true;
  13107. if (!ctx.cert) return false;
  13108. sans = ctx.sans();
  13109. return true; // Accept for the purpose of this test
  13110. });
  13111. cli.Get("/test");
  13112. ASSERT_TRUE(verify_callback_called)
  13113. << "Verify callback should have been called";
  13114. auto has_san = [&](SanType type, const std::string &value) {
  13115. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13116. return san.type == type && san.value == value;
  13117. });
  13118. };
  13119. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13120. << "sans() should report the dNSName SAN";
  13121. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13122. << "sans() should report the iPAddress SAN";
  13123. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13124. << "sans() must not report the dNSName SAN as an address";
  13125. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13126. << "sans() must not report the iPAddress SAN as a DNS name";
  13127. }
  13128. #endif
  13129. // mbedTLS-specific callback constructor test
  13130. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13131. #ifdef CPPHTTPLIB_SSL_ENABLED
  13132. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13134. ASSERT_TRUE(svr.is_valid());
  13135. // Set up a handler to verify client certificate is present
  13136. bool client_cert_verified = false;
  13137. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13138. // Verify that client certificate was provided
  13139. client_cert_verified = true;
  13140. res.set_content("success", "text/plain");
  13141. });
  13142. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13143. auto se = detail::scope_exit([&] {
  13144. svr.stop();
  13145. t.join();
  13146. ASSERT_FALSE(svr.is_running());
  13147. });
  13148. svr.wait_until_ready();
  13149. // Client with certificate
  13150. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13151. cli.enable_server_certificate_verification(false);
  13152. cli.set_connection_timeout(30);
  13153. auto res = cli.Get("/test");
  13154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13155. ASSERT_EQ(StatusCode::OK_200, res->status);
  13156. ASSERT_TRUE(client_cert_verified);
  13157. EXPECT_EQ("success", res->body);
  13158. }
  13159. #endif
  13160. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13161. // backends
  13162. #ifdef CPPHTTPLIB_SSL_ENABLED
  13163. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13164. using namespace httplib::tls;
  13165. // Test that when client CA cert file is provided,
  13166. // the server properly requests and validates client certificates
  13167. // Create a server with client authentication
  13168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13169. ASSERT_TRUE(svr.is_valid());
  13170. bool handler_called = false;
  13171. svr.Get("/test", [&](const Request &req, Response &res) {
  13172. handler_called = true;
  13173. // Verify that a client certificate was provided
  13174. auto cert = req.peer_cert();
  13175. ASSERT_TRUE(static_cast<bool>(cert));
  13176. // Get the issuer name
  13177. std::string issuer_str = cert.issuer_name();
  13178. ASSERT_FALSE(issuer_str.empty());
  13179. // The client certificate should be issued by our test CA
  13180. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13181. res.set_content("authenticated", "text/plain");
  13182. });
  13183. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13184. auto se = detail::scope_exit([&] {
  13185. svr.stop();
  13186. t.join();
  13187. ASSERT_FALSE(svr.is_running());
  13188. });
  13189. svr.wait_until_ready();
  13190. // Connect with a client certificate issued by the CA
  13191. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13192. cli.enable_server_certificate_verification(false);
  13193. cli.set_connection_timeout(30);
  13194. auto res = cli.Get("/test");
  13195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13196. ASSERT_EQ(StatusCode::OK_200, res->status);
  13197. ASSERT_TRUE(handler_called);
  13198. EXPECT_EQ("authenticated", res->body);
  13199. }
  13200. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13201. using namespace httplib::tls;
  13202. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13203. ASSERT_TRUE(svr.is_valid());
  13204. svr.Get("/test", [](const Request &, Response &res) {
  13205. res.set_content("ok", "text/plain");
  13206. });
  13207. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13208. auto se = detail::scope_exit([&] {
  13209. svr.stop();
  13210. t.join();
  13211. });
  13212. svr.wait_until_ready();
  13213. SSLClient cli(HOST, PORT);
  13214. cli.enable_server_certificate_verification(false);
  13215. cli.set_connection_timeout(30);
  13216. bool cert_checked = false;
  13217. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13218. if (ctx.cert) {
  13219. auto sans = ctx.sans();
  13220. // Test certificate may or may not have SANs - just verify the API
  13221. // works If SANs exist, verify the types are valid
  13222. for (const auto &san : sans) {
  13223. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13224. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13225. san.type == SanType::OTHER);
  13226. EXPECT_FALSE(san.value.empty());
  13227. }
  13228. cert_checked = true;
  13229. }
  13230. return true;
  13231. });
  13232. auto res = cli.Get("/test");
  13233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13234. EXPECT_TRUE(cert_checked);
  13235. }
  13236. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13237. using namespace httplib::tls;
  13238. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13239. ASSERT_TRUE(svr.is_valid());
  13240. svr.Get("/test", [](const Request &, Response &res) {
  13241. res.set_content("ok", "text/plain");
  13242. });
  13243. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13244. auto se = detail::scope_exit([&] {
  13245. svr.stop();
  13246. t.join();
  13247. });
  13248. svr.wait_until_ready();
  13249. SSLClient cli(HOST, PORT);
  13250. cli.enable_server_certificate_verification(false);
  13251. cli.set_connection_timeout(30);
  13252. bool validity_checked = false;
  13253. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13254. if (ctx.cert) {
  13255. time_t not_before = 0, not_after = 0;
  13256. bool result = ctx.validity(not_before, not_after);
  13257. EXPECT_TRUE(result);
  13258. // Verify that not_before < now < not_after for a valid cert
  13259. time_t now = time(nullptr);
  13260. EXPECT_LT(not_before, now);
  13261. EXPECT_GT(not_after, now);
  13262. validity_checked = true;
  13263. }
  13264. return true;
  13265. });
  13266. auto res = cli.Get("/test");
  13267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13268. EXPECT_TRUE(validity_checked);
  13269. }
  13270. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13271. using namespace httplib::tls;
  13272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13273. ASSERT_TRUE(svr.is_valid());
  13274. svr.Get("/test", [](const Request &, Response &res) {
  13275. res.set_content("ok", "text/plain");
  13276. });
  13277. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13278. auto se = detail::scope_exit([&] {
  13279. svr.stop();
  13280. t.join();
  13281. });
  13282. svr.wait_until_ready();
  13283. SSLClient cli(HOST, PORT);
  13284. cli.enable_server_certificate_verification(false);
  13285. cli.set_connection_timeout(30);
  13286. bool serial_checked = false;
  13287. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13288. if (ctx.cert) {
  13289. std::string serial = ctx.serial();
  13290. EXPECT_FALSE(serial.empty());
  13291. // Serial should be a hex string
  13292. for (char c : serial) {
  13293. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13294. (c >= 'a' && c <= 'f'));
  13295. }
  13296. serial_checked = true;
  13297. }
  13298. return true;
  13299. });
  13300. auto res = cli.Get("/test");
  13301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13302. EXPECT_TRUE(serial_checked);
  13303. }
  13304. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13305. // Test 1: Valid CA file - no error should be recorded
  13306. {
  13307. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13308. CLIENT_CA_CERT_FILE);
  13309. ASSERT_TRUE(svr.is_valid());
  13310. // With valid setup, last_ssl_error should be 0
  13311. EXPECT_EQ(0, svr.ssl_last_error());
  13312. }
  13313. // Test 2: Invalid CA file content
  13314. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13315. {
  13316. // Create a temporary file with completely invalid content
  13317. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13318. {
  13319. std::ofstream ofs(temp_invalid_ca);
  13320. ofs << "This is not a certificate file at all\n";
  13321. ofs << "Just plain text content\n";
  13322. }
  13323. // Create server with invalid CA file
  13324. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13325. // Clean up temporary file
  13326. std::remove(temp_invalid_ca);
  13327. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13328. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13329. // Note: SSL_CTX_load_verify_locations typically fails first,
  13330. // but our error handling code path is still exercised
  13331. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13332. }
  13333. }
  13334. TEST(VerifyCallbackTest, VerifyContextFields) {
  13335. using namespace httplib::tls;
  13336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13337. ASSERT_TRUE(svr.is_valid());
  13338. svr.Get("/test", [](const Request &, Response &res) {
  13339. res.set_content("ok", "text/plain");
  13340. });
  13341. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13342. auto se = detail::scope_exit([&] {
  13343. svr.stop();
  13344. t.join();
  13345. });
  13346. svr.wait_until_ready();
  13347. SSLClient cli(HOST, PORT);
  13348. cli.enable_server_certificate_verification(false);
  13349. cli.set_connection_timeout(30);
  13350. int callback_count = 0;
  13351. bool saw_leaf_cert = false;
  13352. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13353. if (ctx.cert) {
  13354. callback_count++;
  13355. // We should see at least one certificate (the leaf)
  13356. std::string cn = ctx.subject_cn();
  13357. if (!cn.empty()) { saw_leaf_cert = true; }
  13358. // Verify context fields are populated
  13359. EXPECT_NE(ctx.session, nullptr);
  13360. EXPECT_GE(ctx.depth, 0);
  13361. }
  13362. return true;
  13363. });
  13364. auto res = cli.Get("/test");
  13365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13366. EXPECT_GT(callback_count, 0);
  13367. EXPECT_TRUE(saw_leaf_cert);
  13368. }
  13369. // A verifier belongs to the client that set it, not to the thread that set it.
  13370. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13371. using namespace httplib::tls;
  13372. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13373. ASSERT_TRUE(svr.is_valid());
  13374. svr.Get("/test", [](const Request &, Response &res) {
  13375. res.set_content("ok", "text/plain");
  13376. });
  13377. auto port = svr.bind_to_any_port(HOST);
  13378. thread t([&]() { svr.listen_after_bind(); });
  13379. auto se = detail::scope_exit([&] {
  13380. svr.stop();
  13381. t.join();
  13382. });
  13383. svr.wait_until_ready();
  13384. auto rejecting_calls = 0;
  13385. SSLClient rejecting(HOST, port);
  13386. rejecting.enable_server_certificate_verification(false);
  13387. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13388. rejecting_calls++;
  13389. return false;
  13390. });
  13391. auto accepting_calls = 0;
  13392. SSLClient accepting(HOST, port);
  13393. accepting.enable_server_certificate_verification(false);
  13394. // Set on another thread than the requests below.
  13395. thread([&]() {
  13396. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13397. accepting_calls++;
  13398. return true;
  13399. });
  13400. }).join();
  13401. // Requested on another thread than the verifier was set on.
  13402. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13403. EXPECT_GT(rejecting_calls, 0);
  13404. auto res = accepting.Get("/test");
  13405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13406. EXPECT_GT(accepting_calls, 0);
  13407. }
  13408. // VerifyContext::session is the same handle the other tls:: functions take.
  13409. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13410. using namespace httplib::tls;
  13411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13412. ASSERT_TRUE(svr.is_valid());
  13413. svr.Get("/test", [](const Request &, Response &res) {
  13414. res.set_content("ok", "text/plain");
  13415. });
  13416. auto port = svr.bind_to_any_port(HOST);
  13417. thread t([&]() { svr.listen_after_bind(); });
  13418. auto se = detail::scope_exit([&] {
  13419. svr.stop();
  13420. t.join();
  13421. });
  13422. svr.wait_until_ready();
  13423. SSLClient cli(HOST, port);
  13424. cli.enable_server_certificate_verification(false);
  13425. session_t verifier_session = nullptr;
  13426. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13427. verifier_session = ctx.session;
  13428. return true;
  13429. });
  13430. session_t session_verifier_session = nullptr;
  13431. cli.set_session_verifier([&](session_t session) {
  13432. session_verifier_session = session;
  13433. return SSLVerifierResponse::NoDecisionMade;
  13434. });
  13435. auto res = cli.Get("/test");
  13436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13437. EXPECT_NE(nullptr, verifier_session);
  13438. EXPECT_EQ(session_verifier_session, verifier_session);
  13439. }
  13440. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13441. using httplib::tls::TlsError;
  13442. // Test that verify_error_to_string returns empty for success
  13443. std::string success_str = TlsError::verify_error_to_string(0);
  13444. EXPECT_TRUE(success_str.empty());
  13445. // Test that verify_error_to_string returns non-empty for error codes
  13446. // Using a common error code (certificate expired)
  13447. std::string error_str =
  13448. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13449. EXPECT_FALSE(error_str.empty());
  13450. }
  13451. TEST(SessionVerifierTest, CertificateAccepted) {
  13452. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13453. ASSERT_TRUE(svr.is_valid());
  13454. svr.Get("/test", [](const Request &, Response &res) {
  13455. res.set_content("ok", "text/plain");
  13456. });
  13457. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13458. auto se = detail::scope_exit([&] {
  13459. svr.stop();
  13460. t.join();
  13461. });
  13462. svr.wait_until_ready();
  13463. SSLClient cli(HOST, PORT);
  13464. cli.enable_server_certificate_verification(false);
  13465. cli.set_connection_timeout(30);
  13466. bool callback_called = false;
  13467. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13468. EXPECT_NE(session, nullptr);
  13469. callback_called = true;
  13470. return SSLVerifierResponse::CertificateAccepted;
  13471. });
  13472. auto res = cli.Get("/test");
  13473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13474. EXPECT_EQ(200, res->status);
  13475. EXPECT_TRUE(callback_called);
  13476. }
  13477. TEST(SessionVerifierTest, CertificateRejected) {
  13478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13479. ASSERT_TRUE(svr.is_valid());
  13480. svr.Get("/test", [](const Request &, Response &res) {
  13481. res.set_content("ok", "text/plain");
  13482. });
  13483. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13484. auto se = detail::scope_exit([&] {
  13485. svr.stop();
  13486. t.join();
  13487. });
  13488. svr.wait_until_ready();
  13489. SSLClient cli(HOST, PORT);
  13490. cli.enable_server_certificate_verification(false);
  13491. cli.set_connection_timeout(30);
  13492. bool callback_called = false;
  13493. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13494. EXPECT_NE(session, nullptr);
  13495. callback_called = true;
  13496. return SSLVerifierResponse::CertificateRejected;
  13497. });
  13498. auto res = cli.Get("/test");
  13499. EXPECT_FALSE(res);
  13500. EXPECT_TRUE(callback_called);
  13501. }
  13502. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13503. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13504. ASSERT_TRUE(svr.is_valid());
  13505. svr.Get("/test", [](const Request &, Response &res) {
  13506. res.set_content("ok", "text/plain");
  13507. });
  13508. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13509. auto se = detail::scope_exit([&] {
  13510. svr.stop();
  13511. t.join();
  13512. });
  13513. svr.wait_until_ready();
  13514. // NoDecisionMade with verification disabled should succeed (no default check)
  13515. SSLClient cli(HOST, PORT);
  13516. cli.enable_server_certificate_verification(false);
  13517. cli.set_connection_timeout(30);
  13518. bool callback_called = false;
  13519. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13520. EXPECT_NE(session, nullptr);
  13521. callback_called = true;
  13522. return SSLVerifierResponse::NoDecisionMade;
  13523. });
  13524. auto res = cli.Get("/test");
  13525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13526. EXPECT_EQ(200, res->status);
  13527. EXPECT_TRUE(callback_called);
  13528. }
  13529. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13530. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13531. ASSERT_TRUE(svr.is_valid());
  13532. svr.Get("/test", [](const Request &, Response &res) {
  13533. res.set_content("ok", "text/plain");
  13534. });
  13535. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13536. auto se = detail::scope_exit([&] {
  13537. svr.stop();
  13538. t.join();
  13539. });
  13540. svr.wait_until_ready();
  13541. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13542. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13543. // so we only check that the request fails, not whether the callback was
  13544. // called.
  13545. SSLClient cli(HOST, PORT);
  13546. cli.enable_server_certificate_verification(true);
  13547. cli.set_connection_timeout(30);
  13548. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13549. EXPECT_NE(session, nullptr);
  13550. return SSLVerifierResponse::NoDecisionMade;
  13551. });
  13552. auto res = cli.Get("/test");
  13553. EXPECT_FALSE(res);
  13554. }
  13555. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13556. // Test SSL server using PemMemory constructor with client CA certificates
  13557. // Read PEM files
  13558. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13559. read_file(SERVER_CERT_FILE, server_cert_pem);
  13560. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13561. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13562. // Create SSLServer with PemMemory constructor including client CA
  13563. SSLServer::PemMemory server_pem = {
  13564. server_cert_pem.c_str(),
  13565. server_cert_pem.size(),
  13566. server_key_pem.c_str(),
  13567. server_key_pem.size(),
  13568. client_ca_pem.c_str(),
  13569. client_ca_pem.size(),
  13570. nullptr // no password for server key
  13571. };
  13572. SSLServer svr(server_pem);
  13573. ASSERT_TRUE(svr.is_valid());
  13574. // No SSL error should be recorded for valid setup
  13575. EXPECT_EQ(0, svr.ssl_last_error());
  13576. // Set up server endpoints
  13577. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13578. res.set_content("ok", "text/plain");
  13579. });
  13580. // Start server in a thread
  13581. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13582. svr.wait_until_ready();
  13583. // Connect with client certificate (using constructor with paths)
  13584. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13585. cli.enable_server_certificate_verification(false);
  13586. auto res = cli.Get("/test-pem-ca");
  13587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13588. EXPECT_EQ(200, res->status);
  13589. EXPECT_EQ("ok", res->body);
  13590. svr.stop();
  13591. server_thread.join();
  13592. }
  13593. #endif
  13594. #ifdef _WIN32
  13595. TEST(CleanupTest, WSACleanup) {
  13596. int ret = WSACleanup();
  13597. ASSERT_EQ(0, ret);
  13598. }
  13599. #endif
  13600. #ifndef CPPHTTPLIB_SSL_ENABLED
  13601. TEST(NoSSLSupport, SimpleInterface) {
  13602. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13603. }
  13604. #endif
  13605. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13606. TEST(InvalidScheme, SimpleInterface) {
  13607. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13608. }
  13609. #endif
  13610. TEST(NoScheme, SimpleInterface) {
  13611. Client cli("yahoo.com:80");
  13612. ASSERT_TRUE(cli.is_valid());
  13613. }
  13614. TEST(SendAPI, SimpleInterface_Online) {
  13615. Client cli("http://yahoo.com");
  13616. Request req;
  13617. req.method = "GET";
  13618. req.path = "/";
  13619. auto res = cli.send(req);
  13620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13621. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13622. }
  13623. TEST(SendAPI, WithParamsInRequest) {
  13624. Server svr;
  13625. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13626. EXPECT_TRUE(req.has_param("test"));
  13627. EXPECT_EQ("test_value", req.get_param_value("test"));
  13628. });
  13629. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13630. auto se = detail::scope_exit([&] {
  13631. svr.stop();
  13632. t.join();
  13633. ASSERT_FALSE(svr.is_running());
  13634. });
  13635. svr.wait_until_ready();
  13636. Client cli(HOST, PORT);
  13637. {
  13638. Request req;
  13639. req.method = "GET";
  13640. req.path = "/";
  13641. req.params.emplace("test", "test_value");
  13642. auto res = cli.send(req);
  13643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13644. }
  13645. {
  13646. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13648. }
  13649. }
  13650. TEST(ClientImplMethods, GetSocketTest) {
  13651. httplib::Server svr;
  13652. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13653. res.status = StatusCode::OK_200;
  13654. });
  13655. auto port = svr.bind_to_any_port("127.0.0.1");
  13656. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13657. auto se = detail::scope_exit([&] {
  13658. svr.stop();
  13659. thread.join();
  13660. ASSERT_FALSE(svr.is_running());
  13661. });
  13662. svr.wait_until_ready();
  13663. {
  13664. httplib::Client cli("127.0.0.1", port);
  13665. cli.set_keep_alive(true);
  13666. // Use the behavior of cpp-httplib of opening the connection
  13667. // only when the first request happens. If that changes,
  13668. // this test would be obsolete.
  13669. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13670. // This also implicitly tests the server. But other tests would fail much
  13671. // earlier than this one to be considered.
  13672. auto res = cli.Get("/");
  13673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13674. EXPECT_EQ(StatusCode::OK_200, res->status);
  13675. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13676. }
  13677. }
  13678. #ifdef CPPHTTPLIB_SSL_ENABLED
  13679. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13680. Client cli("http://yahoo.com");
  13681. auto res = cli.Get("/");
  13682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13683. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13684. cli.set_follow_location(true);
  13685. res = cli.Get("/");
  13686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13687. EXPECT_EQ(StatusCode::OK_200, res->status);
  13688. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13689. }
  13690. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13691. Client cli("https://yahoo.com");
  13692. auto res = cli.Get("/");
  13693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13694. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13695. cli.set_follow_location(true);
  13696. res = cli.Get("/");
  13697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13698. EXPECT_EQ(StatusCode::OK_200, res->status);
  13699. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13700. }
  13701. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13702. Client cli("https://yahoo.com");
  13703. auto res = cli.Get("/");
  13704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13705. ASSERT_FALSE(!res);
  13706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13707. ASSERT_FALSE(res == nullptr);
  13708. ASSERT_TRUE(res != nullptr);
  13709. EXPECT_EQ(Error::Success, res.error());
  13710. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13711. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13712. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13713. cli.set_follow_location(true);
  13714. res = cli.Get("/");
  13715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13716. EXPECT_EQ(Error::Success, res.error());
  13717. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13718. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13719. EXPECT_EQ(StatusCode::OK_200, res->status);
  13720. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13721. }
  13722. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13723. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13724. Client cli("https://cdnjs.cloudflare.com");
  13725. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13726. Headers{{"Accept-Encoding", "br"}});
  13727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13728. EXPECT_EQ(StatusCode::OK_200, res->status);
  13729. EXPECT_EQ(287630U, res->body.size());
  13730. EXPECT_EQ("application/javascript; charset=utf-8",
  13731. res->get_header_value("Content-Type"));
  13732. }
  13733. #endif
  13734. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13735. #undef REDIR_HOST // Silence compiler warning
  13736. #define REDIR_HOST "https://httpbingo.org"
  13737. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13738. Client cli(REDIR_HOST);
  13739. cli.set_follow_location(true);
  13740. auto res =
  13741. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13743. EXPECT_EQ(StatusCode::OK_200, res->status);
  13744. }
  13745. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13746. Client cli(REDIR_HOST);
  13747. cli.set_follow_location(true);
  13748. Params params;
  13749. params.emplace("url", "http://example.com");
  13750. params.emplace("status_code", "302");
  13751. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13753. EXPECT_EQ(StatusCode::OK_200, res->status);
  13754. }
  13755. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13756. Client cli(REDIR_HOST);
  13757. cli.set_follow_location(true);
  13758. Params params;
  13759. params.emplace("url", "http://example.com");
  13760. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13762. EXPECT_EQ(StatusCode::OK_200, res->status);
  13763. }
  13764. TEST(HttpToHttpsRedirectTest, CertFile) {
  13765. auto ssl_port = PORT + 1;
  13766. Server svr;
  13767. ASSERT_TRUE(svr.is_valid());
  13768. svr.Get("/index", [&](const Request &, Response &res) {
  13769. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13770. "/index");
  13771. svr.stop();
  13772. });
  13773. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13774. ASSERT_TRUE(ssl_svr.is_valid());
  13775. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13776. res.set_content("test", "text/plain");
  13777. ssl_svr.stop();
  13778. });
  13779. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13780. thread t2 =
  13781. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13782. auto se = detail::scope_exit([&] {
  13783. t2.join();
  13784. t.join();
  13785. ASSERT_FALSE(svr.is_running());
  13786. });
  13787. svr.wait_until_ready();
  13788. ssl_svr.wait_until_ready();
  13789. Client cli("127.0.0.1", PORT);
  13790. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13791. cli.enable_server_certificate_verification(true);
  13792. cli.set_follow_location(true);
  13793. cli.set_connection_timeout(30);
  13794. auto res = cli.Get("/index");
  13795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13796. ASSERT_EQ(StatusCode::OK_200, res->status);
  13797. }
  13798. TEST(SSLClientRedirectTest, CertFile) {
  13799. auto ssl_port = PORT + 1;
  13800. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13801. ASSERT_TRUE(ssl_svr1.is_valid());
  13802. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13803. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13804. "/index");
  13805. ssl_svr1.stop();
  13806. });
  13807. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13808. ASSERT_TRUE(ssl_svr2.is_valid());
  13809. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13810. res.set_content("test", "text/plain");
  13811. ssl_svr2.stop();
  13812. });
  13813. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13814. thread t2 =
  13815. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13816. auto se = detail::scope_exit([&] {
  13817. t2.join();
  13818. t.join();
  13819. ASSERT_FALSE(ssl_svr1.is_running());
  13820. });
  13821. ssl_svr1.wait_until_ready();
  13822. ssl_svr2.wait_until_ready();
  13823. SSLClient cli("127.0.0.1", PORT);
  13824. std::string cert;
  13825. read_file(SERVER_CERT2_FILE, cert);
  13826. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13827. cli.enable_server_certificate_verification(true);
  13828. cli.set_follow_location(true);
  13829. cli.set_connection_timeout(30);
  13830. auto res = cli.Get("/index");
  13831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13832. ASSERT_EQ(StatusCode::OK_200, res->status);
  13833. }
  13834. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  13835. // another port, so the client follows it with a new client.
  13836. static Result GetThroughTlsRedirectToDifferentPort(
  13837. const std::function<void(SSLClient &)> &setup,
  13838. const char *target_cert = SERVER_CERT2_FILE) {
  13839. auto ssl_port = PORT + 1;
  13840. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13841. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13842. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13843. "/index");
  13844. });
  13845. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  13846. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13847. res.set_content("test", "text/plain");
  13848. });
  13849. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  13850. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  13851. auto se = detail::scope_exit([&] {
  13852. ssl_svr2.stop();
  13853. ssl_svr1.stop();
  13854. t2.join();
  13855. t.join();
  13856. });
  13857. ssl_svr1.wait_until_ready();
  13858. ssl_svr2.wait_until_ready();
  13859. SSLClient cli("127.0.0.1", PORT);
  13860. cli.set_follow_location(true);
  13861. cli.set_connection_timeout(30);
  13862. setup(cli);
  13863. return cli.Get("/index");
  13864. }
  13865. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  13866. auto calls = 0;
  13867. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  13868. cli.enable_server_certificate_verification(false);
  13869. // Accept the first server only.
  13870. cli.set_session_verifier([&](tls::session_t) {
  13871. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  13872. : SSLVerifierResponse::CertificateRejected;
  13873. });
  13874. });
  13875. EXPECT_FALSE(res);
  13876. EXPECT_EQ(2, calls);
  13877. }
  13878. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  13879. std::string pinned;
  13880. auto res = GetThroughTlsRedirectToDifferentPort(
  13881. [&](SSLClient &cli) {
  13882. cli.enable_server_certificate_verification(false);
  13883. // Pin the first certificate seen.
  13884. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  13885. if (pinned.empty()) { pinned = ctx.serial(); }
  13886. return ctx.serial() == pinned;
  13887. });
  13888. },
  13889. // A certificate other than the first server's.
  13890. SERVER_CERT_FILE);
  13891. EXPECT_FALSE(res);
  13892. EXPECT_FALSE(pinned.empty());
  13893. }
  13894. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  13895. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  13896. std::string cert;
  13897. read_file(SERVER_CERT2_FILE, cert);
  13898. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13899. });
  13900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13901. EXPECT_EQ(StatusCode::OK_200, res->status);
  13902. }
  13903. #endif
  13904. #ifdef CPPHTTPLIB_SSL_ENABLED
  13905. // Test that set_ca_cert_store() skips system certs (consistent with
  13906. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13907. // should be trusted - system certs should NOT be loaded.
  13908. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13909. // Load a specific cert that is NOT a system CA cert
  13910. std::string cert;
  13911. read_file(SERVER_CERT2_FILE, cert);
  13912. SSLClient cli("google.com");
  13913. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13914. cli.enable_server_certificate_verification(true);
  13915. // This should FAIL because:
  13916. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13917. // 2. System certs should NOT be loaded when custom store is set
  13918. // If system certs WERE loaded, this would succeed
  13919. auto res = cli.Get("/");
  13920. ASSERT_FALSE(res);
  13921. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13922. }
  13923. // Same as above, but through the native store handle path. Regression test:
  13924. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13925. // merged system certs into the user-provided store.
  13926. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13927. std::string cert;
  13928. read_file(SERVER_CERT2_FILE, cert);
  13929. SSLClient cli("google.com");
  13930. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13931. cli.enable_server_certificate_verification(true);
  13932. auto res = cli.Get("/");
  13933. ASSERT_FALSE(res);
  13934. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13935. }
  13936. // A custom store set via the native handle must still verify a server whose
  13937. // cert it does contain.
  13938. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13939. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13940. ASSERT_TRUE(svr.is_valid());
  13941. svr.Get("/test", [&](const Request &, Response &res) {
  13942. res.set_content("test", "text/plain");
  13943. });
  13944. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13945. auto se = detail::scope_exit([&] {
  13946. svr.stop();
  13947. t.join();
  13948. ASSERT_FALSE(svr.is_running());
  13949. });
  13950. svr.wait_until_ready();
  13951. SSLClient cli("127.0.0.1", PORT);
  13952. std::string cert;
  13953. read_file(SERVER_CERT2_FILE, cert);
  13954. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13955. cli.enable_server_certificate_verification(true);
  13956. cli.set_connection_timeout(30);
  13957. auto res = cli.Get("/test");
  13958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13959. ASSERT_EQ(StatusCode::OK_200, res->status);
  13960. }
  13961. // CA certs loaded through the universal Client must be transferred to the
  13962. // client created internally for following an HTTPS redirect. Regression test:
  13963. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13964. // the CA data for redirect transfer.
  13965. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13966. auto ssl_port = PORT + 1;
  13967. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13968. ASSERT_TRUE(ssl_svr1.is_valid());
  13969. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13970. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13971. "/index");
  13972. });
  13973. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13974. ASSERT_TRUE(ssl_svr2.is_valid());
  13975. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13976. res.set_content("test", "text/plain");
  13977. });
  13978. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13979. thread t2 =
  13980. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13981. auto se = detail::scope_exit([&] {
  13982. ssl_svr2.stop();
  13983. ssl_svr1.stop();
  13984. t2.join();
  13985. t.join();
  13986. ASSERT_FALSE(ssl_svr1.is_running());
  13987. });
  13988. ssl_svr1.wait_until_ready();
  13989. ssl_svr2.wait_until_ready();
  13990. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13991. std::string cert;
  13992. read_file(SERVER_CERT2_FILE, cert);
  13993. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13994. cli.enable_server_certificate_verification(true);
  13995. cli.set_follow_location(true);
  13996. cli.set_connection_timeout(30);
  13997. auto res = cli.Get("/index");
  13998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13999. ASSERT_EQ(StatusCode::OK_200, res->status);
  14000. }
  14001. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14002. // so a host signed by a system CA verifies even though a custom CA is set
  14003. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14004. std::string cert;
  14005. read_file(SERVER_CERT2_FILE, cert);
  14006. SSLClient cli("google.com");
  14007. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14008. cli.enable_system_ca(true);
  14009. cli.enable_server_certificate_verification(true);
  14010. auto res = cli.Get("/");
  14011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14012. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14013. }
  14014. // The custom CA remains effective when combined with the system CA
  14015. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14016. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14017. ASSERT_TRUE(svr.is_valid());
  14018. svr.Get("/test", [&](const Request &, Response &res) {
  14019. res.set_content("test", "text/plain");
  14020. });
  14021. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14022. auto se = detail::scope_exit([&] {
  14023. svr.stop();
  14024. t.join();
  14025. ASSERT_FALSE(svr.is_running());
  14026. });
  14027. svr.wait_until_ready();
  14028. SSLClient cli("127.0.0.1", PORT);
  14029. std::string cert;
  14030. read_file(SERVER_CERT2_FILE, cert);
  14031. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14032. cli.enable_system_ca(true);
  14033. cli.enable_server_certificate_verification(true);
  14034. cli.set_connection_timeout(30);
  14035. auto res = cli.Get("/test");
  14036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14037. ASSERT_EQ(StatusCode::OK_200, res->status);
  14038. }
  14039. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14040. // skip chain verification entirely (only the certificate identity was
  14041. // checked), so a server presenting an untrusted certificate with a matching
  14042. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14043. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14044. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14045. ASSERT_TRUE(svr.is_valid());
  14046. svr.Get("/test", [&](const Request &, Response &res) {
  14047. res.set_content("test", "text/plain");
  14048. });
  14049. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14050. auto se = detail::scope_exit([&] {
  14051. svr.stop();
  14052. t.join();
  14053. ASSERT_FALSE(svr.is_running());
  14054. });
  14055. svr.wait_until_ready();
  14056. SSLClient cli("127.0.0.1", PORT);
  14057. std::string cert;
  14058. // A trusted CA that did not sign the server certificate. The server cert
  14059. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14060. // this connection.
  14061. read_file(CLIENT_CA_CERT_FILE, cert);
  14062. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14063. cli.enable_server_certificate_verification(true);
  14064. cli.set_connection_timeout(30);
  14065. auto res = cli.Get("/test");
  14066. ASSERT_FALSE(res);
  14067. }
  14068. // enable_system_ca(false) prevents system CA loading entirely
  14069. TEST(SSLClientTest, DisableSystemCa_Online) {
  14070. SSLClient cli("google.com");
  14071. cli.enable_system_ca(false);
  14072. cli.enable_server_certificate_verification(true);
  14073. auto res = cli.Get("/");
  14074. ASSERT_FALSE(res);
  14075. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14076. // itself when the CA chain is empty
  14077. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14078. res.error() == Error::SSLConnection);
  14079. }
  14080. // The universal Client forwards enable_system_ca()
  14081. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14082. std::string cert;
  14083. read_file(SERVER_CERT2_FILE, cert);
  14084. Client cli("https://google.com");
  14085. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14086. cli.enable_system_ca(true);
  14087. cli.enable_server_certificate_verification(true);
  14088. auto res = cli.Get("/");
  14089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14090. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14091. }
  14092. // The system CA policy must carry over to the client created internally for
  14093. // following a cross-host HTTPS redirect
  14094. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14095. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14096. ASSERT_TRUE(svr.is_valid());
  14097. svr.Get("/index", [&](const Request &, Response &res) {
  14098. res.set_redirect("https://www.google.com/");
  14099. });
  14100. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14101. auto se = detail::scope_exit([&] {
  14102. svr.stop();
  14103. t.join();
  14104. ASSERT_FALSE(svr.is_running());
  14105. });
  14106. svr.wait_until_ready();
  14107. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14108. std::string cert;
  14109. read_file(SERVER_CERT2_FILE, cert);
  14110. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14111. cli.enable_system_ca(true);
  14112. cli.enable_server_certificate_verification(true);
  14113. cli.set_follow_location(true);
  14114. cli.set_connection_timeout(30);
  14115. // Receiving any response proves the redirect client completed the TLS
  14116. // handshake with a system-CA-signed host
  14117. auto res = cli.Get("/index");
  14118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14119. }
  14120. TEST(MultipartFormDataTest, LargeData) {
  14121. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14122. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14123. const ContentReader &content_reader) {
  14124. if (req.is_multipart_form_data()) {
  14125. std::vector<FormData> items;
  14126. content_reader(
  14127. [&](const FormData &file) {
  14128. items.push_back(file);
  14129. return true;
  14130. },
  14131. [&](const char *data, size_t data_length) {
  14132. items.back().content.append(data, data_length);
  14133. return true;
  14134. });
  14135. EXPECT_TRUE(std::string(items[0].name) == "document");
  14136. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14137. EXPECT_TRUE(items[0].filename == "2MB_data");
  14138. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14139. EXPECT_TRUE(items[1].name == "hello");
  14140. EXPECT_TRUE(items[1].content == "world");
  14141. EXPECT_TRUE(items[1].filename == "");
  14142. EXPECT_TRUE(items[1].content_type == "");
  14143. } else {
  14144. std::string body;
  14145. content_reader([&](const char *data, size_t data_length) {
  14146. body.append(data, data_length);
  14147. return true;
  14148. });
  14149. }
  14150. });
  14151. auto port = svr.bind_to_any_port(HOST);
  14152. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14153. auto se = detail::scope_exit([&] {
  14154. svr.stop();
  14155. t.join();
  14156. ASSERT_FALSE(svr.is_running());
  14157. });
  14158. svr.wait_until_ready();
  14159. {
  14160. std::string data(1024 * 1024 * 2, '.');
  14161. std::stringstream buffer;
  14162. buffer << data;
  14163. SSLClient cli(HOST, port);
  14164. cli.enable_server_certificate_verification(false);
  14165. UploadFormDataItems items{
  14166. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14167. {"hello", "world", "", ""},
  14168. };
  14169. auto res = cli.Post("/post", items);
  14170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14171. ASSERT_EQ(StatusCode::OK_200, res->status);
  14172. }
  14173. }
  14174. TEST(MultipartFormDataTest, DataProviderItems) {
  14175. std::random_device seed_gen;
  14176. std::mt19937 random(seed_gen());
  14177. std::string rand1;
  14178. rand1.resize(1000);
  14179. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14180. std::string rand2;
  14181. rand2.resize(3000);
  14182. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14183. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14184. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14185. const ContentReader &content_reader) {
  14186. ASSERT_FALSE(req.is_multipart_form_data());
  14187. std::string body;
  14188. content_reader([&](const char *data, size_t data_length) {
  14189. body.append(data, data_length);
  14190. return true;
  14191. });
  14192. EXPECT_EQ(body, "");
  14193. });
  14194. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14195. const ContentReader &content_reader) {
  14196. ASSERT_TRUE(req.is_multipart_form_data());
  14197. std::vector<FormData> items;
  14198. content_reader(
  14199. [&](const FormData &file) {
  14200. items.push_back(file);
  14201. return true;
  14202. },
  14203. [&](const char *data, size_t data_length) {
  14204. items.back().content.append(data, data_length);
  14205. return true;
  14206. });
  14207. ASSERT_TRUE(items.size() == 2);
  14208. EXPECT_EQ(std::string(items[0].name), "name1");
  14209. EXPECT_EQ(items[0].content, "Testing123");
  14210. EXPECT_EQ(items[0].filename, "filename1");
  14211. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14212. EXPECT_EQ(items[1].name, "name2");
  14213. EXPECT_EQ(items[1].content, "Testing456");
  14214. EXPECT_EQ(items[1].filename, "");
  14215. EXPECT_EQ(items[1].content_type, "");
  14216. });
  14217. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14218. const ContentReader &content_reader) {
  14219. ASSERT_TRUE(req.is_multipart_form_data());
  14220. std::vector<FormData> items;
  14221. content_reader(
  14222. [&](const FormData &file) {
  14223. items.push_back(file);
  14224. return true;
  14225. },
  14226. [&](const char *data, size_t data_length) {
  14227. items.back().content.append(data, data_length);
  14228. return true;
  14229. });
  14230. ASSERT_TRUE(items.size() == 2);
  14231. EXPECT_EQ(items[0].name, "name3");
  14232. EXPECT_EQ(items[0].content, rand1);
  14233. EXPECT_EQ(items[0].filename, "filename3");
  14234. EXPECT_EQ(items[0].content_type, "");
  14235. EXPECT_EQ(items[1].name, "name4");
  14236. EXPECT_EQ(items[1].content, rand2);
  14237. EXPECT_EQ(items[1].filename, "filename4");
  14238. EXPECT_EQ(items[1].content_type, "");
  14239. });
  14240. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14241. const ContentReader &content_reader) {
  14242. ASSERT_TRUE(req.is_multipart_form_data());
  14243. std::vector<FormData> items;
  14244. content_reader(
  14245. [&](const FormData &file) {
  14246. items.push_back(file);
  14247. return true;
  14248. },
  14249. [&](const char *data, size_t data_length) {
  14250. items.back().content.append(data, data_length);
  14251. return true;
  14252. });
  14253. ASSERT_TRUE(items.size() == 4);
  14254. EXPECT_EQ(std::string(items[0].name), "name1");
  14255. EXPECT_EQ(items[0].content, "Testing123");
  14256. EXPECT_EQ(items[0].filename, "filename1");
  14257. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14258. EXPECT_EQ(items[1].name, "name2");
  14259. EXPECT_EQ(items[1].content, "Testing456");
  14260. EXPECT_EQ(items[1].filename, "");
  14261. EXPECT_EQ(items[1].content_type, "");
  14262. EXPECT_EQ(items[2].name, "name3");
  14263. EXPECT_EQ(items[2].content, rand1);
  14264. EXPECT_EQ(items[2].filename, "filename3");
  14265. EXPECT_EQ(items[2].content_type, "");
  14266. EXPECT_EQ(items[3].name, "name4");
  14267. EXPECT_EQ(items[3].content, rand2);
  14268. EXPECT_EQ(items[3].filename, "filename4");
  14269. EXPECT_EQ(items[3].content_type, "");
  14270. });
  14271. auto port = svr.bind_to_any_port("localhost");
  14272. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14273. auto se = detail::scope_exit([&] {
  14274. svr.stop();
  14275. t.join();
  14276. ASSERT_FALSE(svr.is_running());
  14277. });
  14278. svr.wait_until_ready();
  14279. {
  14280. SSLClient cli("localhost", port);
  14281. cli.enable_server_certificate_verification(false);
  14282. UploadFormDataItems items{
  14283. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14284. {"name2", "Testing456", "", ""}, // not a file
  14285. };
  14286. {
  14287. auto res = cli.Post("/post-none", {}, {}, {});
  14288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14289. ASSERT_EQ(StatusCode::OK_200, res->status);
  14290. }
  14291. FormDataProviderItems providers;
  14292. {
  14293. auto res =
  14294. cli.Post("/post-items", {}, items, providers); // empty providers
  14295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14296. ASSERT_EQ(StatusCode::OK_200, res->status);
  14297. }
  14298. providers.push_back({"name3",
  14299. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14300. // test the offset is given correctly at each step
  14301. if (!offset)
  14302. sink.os.write(rand1.data(), 30);
  14303. else if (offset == 30)
  14304. sink.os.write(rand1.data() + 30, 300);
  14305. else if (offset == 330)
  14306. sink.os.write(rand1.data() + 330, 670);
  14307. else if (offset == rand1.size())
  14308. sink.done();
  14309. return true;
  14310. },
  14311. "filename3",
  14312. {}});
  14313. providers.push_back({"name4",
  14314. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14315. // test the offset is given correctly at each step
  14316. if (!offset)
  14317. sink.os.write(rand2.data(), 2000);
  14318. else if (offset == 2000)
  14319. sink.os.write(rand2.data() + 2000, 1);
  14320. else if (offset == 2001)
  14321. sink.os.write(rand2.data() + 2001, 999);
  14322. else if (offset == rand2.size())
  14323. sink.done();
  14324. return true;
  14325. },
  14326. "filename4",
  14327. {}});
  14328. {
  14329. auto res = cli.Post("/post-providers", {}, {}, providers);
  14330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14331. ASSERT_EQ(StatusCode::OK_200, res->status);
  14332. }
  14333. {
  14334. auto res = cli.Post("/post-both", {}, items, providers);
  14335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14336. ASSERT_EQ(StatusCode::OK_200, res->status);
  14337. }
  14338. }
  14339. }
  14340. TEST(MultipartFormDataTest, BadHeader) {
  14341. Server svr;
  14342. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14343. res.set_content("ok", "text/plain");
  14344. });
  14345. thread t = thread([&] { svr.listen(HOST, PORT); });
  14346. auto se = detail::scope_exit([&] {
  14347. svr.stop();
  14348. t.join();
  14349. ASSERT_FALSE(svr.is_running());
  14350. });
  14351. svr.wait_until_ready();
  14352. const std::string body =
  14353. "This is the preamble. It is to be ignored, though it\r\n"
  14354. "is a handy place for composition agents to include an\r\n"
  14355. "explanatory note to non-MIME conformant readers.\r\n"
  14356. "\r\n"
  14357. "\r\n"
  14358. "--simple boundary\r\n"
  14359. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14360. ": BAD...\r\n"
  14361. "\r\n"
  14362. "value1\r\n"
  14363. "--simple boundary\r\n"
  14364. "Content-Disposition: form-data; name=\"field2\"; "
  14365. "filename=\"example.txt\"\r\n"
  14366. "\r\n"
  14367. "value2\r\n"
  14368. "--simple boundary--\r\n"
  14369. "This is the epilogue. It is also to be ignored.\r\n";
  14370. std::string content_type =
  14371. R"(multipart/form-data; boundary="simple boundary")";
  14372. Client cli(HOST, PORT);
  14373. auto res = cli.Post("/post", body, content_type.c_str());
  14374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14375. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14376. }
  14377. TEST(MultipartFormDataTest, WithPreamble) {
  14378. Server svr;
  14379. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14380. res.set_content("ok", "text/plain");
  14381. });
  14382. thread t = thread([&] { svr.listen(HOST, PORT); });
  14383. auto se = detail::scope_exit([&] {
  14384. svr.stop();
  14385. t.join();
  14386. ASSERT_FALSE(svr.is_running());
  14387. });
  14388. svr.wait_until_ready();
  14389. const std::string body =
  14390. "This is the preamble. It is to be ignored, though it\r\n"
  14391. "is a handy place for composition agents to include an\r\n"
  14392. "explanatory note to non-MIME conformant readers.\r\n"
  14393. "\r\n"
  14394. "\r\n"
  14395. "--simple boundary\r\n"
  14396. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14397. "\r\n"
  14398. "value1\r\n"
  14399. "--simple boundary\r\n"
  14400. "Content-Disposition: form-data; name=\"field2\"; "
  14401. "filename=\"example.txt\"\r\n"
  14402. "\r\n"
  14403. "value2\r\n"
  14404. "--simple boundary--\r\n"
  14405. "This is the epilogue. It is also to be ignored.\r\n";
  14406. std::string content_type =
  14407. R"(multipart/form-data; boundary="simple boundary")";
  14408. Client cli(HOST, PORT);
  14409. auto res = cli.Post("/post", body, content_type.c_str());
  14410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14411. EXPECT_EQ(StatusCode::OK_200, res->status);
  14412. }
  14413. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14414. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14415. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14416. const ContentReader &content_reader) {
  14417. if (req.is_multipart_form_data()) {
  14418. std::vector<FormData> items;
  14419. content_reader(
  14420. [&](const FormData &file) {
  14421. items.push_back(file);
  14422. return true;
  14423. },
  14424. [&](const char *data, size_t data_length) {
  14425. items.back().content.append(data, data_length);
  14426. return true;
  14427. });
  14428. EXPECT_TRUE(std::string(items[0].name) == "document");
  14429. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14430. EXPECT_TRUE(items[0].filename == "2MB_data");
  14431. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14432. EXPECT_TRUE(items[1].name == "hello");
  14433. EXPECT_TRUE(items[1].content == "world");
  14434. EXPECT_TRUE(items[1].filename == "");
  14435. EXPECT_TRUE(items[1].content_type == "");
  14436. } else {
  14437. std::string body;
  14438. content_reader([&](const char *data, size_t data_length) {
  14439. body.append(data, data_length);
  14440. return true;
  14441. });
  14442. }
  14443. });
  14444. auto port = svr.bind_to_any_port("localhost");
  14445. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14446. auto se = detail::scope_exit([&] {
  14447. svr.stop();
  14448. t.join();
  14449. ASSERT_FALSE(svr.is_running());
  14450. });
  14451. svr.wait_until_ready();
  14452. {
  14453. std::string data(1024 * 1024 * 2, '.');
  14454. std::stringstream buffer;
  14455. buffer << data;
  14456. SSLClient cli("localhost", port);
  14457. cli.enable_server_certificate_verification(false);
  14458. UploadFormDataItems items{
  14459. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14460. {"hello", "world", "", ""},
  14461. };
  14462. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14464. ASSERT_EQ(StatusCode::OK_200, res->status);
  14465. }
  14466. }
  14467. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14468. std::string data(1024 * 1024 * 2, '&');
  14469. std::stringstream buffer;
  14470. buffer << data;
  14471. Client cli("https://localhost:8080");
  14472. UploadFormDataItems items{
  14473. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14474. {"hello", "world", "", ""},
  14475. };
  14476. for (const char &c : " \t\r\n") {
  14477. auto res =
  14478. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14479. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14480. ASSERT_FALSE(res);
  14481. }
  14482. }
  14483. TEST(MultipartFormDataTest, PutFormData) {
  14484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14485. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14486. const ContentReader &content_reader) {
  14487. if (req.is_multipart_form_data()) {
  14488. std::vector<FormData> items;
  14489. content_reader(
  14490. [&](const FormData &file) {
  14491. items.push_back(file);
  14492. return true;
  14493. },
  14494. [&](const char *data, size_t data_length) {
  14495. items.back().content.append(data, data_length);
  14496. return true;
  14497. });
  14498. EXPECT_TRUE(std::string(items[0].name) == "document");
  14499. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14500. EXPECT_TRUE(items[0].filename == "2MB_data");
  14501. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14502. EXPECT_TRUE(items[1].name == "hello");
  14503. EXPECT_TRUE(items[1].content == "world");
  14504. EXPECT_TRUE(items[1].filename == "");
  14505. EXPECT_TRUE(items[1].content_type == "");
  14506. } else {
  14507. std::string body;
  14508. content_reader([&](const char *data, size_t data_length) {
  14509. body.append(data, data_length);
  14510. return true;
  14511. });
  14512. }
  14513. });
  14514. auto port = svr.bind_to_any_port("localhost");
  14515. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14516. auto se = detail::scope_exit([&] {
  14517. svr.stop();
  14518. t.join();
  14519. ASSERT_FALSE(svr.is_running());
  14520. });
  14521. svr.wait_until_ready();
  14522. {
  14523. std::string data(1024 * 1024 * 2, '&');
  14524. std::stringstream buffer;
  14525. buffer << data;
  14526. SSLClient cli("localhost", port);
  14527. cli.enable_server_certificate_verification(false);
  14528. UploadFormDataItems items{
  14529. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14530. {"hello", "world", "", ""},
  14531. };
  14532. auto res = cli.Put("/put", items);
  14533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14534. ASSERT_EQ(StatusCode::OK_200, res->status);
  14535. }
  14536. }
  14537. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14539. svr.Put("/put_customboundary",
  14540. [&](const Request &req, const Response & /*res*/,
  14541. const ContentReader &content_reader) {
  14542. if (req.is_multipart_form_data()) {
  14543. std::vector<FormData> items;
  14544. content_reader(
  14545. [&](const FormData &file) {
  14546. items.push_back(file);
  14547. return true;
  14548. },
  14549. [&](const char *data, size_t data_length) {
  14550. items.back().content.append(data, data_length);
  14551. return true;
  14552. });
  14553. EXPECT_TRUE(std::string(items[0].name) == "document");
  14554. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14555. EXPECT_TRUE(items[0].filename == "2MB_data");
  14556. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14557. EXPECT_TRUE(items[1].name == "hello");
  14558. EXPECT_TRUE(items[1].content == "world");
  14559. EXPECT_TRUE(items[1].filename == "");
  14560. EXPECT_TRUE(items[1].content_type == "");
  14561. } else {
  14562. std::string body;
  14563. content_reader([&](const char *data, size_t data_length) {
  14564. body.append(data, data_length);
  14565. return true;
  14566. });
  14567. }
  14568. });
  14569. auto port = svr.bind_to_any_port("localhost");
  14570. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14571. auto se = detail::scope_exit([&] {
  14572. svr.stop();
  14573. t.join();
  14574. ASSERT_FALSE(svr.is_running());
  14575. });
  14576. svr.wait_until_ready();
  14577. {
  14578. std::string data(1024 * 1024 * 2, '&');
  14579. std::stringstream buffer;
  14580. buffer << data;
  14581. SSLClient cli("localhost", port);
  14582. cli.enable_server_certificate_verification(false);
  14583. UploadFormDataItems items{
  14584. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14585. {"hello", "world", "", ""},
  14586. };
  14587. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14589. ASSERT_EQ(StatusCode::OK_200, res->status);
  14590. }
  14591. }
  14592. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14593. std::string data(1024 * 1024 * 2, '&');
  14594. std::stringstream buffer;
  14595. buffer << data;
  14596. Client cli("https://localhost:8080");
  14597. cli.enable_server_certificate_verification(false);
  14598. UploadFormDataItems items{
  14599. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14600. {"hello", "world", "", ""},
  14601. };
  14602. for (const char &c : " \t\r\n") {
  14603. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14604. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14605. ASSERT_FALSE(res);
  14606. }
  14607. }
  14608. TEST(MultipartFormDataTest, AlternateFilename) {
  14609. auto handled = false;
  14610. Server svr;
  14611. svr.Post("/test", [&](const Request &req, Response &res) {
  14612. ASSERT_EQ(2u, req.form.files.size());
  14613. ASSERT_EQ(1u, req.form.fields.size());
  14614. // Test files
  14615. const auto &file1 = req.form.get_file("file1");
  14616. ASSERT_EQ("file1", file1.name);
  14617. ASSERT_EQ("A.txt", file1.filename);
  14618. ASSERT_EQ("text/plain", file1.content_type);
  14619. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14620. const auto &file2 = req.form.get_file("file2");
  14621. ASSERT_EQ("file2", file2.name);
  14622. ASSERT_EQ("a.html", file2.filename);
  14623. ASSERT_EQ("text/html", file2.content_type);
  14624. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14625. file2.content);
  14626. // Test text field
  14627. const auto &text = req.form.get_field("text");
  14628. ASSERT_EQ("text default", text);
  14629. res.set_content("ok", "text/plain");
  14630. handled = true;
  14631. });
  14632. thread t = thread([&] { svr.listen(HOST, PORT); });
  14633. auto se = detail::scope_exit([&] {
  14634. svr.stop();
  14635. t.join();
  14636. ASSERT_FALSE(svr.is_running());
  14637. ASSERT_TRUE(handled);
  14638. });
  14639. svr.wait_until_ready();
  14640. auto req = "POST /test HTTP/1.1\r\n"
  14641. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14642. "Content-Length: 399\r\n"
  14643. "\r\n"
  14644. "----------\r\n"
  14645. "Content-Disposition: form-data; name=\"text\"\r\n"
  14646. "\r\n"
  14647. "text default\r\n"
  14648. "----------\r\n"
  14649. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14650. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14651. "Content-Type: text/plain\r\n"
  14652. "\r\n"
  14653. "Content of a.txt.\r\n"
  14654. "\r\n"
  14655. "----------\r\n"
  14656. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14657. "\"a.html\"\r\n"
  14658. "Content-Type: text/html\r\n"
  14659. "\r\n"
  14660. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14661. "\r\n"
  14662. "------------\r\n";
  14663. ASSERT_TRUE(send_request(1, req));
  14664. }
  14665. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14666. auto handled = false;
  14667. Server svr;
  14668. svr.Post("/test", [&](const Request &req, Response &res) {
  14669. // Case-insensitive "utf-8''" prefix with a long value
  14670. const auto &file = req.form.get_file("file1");
  14671. ASSERT_EQ("file1", file.name);
  14672. // 8000 chars exercises both the Content-Disposition parser and the
  14673. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14674. // Prior to the fix, std::regex_match on this header would cause O(N)
  14675. // stack recursion in libstdc++, leading to SIGSEGV.
  14676. std::string expected_filename(8000, 'A');
  14677. ASSERT_EQ(expected_filename, file.filename);
  14678. res.set_content("ok", "text/plain");
  14679. handled = true;
  14680. });
  14681. thread t = thread([&] { svr.listen(HOST, PORT); });
  14682. auto se = detail::scope_exit([&] {
  14683. svr.stop();
  14684. t.join();
  14685. ASSERT_FALSE(svr.is_running());
  14686. ASSERT_TRUE(handled);
  14687. });
  14688. svr.wait_until_ready();
  14689. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14690. // Regression test for GHSA-qq6v-r583-3h69
  14691. std::string long_filename(8000, 'A');
  14692. std::string body = "----------\r\n"
  14693. "Content-Disposition: form-data; name=\"file1\"; "
  14694. "filename*=\"Utf-8''" +
  14695. long_filename +
  14696. "\"\r\n"
  14697. "\r\n"
  14698. "hello\r\n"
  14699. "------------\r\n";
  14700. auto req = "POST /test HTTP/1.1\r\n"
  14701. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14702. "Content-Length: " +
  14703. std::to_string(body.size()) + "\r\n\r\n" + body;
  14704. ASSERT_TRUE(send_request(1, req));
  14705. }
  14706. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14707. auto handled = false;
  14708. Server svr;
  14709. svr.Post("/test", [&](const Request &req, Response &) {
  14710. ASSERT_EQ(2u, req.form.fields.size());
  14711. const auto &text1 = req.form.get_field("text1");
  14712. ASSERT_EQ("text1", text1);
  14713. const auto &text2 = req.form.get_field("text2");
  14714. ASSERT_EQ("text2", text2);
  14715. handled = true;
  14716. });
  14717. thread t = thread([&] { svr.listen(HOST, PORT); });
  14718. auto se = detail::scope_exit([&] {
  14719. svr.stop();
  14720. t.join();
  14721. ASSERT_FALSE(svr.is_running());
  14722. ASSERT_TRUE(handled);
  14723. });
  14724. svr.wait_until_ready();
  14725. auto req = "POST /test HTTP/1.1\r\n"
  14726. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14727. "Content-Length: 146\r\n"
  14728. "\r\n----------\r\n"
  14729. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14730. "\r\n"
  14731. "text1"
  14732. "\r\n----------\r\n"
  14733. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14734. "\r\n"
  14735. "text2"
  14736. "\r\n------------";
  14737. std::string response;
  14738. ASSERT_TRUE(send_request(1, req, &response));
  14739. ASSERT_EQ("200", response.substr(9, 3));
  14740. }
  14741. TEST(MultipartFormDataTest, ContentLength) {
  14742. auto handled = false;
  14743. Server svr;
  14744. svr.Post("/test", [&](const Request &req, Response &) {
  14745. ASSERT_EQ(2u, req.form.fields.size());
  14746. const auto &text1 = req.form.get_field("text1");
  14747. ASSERT_EQ("text1", text1);
  14748. const auto &text2 = req.form.get_field("text2");
  14749. ASSERT_EQ("text2", text2);
  14750. handled = true;
  14751. });
  14752. thread t = thread([&] { svr.listen(HOST, PORT); });
  14753. auto se = detail::scope_exit([&] {
  14754. svr.stop();
  14755. t.join();
  14756. ASSERT_FALSE(svr.is_running());
  14757. ASSERT_TRUE(handled);
  14758. });
  14759. svr.wait_until_ready();
  14760. auto req = "POST /test HTTP/1.1\r\n"
  14761. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14762. "Content-Length: 167\r\n"
  14763. "\r\n----------\r\n"
  14764. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14765. "Content-Length: 5\r\n"
  14766. "\r\n"
  14767. "text1"
  14768. "\r\n----------\r\n"
  14769. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14770. "\r\n"
  14771. "text2"
  14772. "\r\n------------\r\n";
  14773. std::string response;
  14774. ASSERT_TRUE(send_request(1, req, &response));
  14775. ASSERT_EQ("200", response.substr(9, 3));
  14776. }
  14777. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14778. auto handled = false;
  14779. Server svr;
  14780. svr.Post("/test", [&](const Request &req, Response &) {
  14781. ASSERT_EQ(2u, req.form.fields.size());
  14782. const auto &text1 = req.form.get_field("text1");
  14783. ASSERT_EQ("text1", text1);
  14784. // TODO: Add header access for text fields if needed
  14785. const auto &text2 = req.form.get_field("text2");
  14786. ASSERT_EQ("text2", text2);
  14787. // TODO: Header access for text fields needs to be implemented
  14788. // auto &headers = it->second.headers;
  14789. // ASSERT_EQ(3U, headers.size());
  14790. // auto custom_header = headers.find("x-whatever");
  14791. // ASSERT_TRUE(custom_header != headers.end());
  14792. // ASSERT_NE("customvalue", custom_header->second);
  14793. // ASSERT_EQ("CustomValue", custom_header->second);
  14794. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14795. handled = true;
  14796. });
  14797. thread t = thread([&] { svr.listen(HOST, PORT); });
  14798. auto se = detail::scope_exit([&] {
  14799. svr.stop();
  14800. t.join();
  14801. ASSERT_FALSE(svr.is_running());
  14802. ASSERT_TRUE(handled);
  14803. });
  14804. svr.wait_until_ready();
  14805. auto req = "POST /test HTTP/1.1\r\n"
  14806. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14807. "Content-Length: 232\r\n"
  14808. "\r\n----------\r\n"
  14809. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14810. "Content-Length: 5\r\n"
  14811. "X-Test: 1\r\n"
  14812. "\r\n"
  14813. "text1"
  14814. "\r\n----------\r\n"
  14815. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14816. "Content-Type: text/plain\r\n"
  14817. "X-Whatever: CustomValue\r\n"
  14818. "\r\n"
  14819. "text2"
  14820. "\r\n------------\r\n"
  14821. "That should be disregarded. Not even read";
  14822. std::string response;
  14823. ASSERT_TRUE(send_request(1, req, &response));
  14824. ASSERT_EQ("200", response.substr(9, 3));
  14825. }
  14826. TEST(MultipartFormDataTest, LargeHeader) {
  14827. auto handled = false;
  14828. Server svr;
  14829. svr.Post("/test", [&](const Request &req, Response &) {
  14830. ASSERT_EQ(1u, req.form.fields.size());
  14831. const auto &text = req.form.get_field("name1");
  14832. ASSERT_EQ("text1", text);
  14833. handled = true;
  14834. });
  14835. thread t = thread([&] { svr.listen(HOST, PORT); });
  14836. auto se = detail::scope_exit([&] {
  14837. svr.stop();
  14838. t.join();
  14839. ASSERT_FALSE(svr.is_running());
  14840. ASSERT_TRUE(handled);
  14841. });
  14842. svr.wait_until_ready();
  14843. auto boundary = std::string("cpp-httplib-multipart-data");
  14844. std::string content = "--" + boundary +
  14845. "\r\n"
  14846. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14847. "\r\n"
  14848. "text1\r\n"
  14849. "--" +
  14850. boundary + "--\r\n";
  14851. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14852. "Content-Type: multipart/form-data;boundary=" +
  14853. boundary +
  14854. "\r\n"
  14855. "Content-Length: " +
  14856. std::to_string(content.size()) +
  14857. "\r\n"
  14858. "Dummy-Header: ";
  14859. std::string header_suffix = "\r\n"
  14860. "\r\n";
  14861. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14862. size_t header_dummy_size =
  14863. read_buff_size -
  14864. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14865. auto header_dummy = std::string(header_dummy_size, '@');
  14866. auto req = header_prefix + header_dummy + header_suffix + content;
  14867. std::string response;
  14868. ASSERT_TRUE(send_request(1, req, &response));
  14869. ASSERT_EQ("200", response.substr(9, 3));
  14870. }
  14871. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14872. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14873. // (not chunked Transfer-Encoding) after the streaming refactor.
  14874. auto handled = false;
  14875. Server svr;
  14876. svr.Post("/upload", [&](const Request &req, Response &res) {
  14877. auto cl_it = req.headers.find("Content-Length");
  14878. EXPECT_TRUE(cl_it != req.headers.end());
  14879. auto te_it = req.headers.find("Transfer-Encoding");
  14880. EXPECT_TRUE(te_it == req.headers.end());
  14881. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14882. res.set_content("ok", "text/plain");
  14883. handled = true;
  14884. });
  14885. auto port = svr.bind_to_any_port(HOST);
  14886. auto t = thread([&] { svr.listen_after_bind(); });
  14887. auto se = detail::scope_exit([&] {
  14888. svr.stop();
  14889. t.join();
  14890. ASSERT_FALSE(svr.is_running());
  14891. ASSERT_TRUE(handled);
  14892. });
  14893. svr.wait_until_ready();
  14894. UploadFormDataItems items = {
  14895. {"field1", "hello", "", "text/plain"},
  14896. {"file1", "world", "test.txt", "application/octet-stream"},
  14897. };
  14898. Client cli(HOST, port);
  14899. auto res = cli.Post("/upload", {}, items);
  14900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14901. EXPECT_EQ(StatusCode::OK_200, res->status);
  14902. }
  14903. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14904. // Verify that make_multipart_content_provider coalesces many small segments
  14905. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14906. constexpr size_t kItemCount = 1000;
  14907. UploadFormDataItems items;
  14908. items.reserve(kItemCount);
  14909. for (size_t i = 0; i < kItemCount; i++) {
  14910. items.push_back(
  14911. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14912. }
  14913. const std::string boundary = "----test-boundary";
  14914. auto content_length = detail::get_multipart_content_length(items, boundary);
  14915. auto provider = detail::make_multipart_content_provider(items, boundary);
  14916. // Drive the provider the same way write_content_with_progress does
  14917. size_t write_count = 0;
  14918. size_t total_bytes = 0;
  14919. DataSink sink;
  14920. size_t offset = 0;
  14921. sink.write = [&](const char *d, size_t l) -> bool {
  14922. (void)d;
  14923. write_count++;
  14924. total_bytes += l;
  14925. offset += l;
  14926. return true;
  14927. };
  14928. sink.is_writable = []() -> bool { return true; };
  14929. while (offset < content_length) {
  14930. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14931. }
  14932. EXPECT_EQ(content_length, total_bytes);
  14933. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14934. // With buffering into 64KB blocks, write_count should be much smaller.
  14935. auto segment_count = 3 * kItemCount + 1;
  14936. EXPECT_LT(write_count, segment_count / 10);
  14937. }
  14938. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14939. // Integration test: send many UploadFormDataItems and verify the server
  14940. // receives all of them correctly (#2410).
  14941. constexpr size_t kItemCount = 500;
  14942. auto handled = false;
  14943. Server svr;
  14944. svr.Post("/upload", [&](const Request &req, Response &res) {
  14945. EXPECT_EQ(kItemCount, req.form.fields.size());
  14946. for (size_t i = 0; i < kItemCount; i++) {
  14947. auto key = "field" + std::to_string(i);
  14948. auto val = "value" + std::to_string(i);
  14949. auto it = req.form.fields.find(key);
  14950. if (it != req.form.fields.end()) {
  14951. EXPECT_EQ(val, it->second.content);
  14952. } else {
  14953. ADD_FAILURE() << "Missing field: " << key;
  14954. }
  14955. }
  14956. res.set_content("ok", "text/plain");
  14957. handled = true;
  14958. });
  14959. auto port = svr.bind_to_any_port(HOST);
  14960. auto t = thread([&] { svr.listen_after_bind(); });
  14961. auto se = detail::scope_exit([&] {
  14962. svr.stop();
  14963. t.join();
  14964. ASSERT_FALSE(svr.is_running());
  14965. ASSERT_TRUE(handled);
  14966. });
  14967. svr.wait_until_ready();
  14968. UploadFormDataItems items;
  14969. items.reserve(kItemCount);
  14970. for (size_t i = 0; i < kItemCount; i++) {
  14971. items.push_back(
  14972. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14973. }
  14974. Client cli(HOST, port);
  14975. auto res = cli.Post("/upload", items);
  14976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14977. EXPECT_EQ(StatusCode::OK_200, res->status);
  14978. }
  14979. TEST(MultipartFormDataTest, MakeFileProvider) {
  14980. // Verify make_file_provider sends a file's contents correctly.
  14981. const std::string file_content(4096, 'Z');
  14982. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14983. {
  14984. std::ofstream ofs(tmp_path, std::ios::binary);
  14985. ofs.write(file_content.data(),
  14986. static_cast<std::streamsize>(file_content.size()));
  14987. }
  14988. auto handled = false;
  14989. Server svr;
  14990. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14991. const ContentReader &content_reader) {
  14992. ASSERT_TRUE(req.is_multipart_form_data());
  14993. std::vector<FormData> items;
  14994. content_reader(
  14995. [&](const FormData &file) {
  14996. items.push_back(file);
  14997. return true;
  14998. },
  14999. [&](const char *data, size_t data_length) {
  15000. items.back().content.append(data, data_length);
  15001. return true;
  15002. });
  15003. ASSERT_EQ(1u, items.size());
  15004. EXPECT_EQ("myfile", items[0].name);
  15005. EXPECT_EQ("data.bin", items[0].filename);
  15006. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15007. EXPECT_EQ(file_content, items[0].content);
  15008. handled = true;
  15009. });
  15010. auto port = svr.bind_to_any_port(HOST);
  15011. auto t = thread([&] { svr.listen_after_bind(); });
  15012. auto se = detail::scope_exit([&] {
  15013. svr.stop();
  15014. t.join();
  15015. ASSERT_FALSE(svr.is_running());
  15016. ASSERT_TRUE(handled);
  15017. std::remove(tmp_path.c_str());
  15018. });
  15019. svr.wait_until_ready();
  15020. FormDataProviderItems providers;
  15021. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15022. "application/octet-stream"));
  15023. Client cli(HOST, port);
  15024. auto res = cli.Post("/upload", {}, {}, providers);
  15025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15026. EXPECT_EQ(StatusCode::OK_200, res->status);
  15027. }
  15028. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15029. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15030. // (100) headers is rejected with a 400 Bad Request response.
  15031. Server svr;
  15032. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15033. res.set_content("ok", "text/plain");
  15034. });
  15035. thread t = thread([&] { svr.listen(HOST, PORT); });
  15036. auto se = detail::scope_exit([&] {
  15037. svr.stop();
  15038. t.join();
  15039. ASSERT_FALSE(svr.is_running());
  15040. });
  15041. svr.wait_until_ready();
  15042. // Build a multipart part with 101 custom headers (exceeding
  15043. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15044. std::stringstream body;
  15045. body << "--simpleboundary\r\n"
  15046. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15047. for (int i = 0; i < 101; i++) {
  15048. body << "X-Custom-Header-" << i << ": value\r\n";
  15049. }
  15050. body << "\r\n"
  15051. << "value1\r\n"
  15052. << "--simpleboundary--\r\n";
  15053. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15054. Client cli(HOST, PORT);
  15055. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15057. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15058. }
  15059. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15060. // A body that never contains the declared boundary must not be accumulated
  15061. // while the parser waits for it. Buffering it would also make every read
  15062. // rescan everything seen so far, which is quadratic in the body size.
  15063. Server svr;
  15064. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15065. res.set_content("ok", "text/plain");
  15066. });
  15067. auto port = svr.bind_to_any_port(HOST);
  15068. thread t = thread([&] { svr.listen_after_bind(); });
  15069. auto se = detail::scope_exit([&] {
  15070. svr.stop();
  15071. t.join();
  15072. ASSERT_FALSE(svr.is_running());
  15073. });
  15074. svr.wait_until_ready();
  15075. Client cli(HOST, port);
  15076. cli.set_read_timeout(60, 0);
  15077. cli.set_write_timeout(60, 0);
  15078. // '-' is the worst case: it matches the first character of the boundary, so
  15079. // every position has to be checked against it.
  15080. auto post_dashes = [&](size_t size) {
  15081. const std::string body(size, '-');
  15082. auto start = std::chrono::steady_clock::now();
  15083. auto res =
  15084. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15085. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15086. std::chrono::steady_clock::now() - start)
  15087. .count();
  15088. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15089. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15090. return ms;
  15091. };
  15092. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15093. // Windows.
  15094. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15095. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15096. // Comparing the two sizes rather than checking an absolute duration keeps
  15097. // this meaningful across build types and CI load, both of which move the
  15098. // absolute numbers by more than an order of magnitude. Four times the bytes
  15099. // costs about four times the time when parsing is linear, and about sixteen
  15100. // times when the body is buffered and rescanned.
  15101. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15102. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15103. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15104. << "ms, which suggests the body is being buffered and rescanned";
  15105. }
  15106. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15107. // A boundary can only be followed by CRLF or by "--", so anything else is
  15108. // malformed no matter what comes next. The parser must say so right away
  15109. // instead of buffering the rest of the declared body.
  15110. Server svr;
  15111. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15112. res.set_content("ok", "text/plain");
  15113. });
  15114. auto port = svr.bind_to_any_port(HOST);
  15115. thread t = thread([&] { svr.listen_after_bind(); });
  15116. auto se = detail::scope_exit([&] {
  15117. svr.stop();
  15118. t.join();
  15119. ASSERT_FALSE(svr.is_running());
  15120. });
  15121. svr.wait_until_ready();
  15122. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15123. // buffers instead of failing would still be waiting for the remaining bytes.
  15124. const std::string body = "--zzzz\r\n"
  15125. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15126. "\r\n"
  15127. "text1"
  15128. "\r\n--zzzzXX";
  15129. const std::string req = "POST /post HTTP/1.1\r\n"
  15130. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15131. "Content-Length: 1048576\r\n"
  15132. "\r\n" +
  15133. body;
  15134. std::string response;
  15135. ASSERT_TRUE(send_request(3, req, &response, port));
  15136. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15137. EXPECT_EQ("400", response.substr(9, 3));
  15138. }
  15139. // Posts a multipart body split into two writes, so that the server sees the
  15140. // split at whatever offset the caller chose, and expects the single "text1"
  15141. // field to come through.
  15142. static void expect_split_multipart_ok(const std::string &body1,
  15143. const std::string &body2) {
  15144. auto handled = false;
  15145. Server svr;
  15146. svr.Post("/post", [&](const Request &req, Response &) {
  15147. EXPECT_EQ(1u, req.form.fields.size());
  15148. EXPECT_EQ("text1", req.form.get_field("text1"));
  15149. handled = true;
  15150. });
  15151. auto port = svr.bind_to_any_port(HOST);
  15152. thread t = thread([&] { svr.listen_after_bind(); });
  15153. auto se = detail::scope_exit([&] {
  15154. svr.stop();
  15155. t.join();
  15156. ASSERT_FALSE(svr.is_running());
  15157. ASSERT_TRUE(handled);
  15158. });
  15159. svr.wait_until_ready();
  15160. // "Connection: close" makes the server close once it has answered, so the
  15161. // response drain ends immediately instead of idling until the read timeout.
  15162. const std::string head =
  15163. "POST /post HTTP/1.1\r\n"
  15164. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15165. "Connection: close\r\n"
  15166. "Content-Length: " +
  15167. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15168. std::string response;
  15169. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15170. ASSERT_GE(response.size(), 12u) << "no response";
  15171. EXPECT_EQ("200", response.substr(9, 3));
  15172. }
  15173. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15174. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15175. // ignored, including when it does not arrive in the same read as the
  15176. // close-delimiter itself.
  15177. expect_split_multipart_ok("--zzzz\r\n"
  15178. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15179. "\r\n"
  15180. "text1"
  15181. "\r\n--zzzz--",
  15182. "\r\nthis epilogue must be ignored\r\n");
  15183. }
  15184. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15185. // The initial boundary may be preceded by a preamble of any length and may
  15186. // straddle a read boundary. Discarding data while waiting for it must not
  15187. // throw away a partial boundary sitting at the end of the buffer.
  15188. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15189. "zz\r\n"
  15190. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15191. "\r\n"
  15192. "text1"
  15193. "\r\n--zzzz--\r\n");
  15194. }
  15195. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15196. // The received boundary was only checked for being non-empty, so it could be
  15197. // as long as a header is allowed to be. The parser scans the body for
  15198. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15199. // costs a nearly full comparison at nearly every position, making the
  15200. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15201. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15202. Server svr;
  15203. svr.Post("/post", [](const Request &req, Response &res) {
  15204. EXPECT_EQ(1u, req.form.fields.size());
  15205. EXPECT_EQ("text1", req.form.get_field("text1"));
  15206. res.set_content("ok", "text/plain");
  15207. });
  15208. auto port = svr.bind_to_any_port(HOST);
  15209. thread t = thread([&] { svr.listen_after_bind(); });
  15210. auto se = detail::scope_exit([&] {
  15211. svr.stop();
  15212. t.join();
  15213. ASSERT_FALSE(svr.is_running());
  15214. });
  15215. svr.wait_until_ready();
  15216. Client cli(HOST, port);
  15217. auto post_with_boundary_of_length = [&](size_t len) {
  15218. const std::string boundary(len, 'a');
  15219. const std::string body =
  15220. "--" + boundary +
  15221. "\r\n"
  15222. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15223. "\r\n"
  15224. "text1"
  15225. "\r\n--" +
  15226. boundary + "--\r\n";
  15227. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15228. };
  15229. auto res = post_with_boundary_of_length(70);
  15230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15231. EXPECT_EQ(StatusCode::OK_200, res->status);
  15232. res = post_with_boundary_of_length(71);
  15233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15234. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15235. }
  15236. TEST(MakeFileBodyTest, Basic) {
  15237. const std::string file_content(4096, 'Z');
  15238. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15239. {
  15240. std::ofstream ofs(tmp_path, std::ios::binary);
  15241. ofs.write(file_content.data(),
  15242. static_cast<std::streamsize>(file_content.size()));
  15243. }
  15244. auto handled = false;
  15245. Server svr;
  15246. svr.Post("/upload", [&](const Request &req, Response &res) {
  15247. EXPECT_EQ(file_content, req.body);
  15248. handled = true;
  15249. res.status = StatusCode::OK_200;
  15250. });
  15251. auto port = svr.bind_to_any_port(HOST);
  15252. auto t = thread([&] { svr.listen_after_bind(); });
  15253. auto se = detail::scope_exit([&] {
  15254. svr.stop();
  15255. t.join();
  15256. ASSERT_FALSE(svr.is_running());
  15257. ASSERT_TRUE(handled);
  15258. std::remove(tmp_path.c_str());
  15259. });
  15260. svr.wait_until_ready();
  15261. auto fb = make_file_body(tmp_path);
  15262. ASSERT_GT(fb.first, 0u);
  15263. Client cli(HOST, port);
  15264. auto res =
  15265. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15267. EXPECT_EQ(StatusCode::OK_200, res->status);
  15268. }
  15269. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15270. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15271. {
  15272. std::ofstream ofs(path, std::ios::binary);
  15273. const std::string content(100, 'A');
  15274. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15275. }
  15276. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15277. auto body = make_file_body(path);
  15278. ASSERT_EQ(100u, body.first);
  15279. ASSERT_TRUE(static_cast<bool>(body.second));
  15280. // Rewritten shorter after its length was measured - and, on a server, after
  15281. // that length has already gone out as Content-Length.
  15282. {
  15283. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15284. const std::string content(10, 'A');
  15285. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15286. }
  15287. std::string written;
  15288. DataSink sink;
  15289. sink.write = [&](const char *d, size_t l) {
  15290. written.append(d, l);
  15291. return true;
  15292. };
  15293. // The provider has to report failure. write_content_with_progress() advances
  15294. // its offset only by what was written, so a provider that returns true
  15295. // without completing the length it promised is called again straight away,
  15296. // and again.
  15297. EXPECT_FALSE(body.second(0, body.first, sink));
  15298. EXPECT_EQ(std::string(10, 'A'), written);
  15299. }
  15300. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15301. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15302. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15303. {
  15304. std::ofstream ofs(path, std::ios::binary);
  15305. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15306. }
  15307. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15308. auto body = make_file_body(path);
  15309. ASSERT_EQ(content.size(), body.first);
  15310. ASSERT_TRUE(static_cast<bool>(body.second));
  15311. std::string written;
  15312. DataSink sink;
  15313. sink.write = [&](const char *d, size_t l) {
  15314. written.append(d, l);
  15315. return true;
  15316. };
  15317. EXPECT_TRUE(body.second(0, body.first, sink));
  15318. EXPECT_EQ(content, written);
  15319. }
  15320. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15321. static constexpr unsigned int number_of_tasks{1000000};
  15322. std::atomic_uint count{0};
  15323. std::unique_ptr<TaskQueue> task_queue{
  15324. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15325. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15326. auto queued = task_queue->enqueue(
  15327. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15328. EXPECT_TRUE(queued);
  15329. }
  15330. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15331. task_queue->shutdown();
  15332. #else
  15333. EXPECT_NO_THROW(task_queue->shutdown());
  15334. #endif
  15335. EXPECT_EQ(number_of_tasks, count.load());
  15336. }
  15337. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15338. static constexpr unsigned int number_of_tasks{1000000};
  15339. static constexpr unsigned int qlimit{2};
  15340. unsigned int queued_count{0};
  15341. std::atomic_uint count{0};
  15342. std::unique_ptr<TaskQueue> task_queue{
  15343. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15344. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15345. if (task_queue->enqueue(
  15346. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15347. queued_count++;
  15348. }
  15349. }
  15350. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15351. task_queue->shutdown();
  15352. #else
  15353. EXPECT_NO_THROW(task_queue->shutdown());
  15354. #endif
  15355. EXPECT_EQ(queued_count, count.load());
  15356. EXPECT_TRUE(queued_count <= number_of_tasks);
  15357. EXPECT_TRUE(queued_count >= qlimit);
  15358. }
  15359. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15360. // Use a short idle timeout so a dynamic thread spawns, times out and
  15361. // exits during the test, and the pool keeps working afterwards.
  15362. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15363. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15364. /*idle_timeout_sec=*/1}};
  15365. std::atomic_uint count{0};
  15366. std::condition_variable cv;
  15367. std::mutex mtx;
  15368. bool release = false;
  15369. // Block the base thread so the second task spawns a dynamic thread.
  15370. EXPECT_TRUE(task_queue->enqueue([&] {
  15371. std::unique_lock<std::mutex> lock(mtx);
  15372. while (!release) {
  15373. cv.wait(lock);
  15374. }
  15375. count++;
  15376. }));
  15377. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15378. // Let the dynamic thread finish its task and exceed the idle timeout.
  15379. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15380. {
  15381. std::unique_lock<std::mutex> lock(mtx);
  15382. release = true;
  15383. }
  15384. cv.notify_all();
  15385. // The pool must still accept and run tasks after the dynamic thread exited.
  15386. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15387. task_queue->shutdown();
  15388. EXPECT_EQ(3u, count.load());
  15389. }
  15390. TEST(TaskQueueTest, MaxQueuedRequests) {
  15391. static constexpr unsigned int qlimit{3};
  15392. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15393. std::condition_variable sem_cv;
  15394. std::mutex sem_mtx;
  15395. int credits = 0;
  15396. bool queued;
  15397. /* Fill up the queue with tasks that will block until we give them credits to
  15398. * complete. */
  15399. for (unsigned int n = 0; n <= qlimit;) {
  15400. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15401. std::unique_lock<std::mutex> lock(sem_mtx);
  15402. while (credits <= 0) {
  15403. sem_cv.wait(lock);
  15404. }
  15405. /* Consume the credit and signal the test code if they are all gone. */
  15406. if (--credits == 0) { sem_cv.notify_one(); }
  15407. });
  15408. if (n < qlimit) {
  15409. /* The first qlimit enqueues must succeed. */
  15410. EXPECT_TRUE(queued);
  15411. } else {
  15412. /* The last one will succeed only when the worker thread
  15413. * starts and dequeues the first blocking task. Although
  15414. * not necessary for the correctness of this test, we sleep for
  15415. * a short while to avoid busy waiting. */
  15416. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15417. }
  15418. if (queued) { n++; }
  15419. }
  15420. /* Further enqueues must fail since the queue is full. */
  15421. for (auto i = 0; i < 4; i++) {
  15422. queued = task_queue->enqueue([] {});
  15423. EXPECT_FALSE(queued);
  15424. }
  15425. /* Give the credits to allow the previous tasks to complete. */
  15426. {
  15427. std::unique_lock<std::mutex> lock(sem_mtx);
  15428. credits += qlimit + 1;
  15429. }
  15430. sem_cv.notify_all();
  15431. /* Wait for all the credits to be consumed. */
  15432. {
  15433. std::unique_lock<std::mutex> lock(sem_mtx);
  15434. while (credits > 0) {
  15435. sem_cv.wait(lock);
  15436. }
  15437. }
  15438. /* Check that we are able again to enqueue at least qlimit tasks. */
  15439. for (unsigned int i = 0; i < qlimit; i++) {
  15440. queued = task_queue->enqueue([] {});
  15441. EXPECT_TRUE(queued);
  15442. }
  15443. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15444. task_queue->shutdown();
  15445. #else
  15446. EXPECT_NO_THROW(task_queue->shutdown());
  15447. #endif
  15448. }
  15449. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15450. Server svr;
  15451. std::string method;
  15452. std::string body;
  15453. auto has_content_length = false;
  15454. auto has_transfer_encoding = false;
  15455. std::atomic<int> bad_requests{0};
  15456. // Leftover body bytes get parsed as a malformed request and answered with
  15457. // 400
  15458. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15459. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15460. });
  15461. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15462. res.set_redirect("/down", StatusCode::SeeOther_303);
  15463. });
  15464. svr.Get("/down", [&](const Request &req, Response &res) {
  15465. method = req.method;
  15466. body = req.body;
  15467. has_content_length = req.has_header("Content-Length");
  15468. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15469. res.set_content("ok", "text/plain");
  15470. });
  15471. auto port = svr.bind_to_any_port(HOST);
  15472. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15473. auto se = detail::scope_exit([&] {
  15474. svr.stop();
  15475. thread.join();
  15476. ASSERT_FALSE(svr.is_running());
  15477. });
  15478. svr.wait_until_ready();
  15479. const std::string payload = "SECRET-BODY";
  15480. auto check = [&](Client &cli, const Result &res) {
  15481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15482. EXPECT_EQ(StatusCode::OK_200, res->status);
  15483. EXPECT_EQ("ok", res->body);
  15484. EXPECT_EQ("GET", method);
  15485. EXPECT_TRUE(body.empty());
  15486. EXPECT_FALSE(has_content_length);
  15487. EXPECT_FALSE(has_transfer_encoding);
  15488. // Nothing of the original body may be left on the connection
  15489. auto res2 = cli.Get("/down");
  15490. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15491. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15492. EXPECT_EQ("ok", res2->body);
  15493. EXPECT_EQ(0, bad_requests);
  15494. };
  15495. // With content length
  15496. {
  15497. Client cli(HOST, port);
  15498. cli.set_keep_alive(true);
  15499. cli.set_follow_location(true);
  15500. auto res = cli.Post(
  15501. "/up", payload.size(),
  15502. [&](size_t offset, size_t length, DataSink &sink) {
  15503. return sink.write(payload.data() + offset, length);
  15504. },
  15505. "text/plain");
  15506. check(cli, res);
  15507. }
  15508. // Without content length (chunked)
  15509. {
  15510. Client cli(HOST, port);
  15511. cli.set_keep_alive(true);
  15512. cli.set_follow_location(true);
  15513. auto res = cli.Post(
  15514. "/up",
  15515. [&](size_t /*offset*/, DataSink &sink) {
  15516. sink.write(payload.data(), payload.size());
  15517. sink.done();
  15518. return true;
  15519. },
  15520. "text/plain");
  15521. check(cli, res);
  15522. }
  15523. }
  15524. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15525. Server svr;
  15526. std::string target;
  15527. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15528. // Echo the still-encoded name back in the Location
  15529. const std::string prefix = "/start/";
  15530. res.status = StatusCode::Found_302;
  15531. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15532. });
  15533. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15534. target = req.target;
  15535. res.set_content("ok", "text/plain");
  15536. });
  15537. auto port = svr.bind_to_any_port(HOST);
  15538. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15539. auto se = detail::scope_exit([&] {
  15540. svr.stop();
  15541. thread.join();
  15542. ASSERT_FALSE(svr.is_running());
  15543. });
  15544. svr.wait_until_ready();
  15545. // Decoding the Location path would turn the first four into a path
  15546. // separator, a query delimiter, a fragment delimiter and a different
  15547. // percent-encoded octet. The rest must keep reaching the server as they are.
  15548. const std::vector<std::string> names = {
  15549. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15550. };
  15551. for (auto path_encode : {true, false}) {
  15552. Client cli(HOST, port);
  15553. cli.set_follow_location(true);
  15554. cli.set_path_encode(path_encode);
  15555. for (const auto &name : names) {
  15556. target.clear();
  15557. auto res = cli.Get("/start/" + name);
  15558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15559. EXPECT_EQ(StatusCode::OK_200, res->status);
  15560. EXPECT_EQ("/dest/" + name, target);
  15561. }
  15562. }
  15563. }
  15564. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15565. Server svr;
  15566. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15567. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15568. });
  15569. svr.Get("/hello", [](const Request &req, Response &res) {
  15570. res.set_content(req.get_param_value("key"), "text/plain");
  15571. });
  15572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15573. auto se = detail::scope_exit([&] {
  15574. svr.stop();
  15575. thread.join();
  15576. ASSERT_FALSE(svr.is_running());
  15577. });
  15578. svr.wait_until_ready();
  15579. {
  15580. Client cli(HOST, PORT);
  15581. cli.set_follow_location(true);
  15582. auto res = cli.Get("/");
  15583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15584. EXPECT_EQ(StatusCode::OK_200, res->status);
  15585. EXPECT_EQ("val&key2=val2", res->body);
  15586. }
  15587. }
  15588. #endif
  15589. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15590. Server svr;
  15591. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15592. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15593. });
  15594. svr.Get("/hello", [](const Request &req, Response &res) {
  15595. res.set_content(req.get_param_value("key"), "text/plain");
  15596. });
  15597. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15598. auto se = detail::scope_exit([&] {
  15599. svr.stop();
  15600. thread.join();
  15601. ASSERT_FALSE(svr.is_running());
  15602. });
  15603. svr.wait_until_ready();
  15604. {
  15605. Client cli(HOST, PORT);
  15606. cli.set_follow_location(true);
  15607. auto res = cli.Get("/");
  15608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15609. EXPECT_EQ(StatusCode::OK_200, res->status);
  15610. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15611. }
  15612. }
  15613. TEST(RedirectTest, RedirectWithPlusInPath) {
  15614. Server svr;
  15615. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15616. res.set_redirect("/a+b");
  15617. });
  15618. // Route pattern uses regex; escape + as \\+
  15619. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15620. res.set_content(req.path, "text/plain");
  15621. });
  15622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15623. auto se = detail::scope_exit([&] {
  15624. svr.stop();
  15625. thread.join();
  15626. ASSERT_FALSE(svr.is_running());
  15627. });
  15628. svr.wait_until_ready();
  15629. {
  15630. Client cli(HOST, PORT);
  15631. cli.set_follow_location(true);
  15632. auto res = cli.Get("/");
  15633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15634. EXPECT_EQ(StatusCode::OK_200, res->status);
  15635. EXPECT_EQ("/a+b", res->body);
  15636. }
  15637. }
  15638. TEST(RedirectTest, ResolveRelativeLocation) {
  15639. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15640. const std::vector<std::pair<std::string, std::string>> cases = {
  15641. {"g", "/b/c/g"},
  15642. {"./g", "/b/c/g"},
  15643. {"g/", "/b/c/g/"},
  15644. {"?y", "/b/c/d;p?y"},
  15645. {"g?y", "/b/c/g?y"},
  15646. {"#s", "/b/c/d;p?q#s"},
  15647. {"g#s", "/b/c/g#s"},
  15648. {"g?y#s", "/b/c/g?y#s"},
  15649. {";x", "/b/c/;x"},
  15650. {"g;x", "/b/c/g;x"},
  15651. {".", "/b/c/"},
  15652. {"./", "/b/c/"},
  15653. {"..", "/b/"},
  15654. {"../", "/b/"},
  15655. {"../g", "/b/g"},
  15656. {"../..", "/"},
  15657. {"../../", "/"},
  15658. {"../../g", "/g"},
  15659. {"../../../g", "/g"},
  15660. {"g.", "/b/c/g."},
  15661. {".g", "/b/c/.g"},
  15662. {"g..", "/b/c/g.."},
  15663. {"..g", "/b/c/..g"},
  15664. {"./../g", "/b/g"},
  15665. {"./g/.", "/b/c/g/"},
  15666. {"g/./h", "/b/c/g/h"},
  15667. {"g/../h", "/b/c/h"},
  15668. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15669. {"g;x=1/../y", "/b/c/y"},
  15670. {"g?y/./x", "/b/c/g?y/./x"},
  15671. {"g#s/../x", "/b/c/g#s/../x"},
  15672. // Not relative-path references, so left for parse_url.
  15673. {"/g", "/g"},
  15674. {"//g", "//g"},
  15675. {"http://g/x", "http://g/x"},
  15676. {"g:h", "g:h"},
  15677. };
  15678. for (const auto &c : cases) {
  15679. EXPECT_EQ(c.second,
  15680. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15681. << c.first;
  15682. }
  15683. }
  15684. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15685. Server svr;
  15686. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15687. res.set_redirect(req.get_param_value("to"));
  15688. });
  15689. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15690. res.set_content(req.target, "text/plain");
  15691. });
  15692. svr.Get("/other", [](const Request &req, Response &res) {
  15693. res.set_content(req.target, "text/plain");
  15694. });
  15695. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15696. auto se = detail::scope_exit([&] {
  15697. svr.stop();
  15698. thread.join();
  15699. ASSERT_FALSE(svr.is_running());
  15700. });
  15701. svr.wait_until_ready();
  15702. const std::vector<std::pair<std::string, std::string>> cases = {
  15703. {"next", "/dir/next"},
  15704. {"./next?x=1", "/dir/next?x=1"},
  15705. {"../other", "/other"},
  15706. };
  15707. for (const auto &c : cases) {
  15708. Client cli(HOST, PORT);
  15709. cli.set_follow_location(true);
  15710. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15711. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15712. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15713. EXPECT_EQ(c.second, res->body) << c.first;
  15714. }
  15715. }
  15716. #ifdef CPPHTTPLIB_SSL_ENABLED
  15717. TEST(RedirectTest, Issue2185_Online) {
  15718. SSLClient client("github.com");
  15719. client.set_follow_location(true);
  15720. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15721. "Coollab-Windows.zip");
  15722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15723. EXPECT_EQ(StatusCode::OK_200, res->status);
  15724. EXPECT_EQ(9920427U, res->body.size());
  15725. }
  15726. #endif
  15727. TEST(VulnerabilityTest, CRLFInjection) {
  15728. Server svr;
  15729. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15730. res.set_content("Hello 1", "text/plain");
  15731. });
  15732. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15733. res.set_content("Hello 2", "text/plain");
  15734. });
  15735. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15736. res.set_content("Hello 3", "text/plain");
  15737. });
  15738. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15739. res.set_content("Hello 4", "text/plain");
  15740. });
  15741. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15742. for (const auto &x : req.headers) {
  15743. auto key = x.first;
  15744. EXPECT_STRNE("evil", key.c_str());
  15745. }
  15746. });
  15747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15748. auto se = detail::scope_exit([&] {
  15749. svr.stop();
  15750. thread.join();
  15751. ASSERT_FALSE(svr.is_running());
  15752. });
  15753. svr.wait_until_ready();
  15754. {
  15755. Client cli(HOST, PORT);
  15756. cli.Post("/test1", "A=B",
  15757. "application/x-www-form-urlencoded\r\nevil: hello1");
  15758. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15759. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15760. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15761. }
  15762. }
  15763. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15764. auto server_thread = std::thread([] {
  15765. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15766. default_socket_options(srv);
  15767. sockaddr_in addr{};
  15768. addr.sin_family = AF_INET;
  15769. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15770. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15771. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15772. ::listen(srv, 1);
  15773. sockaddr_in cli_addr{};
  15774. socklen_t cli_len = sizeof(cli_addr);
  15775. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15776. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15777. std::string buf_all;
  15778. char buf[2048];
  15779. ssize_t n;
  15780. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15781. buf_all.append(buf, static_cast<size_t>(n));
  15782. size_t pos;
  15783. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15784. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15785. auto e = request_block.find("\r\n");
  15786. if (e != std::string::npos) {
  15787. auto request_line = request_block.substr(0, e);
  15788. std::string msg =
  15789. "CRLF injection detected in request line: '" + request_line + "'";
  15790. EXPECT_FALSE(true) << msg;
  15791. }
  15792. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15793. ::send(cli,
  15794. #ifdef _WIN32
  15795. static_cast<const char *>(resp.c_str()),
  15796. static_cast<int>(resp.size()),
  15797. #else
  15798. resp.c_str(), resp.size(),
  15799. #endif
  15800. 0);
  15801. buf_all.erase(0, pos + 4);
  15802. }
  15803. }
  15804. detail::close_socket(cli);
  15805. detail::close_socket(srv);
  15806. });
  15807. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15808. auto cli = Client("127.0.0.1", PORT + 1);
  15809. auto headers = Headers{
  15810. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15811. {"Connection", "keep-alive"}};
  15812. auto res = cli.Get("/hi", headers);
  15813. EXPECT_FALSE(res);
  15814. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15815. server_thread.join();
  15816. }
  15817. // A request rejected before any byte reaches the socket must fail right away
  15818. // instead of waiting for a response the server will never send.
  15819. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15820. // The kernel completes the TCP handshake from the listen backlog, so the
  15821. // client connects, but nothing ever reads, responds or closes.
  15822. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15823. default_socket_options(srv);
  15824. sockaddr_in addr{};
  15825. addr.sin_family = AF_INET;
  15826. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15827. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15828. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15829. ASSERT_EQ(0, ::listen(srv, 8));
  15830. auto cli = Client("127.0.0.1", PORT + 1);
  15831. cli.set_read_timeout(10, 0);
  15832. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15833. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15834. std::chrono::steady_clock::now() - start)
  15835. .count();
  15836. };
  15837. {
  15838. Request req;
  15839. req.method = "GE T";
  15840. req.path = "/";
  15841. auto start = std::chrono::steady_clock::now();
  15842. auto res = cli.send(req);
  15843. EXPECT_FALSE(res);
  15844. EXPECT_EQ(Error::Write, res.error());
  15845. EXPECT_LT(elapsed_ms(start), 1000);
  15846. }
  15847. {
  15848. auto start = std::chrono::steady_clock::now();
  15849. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15850. EXPECT_FALSE(res);
  15851. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15852. EXPECT_LT(elapsed_ms(start), 1000);
  15853. }
  15854. EXPECT_FALSE(cli.is_socket_open());
  15855. detail::close_socket(srv);
  15856. }
  15857. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15858. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15859. default_socket_options(srv);
  15860. sockaddr_in addr{};
  15861. addr.sin_family = AF_INET;
  15862. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15863. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15864. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15865. ASSERT_EQ(0, ::listen(srv, 1));
  15866. std::string received;
  15867. auto server_thread = std::thread([&] {
  15868. auto sock = ::accept(srv, nullptr, nullptr);
  15869. if (sock == INVALID_SOCKET) { return; }
  15870. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15871. char buf[2048];
  15872. ssize_t n;
  15873. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15874. received.append(buf, static_cast<size_t>(n));
  15875. }
  15876. detail::close_socket(sock);
  15877. });
  15878. {
  15879. auto cli = Client("127.0.0.1", PORT + 1);
  15880. // "Z" sorts after the default headers, so writing straight to the socket
  15881. // would have sent the request line and those headers before the rejection.
  15882. auto handle =
  15883. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15884. EXPECT_FALSE(handle.is_valid());
  15885. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15886. }
  15887. server_thread.join();
  15888. detail::close_socket(srv);
  15889. EXPECT_TRUE(received.empty()) << received;
  15890. }
  15891. TEST(PathParamsTest, StaticMatch) {
  15892. const auto pattern = "/users/all";
  15893. detail::PathParamsMatcher matcher(pattern);
  15894. Request request;
  15895. request.path = "/users/all";
  15896. ASSERT_TRUE(matcher.match(request));
  15897. std::unordered_map<std::string, std::string> expected_params = {};
  15898. EXPECT_EQ(request.path_params, expected_params);
  15899. }
  15900. TEST(PathParamsTest, StaticMismatch) {
  15901. const auto pattern = "/users/all";
  15902. detail::PathParamsMatcher matcher(pattern);
  15903. Request request;
  15904. request.path = "/users/1";
  15905. ASSERT_FALSE(matcher.match(request));
  15906. }
  15907. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15908. const auto pattern = "/users/:id/subscriptions";
  15909. detail::PathParamsMatcher matcher(pattern);
  15910. Request request;
  15911. request.path = "/users/42/subscriptions";
  15912. ASSERT_TRUE(matcher.match(request));
  15913. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15914. EXPECT_EQ(request.path_params, expected_params);
  15915. }
  15916. TEST(PathParamsTest, SingleParamInTheEnd) {
  15917. const auto pattern = "/users/:id";
  15918. detail::PathParamsMatcher matcher(pattern);
  15919. Request request;
  15920. request.path = "/users/24";
  15921. ASSERT_TRUE(matcher.match(request));
  15922. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15923. EXPECT_EQ(request.path_params, expected_params);
  15924. }
  15925. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15926. const auto pattern = "/users/:id/";
  15927. detail::PathParamsMatcher matcher(pattern);
  15928. Request request;
  15929. request.path = "/users/42/";
  15930. ASSERT_TRUE(matcher.match(request));
  15931. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15932. EXPECT_EQ(request.path_params, expected_params);
  15933. }
  15934. TEST(PathParamsTest, EmptyParam) {
  15935. const auto pattern = "/users/:id/";
  15936. detail::PathParamsMatcher matcher(pattern);
  15937. Request request;
  15938. request.path = "/users//";
  15939. ASSERT_TRUE(matcher.match(request));
  15940. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15941. EXPECT_EQ(request.path_params, expected_params);
  15942. }
  15943. TEST(PathParamsTest, FragmentMismatch) {
  15944. const auto pattern = "/users/:id/";
  15945. detail::PathParamsMatcher matcher(pattern);
  15946. Request request;
  15947. request.path = "/admins/24/";
  15948. ASSERT_FALSE(matcher.match(request));
  15949. }
  15950. TEST(PathParamsTest, ExtraFragments) {
  15951. const auto pattern = "/users/:id";
  15952. detail::PathParamsMatcher matcher(pattern);
  15953. Request request;
  15954. request.path = "/users/42/subscriptions";
  15955. ASSERT_FALSE(matcher.match(request));
  15956. }
  15957. TEST(PathParamsTest, MissingTrailingParam) {
  15958. const auto pattern = "/users/:id";
  15959. detail::PathParamsMatcher matcher(pattern);
  15960. Request request;
  15961. request.path = "/users";
  15962. ASSERT_FALSE(matcher.match(request));
  15963. }
  15964. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15965. const auto pattern = "/users/:id/subscriptions";
  15966. detail::PathParamsMatcher matcher(pattern);
  15967. Request request;
  15968. request.path = "/users/subscriptions";
  15969. ASSERT_FALSE(matcher.match(request));
  15970. }
  15971. TEST(PathParamsTest, MultipleParams) {
  15972. const auto pattern = "/users/:userid/subscriptions/:subid";
  15973. detail::PathParamsMatcher matcher(pattern);
  15974. Request request;
  15975. request.path = "/users/42/subscriptions/2";
  15976. ASSERT_TRUE(matcher.match(request));
  15977. std::unordered_map<std::string, std::string> expected_params = {
  15978. {"userid", "42"}, {"subid", "2"}};
  15979. EXPECT_EQ(request.path_params, expected_params);
  15980. }
  15981. TEST(PathParamsTest, SequenceOfParams) {
  15982. const auto pattern = "/values/:x/:y/:z";
  15983. detail::PathParamsMatcher matcher(pattern);
  15984. Request request;
  15985. request.path = "/values/1/2/3";
  15986. ASSERT_TRUE(matcher.match(request));
  15987. std::unordered_map<std::string, std::string> expected_params = {
  15988. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15989. EXPECT_EQ(request.path_params, expected_params);
  15990. }
  15991. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15992. const auto pattern = "/prefix:suffix";
  15993. detail::PathParamsMatcher matcher(pattern);
  15994. Request request;
  15995. request.path = "/prefix:suffix";
  15996. ASSERT_TRUE(matcher.match(request));
  15997. const std::unordered_map<std::string, std::string> expected_params = {};
  15998. EXPECT_EQ(request.path_params, expected_params);
  15999. }
  16000. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16001. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16002. // calling thread's stack on a long enough path for a quantified pattern;
  16003. // RegexMatcher must refuse to run regex matching on paths beyond
  16004. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16005. detail::RegexMatcher matcher("/files/(.*)");
  16006. Request within_limit;
  16007. within_limit.path = "/files/" + std::string(10, 'A');
  16008. EXPECT_TRUE(matcher.match(within_limit));
  16009. Request over_limit;
  16010. over_limit.path =
  16011. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16012. EXPECT_FALSE(matcher.match(over_limit));
  16013. }
  16014. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16015. Server svr;
  16016. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16017. res.set_content("ok", "text/plain");
  16018. });
  16019. auto port = svr.bind_to_any_port(HOST);
  16020. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16021. auto se = detail::scope_exit([&] {
  16022. svr.stop();
  16023. thread.join();
  16024. ASSERT_FALSE(svr.is_running());
  16025. });
  16026. svr.wait_until_ready();
  16027. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16028. // request URI limit; this used to be able to crash the process.
  16029. std::string path =
  16030. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16031. std::string req = "GET " + path +
  16032. " HTTP/1.1\r\n"
  16033. "Host: " +
  16034. std::string(HOST) + ":" + std::to_string(port) +
  16035. "\r\n"
  16036. "Connection: close\r\n"
  16037. "\r\n";
  16038. std::string response;
  16039. ASSERT_TRUE(send_request(5, req, &response, port));
  16040. EXPECT_NE(std::string::npos, response.find("404"));
  16041. }
  16042. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16043. Server svr;
  16044. auto handler = [](const Request & /*req*/, Response &res) {
  16045. res.set_content("hit", "text/plain");
  16046. };
  16047. // No regex metacharacter, so this one is compared literally
  16048. svr.Get("/literal/route", handler);
  16049. // '.' is a regex metacharacter, so this one must keep regex semantics
  16050. svr.Get("/a.c", handler);
  16051. auto port = svr.bind_to_any_port(HOST);
  16052. std::thread t([&]() { svr.listen_after_bind(); });
  16053. auto se = detail::scope_exit([&] {
  16054. svr.stop();
  16055. t.join();
  16056. ASSERT_FALSE(svr.is_running());
  16057. });
  16058. svr.wait_until_ready();
  16059. Client cli(HOST, port);
  16060. struct {
  16061. const char *path;
  16062. int status;
  16063. } cases[] = {
  16064. {"/literal/route", StatusCode::OK_200},
  16065. {"/literal/routes", StatusCode::NotFound_404},
  16066. {"/literal/rout", StatusCode::NotFound_404},
  16067. {"/abc", StatusCode::OK_200},
  16068. {"/a.c", StatusCode::OK_200},
  16069. };
  16070. for (const auto &x : cases) {
  16071. auto res = cli.Get(x.path);
  16072. ASSERT_TRUE(res) << x.path;
  16073. EXPECT_EQ(x.status, res->status) << x.path;
  16074. }
  16075. }
  16076. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16077. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16078. // from exhausting the stack, so it must only constrain routes that actually
  16079. // run a regular expression. A literal route is matched by comparison and
  16080. // stays usable at any length.
  16081. Server svr;
  16082. const std::string pattern =
  16083. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16084. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16085. res.set_content("hit", "text/plain");
  16086. });
  16087. auto port = svr.bind_to_any_port(HOST);
  16088. std::thread t([&]() { svr.listen_after_bind(); });
  16089. auto se = detail::scope_exit([&] {
  16090. svr.stop();
  16091. t.join();
  16092. ASSERT_FALSE(svr.is_running());
  16093. });
  16094. svr.wait_until_ready();
  16095. Client cli(HOST, port);
  16096. auto res = cli.Get(pattern);
  16097. ASSERT_TRUE(res);
  16098. EXPECT_EQ(StatusCode::OK_200, res->status);
  16099. }
  16100. TEST(ParseUrlTest, VariousPatterns) {
  16101. {
  16102. detail::UrlComponents uc;
  16103. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16104. EXPECT_EQ("http", uc.scheme);
  16105. EXPECT_EQ("example.com", uc.host);
  16106. EXPECT_EQ("8080", uc.port);
  16107. EXPECT_EQ("/path", uc.path);
  16108. EXPECT_EQ("?q=1", uc.query);
  16109. }
  16110. {
  16111. detail::UrlComponents uc;
  16112. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16113. EXPECT_EQ("https", uc.scheme);
  16114. EXPECT_EQ("example.com", uc.host);
  16115. EXPECT_TRUE(uc.port.empty());
  16116. EXPECT_EQ("/path", uc.path);
  16117. }
  16118. {
  16119. detail::UrlComponents uc;
  16120. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16121. EXPECT_EQ("::1", uc.host);
  16122. EXPECT_EQ("8080", uc.port);
  16123. EXPECT_EQ("/path", uc.path);
  16124. }
  16125. {
  16126. detail::UrlComponents uc;
  16127. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16128. }
  16129. {
  16130. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16131. // the path while the connection still targets the bracketed host.
  16132. detail::UrlComponents uc;
  16133. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16134. }
  16135. {
  16136. detail::UrlComponents uc;
  16137. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16138. }
  16139. {
  16140. detail::UrlComponents uc;
  16141. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16142. EXPECT_EQ("::1", uc.host);
  16143. EXPECT_TRUE(uc.port.empty());
  16144. EXPECT_EQ("/path", uc.path);
  16145. }
  16146. {
  16147. detail::UrlComponents uc;
  16148. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16149. EXPECT_TRUE(uc.scheme.empty());
  16150. EXPECT_EQ("example.com", uc.host);
  16151. EXPECT_EQ("/path", uc.path);
  16152. EXPECT_EQ("?q=1", uc.query);
  16153. }
  16154. {
  16155. detail::UrlComponents uc;
  16156. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16157. EXPECT_TRUE(uc.host.empty());
  16158. EXPECT_EQ("/path", uc.path);
  16159. EXPECT_EQ("?q=1", uc.query);
  16160. }
  16161. {
  16162. detail::UrlComponents uc;
  16163. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16164. EXPECT_EQ("example.com", uc.host);
  16165. EXPECT_EQ("8080", uc.port);
  16166. }
  16167. {
  16168. // Unix socket path — must not be parsed as host
  16169. detail::UrlComponents uc;
  16170. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16171. EXPECT_TRUE(uc.host.empty());
  16172. }
  16173. {
  16174. detail::UrlComponents uc;
  16175. ASSERT_TRUE(detail::parse_url("", uc));
  16176. EXPECT_TRUE(uc.host.empty());
  16177. EXPECT_TRUE(uc.path.empty());
  16178. }
  16179. {
  16180. detail::UrlComponents uc;
  16181. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16182. }
  16183. {
  16184. detail::UrlComponents uc;
  16185. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16186. }
  16187. {
  16188. // Accepted by parse_url; callers restrict to http/https
  16189. detail::UrlComponents uc;
  16190. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16191. EXPECT_EQ("ftp", uc.scheme);
  16192. }
  16193. {
  16194. detail::UrlComponents uc;
  16195. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16196. }
  16197. {
  16198. detail::UrlComponents uc;
  16199. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16200. }
  16201. }
  16202. TEST(ParseUrlTest, FragmentHandling) {
  16203. {
  16204. detail::UrlComponents uc;
  16205. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16206. EXPECT_EQ("/path", uc.path);
  16207. EXPECT_TRUE(uc.query.empty());
  16208. }
  16209. {
  16210. detail::UrlComponents uc;
  16211. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16212. EXPECT_TRUE(uc.path.empty());
  16213. EXPECT_TRUE(uc.query.empty());
  16214. }
  16215. }
  16216. TEST(ParseUrlTest, UserinfoHandling) {
  16217. // Userinfo with @ but no colon — host includes @
  16218. detail::UrlComponents uc;
  16219. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16220. EXPECT_EQ("user@host.com", uc.host);
  16221. EXPECT_EQ("/path", uc.path);
  16222. }
  16223. TEST(ParseUrlTest, IPv6EdgeCases) {
  16224. {
  16225. detail::UrlComponents uc;
  16226. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16227. EXPECT_TRUE(uc.scheme.empty());
  16228. EXPECT_EQ("::1", uc.host);
  16229. EXPECT_EQ("8080", uc.port);
  16230. }
  16231. {
  16232. // Zone ID '%25' is not in [a-fA-F0-9:]
  16233. detail::UrlComponents uc;
  16234. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16235. }
  16236. }
  16237. TEST(ParseUrlTest, SchemeEdgeCases) {
  16238. {
  16239. detail::UrlComponents uc;
  16240. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16241. }
  16242. {
  16243. detail::UrlComponents uc;
  16244. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16245. }
  16246. {
  16247. detail::UrlComponents uc;
  16248. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16249. }
  16250. }
  16251. TEST(ParseUrlTest, PortEdgeCases) {
  16252. {
  16253. detail::UrlComponents uc;
  16254. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16255. EXPECT_TRUE(uc.port.empty());
  16256. EXPECT_EQ("/path", uc.path);
  16257. }
  16258. {
  16259. // parse_url accepts any port string; validation is done by parse_port
  16260. detail::UrlComponents uc;
  16261. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16262. EXPECT_EQ("abc", uc.port);
  16263. }
  16264. }
  16265. TEST(ParseUrlTest, WebSocketPatterns) {
  16266. {
  16267. detail::UrlComponents uc;
  16268. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16269. EXPECT_EQ("ws", uc.scheme);
  16270. EXPECT_EQ("echo.example.com", uc.host);
  16271. EXPECT_EQ("8080", uc.port);
  16272. EXPECT_EQ("/ws", uc.path);
  16273. }
  16274. {
  16275. detail::UrlComponents uc;
  16276. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16277. EXPECT_EQ("wss", uc.scheme);
  16278. EXPECT_EQ("echo.example.com", uc.host);
  16279. EXPECT_TRUE(uc.port.empty());
  16280. EXPECT_EQ("/ws", uc.path);
  16281. }
  16282. }
  16283. TEST(ParseUrlTest, QueryOnly) {
  16284. detail::UrlComponents uc;
  16285. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16286. EXPECT_TRUE(uc.host.empty());
  16287. EXPECT_TRUE(uc.path.empty());
  16288. EXPECT_EQ("?q=1&r=2", uc.query);
  16289. }
  16290. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16291. detail::UrlComponents uc;
  16292. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16293. EXPECT_TRUE(uc.scheme.empty());
  16294. EXPECT_EQ("example.com", uc.host);
  16295. EXPECT_EQ("443", uc.port);
  16296. EXPECT_EQ("/path", uc.path);
  16297. }
  16298. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16299. // If ipv6 regex working, regex match codepath is taken.
  16300. // else port will default to 80 in Client impl
  16301. int clientImplMagicPort = 80;
  16302. int port = 4321;
  16303. // above ports must be different to avoid false negative
  16304. EXPECT_NE(clientImplMagicPort, port);
  16305. std::string ipV6TestURL = "http://[ff06::c3]";
  16306. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16307. CLIENT_PRIVATE_KEY_FILE);
  16308. EXPECT_EQ(cli.port(), port);
  16309. }
  16310. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16311. auto file_path = "./www/dir/index.html";
  16312. auto dir_path = "./www/dir";
  16313. detail::FileStat stat_file(file_path);
  16314. EXPECT_TRUE(stat_file.is_file());
  16315. EXPECT_FALSE(stat_file.is_dir());
  16316. detail::FileStat stat_dir(dir_path);
  16317. EXPECT_FALSE(stat_dir.is_file());
  16318. EXPECT_TRUE(stat_dir.is_dir());
  16319. }
  16320. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16321. // IPv4 with default HTTP port (80)
  16322. EXPECT_EQ("example.com",
  16323. detail::make_host_and_port_string("example.com", 80, false));
  16324. // IPv4 with default HTTPS port (443)
  16325. EXPECT_EQ("example.com",
  16326. detail::make_host_and_port_string("example.com", 443, true));
  16327. // IPv4 with non-default HTTP port
  16328. EXPECT_EQ("example.com:8080",
  16329. detail::make_host_and_port_string("example.com", 8080, false));
  16330. // IPv4 with non-default HTTPS port
  16331. EXPECT_EQ("example.com:8443",
  16332. detail::make_host_and_port_string("example.com", 8443, true));
  16333. // IPv6 with default HTTP port (80)
  16334. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16335. // IPv6 with default HTTPS port (443)
  16336. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16337. // IPv6 with non-default HTTP port
  16338. EXPECT_EQ("[::1]:8080",
  16339. detail::make_host_and_port_string("::1", 8080, false));
  16340. // IPv6 with non-default HTTPS port
  16341. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16342. // IPv6 full address with default port
  16343. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16344. detail::make_host_and_port_string(
  16345. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16346. // IPv6 full address with non-default port
  16347. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16348. detail::make_host_and_port_string(
  16349. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16350. // IPv6 localhost with non-default port
  16351. EXPECT_EQ("[::1]:3000",
  16352. detail::make_host_and_port_string("::1", 3000, false));
  16353. // IPv6 with zone ID (link-local address) with default port
  16354. EXPECT_EQ("[fe80::1%eth0]",
  16355. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16356. // IPv6 with zone ID (link-local address) with non-default port
  16357. EXPECT_EQ("[fe80::1%eth0]:8080",
  16358. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16359. // Edge case: Port 443 with is_ssl=false (should add port)
  16360. EXPECT_EQ("example.com:443",
  16361. detail::make_host_and_port_string("example.com", 443, false));
  16362. // Edge case: Port 80 with is_ssl=true (should add port)
  16363. EXPECT_EQ("example.com:80",
  16364. detail::make_host_and_port_string("example.com", 80, true));
  16365. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16366. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16367. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16368. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16369. // Security fix: Already bracketed IPv6 should not get double brackets
  16370. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16371. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16372. EXPECT_EQ("[::1]:8080",
  16373. detail::make_host_and_port_string("[::1]", 8080, false));
  16374. EXPECT_EQ("[2001:db8::1]:8080",
  16375. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16376. EXPECT_EQ("[fe80::1%eth0]",
  16377. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16378. EXPECT_EQ("[fe80::1%eth0]:8080",
  16379. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16380. // Edge case: Empty host (should return as-is)
  16381. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16382. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16383. // This is a known limitation but shouldn't crash
  16384. EXPECT_EQ("[host:name]",
  16385. detail::make_host_and_port_string("host:name", 80, false));
  16386. // Port number edge cases (no validation, but should not crash)
  16387. EXPECT_EQ("example.com:0",
  16388. detail::make_host_and_port_string("example.com", 0, false));
  16389. EXPECT_EQ("example.com:-1",
  16390. detail::make_host_and_port_string("example.com", -1, false));
  16391. EXPECT_EQ("example.com:65535",
  16392. detail::make_host_and_port_string("example.com", 65535, false));
  16393. EXPECT_EQ("example.com:65536",
  16394. detail::make_host_and_port_string("example.com", 65536, false));
  16395. }
  16396. #ifdef CPPHTTPLIB_SSL_ENABLED
  16397. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16398. httplib::SSLClient cli("roblox.com", 443);
  16399. cli.set_follow_location(true);
  16400. auto res = cli.Get("/");
  16401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16402. EXPECT_EQ(StatusCode::OK_200, res->status);
  16403. }
  16404. #endif
  16405. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16406. Server svr;
  16407. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16408. EXPECT_EQ(res.status, 400);
  16409. });
  16410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16411. auto se = detail::scope_exit([&] {
  16412. svr.stop();
  16413. thread.join();
  16414. ASSERT_FALSE(svr.is_running());
  16415. });
  16416. svr.wait_until_ready();
  16417. Client cli(HOST, PORT);
  16418. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16419. }
  16420. TEST(InvalidHeaderCharsTest, is_field_name) {
  16421. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16422. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16423. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16424. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16425. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16426. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16427. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16428. EXPECT_FALSE(detail::fields::is_field_name(""));
  16429. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16430. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16431. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16432. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16433. }
  16434. TEST(InvalidHeaderCharsTest, is_field_value) {
  16435. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16436. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16437. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16438. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16439. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16440. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16441. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16442. EXPECT_TRUE(detail::fields::is_field_value(""));
  16443. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16444. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16445. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16446. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16447. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16448. }
  16449. TEST(InvalidHeaderCharsTest, OnServer) {
  16450. Server svr;
  16451. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16452. std::string header = "Not Set";
  16453. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16454. res.set_header(header, "value");
  16455. res.set_content("Page Content Page Content", "text/plain");
  16456. });
  16457. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16458. std::string header = "Not Set";
  16459. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16460. res.set_header("X-Test", header);
  16461. res.set_content("Page Content Page Content", "text/plain");
  16462. });
  16463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16464. auto se = detail::scope_exit([&] {
  16465. svr.stop();
  16466. thread.join();
  16467. ASSERT_FALSE(svr.is_running());
  16468. });
  16469. svr.wait_until_ready();
  16470. Client cli(HOST, PORT);
  16471. {
  16472. auto res = cli.Get(
  16473. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16475. EXPECT_EQ("Page Content Page Content", res->body);
  16476. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16477. }
  16478. {
  16479. auto res = cli.Get(
  16480. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16482. EXPECT_EQ("Page Content Page Content", res->body);
  16483. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16484. }
  16485. }
  16486. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16487. auto handled = false;
  16488. Server svr;
  16489. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16490. thread t = thread([&] { svr.listen(HOST, PORT); });
  16491. auto se = detail::scope_exit([&] {
  16492. svr.stop();
  16493. t.join();
  16494. ASSERT_FALSE(svr.is_running());
  16495. ASSERT_FALSE(handled);
  16496. });
  16497. svr.wait_until_ready();
  16498. auto req = "POST /test HTTP/1.1\r\n"
  16499. "Content-Length: x\r\n"
  16500. "\r\n";
  16501. std::string response;
  16502. ASSERT_TRUE(send_request(1, req, &response));
  16503. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16504. response.substr(0, response.find("\r\n")));
  16505. }
  16506. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16507. // case-insensitive, and a server that receives a 100-continue expectation in
  16508. // an HTTP/1.0 request MUST ignore it.
  16509. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16510. std::string response;
  16511. ASSERT_TRUE(send_request(1, req, &response, port));
  16512. *got_100 = response.find("100 Continue") != std::string::npos;
  16513. }
  16514. class ExpectTokenTest : public ::testing::Test {
  16515. protected:
  16516. void SetUp() override {
  16517. svr_.Post("/p", [](const Request &, Response &res) {
  16518. res.set_content("ok", "text/plain");
  16519. });
  16520. port_ = svr_.bind_to_any_port(HOST);
  16521. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16522. svr_.wait_until_ready();
  16523. }
  16524. void TearDown() override {
  16525. svr_.stop();
  16526. if (thread_.joinable()) { thread_.join(); }
  16527. }
  16528. std::string request(const char *version, const char *expect_value) const {
  16529. return std::string("POST /p ") + version +
  16530. "\r\n"
  16531. "Host: localhost\r\n"
  16532. "Content-Length: 2\r\n"
  16533. "Connection: close\r\n"
  16534. "Expect: " +
  16535. expect_value +
  16536. "\r\n"
  16537. "\r\n"
  16538. "hi";
  16539. }
  16540. Server svr_;
  16541. int port_ = 0;
  16542. thread thread_;
  16543. };
  16544. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16545. bool got_100 = false;
  16546. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16547. EXPECT_TRUE(got_100);
  16548. }
  16549. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16550. bool got_100 = true;
  16551. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16552. EXPECT_FALSE(got_100);
  16553. }
  16554. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16555. bool got_100 = false;
  16556. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16557. EXPECT_TRUE(got_100);
  16558. }
  16559. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16560. bool got_100 = false;
  16561. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16562. EXPECT_TRUE(got_100);
  16563. }
  16564. // `100 Continue` is sent only when the server starts reading the body, so a
  16565. // request rejected before that never invites the client to send it. The
  16566. // requests below carry the expectation but withhold the body, as a client
  16567. // waiting for `100 Continue` would.
  16568. // A POST that expects `100 Continue` and withholds its two-byte body.
  16569. static std::string expect_headers_only(const std::string &path) {
  16570. return "POST " + path +
  16571. " HTTP/1.1\r\n"
  16572. "Host: localhost\r\n"
  16573. "Content-Length: 2\r\n"
  16574. "Expect: 100-continue\r\n"
  16575. "\r\n";
  16576. }
  16577. class ExpectLazyContinueTest : public ::testing::Test {
  16578. protected:
  16579. void SetUp() override {
  16580. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16581. if (req.path == "/pre-routing") {
  16582. res.status = StatusCode::Unauthorized_401;
  16583. return Server::HandlerResponse::Handled;
  16584. }
  16585. return Server::HandlerResponse::Unhandled;
  16586. });
  16587. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16588. if (req.matched_route == "/pre-request") {
  16589. res.status = StatusCode::Forbidden_403;
  16590. return Server::HandlerResponse::Handled;
  16591. }
  16592. return Server::HandlerResponse::Unhandled;
  16593. });
  16594. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16595. res.set_content("ok", "text/plain");
  16596. });
  16597. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16598. res.set_content("ok", "text/plain");
  16599. });
  16600. svr_.Post("/reader-used", [](const Request &, Response &res,
  16601. const ContentReader &content_reader) {
  16602. std::string body;
  16603. content_reader([&](const char *data, size_t len) {
  16604. body.append(data, len);
  16605. return true;
  16606. });
  16607. res.set_content(body, "text/plain");
  16608. });
  16609. svr_.Post("/reader-unused",
  16610. [](const Request &, Response &res, const ContentReader &) {
  16611. res.set_content("ignored", "text/plain");
  16612. });
  16613. port_ = svr_.bind_to_any_port(HOST);
  16614. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16615. svr_.wait_until_ready();
  16616. }
  16617. void TearDown() override {
  16618. svr_.stop();
  16619. if (thread_.joinable()) { thread_.join(); }
  16620. }
  16621. // Sends `req` and reads until the server closes the connection. Returns
  16622. // false if the read had to wait for the client-side timeout instead.
  16623. bool send_until_closed(const std::string &req, std::string *resp) const {
  16624. auto start = std::chrono::steady_clock::now();
  16625. if (!send_request(3, req, resp, port_)) { return false; }
  16626. auto elapsed = std::chrono::steady_clock::now() - start;
  16627. return elapsed < std::chrono::seconds(2);
  16628. }
  16629. // The final response comes without `100 Continue`, and the server closes
  16630. // the connection since the body may or may not follow.
  16631. void expect_final_without_interim(const std::string &path,
  16632. const char *status_line) const {
  16633. std::string resp;
  16634. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16635. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16636. EXPECT_EQ(0u, resp.find(status_line));
  16637. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16638. }
  16639. Server svr_;
  16640. int port_ = 0;
  16641. thread thread_;
  16642. };
  16643. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16644. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16645. }
  16646. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16647. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16648. }
  16649. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16650. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16651. }
  16652. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16653. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16654. }
  16655. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16656. // The body follows once `100 Continue` has had time to arrive.
  16657. auto req = expect_headers_only("/reader-used");
  16658. req.insert(req.size() - 2, "Connection: close\r\n");
  16659. std::string resp;
  16660. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16661. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16662. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16663. EXPECT_NE(std::string::npos, resp.find("hi"));
  16664. }
  16665. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16666. // Large enough for the client to add `Expect: 100-continue` itself.
  16667. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16668. std::atomic<bool> body_sent{false};
  16669. Client cli(HOST, port_);
  16670. auto res = cli.Post(
  16671. "/pre-request", length,
  16672. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16673. body_sent = true;
  16674. std::string chunk(len, 'x');
  16675. sink.write(chunk.data(), chunk.size());
  16676. return true;
  16677. },
  16678. "application/octet-stream");
  16679. ASSERT_TRUE(res);
  16680. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16681. EXPECT_FALSE(body_sent);
  16682. }
  16683. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16684. Server svr;
  16685. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16686. return StatusCode::ExpectationFailed_417;
  16687. });
  16688. svr.Post("/p", [](const Request &, Response &res) {
  16689. res.set_content("ok", "text/plain");
  16690. });
  16691. auto port = svr.bind_to_any_port(HOST);
  16692. thread t = thread([&] { svr.listen_after_bind(); });
  16693. auto se = detail::scope_exit([&] {
  16694. svr.stop();
  16695. t.join();
  16696. });
  16697. svr.wait_until_ready();
  16698. std::string resp;
  16699. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16700. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16701. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16702. // Exactly one response: the route handler must not run after the 417.
  16703. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16704. }
  16705. #ifndef _WIN32
  16706. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16707. static constexpr char reject[] = "Unauthorized";
  16708. static constexpr char accept[] = "Upload accepted";
  16709. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16710. Server svr;
  16711. svr.set_expect_100_continue_handler(
  16712. [](const Request & /*req*/, Response &res) {
  16713. res.status = StatusCode::Unauthorized_401;
  16714. res.set_content(reject, "text/plain");
  16715. return res.status;
  16716. });
  16717. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16718. res.set_content(accept, "text/plain");
  16719. });
  16720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16721. auto se = detail::scope_exit([&] {
  16722. svr.stop();
  16723. thread.join();
  16724. ASSERT_FALSE(svr.is_running());
  16725. });
  16726. svr.wait_until_ready();
  16727. {
  16728. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16729. curl_easy_init(), &curl_easy_cleanup};
  16730. ASSERT_NE(curl, nullptr);
  16731. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16732. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16733. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16734. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16735. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16736. &curl_slist_free_all};
  16737. ASSERT_NE(list, nullptr);
  16738. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16739. struct read_data {
  16740. size_t read_size;
  16741. size_t total_size;
  16742. } data = {0, total_size};
  16743. using read_callback_t =
  16744. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16745. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16746. void *userdata) -> size_t {
  16747. read_data *d = (read_data *)userdata;
  16748. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16749. std::fill_n(ptr, size * nmemb, 'A');
  16750. d->read_size += size * nmemb;
  16751. return size * nmemb;
  16752. };
  16753. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16754. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16755. std::vector<char> buffer;
  16756. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16757. using write_callback_t =
  16758. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16759. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16760. void *userdata) -> size_t {
  16761. std::vector<char> *buf = (std::vector<char> *)userdata;
  16762. buf->reserve(buf->size() + size * nmemb + 1);
  16763. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16764. return size * nmemb;
  16765. };
  16766. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16767. {
  16768. const auto res = curl_easy_perform(curl.get());
  16769. ASSERT_EQ(res, CURLE_OK);
  16770. }
  16771. {
  16772. auto response_code = long{};
  16773. const auto res =
  16774. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16775. ASSERT_EQ(res, CURLE_OK);
  16776. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16777. }
  16778. {
  16779. auto dl = curl_off_t{};
  16780. const auto res =
  16781. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16782. ASSERT_EQ(res, CURLE_OK);
  16783. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16784. }
  16785. {
  16786. buffer.push_back('\0');
  16787. ASSERT_STRCASEEQ(buffer.data(), reject);
  16788. }
  16789. }
  16790. }
  16791. #endif
  16792. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16793. // Regression test for #2458.
  16794. //
  16795. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16796. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16797. // ticket can make the client socket spuriously readable during the
  16798. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16799. // the client withholds the body and then blocks reading a response that never
  16800. // comes, failing with `Failed to read connection`.
  16801. //
  16802. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16803. // within the timeout. This raw OpenSSL server deliberately never sends
  16804. // `100 Continue`; the client must still deliver the body and receive 200.
  16805. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16806. signal(SIGPIPE, SIG_IGN);
  16807. const auto port = PORT + 4;
  16808. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16809. ASSERT_NE(srv, INVALID_SOCKET);
  16810. int opt = 1;
  16811. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16812. sockaddr_in addr{};
  16813. addr.sin_family = AF_INET;
  16814. addr.sin_port = htons(static_cast<uint16_t>(port));
  16815. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16816. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16817. ASSERT_EQ(0, ::listen(srv, 1));
  16818. std::atomic<size_t> server_body_bytes{0};
  16819. auto server_thread = std::thread([&] {
  16820. sockaddr_in cli_addr{};
  16821. socklen_t cli_len = sizeof(cli_addr);
  16822. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16823. if (cli == INVALID_SOCKET) { return; }
  16824. // Bound the lifetime of the server side so a buggy client (which never
  16825. // sends the body) cannot make this thread block forever on join.
  16826. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16827. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16828. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16829. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16830. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16831. SSL *ssl = SSL_new(ctx);
  16832. SSL_set_fd(ssl, static_cast<int>(cli));
  16833. if (SSL_accept(ssl) > 0) {
  16834. // Read the request headers. Reading here also flushes the TLS 1.3
  16835. // session tickets to the client. Deliberately do NOT send
  16836. // `100 Continue`.
  16837. std::string buf;
  16838. char tmp[1024];
  16839. while (buf.find("\r\n\r\n") == std::string::npos) {
  16840. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16841. if (n <= 0) { break; }
  16842. buf.append(tmp, static_cast<size_t>(n));
  16843. }
  16844. // A correct client sends the body now; count what arrives.
  16845. auto pos = buf.find("\r\n\r\n");
  16846. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16847. while (body < 4096) {
  16848. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16849. if (n <= 0) { break; }
  16850. body += static_cast<size_t>(n);
  16851. }
  16852. server_body_bytes = body;
  16853. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16854. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16855. SSL_shutdown(ssl);
  16856. }
  16857. SSL_free(ssl);
  16858. detail::close_socket(cli);
  16859. SSL_CTX_free(ctx);
  16860. });
  16861. auto se = detail::scope_exit([&] {
  16862. server_thread.join();
  16863. detail::close_socket(srv);
  16864. });
  16865. SSLClient cli("127.0.0.1", port);
  16866. cli.enable_server_certificate_verification(false);
  16867. cli.set_connection_timeout(5, 0);
  16868. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16869. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16870. std::string body(4096, 'A');
  16871. auto res = cli.Put("/api/test", body, "application/json");
  16872. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16873. EXPECT_EQ(StatusCode::OK_200, res->status);
  16874. EXPECT_EQ(body.size(), server_body_bytes.load());
  16875. }
  16876. #endif
  16877. template <typename S, typename C>
  16878. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16879. svr.Get("/stream", [&](const Request &, Response &res) {
  16880. auto data = new std::string("01234567890123456789");
  16881. res.set_content_provider(
  16882. data->size(), "text/plain",
  16883. [&, data](size_t offset, size_t length, DataSink &sink) {
  16884. const size_t DATA_CHUNK_SIZE = 4;
  16885. const auto &d = *data;
  16886. std::this_thread::sleep_for(std::chrono::seconds(1));
  16887. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16888. return true;
  16889. },
  16890. [data](bool success) {
  16891. EXPECT_FALSE(success);
  16892. delete data;
  16893. });
  16894. });
  16895. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16896. auto i = new size_t(0);
  16897. res.set_content_provider(
  16898. "text/plain",
  16899. [i](size_t, DataSink &sink) {
  16900. if (*i < 5) {
  16901. std::this_thread::sleep_for(std::chrono::seconds(1));
  16902. sink.write("abcd", 4);
  16903. (*i)++;
  16904. } else {
  16905. sink.done();
  16906. }
  16907. return true;
  16908. },
  16909. [i](bool success) {
  16910. EXPECT_FALSE(success);
  16911. delete i;
  16912. });
  16913. });
  16914. svr.Get("/chunked", [&](const Request &, Response &res) {
  16915. auto i = new size_t(0);
  16916. res.set_chunked_content_provider(
  16917. "text/plain",
  16918. [i](size_t, DataSink &sink) {
  16919. if (*i < 5) {
  16920. std::this_thread::sleep_for(std::chrono::seconds(1));
  16921. sink.os << "abcd";
  16922. (*i)++;
  16923. } else {
  16924. sink.done();
  16925. }
  16926. return true;
  16927. },
  16928. [i](bool success) {
  16929. EXPECT_FALSE(success);
  16930. delete i;
  16931. });
  16932. });
  16933. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16934. auto se = detail::scope_exit([&] {
  16935. svr.stop();
  16936. listen_thread.join();
  16937. ASSERT_FALSE(svr.is_running());
  16938. });
  16939. svr.wait_until_ready();
  16940. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16941. {
  16942. auto start = std::chrono::steady_clock::now();
  16943. auto res = cli.Get("/stream");
  16944. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16945. std::chrono::steady_clock::now() - start)
  16946. .count();
  16947. ASSERT_FALSE(res);
  16948. EXPECT_EQ(Error::Read, res.error());
  16949. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16950. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16951. }
  16952. {
  16953. auto start = std::chrono::steady_clock::now();
  16954. auto res = cli.Get("/stream_without_length");
  16955. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16956. std::chrono::steady_clock::now() - start)
  16957. .count();
  16958. ASSERT_FALSE(res);
  16959. EXPECT_EQ(Error::Read, res.error());
  16960. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16961. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16962. }
  16963. {
  16964. auto start = std::chrono::steady_clock::now();
  16965. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16966. EXPECT_EQ("abcd", string(data, data_length));
  16967. return true;
  16968. });
  16969. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16970. std::chrono::steady_clock::now() - start)
  16971. .count();
  16972. ASSERT_FALSE(res);
  16973. EXPECT_EQ(Error::Read, res.error());
  16974. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16975. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16976. }
  16977. }
  16978. TEST(MaxTimeoutTest, ContentStream) {
  16979. time_t timeout = 2000;
  16980. time_t threshold = 200;
  16981. Server svr;
  16982. Client cli("localhost", PORT);
  16983. max_timeout_test(svr, cli, timeout, threshold);
  16984. }
  16985. #ifdef CPPHTTPLIB_SSL_ENABLED
  16986. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16987. time_t timeout = 2000;
  16988. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16989. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16990. SSLClient cli("localhost", PORT);
  16991. cli.enable_server_certificate_verification(false);
  16992. max_timeout_test(svr, cli, timeout, threshold);
  16993. }
  16994. #endif
  16995. class EventDispatcher {
  16996. public:
  16997. EventDispatcher() {}
  16998. bool wait_event(DataSink *sink) {
  16999. unique_lock<mutex> lk(m_);
  17000. int id = id_;
  17001. // Wait with timeout to prevent hanging if client disconnects
  17002. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17003. [&] { return cid_ == id; })) {
  17004. return false; // Timeout occurred
  17005. }
  17006. sink->write(message_.data(), message_.size());
  17007. return true;
  17008. }
  17009. void send_event(const string &message) {
  17010. lock_guard<mutex> lk(m_);
  17011. cid_ = id_++;
  17012. message_ = message;
  17013. cv_.notify_all();
  17014. }
  17015. private:
  17016. mutex m_;
  17017. condition_variable cv_;
  17018. atomic_int id_{0};
  17019. atomic_int cid_{-1};
  17020. string message_;
  17021. };
  17022. TEST(ClientInThreadTest, Issue2068) {
  17023. EventDispatcher ed;
  17024. Server svr;
  17025. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17026. res.set_chunked_content_provider("text/event-stream",
  17027. [&](size_t /*offset*/, DataSink &sink) {
  17028. return ed.wait_event(&sink);
  17029. });
  17030. });
  17031. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17032. svr.wait_until_ready();
  17033. thread event_thread([&] {
  17034. int id = 0;
  17035. while (svr.is_running()) {
  17036. this_thread::sleep_for(chrono::milliseconds(500));
  17037. std::stringstream ss;
  17038. ss << "data: " << id << "\n\n";
  17039. ed.send_event(ss.str());
  17040. id++;
  17041. }
  17042. });
  17043. auto se = detail::scope_exit([&] {
  17044. svr.stop();
  17045. listen_thread.join();
  17046. event_thread.join();
  17047. ASSERT_FALSE(svr.is_running());
  17048. });
  17049. {
  17050. auto client = detail::make_unique<Client>(HOST, PORT);
  17051. client->set_read_timeout(std::chrono::minutes(10));
  17052. std::atomic<bool> stop{false};
  17053. std::thread t([&] {
  17054. client->Get("/event1",
  17055. [&](const char *, size_t) -> bool { return !stop; });
  17056. });
  17057. std::this_thread::sleep_for(std::chrono::seconds(2));
  17058. stop = true;
  17059. client->stop();
  17060. t.join();
  17061. // Reset client after thread has finished
  17062. client.reset();
  17063. }
  17064. }
  17065. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17066. auto handled = false;
  17067. Server svr;
  17068. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17069. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17070. auto se = detail::scope_exit([&] {
  17071. svr.stop();
  17072. t.join();
  17073. ASSERT_FALSE(svr.is_running());
  17074. ASSERT_FALSE(handled);
  17075. });
  17076. svr.wait_until_ready();
  17077. // Two Content-Length headers with different values — must be rejected
  17078. auto req = "POST /test HTTP/1.1\r\n"
  17079. "Content-Length: 5\r\n"
  17080. "Content-Length: 10\r\n"
  17081. "\r\n"
  17082. "hello";
  17083. std::string response;
  17084. ASSERT_TRUE(send_request(1, req, &response));
  17085. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17086. response.substr(0, response.find("\r\n")));
  17087. }
  17088. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17089. auto handled = false;
  17090. Server svr;
  17091. svr.Post("/test", [&](const Request &, Response &res) {
  17092. handled = true;
  17093. res.set_content("ok", "text/plain");
  17094. });
  17095. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17096. auto se = detail::scope_exit([&] {
  17097. svr.stop();
  17098. t.join();
  17099. ASSERT_FALSE(svr.is_running());
  17100. ASSERT_TRUE(handled);
  17101. });
  17102. svr.wait_until_ready();
  17103. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17104. auto req = "POST /test HTTP/1.1\r\n"
  17105. "Content-Length: 5\r\n"
  17106. "Content-Length: 5\r\n"
  17107. "\r\n"
  17108. "hello";
  17109. std::string response;
  17110. ASSERT_TRUE(send_request(1, req, &response));
  17111. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17112. }
  17113. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17114. Server svr;
  17115. svr.Get("/test", [](const Request &, Response &res) {
  17116. res.set_content("ok", "text/plain");
  17117. });
  17118. auto port = svr.bind_to_any_port(HOST);
  17119. thread t = thread([&] { svr.listen_after_bind(); });
  17120. auto se = detail::scope_exit([&] {
  17121. svr.stop();
  17122. t.join();
  17123. ASSERT_FALSE(svr.is_running());
  17124. });
  17125. svr.wait_until_ready();
  17126. auto status_line = [&](const std::string &host_lines) {
  17127. std::string res;
  17128. send_request(
  17129. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17130. &res, port);
  17131. return res.substr(0, res.find("\r\n"));
  17132. };
  17133. const char *accepted[] = {
  17134. "Host: localhost\r\n",
  17135. "Host: a.example:8080\r\n",
  17136. "Host: my_service\r\n",
  17137. "Host: [::1]:8080\r\n",
  17138. "Host: [fe80::1%25eth0]\r\n",
  17139. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17140. };
  17141. for (auto host_lines : accepted) {
  17142. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17143. }
  17144. const char *rejected[] = {
  17145. "Host: a.example\r\nHost: b.example\r\n",
  17146. "Host: a.example\r\nHost: a.example\r\n",
  17147. "Host: a@b.example\r\n",
  17148. "Host: a.example/b\r\n",
  17149. "Host: a.example\\b\r\n",
  17150. "Host: a.example?b\r\n",
  17151. "Host: a.example#b\r\n",
  17152. "Host: a.example b.example\r\n",
  17153. };
  17154. for (auto host_lines : rejected) {
  17155. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17156. << host_lines;
  17157. }
  17158. }
  17159. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17160. Server svr;
  17161. svr.Get("/", [](const Request &req, Response &res) {
  17162. EXPECT_EQ(2U, req.trailers.size());
  17163. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17164. // Denied
  17165. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17166. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17167. // Accepted
  17168. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17169. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17170. EXPECT_TRUE(req.has_trailer("X-World"));
  17171. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17172. res.set_content("ok", "text/plain");
  17173. });
  17174. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17175. auto se = detail::scope_exit([&] {
  17176. svr.stop();
  17177. t.join();
  17178. ASSERT_FALSE(svr.is_running());
  17179. });
  17180. svr.wait_until_ready();
  17181. const std::string req = "GET / HTTP/1.1\r\n"
  17182. "Transfer-Encoding: chunked\r\n"
  17183. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17184. "\r\n"
  17185. "0\r\n"
  17186. "Content-Length: 10\r\n"
  17187. "Host: internal.local\r\n"
  17188. "Content-Type: malicious/content\r\n"
  17189. "Cookie: any\r\n"
  17190. "Set-Cookie: any\r\n"
  17191. "X-Forwarded-For: attacker.com\r\n"
  17192. "X-Real-Ip: 1.1.1.1\r\n"
  17193. "X-Hello: hello\r\n"
  17194. "X-World: world\r\n"
  17195. "\r\n";
  17196. std::string res;
  17197. ASSERT_TRUE(send_request(1, req, &res));
  17198. }
  17199. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17200. // several field lines, and the combined value is what has to be parsed. A
  17201. // Trailer field split across lines therefore declares every name it lists;
  17202. // reading only the first line silently drops the trailers the later lines
  17203. // declare. The prohibited-trailer filter still applies to every line.
  17204. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17205. Server svr;
  17206. size_t observed_trailer_count = 0;
  17207. std::string observed_hello;
  17208. std::string observed_world;
  17209. bool observed_content_length = true;
  17210. svr.Get("/", [&](const Request &req, Response &res) {
  17211. observed_trailer_count = req.trailers.size();
  17212. observed_hello = req.get_trailer_value("X-Hello");
  17213. observed_world = req.get_trailer_value("X-World");
  17214. observed_content_length = req.has_trailer("Content-Length");
  17215. res.set_content("ok", "text/plain");
  17216. });
  17217. auto port = svr.bind_to_any_port(HOST);
  17218. thread t = thread([&]() { svr.listen_after_bind(); });
  17219. auto se = detail::scope_exit([&] {
  17220. svr.stop();
  17221. t.join();
  17222. ASSERT_FALSE(svr.is_running());
  17223. });
  17224. svr.wait_until_ready();
  17225. const std::string req = "GET / HTTP/1.1\r\n"
  17226. "Transfer-Encoding: chunked\r\n"
  17227. "Trailer: X-Hello\r\n"
  17228. "Trailer: X-World, Content-Length\r\n"
  17229. "\r\n"
  17230. "0\r\n"
  17231. "X-Hello: hello\r\n"
  17232. "X-World: world\r\n"
  17233. "Content-Length: 10\r\n"
  17234. "\r\n";
  17235. std::string res;
  17236. ASSERT_TRUE(send_request(1, req, &res, port));
  17237. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17238. // Accepted: both field lines contribute to the declared set
  17239. EXPECT_EQ(2U, observed_trailer_count);
  17240. EXPECT_EQ(observed_hello, "hello");
  17241. EXPECT_EQ(observed_world, "world");
  17242. // Denied: a prohibited name stays prohibited on a later field line
  17243. EXPECT_FALSE(observed_content_length);
  17244. }
  17245. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17246. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17247. // unbounded run of fields that are never declared, because the counter would
  17248. // only advance for declared fields.
  17249. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17250. Server svr;
  17251. bool handler_called = false;
  17252. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17253. handler_called = true;
  17254. res.set_content("ok", "text/plain");
  17255. });
  17256. auto port = svr.bind_to_any_port(HOST);
  17257. thread t = thread([&]() { svr.listen_after_bind(); });
  17258. auto se = detail::scope_exit([&] {
  17259. svr.stop();
  17260. t.join();
  17261. ASSERT_FALSE(svr.is_running());
  17262. });
  17263. svr.wait_until_ready();
  17264. // Declare nothing, then send far more undeclared trailer fields than the
  17265. // header-count limit. Parsing must stop and reject the request rather than
  17266. // read every line.
  17267. std::string req = "GET / HTTP/1.1\r\n"
  17268. "Transfer-Encoding: chunked\r\n"
  17269. "\r\n"
  17270. "0\r\n";
  17271. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17272. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17273. }
  17274. req += "\r\n";
  17275. std::string res;
  17276. ASSERT_TRUE(send_request(1, req, &res, port));
  17277. // The request is rejected before the handler runs.
  17278. EXPECT_FALSE(handler_called);
  17279. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17280. }
  17281. // The set of declared trailer names is capped so a peer cannot grow it without
  17282. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17283. // declared past the cap is not honored, even if the field is actually sent.
  17284. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17285. Server svr;
  17286. // One name inside the cap and one past it, so the test tracks the cap rather
  17287. // than a fixed count.
  17288. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17289. const std::string within_cap_name = "X-T-0";
  17290. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17291. bool observed_within_cap = false;
  17292. bool observed_past_cap = false;
  17293. svr.Get("/", [&](const Request &req, Response &res) {
  17294. observed_within_cap = req.has_trailer(within_cap_name);
  17295. observed_past_cap = req.has_trailer(past_cap_name);
  17296. res.set_content("ok", "text/plain");
  17297. });
  17298. auto port = svr.bind_to_any_port(HOST);
  17299. thread t = thread([&]() { svr.listen_after_bind(); });
  17300. auto se = detail::scope_exit([&] {
  17301. svr.stop();
  17302. t.join();
  17303. ASSERT_FALSE(svr.is_running());
  17304. });
  17305. svr.wait_until_ready();
  17306. // Declare more trailer names than the cap in a single Trailer field, then
  17307. // actually send the first (within the cap) and the last (past it).
  17308. std::string trailer_decl = "Trailer: ";
  17309. for (int i = 0; i < declared_count; i++) {
  17310. if (i != 0) { trailer_decl += ", "; }
  17311. trailer_decl += "X-T-" + std::to_string(i);
  17312. }
  17313. trailer_decl += "\r\n";
  17314. const std::string req = "GET / HTTP/1.1\r\n"
  17315. "Transfer-Encoding: chunked\r\n" +
  17316. trailer_decl +
  17317. "\r\n"
  17318. "0\r\n" +
  17319. within_cap_name + ": a\r\n" + past_cap_name +
  17320. ": b\r\n"
  17321. "\r\n";
  17322. std::string res;
  17323. ASSERT_TRUE(send_request(1, req, &res, port));
  17324. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17325. // A name within the cap is honored; one declared past the cap is dropped.
  17326. EXPECT_TRUE(observed_within_cap);
  17327. EXPECT_FALSE(observed_past_cap);
  17328. }
  17329. // A direct client that is not listed in trusted_proxies must not be able to
  17330. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17331. // the peer address on the actual TCP connection determines whether the
  17332. // header is honored.
  17333. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17334. Server svr;
  17335. // Deliberately does NOT include the loopback address the test client
  17336. // actually connects from, so the direct connection is not a trusted proxy.
  17337. svr.set_trusted_proxies({"203.0.113.66"});
  17338. std::string observed_remote_addr;
  17339. svr.Get("/ip", [&](const Request &req, Response &res) {
  17340. observed_remote_addr = req.remote_addr;
  17341. res.set_content("ok", "text/plain");
  17342. });
  17343. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17344. auto se = detail::scope_exit([&] {
  17345. svr.stop();
  17346. t.join();
  17347. ASSERT_FALSE(svr.is_running());
  17348. });
  17349. svr.wait_until_ready();
  17350. Client cli(HOST, PORT);
  17351. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17353. EXPECT_EQ(StatusCode::OK_200, res->status);
  17354. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17355. // ignored entirely and the real connection-level address retained.
  17356. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17357. observed_remote_addr == "127.0.0.1");
  17358. }
  17359. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17360. Server svr;
  17361. std::string observed_remote_addr;
  17362. std::string observed_xff;
  17363. svr.Get("/ip", [&](const Request &req, Response &res) {
  17364. observed_remote_addr = req.remote_addr;
  17365. observed_xff = req.get_header_value("X-Forwarded-For");
  17366. res.set_content("ok", "text/plain");
  17367. });
  17368. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17369. auto se = detail::scope_exit([&] {
  17370. svr.stop();
  17371. t.join();
  17372. ASSERT_FALSE(svr.is_running());
  17373. });
  17374. svr.wait_until_ready();
  17375. Client cli(HOST, PORT);
  17376. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17378. EXPECT_EQ(StatusCode::OK_200, res->status);
  17379. EXPECT_EQ(observed_xff, "203.0.113.66");
  17380. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17381. observed_remote_addr == "127.0.0.1");
  17382. }
  17383. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17384. Server svr;
  17385. svr.set_trusted_proxies({"203.0.113.66"});
  17386. std::string observed_remote_addr;
  17387. std::string observed_xff;
  17388. svr.Get("/ip", [&](const Request &req, Response &res) {
  17389. observed_remote_addr = req.remote_addr;
  17390. observed_xff = req.get_header_value("X-Forwarded-For");
  17391. res.set_content("ok", "text/plain");
  17392. });
  17393. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17394. auto se = detail::scope_exit([&] {
  17395. svr.stop();
  17396. t.join();
  17397. ASSERT_FALSE(svr.is_running());
  17398. });
  17399. svr.wait_until_ready();
  17400. Client cli(HOST, PORT);
  17401. auto res = cli.Get("/ip");
  17402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17403. EXPECT_EQ(StatusCode::OK_200, res->status);
  17404. EXPECT_EQ(observed_xff, "");
  17405. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17406. observed_remote_addr == "127.0.0.1");
  17407. }
  17408. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17409. Server svr;
  17410. // Include the loopback address the test client actually connects from, so
  17411. // the direct connection itself is recognized as the trusted proxy hop.
  17412. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17413. std::string observed_remote_addr;
  17414. std::string observed_xff;
  17415. svr.Get("/ip", [&](const Request &req, Response &res) {
  17416. observed_remote_addr = req.remote_addr;
  17417. observed_xff = req.get_header_value("X-Forwarded-For");
  17418. res.set_content("ok", "text/plain");
  17419. });
  17420. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17421. auto se = detail::scope_exit([&] {
  17422. svr.stop();
  17423. t.join();
  17424. ASSERT_FALSE(svr.is_running());
  17425. });
  17426. svr.wait_until_ready();
  17427. Client cli(HOST, PORT);
  17428. auto res = cli.Get(
  17429. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17431. EXPECT_EQ(StatusCode::OK_200, res->status);
  17432. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17433. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17434. }
  17435. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17436. Server svr;
  17437. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17438. std::string observed_remote_addr;
  17439. std::string observed_xff;
  17440. svr.Get("/ip", [&](const Request &req, Response &res) {
  17441. observed_remote_addr = req.remote_addr;
  17442. observed_xff = req.get_header_value("X-Forwarded-For");
  17443. res.set_content("ok", "text/plain");
  17444. });
  17445. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17446. auto se = detail::scope_exit([&] {
  17447. svr.stop();
  17448. t.join();
  17449. ASSERT_FALSE(svr.is_running());
  17450. });
  17451. svr.wait_until_ready();
  17452. Client cli(HOST, PORT);
  17453. auto res = cli.Get(
  17454. "/ip",
  17455. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17457. EXPECT_EQ(StatusCode::OK_200, res->status);
  17458. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17459. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17460. }
  17461. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17462. Server svr;
  17463. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17464. std::string observed_remote_addr;
  17465. std::string observed_xff;
  17466. svr.Get("/ip", [&](const Request &req, Response &res) {
  17467. observed_remote_addr = req.remote_addr;
  17468. observed_xff = req.get_header_value("X-Forwarded-For");
  17469. res.set_content("ok", "text/plain");
  17470. });
  17471. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17472. auto se = detail::scope_exit([&] {
  17473. svr.stop();
  17474. t.join();
  17475. ASSERT_FALSE(svr.is_running());
  17476. });
  17477. svr.wait_until_ready();
  17478. Client cli(HOST, PORT);
  17479. auto res = cli.Get(
  17480. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17482. EXPECT_EQ(StatusCode::OK_200, res->status);
  17483. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17484. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17485. // and must not be selected.
  17486. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17487. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17488. }
  17489. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17490. Server svr;
  17491. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17492. std::string observed_remote_addr;
  17493. svr.Get("/ip", [&](const Request &req, Response &res) {
  17494. observed_remote_addr = req.remote_addr;
  17495. res.set_content("ok", "text/plain");
  17496. });
  17497. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17498. auto se = detail::scope_exit([&] {
  17499. svr.stop();
  17500. t.join();
  17501. ASSERT_FALSE(svr.is_running());
  17502. });
  17503. svr.wait_until_ready();
  17504. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17505. // a forged address and the trusted proxy's own address; the forged value must
  17506. // not win over the address the trusted proxy actually recorded.
  17507. Client cli(HOST, PORT);
  17508. auto res = cli.Get(
  17509. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17511. EXPECT_EQ(StatusCode::OK_200, res->status);
  17512. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17513. }
  17514. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17515. Server svr;
  17516. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17517. std::string observed_remote_addr;
  17518. std::string observed_xff;
  17519. svr.Get("/ip", [&](const Request &req, Response &res) {
  17520. observed_remote_addr = req.remote_addr;
  17521. observed_xff = req.get_header_value("X-Forwarded-For");
  17522. res.set_content("ok", "text/plain");
  17523. });
  17524. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17525. auto se = detail::scope_exit([&] {
  17526. svr.stop();
  17527. t.join();
  17528. ASSERT_FALSE(svr.is_running());
  17529. });
  17530. svr.wait_until_ready();
  17531. Client cli(HOST, PORT);
  17532. auto res = cli.Get(
  17533. "/ip",
  17534. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17536. EXPECT_EQ(StatusCode::OK_200, res->status);
  17537. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17538. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17539. }
  17540. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17541. Server svr;
  17542. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17543. std::string observed_remote_addr;
  17544. std::string observed_xff;
  17545. svr.Get("/ip", [&](const Request &req, Response &res) {
  17546. observed_remote_addr = req.remote_addr;
  17547. observed_xff = req.get_header_value("X-Forwarded-For");
  17548. res.set_content("ok", "text/plain");
  17549. });
  17550. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17551. auto se = detail::scope_exit([&] {
  17552. svr.stop();
  17553. t.join();
  17554. ASSERT_FALSE(svr.is_running());
  17555. });
  17556. svr.wait_until_ready();
  17557. std::string raw_req =
  17558. "GET /ip HTTP/1.1\r\n"
  17559. "Host: localhost\r\n"
  17560. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17561. "Connection: close\r\n"
  17562. "\r\n";
  17563. std::string out;
  17564. ASSERT_TRUE(send_request(5, raw_req, &out));
  17565. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17566. // Header parser trims surrounding whitespace of the header value
  17567. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17568. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17569. }
  17570. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17571. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17572. // their own X-Forwarded-For as a separate field line rather than extending the
  17573. // one the client sent, so every occurrence has to be taken into account.
  17574. // Reading only the first one hands back the address the client chose.
  17575. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17576. Server svr;
  17577. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17578. std::string observed_remote_addr;
  17579. size_t observed_xff_count = 0;
  17580. svr.Get("/ip", [&](const Request &req, Response &res) {
  17581. observed_remote_addr = req.remote_addr;
  17582. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17583. res.set_content("ok", "text/plain");
  17584. });
  17585. auto port = svr.bind_to_any_port(HOST);
  17586. thread t = thread([&]() { svr.listen_after_bind(); });
  17587. auto se = detail::scope_exit([&] {
  17588. svr.stop();
  17589. t.join();
  17590. ASSERT_FALSE(svr.is_running());
  17591. });
  17592. svr.wait_until_ready();
  17593. // The client supplies the first field line; the trusted proxy appends the
  17594. // address it observed as a second one.
  17595. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17596. "Host: localhost\r\n"
  17597. "X-Forwarded-For: 1.2.3.4\r\n"
  17598. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17599. "Connection: close\r\n"
  17600. "\r\n";
  17601. std::string out;
  17602. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17603. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17604. EXPECT_EQ(observed_xff_count, 2U);
  17605. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17606. // The same chain spread over one field line per hop derives the same client
  17607. // address, i.e. the split and the comma-joined representations agree.
  17608. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17609. "Host: localhost\r\n"
  17610. "X-Forwarded-For: 1.2.3.4\r\n"
  17611. "X-Forwarded-For: 198.51.100.23\r\n"
  17612. "X-Forwarded-For: 192.0.2.45\r\n"
  17613. "Connection: close\r\n"
  17614. "\r\n";
  17615. out.clear();
  17616. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17617. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17618. EXPECT_EQ(observed_xff_count, 3U);
  17619. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17620. }
  17621. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17622. // crash the server (it used to call front() on an empty vector inside
  17623. // get_client_ip). The connection-level remote address must be retained instead.
  17624. static void run_malformed_xff_test(const std::string &xff_value) {
  17625. Server svr;
  17626. svr.set_trusted_proxies({"192.0.2.45"});
  17627. std::string observed_remote_addr;
  17628. svr.Get("/ip", [&](const Request &req, Response &res) {
  17629. observed_remote_addr = req.remote_addr;
  17630. res.set_content("ok", "text/plain");
  17631. });
  17632. int port = 0;
  17633. thread t = thread([&]() {
  17634. port = svr.bind_to_any_port(HOST);
  17635. svr.listen_after_bind();
  17636. });
  17637. auto se = detail::scope_exit([&] {
  17638. svr.stop();
  17639. t.join();
  17640. ASSERT_FALSE(svr.is_running());
  17641. });
  17642. svr.wait_until_ready();
  17643. Client cli(HOST, port);
  17644. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17646. EXPECT_EQ(StatusCode::OK_200, res->status);
  17647. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17648. observed_remote_addr == "127.0.0.1");
  17649. }
  17650. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17651. run_malformed_xff_test("");
  17652. }
  17653. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17654. run_malformed_xff_test(",");
  17655. }
  17656. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17657. run_malformed_xff_test(", , ,");
  17658. }
  17659. // The same rule applies to Accept: a request whose acceptable types are spread
  17660. // over several field lines must be negotiated against all of them.
  17661. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17662. // case-insensitive connection options. Comparing the whole field value against
  17663. // one option misses a client that sends several of them, and misses every
  17664. // casing but the one written in the comparison.
  17665. //
  17666. // Sends req, reads the response, then reuses the same socket for a second
  17667. // request to find out whether the server kept the connection.
  17668. static void probe_connection_reuse(int port, const std::string &req,
  17669. bool *announced_close, bool *reusable) {
  17670. auto error = Error::Success;
  17671. auto sock = detail::create_client_socket(
  17672. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17673. /*connection_timeout_sec=*/5, 0,
  17674. /*read_timeout_sec=*/1, 0,
  17675. /*write_timeout_sec=*/5, 0, std::string(), error);
  17676. ASSERT_NE(sock, INVALID_SOCKET);
  17677. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17678. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17679. "Host: localhost\r\n"
  17680. "Connection: close\r\n"
  17681. "\r\n";
  17682. std::string first_response;
  17683. std::string second_response;
  17684. detail::process_client_socket(
  17685. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17686. [&](Stream &strm) {
  17687. if (strm.write(req.data(), req.size()) !=
  17688. static_cast<ssize_t>(req.size())) {
  17689. return false;
  17690. }
  17691. char buf[512];
  17692. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17693. // Headers plus the two-byte body of the handler below
  17694. while (reader.getline()) {
  17695. first_response += reader.ptr();
  17696. if (first_response.find("ok") != std::string::npos) { break; }
  17697. }
  17698. if (strm.write(second.data(), second.size()) !=
  17699. static_cast<ssize_t>(second.size())) {
  17700. return true;
  17701. }
  17702. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17703. while (reader2.getline()) {
  17704. second_response += reader2.ptr();
  17705. if (second_response.find("ok") != std::string::npos) { break; }
  17706. }
  17707. return true;
  17708. });
  17709. *announced_close =
  17710. first_response.find("Connection: close") != std::string::npos;
  17711. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17712. }
  17713. class ConnectionTokenTest : public ::testing::Test {
  17714. protected:
  17715. void SetUp() override {
  17716. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17717. res.set_content("ok", "text/plain");
  17718. });
  17719. port_ = svr_.bind_to_any_port(HOST);
  17720. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17721. svr_.wait_until_ready();
  17722. }
  17723. void TearDown() override {
  17724. svr_.stop();
  17725. if (thread_.joinable()) { thread_.join(); }
  17726. }
  17727. Server svr_;
  17728. int port_ = 0;
  17729. thread thread_;
  17730. };
  17731. // "close" alongside another option still closes the connection, and the
  17732. // response says so rather than leaving the peer to discover it.
  17733. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17734. bool announced_close = false;
  17735. bool reusable = true;
  17736. probe_connection_reuse(port_,
  17737. "GET /keepalive HTTP/1.1\r\n"
  17738. "Host: localhost\r\n"
  17739. "Connection: keep-alive, close\r\n"
  17740. "\r\n",
  17741. &announced_close, &reusable);
  17742. EXPECT_TRUE(announced_close);
  17743. EXPECT_FALSE(reusable);
  17744. }
  17745. // "close" split over two field lines is the same list, so it is honored too.
  17746. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17747. bool announced_close = false;
  17748. bool reusable = true;
  17749. probe_connection_reuse(port_,
  17750. "GET /keepalive HTTP/1.1\r\n"
  17751. "Host: localhost\r\n"
  17752. "Connection: keep-alive\r\n"
  17753. "Connection: close\r\n"
  17754. "\r\n",
  17755. &announced_close, &reusable);
  17756. EXPECT_TRUE(announced_close);
  17757. EXPECT_FALSE(reusable);
  17758. }
  17759. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17760. // keep-alive in the spelling everyone actually sends keeps its connection.
  17761. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17762. bool announced_close = false;
  17763. bool reusable = false;
  17764. probe_connection_reuse(port_,
  17765. "GET /keepalive HTTP/1.0\r\n"
  17766. "Host: localhost\r\n"
  17767. "Connection: keep-alive\r\n"
  17768. "\r\n",
  17769. &announced_close, &reusable);
  17770. EXPECT_FALSE(announced_close);
  17771. EXPECT_TRUE(reusable);
  17772. }
  17773. // A token the value merely contains is not the token itself.
  17774. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17775. bool announced_close = false;
  17776. bool reusable = false;
  17777. probe_connection_reuse(port_,
  17778. "GET /keepalive HTTP/1.1\r\n"
  17779. "Host: localhost\r\n"
  17780. "Connection: notclose\r\n"
  17781. "\r\n",
  17782. &announced_close, &reusable);
  17783. EXPECT_FALSE(announced_close);
  17784. EXPECT_TRUE(reusable);
  17785. }
  17786. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17787. Server svr;
  17788. std::vector<std::string> observed_types;
  17789. svr.Get("/", [&](const Request &req, Response &res) {
  17790. observed_types = req.accept_content_types;
  17791. res.set_content("ok", "text/plain");
  17792. });
  17793. auto port = svr.bind_to_any_port(HOST);
  17794. thread t = thread([&]() { svr.listen_after_bind(); });
  17795. auto se = detail::scope_exit([&] {
  17796. svr.stop();
  17797. t.join();
  17798. ASSERT_FALSE(svr.is_running());
  17799. });
  17800. svr.wait_until_ready();
  17801. Client cli(HOST, port);
  17802. Headers headers;
  17803. headers.emplace("Accept", "text/plain;q=0.5");
  17804. headers.emplace("Accept", "application/json");
  17805. auto res = cli.Get("/", headers);
  17806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17807. EXPECT_EQ(StatusCode::OK_200, res->status);
  17808. // Sorted by q-value, so the second field line's type comes first
  17809. ASSERT_EQ(2U, observed_types.size());
  17810. EXPECT_EQ("application/json", observed_types[0]);
  17811. EXPECT_EQ("text/plain", observed_types[1]);
  17812. }
  17813. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17814. // empty field line must not contribute a bare comma to the combined value.
  17815. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17816. Server svr;
  17817. std::vector<std::string> observed_types;
  17818. svr.Get("/", [&](const Request &req, Response &res) {
  17819. observed_types = req.accept_content_types;
  17820. res.set_content("ok", "text/plain");
  17821. });
  17822. auto port = svr.bind_to_any_port(HOST);
  17823. thread t = thread([&]() { svr.listen_after_bind(); });
  17824. auto se = detail::scope_exit([&] {
  17825. svr.stop();
  17826. t.join();
  17827. ASSERT_FALSE(svr.is_running());
  17828. });
  17829. svr.wait_until_ready();
  17830. // Empty first field line, then a real one
  17831. std::string raw_req = "GET / HTTP/1.1\r\n"
  17832. "Host: localhost\r\n"
  17833. "Accept:\r\n"
  17834. "Accept: application/json\r\n"
  17835. "Connection: close\r\n"
  17836. "\r\n";
  17837. std::string out;
  17838. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17839. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17840. ASSERT_EQ(1U, observed_types.size());
  17841. EXPECT_EQ("application/json", observed_types[0]);
  17842. }
  17843. // The skip in get_combined_header_value() is what keeps an empty field line
  17844. // from contributing a bare comma. Only a trailing empty field line exercises
  17845. // it: a leading one is already covered by the "combined is still empty" check,
  17846. // and parse_accept_header() now ignores the empty element either way, so the
  17847. // request-level test above can no longer tell the two apart.
  17848. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17849. Headers headers;
  17850. headers.emplace("Accept", "text/html");
  17851. headers.emplace("Accept", "");
  17852. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17853. headers.clear();
  17854. headers.emplace("Accept", "");
  17855. headers.emplace("Accept", "application/json");
  17856. EXPECT_EQ("application/json",
  17857. detail::get_combined_header_value(headers, "Accept"));
  17858. }
  17859. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17860. // An encoding offered on a later Accept-Encoding field line is still offered.
  17861. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17862. Server svr;
  17863. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17864. res.set_content(std::string(1024, 'x'), "text/plain");
  17865. });
  17866. auto port = svr.bind_to_any_port(HOST);
  17867. thread t = thread([&]() { svr.listen_after_bind(); });
  17868. auto se = detail::scope_exit([&] {
  17869. svr.stop();
  17870. t.join();
  17871. ASSERT_FALSE(svr.is_running());
  17872. });
  17873. svr.wait_until_ready();
  17874. Client cli(HOST, port);
  17875. cli.set_decompress(false);
  17876. Headers headers;
  17877. headers.emplace("Accept-Encoding", "identity");
  17878. headers.emplace("Accept-Encoding", "gzip");
  17879. auto res = cli.Get("/", headers);
  17880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17881. EXPECT_EQ(StatusCode::OK_200, res->status);
  17882. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17883. }
  17884. #endif
  17885. #ifndef _WIN32
  17886. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17887. Server svr;
  17888. svr.Post("/post", [&](const Request &req, Response &res) {
  17889. res.set_content(req.body, "text/plain");
  17890. });
  17891. svr.Put("/put", [&](const Request &req, Response &res) {
  17892. res.set_content(req.body, "text/plain");
  17893. });
  17894. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17895. res.set_content(req.body, "text/plain");
  17896. });
  17897. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17898. res.set_content(req.body, "text/plain");
  17899. });
  17900. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17901. auto se = detail::scope_exit([&] {
  17902. svr.stop();
  17903. t.join();
  17904. ASSERT_FALSE(svr.is_running());
  17905. });
  17906. svr.wait_until_ready();
  17907. std::string resp;
  17908. // POST without Content-Length
  17909. ASSERT_TRUE(send_request(5,
  17910. "POST /post HTTP/1.1\r\n"
  17911. "Host: localhost\r\n"
  17912. "Connection: close\r\n"
  17913. "\r\n",
  17914. &resp));
  17915. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17916. // PUT without Content-Length
  17917. resp.clear();
  17918. ASSERT_TRUE(send_request(5,
  17919. "PUT /put HTTP/1.1\r\n"
  17920. "Host: localhost\r\n"
  17921. "Connection: close\r\n"
  17922. "\r\n",
  17923. &resp));
  17924. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17925. // PATCH without Content-Length
  17926. resp.clear();
  17927. ASSERT_TRUE(send_request(5,
  17928. "PATCH /patch HTTP/1.1\r\n"
  17929. "Host: localhost\r\n"
  17930. "Connection: close\r\n"
  17931. "\r\n",
  17932. &resp));
  17933. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17934. // DELETE without Content-Length
  17935. resp.clear();
  17936. ASSERT_TRUE(send_request(5,
  17937. "DELETE /delete HTTP/1.1\r\n"
  17938. "Host: localhost\r\n"
  17939. "Connection: close\r\n"
  17940. "\r\n",
  17941. &resp));
  17942. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17943. }
  17944. #endif
  17945. //==============================================================================
  17946. // open_stream() Tests
  17947. //==============================================================================
  17948. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17949. std::string result;
  17950. char buf[8192];
  17951. ssize_t n;
  17952. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17953. result.append(buf, static_cast<size_t>(n));
  17954. }
  17955. return result;
  17956. }
  17957. // Mock stream for unit tests
  17958. class MockStream : public Stream {
  17959. public:
  17960. std::string data;
  17961. size_t pos = 0;
  17962. ssize_t error_after = -1; // -1 = no error
  17963. explicit MockStream(const std::string &d, ssize_t err = -1)
  17964. : data(d), error_after(err) {}
  17965. bool is_readable() const override { return true; }
  17966. bool wait_readable() const override { return true; }
  17967. bool wait_writable() const override { return true; }
  17968. ssize_t read(char *ptr, size_t size) override {
  17969. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17970. if (pos >= data.size()) return 0;
  17971. size_t limit =
  17972. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17973. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17974. std::memcpy(ptr, data.data() + pos, to_read);
  17975. pos += to_read;
  17976. return static_cast<ssize_t>(to_read);
  17977. }
  17978. ssize_t write(const char *, size_t) override { return -1; }
  17979. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17980. ip = "127.0.0.1";
  17981. port = 0;
  17982. }
  17983. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17984. ip = "127.0.0.1";
  17985. port = 0;
  17986. }
  17987. socket_t socket() const override { return INVALID_SOCKET; }
  17988. time_t duration() const override { return 0; }
  17989. };
  17990. TEST(StreamHandleTest, Basic) {
  17991. ClientImpl::StreamHandle handle;
  17992. EXPECT_FALSE(handle.is_valid());
  17993. handle.response = detail::make_unique<Response>();
  17994. handle.error = Error::Connection;
  17995. EXPECT_FALSE(handle.is_valid());
  17996. handle.error = Error::Success;
  17997. EXPECT_TRUE(handle.is_valid());
  17998. }
  17999. TEST(BodyReaderTest, Basic) {
  18000. MockStream stream("Hello, World!");
  18001. detail::BodyReader reader;
  18002. reader.stream = &stream;
  18003. reader.content_length = 13;
  18004. char buf[32];
  18005. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18006. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18007. EXPECT_TRUE(reader.eof);
  18008. }
  18009. TEST(BodyReaderTest, NoStream) {
  18010. detail::BodyReader reader;
  18011. char buf[32];
  18012. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18013. EXPECT_EQ(Error::Connection, reader.last_error);
  18014. }
  18015. TEST(BodyReaderTest, Error) {
  18016. MockStream stream("Hello, World!", 5);
  18017. detail::BodyReader reader;
  18018. reader.stream = &stream;
  18019. reader.content_length = 13;
  18020. char buf[32];
  18021. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18022. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18023. EXPECT_EQ(Error::Read, reader.last_error);
  18024. }
  18025. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18026. // Mock-based StreamHandle tests relying on private internals are removed.
  18027. class OpenStreamTest : public ::testing::Test {
  18028. protected:
  18029. void SetUp() override {
  18030. svr_.Get("/hello", [](const Request &, Response &res) {
  18031. res.set_content("Hello World!", "text/plain");
  18032. });
  18033. svr_.Get("/large", [](const Request &, Response &res) {
  18034. res.set_content(std::string(10000, 'X'), "text/plain");
  18035. });
  18036. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18037. res.set_content("Hello World!", "image/jpeg");
  18038. res.set_header("Content-Encoding", "UTF-8");
  18039. });
  18040. svr_.Get("/chunked", [](const Request &, Response &res) {
  18041. res.set_chunked_content_provider("text/plain",
  18042. [](size_t offset, DataSink &sink) {
  18043. if (offset < 15) {
  18044. sink.write("chunk", 5);
  18045. return true;
  18046. }
  18047. sink.done();
  18048. return true;
  18049. });
  18050. });
  18051. svr_.Get("/compressible", [](const Request &, Response &res) {
  18052. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18053. DataSink &sink) {
  18054. if (offset < 100 * 1024) {
  18055. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18056. sink.write(chunk.data(), chunk.size());
  18057. return true;
  18058. }
  18059. sink.done();
  18060. return true;
  18061. });
  18062. });
  18063. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18064. [](const Request & /*req*/, Response &res) {
  18065. auto i = new int(0);
  18066. res.set_header("Trailer", "Content-Length, X-Allowed");
  18067. res.set_chunked_content_provider(
  18068. "text/plain",
  18069. [i](size_t /*offset*/, DataSink &sink) {
  18070. switch (*i) {
  18071. case 0: sink.os << "123"; break;
  18072. case 1: sink.os << "456"; break;
  18073. case 2: sink.os << "789"; break;
  18074. case 3: {
  18075. sink.done_with_trailer(
  18076. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18077. } break;
  18078. }
  18079. (*i)++;
  18080. return true;
  18081. },
  18082. [i](bool success) {
  18083. EXPECT_TRUE(success);
  18084. delete i;
  18085. });
  18086. });
  18087. // Echo headers endpoint for header-related tests
  18088. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18089. std::string body;
  18090. for (const auto &h : req.headers) {
  18091. body.append(h.first);
  18092. body.push_back(':');
  18093. body.append(h.second);
  18094. body.push_back('\n');
  18095. }
  18096. res.set_content(body, "text/plain");
  18097. });
  18098. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18099. std::string body;
  18100. for (const auto &h : req.headers) {
  18101. body.append(h.first);
  18102. body.push_back(':');
  18103. body.append(h.second);
  18104. body.push_back('\n');
  18105. }
  18106. res.set_content(body, "text/plain");
  18107. });
  18108. port_ = svr_.bind_to_any_port("127.0.0.1");
  18109. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18110. svr_.wait_until_ready();
  18111. }
  18112. void TearDown() override {
  18113. svr_.stop();
  18114. if (thread_.joinable()) thread_.join();
  18115. }
  18116. Server svr_;
  18117. std::thread thread_;
  18118. int port_ = 0;
  18119. };
  18120. TEST_F(OpenStreamTest, Basic) {
  18121. Client cli("127.0.0.1", port_);
  18122. auto handle = cli.open_stream("GET", "/hello");
  18123. EXPECT_TRUE(handle.is_valid());
  18124. EXPECT_EQ("Hello World!", read_all(handle));
  18125. }
  18126. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18127. Client cli("127.0.0.1", port_);
  18128. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18129. ASSERT_TRUE(handle.is_valid());
  18130. EXPECT_EQ("Hello World!", read_all(handle));
  18131. }
  18132. TEST_F(OpenStreamTest, SmallBuffer) {
  18133. Client cli("127.0.0.1", port_);
  18134. auto handle = cli.open_stream("GET", "/hello");
  18135. std::string result;
  18136. char buf[4];
  18137. ssize_t n;
  18138. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18139. result.append(buf, static_cast<size_t>(n));
  18140. EXPECT_EQ("Hello World!", result);
  18141. }
  18142. TEST_F(OpenStreamTest, DefaultHeaders) {
  18143. Client cli("127.0.0.1", port_);
  18144. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18145. {
  18146. auto handle = cli.open_stream("GET", "/echo-headers");
  18147. ASSERT_TRUE(handle.is_valid());
  18148. auto body = read_all(handle);
  18149. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18150. std::string::npos);
  18151. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18152. std::string::npos);
  18153. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18154. }
  18155. // open_stream POST with body and no explicit content_type should NOT add
  18156. // text/plain Content-Type (behavior differs from non-streaming path), but
  18157. // should include Content-Length
  18158. {
  18159. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18160. ASSERT_TRUE(handle.is_valid());
  18161. auto body = read_all(handle);
  18162. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18163. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18164. }
  18165. // open_stream POST with explicit Content-Type should preserve it
  18166. {
  18167. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18168. {{"Content-Type", "application/custom"}},
  18169. "{}", "application/custom");
  18170. ASSERT_TRUE(handle.is_valid());
  18171. auto body = read_all(handle);
  18172. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18173. }
  18174. // User-specified User-Agent must not be overwritten for stream API
  18175. {
  18176. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18177. {{"User-Agent", "MyAgent/1.2"}});
  18178. ASSERT_TRUE(handle.is_valid());
  18179. auto body = read_all(handle);
  18180. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18181. }
  18182. }
  18183. TEST_F(OpenStreamTest, Large) {
  18184. Client cli("127.0.0.1", port_);
  18185. auto handle = cli.open_stream("GET", "/large");
  18186. EXPECT_EQ(10000u, read_all(handle).size());
  18187. }
  18188. TEST_F(OpenStreamTest, ConnectionError) {
  18189. Client cli("127.0.0.1", 9999);
  18190. auto handle = cli.open_stream("GET", "/hello");
  18191. EXPECT_FALSE(handle.is_valid());
  18192. }
  18193. TEST_F(OpenStreamTest, Chunked) {
  18194. Client cli("127.0.0.1", port_);
  18195. auto handle = cli.open_stream("GET", "/chunked");
  18196. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18197. "Transfer-Encoding") == "chunked");
  18198. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18199. }
  18200. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18201. Client cli("127.0.0.1", port_);
  18202. auto handle =
  18203. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18204. ASSERT_TRUE(handle.is_valid());
  18205. // Consume body to allow trailers to be received/parsed
  18206. auto body = read_all(handle);
  18207. // Explicitly parse trailers (ensure trailers are available for assertion)
  18208. handle.parse_trailers_if_needed();
  18209. EXPECT_EQ(std::string("123456789"), body);
  18210. // The response should include a Trailer header declaring both names
  18211. ASSERT_TRUE(handle.response);
  18212. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18213. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18214. handle.response->get_header_value("Trailer"));
  18215. // Prohibited trailer must not be present
  18216. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18217. // Allowed trailer should be present
  18218. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18219. EXPECT_EQ(std::string("yes"),
  18220. handle.response->get_trailer_value("X-Allowed"));
  18221. // Verify trailers are NOT present as regular headers
  18222. EXPECT_EQ(std::string(""),
  18223. handle.response->get_header_value("Content-Length"));
  18224. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18225. }
  18226. static std::thread serve_single_response(std::promise<int> &port_promise,
  18227. const std::string &response) {
  18228. return std::thread([&port_promise, response] {
  18229. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18230. default_socket_options(srv);
  18231. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18232. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18233. sockaddr_in addr{};
  18234. addr.sin_family = AF_INET;
  18235. addr.sin_port = htons(0); // Let OS assign a free port
  18236. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18237. int opt = 1;
  18238. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18239. #ifdef _WIN32
  18240. reinterpret_cast<const char *>(&opt),
  18241. #else
  18242. &opt,
  18243. #endif
  18244. sizeof(opt));
  18245. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18246. ::listen(srv, 1) != 0) {
  18247. port_promise.set_value(-1);
  18248. detail::close_socket(srv);
  18249. return;
  18250. }
  18251. socklen_t addr_len = sizeof(addr);
  18252. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18253. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18254. sockaddr_in cli_addr{};
  18255. socklen_t cli_len = sizeof(cli_addr);
  18256. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18257. if (cli != INVALID_SOCKET) {
  18258. // Read the complete HTTP request (until the blank line that terminates
  18259. // headers) before sending the response. If the server closes the socket
  18260. // while the client's request data is still unread in the kernel receive
  18261. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18262. // connection on both sides: it discards the client's receive buffer
  18263. // (which already holds our response) and causes any in-progress write on
  18264. // the client to fail with ECONNRESET. Reading all request data first
  18265. // ensures close() emits a graceful FIN.
  18266. {
  18267. char rbuf[256];
  18268. std::string req;
  18269. while (req.find("\r\n\r\n") == std::string::npos) {
  18270. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18271. if (n <= 0) { break; }
  18272. req.append(rbuf, static_cast<size_t>(n));
  18273. }
  18274. }
  18275. ::send(cli,
  18276. #ifdef _WIN32
  18277. static_cast<const char *>(response.c_str()),
  18278. static_cast<int>(response.size()),
  18279. #else
  18280. response.c_str(), response.size(),
  18281. #endif
  18282. 0);
  18283. detail::close_socket(cli);
  18284. }
  18285. detail::close_socket(srv);
  18286. });
  18287. }
  18288. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18289. #ifndef _WIN32
  18290. signal(SIGPIPE, SIG_IGN);
  18291. #endif
  18292. std::promise<int> port_promise;
  18293. auto port_future = port_promise.get_future();
  18294. auto server_thread =
  18295. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18296. "Content-Type: text/plain\r\n"
  18297. "Content-Length: not-a-number\r\n"
  18298. "Connection: close\r\n"
  18299. "\r\n"
  18300. "hello");
  18301. auto port = port_future.get();
  18302. ASSERT_GT(port, 0);
  18303. Client cli("127.0.0.1", port);
  18304. auto handle = cli.open_stream("GET", "/");
  18305. EXPECT_FALSE(handle.is_valid());
  18306. server_thread.join();
  18307. }
  18308. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18309. #ifndef _WIN32
  18310. signal(SIGPIPE, SIG_IGN);
  18311. #endif
  18312. std::promise<int> port_promise;
  18313. auto port_future = port_promise.get_future();
  18314. auto server_thread = serve_single_response(
  18315. port_promise, "HTTP/1.1 200 OK\r\n"
  18316. "Content-Type: text/plain\r\n"
  18317. "Content-Length: 99999999999999999999999999\r\n"
  18318. "Connection: close\r\n"
  18319. "\r\n"
  18320. "hello");
  18321. auto port = port_future.get();
  18322. ASSERT_GT(port, 0);
  18323. // Historically std::stoull would throw std::out_of_range here and crash
  18324. // the process, then parsing silently clamped to a bogus framing length and
  18325. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18326. // so the stream fails to open, matching the not-a-number case above. The
  18327. // process still must NOT terminate.
  18328. Client cli("127.0.0.1", port);
  18329. auto handle = cli.open_stream("GET", "/");
  18330. EXPECT_FALSE(handle.is_valid());
  18331. server_thread.join();
  18332. }
  18333. // Serves `response` to the single request `fn` makes with a fresh client.
  18334. template <typename Fn>
  18335. static void with_single_response(const std::string &response, Fn fn) {
  18336. #ifndef _WIN32
  18337. signal(SIGPIPE, SIG_IGN);
  18338. #endif
  18339. std::promise<int> port_promise;
  18340. auto port_future = port_promise.get_future();
  18341. auto server_thread = serve_single_response(port_promise, response);
  18342. auto se = detail::scope_exit([&] { server_thread.join(); });
  18343. auto port = port_future.get();
  18344. ASSERT_GT(port, 0);
  18345. Client cli("127.0.0.1", port);
  18346. fn(cli);
  18347. }
  18348. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18349. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18350. // the chunked coding and drop Content-Length, so a front-end that trusts
  18351. // Content-Length would disagree about where the body ends (response
  18352. // smuggling). The client must reject such a response.
  18353. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18354. for (const char *te : {"chunked", "gzip, chunked"}) {
  18355. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18356. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18357. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18358. "5\r\nhello\r\n0\r\n\r\n";
  18359. with_single_response(response, [&](Client &cli) {
  18360. auto res = cli.Get("/");
  18361. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18362. EXPECT_EQ(Error::Read, res.error()) << te;
  18363. });
  18364. with_single_response(response, [&](Client &cli) {
  18365. auto handle = cli.open_stream("GET", "/");
  18366. EXPECT_FALSE(handle.is_valid()) << te;
  18367. EXPECT_EQ(Error::Read, handle.error) << te;
  18368. });
  18369. }
  18370. }
  18371. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18372. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18373. // closing the connection (unlike a request, which must be rejected).
  18374. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18375. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18376. "Transfer-Encoding: chunked\r\n"
  18377. "Connection: close\r\n"
  18378. "\r\n"
  18379. "5\r\nhello\r\n0\r\n\r\n",
  18380. "HTTP/1.1 200 OK\r\n"
  18381. "Transfer-Encoding: gzip\r\n"
  18382. "Connection: close\r\n"
  18383. "\r\n"
  18384. "hello"}) {
  18385. with_single_response(response, [&](Client &cli) {
  18386. auto res = cli.Get("/");
  18387. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18388. EXPECT_EQ("hello", res->body);
  18389. });
  18390. with_single_response(response, [&](Client &cli) {
  18391. auto handle = cli.open_stream("GET", "/");
  18392. ASSERT_TRUE(handle.is_valid()) << response;
  18393. EXPECT_EQ("hello", read_all(handle));
  18394. });
  18395. }
  18396. }
  18397. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18398. // framing headers describe nothing to read and must not be rejected.
  18399. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18400. const std::string framing = "Content-Length: 5\r\n"
  18401. "Transfer-Encoding: chunked\r\n"
  18402. "Connection: close\r\n"
  18403. "\r\n";
  18404. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18405. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18406. });
  18407. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18408. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18409. });
  18410. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18411. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18412. with_single_response(response, [&](Client &cli) {
  18413. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18414. });
  18415. with_single_response(response, [&](Client &cli) {
  18416. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18417. });
  18418. }
  18419. }
  18420. // A payload max length of 0 means no limit, however the body is framed.
  18421. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18422. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18423. "Transfer-Encoding: chunked\r\n"
  18424. "\r\n"
  18425. "5\r\nhello\r\n0\r\n\r\n",
  18426. "HTTP/1.1 200 OK\r\n"
  18427. "Connection: close\r\n"
  18428. "\r\n"
  18429. "hello"}) {
  18430. with_single_response(response, [&](Client &cli) {
  18431. cli.set_payload_max_length(0);
  18432. auto res = cli.Get("/");
  18433. ASSERT_TRUE(res) << response;
  18434. EXPECT_EQ("hello", res->body) << response;
  18435. });
  18436. }
  18437. }
  18438. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18439. Server svr;
  18440. svr.set_payload_max_length(0);
  18441. svr.Post("/echo", [](const Request &req, Response &res) {
  18442. res.set_content(req.body, "text/plain");
  18443. });
  18444. auto port = svr.bind_to_any_port(HOST);
  18445. thread t = thread([&] { svr.listen_after_bind(); });
  18446. auto se = detail::scope_exit([&] {
  18447. svr.stop();
  18448. t.join();
  18449. ASSERT_FALSE(svr.is_running());
  18450. });
  18451. svr.wait_until_ready();
  18452. Client cli(HOST, port);
  18453. auto res = cli.Post(
  18454. "/echo",
  18455. [](size_t /*offset*/, DataSink &sink) {
  18456. sink.write("hello", 5);
  18457. sink.done();
  18458. return true;
  18459. },
  18460. "text/plain");
  18461. ASSERT_TRUE(res);
  18462. EXPECT_EQ(StatusCode::OK_200, res->status);
  18463. EXPECT_EQ("hello", res->body);
  18464. }
  18465. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18466. TEST_F(OpenStreamTest, Gzip) {
  18467. Client cli("127.0.0.1", port_);
  18468. auto handle = cli.open_stream("GET", "/compressible", {},
  18469. {{"Accept-Encoding", "gzip"}});
  18470. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18471. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18472. }
  18473. #endif
  18474. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18475. TEST_F(OpenStreamTest, Brotli) {
  18476. Client cli("127.0.0.1", port_);
  18477. auto handle =
  18478. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18479. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18480. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18481. }
  18482. #endif
  18483. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18484. TEST_F(OpenStreamTest, Zstd) {
  18485. Client cli("127.0.0.1", port_);
  18486. auto handle = cli.open_stream("GET", "/compressible", {},
  18487. {{"Accept-Encoding", "zstd"}});
  18488. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18489. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18490. }
  18491. #endif
  18492. #ifdef CPPHTTPLIB_SSL_ENABLED
  18493. class SSLOpenStreamTest : public ::testing::Test {
  18494. protected:
  18495. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18496. void SetUp() override {
  18497. svr_.Get("/hello", [](const Request &, Response &res) {
  18498. res.set_content("Hello SSL World!", "text/plain");
  18499. });
  18500. svr_.Get("/chunked", [](const Request &, Response &res) {
  18501. res.set_chunked_content_provider("text/plain",
  18502. [](size_t offset, DataSink &sink) {
  18503. if (offset < 15) {
  18504. sink.write("chunk", 5);
  18505. return true;
  18506. }
  18507. sink.done();
  18508. return true;
  18509. });
  18510. });
  18511. svr_.Post("/echo", [](const Request &req, Response &res) {
  18512. res.set_content(req.body, req.get_header_value("Content-Type"));
  18513. });
  18514. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18515. std::string body = req.body;
  18516. res.set_chunked_content_provider(
  18517. "text/plain", [body](size_t offset, DataSink &sink) {
  18518. if (offset < body.size()) {
  18519. sink.write(body.data() + offset, body.size() - offset);
  18520. }
  18521. sink.done();
  18522. return true;
  18523. });
  18524. });
  18525. port_ = svr_.bind_to_any_port("127.0.0.1");
  18526. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18527. svr_.wait_until_ready();
  18528. }
  18529. void TearDown() override {
  18530. svr_.stop();
  18531. if (thread_.joinable()) thread_.join();
  18532. }
  18533. SSLServer svr_;
  18534. std::thread thread_;
  18535. int port_ = 0;
  18536. };
  18537. TEST_F(SSLOpenStreamTest, Basic) {
  18538. SSLClient cli("127.0.0.1", port_);
  18539. cli.enable_server_certificate_verification(false);
  18540. auto handle = cli.open_stream("GET", "/hello");
  18541. ASSERT_TRUE(handle.is_valid());
  18542. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18543. }
  18544. TEST_F(SSLOpenStreamTest, Chunked) {
  18545. SSLClient cli("127.0.0.1", port_);
  18546. cli.enable_server_certificate_verification(false);
  18547. auto handle = cli.open_stream("GET", "/chunked");
  18548. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18549. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18550. "Transfer-Encoding") == "chunked");
  18551. auto body = read_all(handle);
  18552. EXPECT_EQ("chunkchunkchunk", body);
  18553. }
  18554. TEST_F(SSLOpenStreamTest, Post) {
  18555. SSLClient cli("127.0.0.1", port_);
  18556. cli.enable_server_certificate_verification(false);
  18557. auto handle =
  18558. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18559. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18560. EXPECT_EQ(200, handle.response->status);
  18561. auto body = read_all(handle);
  18562. EXPECT_EQ("Hello SSL POST", body);
  18563. }
  18564. TEST_F(SSLOpenStreamTest, PostChunked) {
  18565. SSLClient cli("127.0.0.1", port_);
  18566. cli.enable_server_certificate_verification(false);
  18567. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18568. "Chunked SSL Data", "text/plain");
  18569. ASSERT_TRUE(handle.is_valid());
  18570. EXPECT_EQ(200, handle.response->status);
  18571. auto body = read_all(handle);
  18572. EXPECT_EQ("Chunked SSL Data", body);
  18573. }
  18574. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18575. // Content-Length is terminated by the server closing the connection. When the
  18576. // SSL peer sends a close_notify after the body, the client must treat it as a
  18577. // clean EOF and return a successful response rather than an error.
  18578. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18579. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18580. ASSERT_TRUE(svr.is_valid());
  18581. svr.set_keep_alive_max_count(1);
  18582. const std::string expected_body = "Hello from connection-close response!";
  18583. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18584. res.set_content_provider("text/plain",
  18585. [&](size_t offset, DataSink &sink) -> bool {
  18586. if (offset < expected_body.size()) {
  18587. sink.write(expected_body.data() + offset,
  18588. expected_body.size() - offset);
  18589. }
  18590. sink.done();
  18591. return true;
  18592. });
  18593. });
  18594. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18595. auto se = detail::scope_exit([&] {
  18596. svr.stop();
  18597. listen_thread.join();
  18598. ASSERT_FALSE(svr.is_running());
  18599. });
  18600. svr.wait_until_ready();
  18601. SSLClient cli(HOST, PORT);
  18602. cli.enable_server_certificate_verification(false);
  18603. auto res = cli.Get("/no-content-length");
  18604. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18605. EXPECT_EQ(StatusCode::OK_200, res->status);
  18606. EXPECT_EQ(expected_body, res->body);
  18607. }
  18608. #endif // CPPHTTPLIB_SSL_ENABLED
  18609. //==============================================================================
  18610. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18611. // results for various scenarios.
  18612. //==============================================================================
  18613. TEST(ParityTest, GetVsOpenStream) {
  18614. Server svr;
  18615. const std::string path = "/parity";
  18616. const std::string content = "Parity test content: hello world";
  18617. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18618. res.set_content(content, "text/plain");
  18619. });
  18620. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18621. auto se = detail::scope_exit([&] {
  18622. svr.stop();
  18623. t.join();
  18624. ASSERT_FALSE(svr.is_running());
  18625. });
  18626. svr.wait_until_ready();
  18627. Client cli(HOST, PORT);
  18628. // Non-stream path
  18629. auto r1 = cli.Get(path);
  18630. ASSERT_TRUE(r1);
  18631. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18632. // Stream path
  18633. auto h = cli.open_stream("GET", path);
  18634. ASSERT_TRUE(h.is_valid());
  18635. EXPECT_EQ(r1->body, read_all(h));
  18636. }
  18637. // Helper to compress data with provided compressor type T
  18638. template <typename Compressor>
  18639. static std::string compress_payload_for_parity(const std::string &in) {
  18640. std::string out;
  18641. Compressor compressor;
  18642. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18643. [&](const char *data, size_t n) {
  18644. out.append(data, n);
  18645. return true;
  18646. });
  18647. EXPECT_TRUE(ok);
  18648. return out;
  18649. }
  18650. // Helper function for compression parity tests
  18651. template <typename Compressor>
  18652. static void test_compression_parity(const std::string &original,
  18653. const std::string &path,
  18654. const std::string &encoding) {
  18655. const std::string compressed =
  18656. compress_payload_for_parity<Compressor>(original);
  18657. Server svr;
  18658. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18659. res.set_content(compressed, "application/octet-stream");
  18660. res.set_header("Content-Encoding", encoding);
  18661. });
  18662. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18663. auto se = detail::scope_exit([&] {
  18664. svr.stop();
  18665. t.join();
  18666. ASSERT_FALSE(svr.is_running());
  18667. });
  18668. svr.wait_until_ready();
  18669. Client cli(HOST, PORT);
  18670. // Non-streaming
  18671. {
  18672. auto res = cli.Get(path);
  18673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18674. EXPECT_EQ(StatusCode::OK_200, res->status);
  18675. EXPECT_EQ(original, res->body);
  18676. }
  18677. // Streaming
  18678. {
  18679. auto h = cli.open_stream("GET", path);
  18680. ASSERT_TRUE(h.is_valid());
  18681. EXPECT_EQ(original, read_all(h));
  18682. }
  18683. }
  18684. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18685. TEST(ParityTest, Gzip) {
  18686. test_compression_parity<detail::gzip_compressor>(
  18687. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18688. }
  18689. #endif
  18690. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18691. TEST(ParityTest, Brotli) {
  18692. test_compression_parity<detail::brotli_compressor>(
  18693. "Hello, brotli parity test payload", "/parity-br", "br");
  18694. }
  18695. #endif
  18696. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18697. TEST(ParityTest, Zstd) {
  18698. test_compression_parity<detail::zstd_compressor>(
  18699. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18700. }
  18701. #endif
  18702. //==============================================================================
  18703. // New Stream API Tests
  18704. //==============================================================================
  18705. inline std::string read_body(httplib::stream::Result &result) {
  18706. std::string body;
  18707. while (result.next()) {
  18708. body.append(result.data(), result.size());
  18709. }
  18710. return body;
  18711. }
  18712. TEST(ClientConnectionTest, Basic) {
  18713. httplib::ClientConnection conn;
  18714. EXPECT_FALSE(conn.is_open());
  18715. conn.sock = 1;
  18716. EXPECT_TRUE(conn.is_open());
  18717. httplib::ClientConnection conn2(std::move(conn));
  18718. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18719. conn2.sock = INVALID_SOCKET;
  18720. }
  18721. // Unified test server for all stream::* tests
  18722. class StreamApiTest : public ::testing::Test {
  18723. protected:
  18724. void SetUp() override {
  18725. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18726. res.set_content("Hello World!", "text/plain");
  18727. });
  18728. svr_.Get("/echo-params",
  18729. [](const httplib::Request &req, httplib::Response &res) {
  18730. std::string r;
  18731. for (const auto &p : req.params) {
  18732. if (!r.empty()) r += "&";
  18733. r += p.first + "=" + p.second;
  18734. }
  18735. res.set_content(r, "text/plain");
  18736. });
  18737. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18738. res.set_content(req.body, req.get_header_value("Content-Type"));
  18739. });
  18740. svr_.Post("/echo-headers",
  18741. [](const httplib::Request &req, httplib::Response &res) {
  18742. std::string r;
  18743. for (const auto &h : req.headers)
  18744. r += h.first + ": " + h.second + "\n";
  18745. res.set_content(r, "text/plain");
  18746. });
  18747. svr_.Post("/echo-params",
  18748. [](const httplib::Request &req, httplib::Response &res) {
  18749. std::string r = "params:";
  18750. for (const auto &p : req.params)
  18751. r += p.first + "=" + p.second + ";";
  18752. res.set_content(r + " body:" + req.body, "text/plain");
  18753. });
  18754. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18755. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18756. });
  18757. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18758. res.set_content("PUT:" + req.body, "text/plain");
  18759. });
  18760. svr_.Patch("/echo",
  18761. [](const httplib::Request &req, httplib::Response &res) {
  18762. res.set_content("PATCH:" + req.body, "text/plain");
  18763. });
  18764. svr_.Delete(
  18765. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18766. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18767. "text/plain");
  18768. });
  18769. svr_.Get("/head-test",
  18770. [](const httplib::Request &, httplib::Response &res) {
  18771. res.set_content("body for HEAD", "text/plain");
  18772. });
  18773. svr_.Options("/options",
  18774. [](const httplib::Request &, httplib::Response &res) {
  18775. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18776. });
  18777. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18778. svr_.wait_until_ready();
  18779. }
  18780. void TearDown() override {
  18781. svr_.stop();
  18782. if (thread_.joinable()) thread_.join();
  18783. }
  18784. httplib::Server svr_;
  18785. std::thread thread_;
  18786. };
  18787. // stream::Get tests
  18788. TEST_F(StreamApiTest, GetBasic) {
  18789. httplib::Client cli(HOST, PORT);
  18790. auto result = httplib::stream::Get(cli, "/hello");
  18791. ASSERT_TRUE(result.is_valid());
  18792. EXPECT_EQ(200, result.status());
  18793. EXPECT_EQ("Hello World!", read_body(result));
  18794. }
  18795. TEST_F(StreamApiTest, GetWithParams) {
  18796. httplib::Client cli(HOST, PORT);
  18797. httplib::Params params{{"foo", "bar"}};
  18798. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18799. ASSERT_TRUE(result.is_valid());
  18800. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18801. }
  18802. TEST_F(StreamApiTest, GetConnectionError) {
  18803. httplib::Client cli(HOST, 9999);
  18804. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18805. }
  18806. TEST_F(StreamApiTest, Get404) {
  18807. httplib::Client cli(HOST, PORT);
  18808. auto result = httplib::stream::Get(cli, "/nonexistent");
  18809. EXPECT_TRUE(result.is_valid());
  18810. EXPECT_EQ(404, result.status());
  18811. }
  18812. // stream::Post tests
  18813. TEST_F(StreamApiTest, PostBasic) {
  18814. httplib::Client cli(HOST, PORT);
  18815. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18816. "application/json");
  18817. ASSERT_TRUE(result.is_valid());
  18818. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18819. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18820. }
  18821. TEST_F(StreamApiTest, PostWithHeaders) {
  18822. httplib::Client cli(HOST, PORT);
  18823. httplib::Headers headers{{"X-Custom", "value"}};
  18824. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18825. "text/plain");
  18826. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18827. }
  18828. TEST_F(StreamApiTest, PostWithParams) {
  18829. httplib::Client cli(HOST, PORT);
  18830. httplib::Params params{{"k", "v"}};
  18831. auto result =
  18832. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18833. auto body = read_body(result);
  18834. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18835. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18836. }
  18837. TEST_F(StreamApiTest, PostLarge) {
  18838. httplib::Client cli(HOST, PORT);
  18839. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18840. size_t total = 0;
  18841. while (result.next()) {
  18842. total += result.size();
  18843. }
  18844. EXPECT_EQ(100u * 1024u, total);
  18845. }
  18846. // stream::Put/Patch tests
  18847. TEST_F(StreamApiTest, PutAndPatch) {
  18848. httplib::Client cli(HOST, PORT);
  18849. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18850. EXPECT_EQ("PUT:test", read_body(put));
  18851. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18852. EXPECT_EQ("PATCH:test", read_body(patch));
  18853. }
  18854. // stream::Delete tests
  18855. TEST_F(StreamApiTest, Delete) {
  18856. httplib::Client cli(HOST, PORT);
  18857. auto del1 = httplib::stream::Delete(cli, "/resource");
  18858. EXPECT_EQ("Deleted", read_body(del1));
  18859. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18860. EXPECT_EQ("Deleted:data", read_body(del2));
  18861. }
  18862. // stream::Head/Options tests
  18863. TEST_F(StreamApiTest, HeadAndOptions) {
  18864. httplib::Client cli(HOST, PORT);
  18865. auto head = httplib::stream::Head(cli, "/head-test");
  18866. EXPECT_TRUE(head.is_valid());
  18867. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18868. auto opts = httplib::stream::Options(cli, "/options");
  18869. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18870. }
  18871. // SSL stream::* tests
  18872. #ifdef CPPHTTPLIB_SSL_ENABLED
  18873. class SSLStreamApiTest : public ::testing::Test {
  18874. protected:
  18875. void SetUp() override {
  18876. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18877. res.set_content("Hello SSL!", "text/plain");
  18878. });
  18879. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18880. res.set_content(req.body, "text/plain");
  18881. });
  18882. port_ = svr_.bind_to_any_port("127.0.0.1");
  18883. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18884. svr_.wait_until_ready();
  18885. }
  18886. void TearDown() override {
  18887. svr_.stop();
  18888. if (thread_.joinable()) thread_.join();
  18889. }
  18890. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18891. std::thread thread_;
  18892. int port_ = 0;
  18893. };
  18894. TEST_F(SSLStreamApiTest, GetAndPost) {
  18895. httplib::SSLClient cli("127.0.0.1", port_);
  18896. cli.enable_server_certificate_verification(false);
  18897. auto get = httplib::stream::Get(cli, "/hello");
  18898. EXPECT_EQ("Hello SSL!", read_body(get));
  18899. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18900. EXPECT_EQ("test", read_body(post));
  18901. }
  18902. #endif
  18903. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18904. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18905. // BodyReader
  18906. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18907. // Test that read timeout during streaming is detected
  18908. // Use a large content-length response where server delays mid-stream
  18909. Server svr;
  18910. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18911. // Send a large response with delay in the middle
  18912. res.set_content_provider(
  18913. 1000, // content_length
  18914. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18915. if (offset < 100) {
  18916. // Send first 100 bytes immediately
  18917. std::string data(100, 'A');
  18918. sink.write(data.c_str(), data.size());
  18919. return true;
  18920. }
  18921. // Then delay longer than client timeout
  18922. std::this_thread::sleep_for(std::chrono::seconds(3));
  18923. std::string data(900, 'B');
  18924. sink.write(data.c_str(), data.size());
  18925. return true;
  18926. });
  18927. });
  18928. auto port = 8091;
  18929. std::thread t([&]() { svr.listen("localhost", port); });
  18930. svr.wait_until_ready();
  18931. Client cli("localhost", port);
  18932. cli.set_read_timeout(1, 0); // 1 second timeout
  18933. auto handle = cli.open_stream("GET", "/slow-stream");
  18934. ASSERT_TRUE(handle.is_valid());
  18935. char buf[256];
  18936. ssize_t total = 0;
  18937. ssize_t n;
  18938. bool got_error = false;
  18939. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18940. total += n;
  18941. }
  18942. if (n < 0) {
  18943. got_error = true;
  18944. // Should be timeout or read error
  18945. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18946. handle.get_read_error() == Error::Read)
  18947. << "Actual error: " << to_string(handle.get_read_error());
  18948. }
  18949. // Either we got an error, or we got less data than expected
  18950. EXPECT_TRUE(got_error || total < 1000)
  18951. << "Expected timeout but got all " << total << " bytes";
  18952. svr.stop();
  18953. t.join();
  18954. }
  18955. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18956. // Test connection closed detection via BodyReader
  18957. Server svr;
  18958. std::atomic<bool> close_now{false};
  18959. svr.Get("/will-close", [&](const Request &, Response &res) {
  18960. res.set_content_provider(
  18961. 10000, // Large content_length that we won't fully send
  18962. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18963. if (offset < 100) {
  18964. std::string data(100, 'X');
  18965. sink.write(data.c_str(), data.size());
  18966. return true;
  18967. }
  18968. // Wait for signal then abort
  18969. while (!close_now) {
  18970. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18971. }
  18972. return false; // Abort - server will close connection
  18973. });
  18974. });
  18975. auto port = 8092;
  18976. std::thread t([&]() { svr.listen("localhost", port); });
  18977. svr.wait_until_ready();
  18978. Client cli("localhost", port);
  18979. auto handle = cli.open_stream("GET", "/will-close");
  18980. ASSERT_TRUE(handle.is_valid());
  18981. char buf[256];
  18982. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18983. EXPECT_GT(n, 0) << "First read should succeed";
  18984. // Signal server to close
  18985. close_now = true;
  18986. // Keep reading until error or EOF
  18987. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18988. // Keep reading
  18989. }
  18990. // Should get an error since content_length wasn't satisfied
  18991. if (n < 0) {
  18992. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18993. handle.get_read_error() == Error::Read)
  18994. << "Actual error: " << to_string(handle.get_read_error());
  18995. }
  18996. svr.stop();
  18997. t.join();
  18998. }
  18999. #ifdef CPPHTTPLIB_SSL_ENABLED
  19000. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19001. // Test that read timeout during SSL streaming is detected
  19002. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19003. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19004. res.set_content_provider(
  19005. 1000, "text/plain",
  19006. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19007. if (offset < 100) {
  19008. std::string data(100, 'A');
  19009. sink.write(data.c_str(), data.size());
  19010. return true;
  19011. }
  19012. std::this_thread::sleep_for(std::chrono::seconds(3));
  19013. std::string data(900, 'B');
  19014. sink.write(data.c_str(), data.size());
  19015. return true;
  19016. });
  19017. });
  19018. auto port = 8093;
  19019. std::thread t([&]() { svr.listen("localhost", port); });
  19020. svr.wait_until_ready();
  19021. SSLClient cli("localhost", port);
  19022. cli.enable_server_certificate_verification(false);
  19023. cli.set_read_timeout(1, 0); // 1 second timeout
  19024. auto handle = cli.open_stream("GET", "/slow-stream");
  19025. ASSERT_TRUE(handle.is_valid());
  19026. char buf[256];
  19027. ssize_t total = 0;
  19028. ssize_t n;
  19029. bool got_error = false;
  19030. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19031. total += n;
  19032. }
  19033. if (n < 0) {
  19034. got_error = true;
  19035. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19036. handle.get_read_error() == Error::Read)
  19037. << "Actual error: " << to_string(handle.get_read_error());
  19038. }
  19039. EXPECT_TRUE(got_error || total < 1000)
  19040. << "Expected timeout but got all " << total << " bytes";
  19041. svr.stop();
  19042. t.join();
  19043. }
  19044. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19045. // Test SSL connection closed detection
  19046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19047. std::atomic<bool> close_now{false};
  19048. svr.Get("/will-close", [&](const Request &, Response &res) {
  19049. res.set_content_provider(
  19050. 10000, "text/plain",
  19051. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19052. if (offset < 100) {
  19053. std::string data(100, 'X');
  19054. sink.write(data.c_str(), data.size());
  19055. return true;
  19056. }
  19057. while (!close_now) {
  19058. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19059. }
  19060. return false;
  19061. });
  19062. });
  19063. auto port = 8094;
  19064. std::thread t([&]() { svr.listen("localhost", port); });
  19065. svr.wait_until_ready();
  19066. SSLClient cli("localhost", port);
  19067. cli.enable_server_certificate_verification(false);
  19068. auto handle = cli.open_stream("GET", "/will-close");
  19069. ASSERT_TRUE(handle.is_valid());
  19070. char buf[256];
  19071. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19072. EXPECT_GT(n, 0);
  19073. // Signal server to close
  19074. close_now = true;
  19075. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19076. // Keep reading
  19077. }
  19078. if (n < 0) {
  19079. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19080. handle.get_read_error() == Error::Read)
  19081. << "Actual error: " << to_string(handle.get_read_error());
  19082. }
  19083. svr.stop();
  19084. t.join();
  19085. }
  19086. #endif
  19087. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19088. using namespace httplib;
  19089. // Create a test file
  19090. const char *fname = "etag_testfile.txt";
  19091. const char *content = "etag-content";
  19092. {
  19093. std::ofstream ofs(fname);
  19094. ofs << content;
  19095. ASSERT_TRUE(ofs.good());
  19096. }
  19097. Server svr;
  19098. svr.set_mount_point("/static", ".");
  19099. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19100. svr.wait_until_ready();
  19101. Client cli(HOST, PORT);
  19102. // First request: should get 200 with ETag header
  19103. auto res1 = cli.Get("/static/etag_testfile.txt");
  19104. ASSERT_TRUE(res1);
  19105. ASSERT_EQ(200, res1->status);
  19106. ASSERT_TRUE(res1->has_header("ETag"));
  19107. std::string etag = res1->get_header_value("ETag");
  19108. EXPECT_FALSE(etag.empty());
  19109. // Verify ETag format: W/"hex-hex"
  19110. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19111. EXPECT_EQ('W', etag[0]);
  19112. EXPECT_EQ('/', etag[1]);
  19113. EXPECT_EQ('"', etag[2]);
  19114. EXPECT_EQ('"', etag.back());
  19115. // Exact match: expect 304 Not Modified
  19116. Headers h2 = {{"If-None-Match", etag}};
  19117. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19118. ASSERT_TRUE(res2);
  19119. EXPECT_EQ(304, res2->status);
  19120. // Wildcard match: expect 304 Not Modified
  19121. Headers h3 = {{"If-None-Match", "*"}};
  19122. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19123. ASSERT_TRUE(res3);
  19124. EXPECT_EQ(304, res3->status);
  19125. // Non-matching ETag: expect 200
  19126. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19127. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19128. ASSERT_TRUE(res4);
  19129. EXPECT_EQ(200, res4->status);
  19130. // Multiple ETags with one matching: expect 304
  19131. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19132. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19133. ASSERT_TRUE(res5);
  19134. EXPECT_EQ(304, res5->status);
  19135. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19136. // that equivalent to the single comma-separated list above, so the match on
  19137. // the second line must still be found.
  19138. Headers h6;
  19139. h6.emplace("If-None-Match", "W/\"other\"");
  19140. h6.emplace("If-None-Match", etag);
  19141. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19142. ASSERT_TRUE(res6);
  19143. EXPECT_EQ(304, res6->status);
  19144. svr.stop();
  19145. t.join();
  19146. std::remove(fname);
  19147. }
  19148. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19149. using namespace httplib;
  19150. Server svr;
  19151. svr.set_mount_point("/static", ".");
  19152. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19153. svr.wait_until_ready();
  19154. Client cli(HOST, PORT);
  19155. // Send If-None-Match: * to a non-existent file
  19156. Headers h = {{"If-None-Match", "*"}};
  19157. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19159. EXPECT_EQ(404, res->status);
  19160. svr.stop();
  19161. t.join();
  19162. }
  19163. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19164. using namespace httplib;
  19165. // Create a test file
  19166. const char *fname = "etag_boundary_testfile.txt";
  19167. const char *content = "boundary-test";
  19168. {
  19169. std::ofstream ofs(fname);
  19170. ofs << content;
  19171. ASSERT_TRUE(ofs.good());
  19172. }
  19173. Server svr;
  19174. svr.set_mount_point("/static", ".");
  19175. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19176. svr.wait_until_ready();
  19177. Client cli(HOST, PORT);
  19178. // Get the actual ETag
  19179. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19180. ASSERT_TRUE(res1);
  19181. ASSERT_EQ(200, res1->status);
  19182. ASSERT_TRUE(res1->has_header("ETag"));
  19183. std::string etag = res1->get_header_value("ETag");
  19184. // Test 1: Very long ETag value (longer than actual ETag)
  19185. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19186. Headers h1 = {{"If-None-Match", "W/"
  19187. "\"very-long-etag-value-that-is-much-longer-"
  19188. "than-the-actual-etag-value\""}};
  19189. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19190. ASSERT_TRUE(res2);
  19191. EXPECT_EQ(200, res2->status); // Should not match
  19192. // Test 2: Long string followed by wildcard
  19193. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19194. // string)
  19195. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19196. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19197. ASSERT_TRUE(res3);
  19198. EXPECT_EQ(304, res3->status); // Should match on "*"
  19199. // Test 3: Wildcard followed by long string
  19200. // Should match on "*" immediately and return 304
  19201. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19202. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19203. ASSERT_TRUE(res4);
  19204. EXPECT_EQ(304, res4->status); // Should match on "*"
  19205. // Test 4: Multiple long non-matching values
  19206. // Should NOT match and return 200 (test that all comparisons are safe)
  19207. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19208. "W/\"second-long-non-matching-value\", "
  19209. "W/\"third-long-non-matching-value\""}};
  19210. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19211. ASSERT_TRUE(res5);
  19212. EXPECT_EQ(200, res5->status); // Should not match
  19213. // Test 5: Single character that is not "*" (edge case)
  19214. Headers h5 = {{"If-None-Match", "X"}};
  19215. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19216. ASSERT_TRUE(res6);
  19217. EXPECT_EQ(200, res6->status); // Should not match
  19218. svr.stop();
  19219. t.join();
  19220. std::remove(fname);
  19221. }
  19222. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19223. using namespace httplib;
  19224. // Create a test file
  19225. const char *fname = "ims_testfile.txt";
  19226. const char *content = "if-modified-since-test";
  19227. {
  19228. std::ofstream ofs(fname);
  19229. ofs << content;
  19230. ASSERT_TRUE(ofs.good());
  19231. }
  19232. Server svr;
  19233. svr.set_mount_point("/static", ".");
  19234. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19235. svr.wait_until_ready();
  19236. Client cli(HOST, PORT);
  19237. // First request: should get 200 with Last-Modified header
  19238. auto res1 = cli.Get("/static/ims_testfile.txt");
  19239. ASSERT_TRUE(res1);
  19240. ASSERT_EQ(200, res1->status);
  19241. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19242. std::string last_modified = res1->get_header_value("Last-Modified");
  19243. EXPECT_FALSE(last_modified.empty());
  19244. // If-Modified-Since with same time: expect 304
  19245. Headers h2 = {{"If-Modified-Since", last_modified}};
  19246. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19247. ASSERT_TRUE(res2);
  19248. EXPECT_EQ(304, res2->status);
  19249. // If-Modified-Since with future time: expect 304
  19250. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19251. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19252. ASSERT_TRUE(res3);
  19253. EXPECT_EQ(304, res3->status);
  19254. // If-Modified-Since with past time: expect 200
  19255. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19256. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19257. ASSERT_TRUE(res4);
  19258. EXPECT_EQ(200, res4->status);
  19259. // If-None-Match takes precedence over If-Modified-Since
  19260. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19261. ASSERT_TRUE(res1->has_header("ETag"));
  19262. std::string etag = res1->get_header_value("ETag");
  19263. Headers h5 = {{"If-None-Match", etag},
  19264. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19265. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19266. ASSERT_TRUE(res5);
  19267. EXPECT_EQ(304, res5->status);
  19268. svr.stop();
  19269. t.join();
  19270. std::remove(fname);
  19271. }
  19272. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19273. using namespace httplib;
  19274. Server svr;
  19275. // Endpoint that returns compressible content
  19276. svr.Get("/compressible", [](const Request &, Response &res) {
  19277. // Return a large enough body to trigger compression
  19278. std::string body(1000, 'a');
  19279. res.set_content(body, "text/plain");
  19280. });
  19281. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19282. svr.wait_until_ready();
  19283. Client cli(HOST, PORT);
  19284. // Request with gzip support: should get Vary header when compressed
  19285. cli.set_compress(true);
  19286. auto res1 = cli.Get("/compressible");
  19287. ASSERT_TRUE(res1);
  19288. EXPECT_EQ(200, res1->status);
  19289. // If Content-Encoding is set, Vary should also be set
  19290. if (res1->has_header("Content-Encoding")) {
  19291. EXPECT_TRUE(res1->has_header("Vary"));
  19292. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19293. }
  19294. // Request without Accept-Encoding header: should not have compression
  19295. Headers h_no_compress;
  19296. auto res2 = cli.Get("/compressible", h_no_compress);
  19297. ASSERT_TRUE(res2);
  19298. EXPECT_EQ(200, res2->status);
  19299. // Verify Vary header is present when compression is applied
  19300. // (the exact behavior depends on server configuration)
  19301. svr.stop();
  19302. t.join();
  19303. }
  19304. TEST(ETagTest, IfRangeWithETag) {
  19305. using namespace httplib;
  19306. // Create a test file with known content
  19307. const char *fname = "if_range_testfile.txt";
  19308. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19309. {
  19310. std::ofstream ofs(fname);
  19311. ofs << content;
  19312. ASSERT_TRUE(ofs.good());
  19313. }
  19314. Server svr;
  19315. svr.set_mount_point("/static", ".");
  19316. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19317. svr.wait_until_ready();
  19318. Client cli(HOST, PORT);
  19319. // First request: get ETag
  19320. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19321. ASSERT_TRUE(res1);
  19322. ASSERT_EQ(200, res1->status);
  19323. ASSERT_TRUE(res1->has_header("ETag"));
  19324. std::string etag = res1->get_header_value("ETag");
  19325. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19326. // Since our server generates weak ETags (W/"..."), If-Range with our
  19327. // ETag should NOT result in partial content - it should return full content.
  19328. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19329. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19330. ASSERT_TRUE(res2);
  19331. // Weak ETag in If-Range -> full content (200), not partial (206)
  19332. EXPECT_EQ(200, res2->status);
  19333. EXPECT_EQ(content, res2->body);
  19334. EXPECT_FALSE(res2->has_header("Content-Range"));
  19335. // Range request with non-matching If-Range (ETag): should get 200 (full
  19336. // content)
  19337. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19338. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19339. ASSERT_TRUE(res3);
  19340. EXPECT_EQ(200, res3->status);
  19341. EXPECT_EQ(content, res3->body);
  19342. EXPECT_FALSE(res3->has_header("Content-Range"));
  19343. // Range request with strong ETag (hypothetical - our server doesn't generate
  19344. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19345. // should return full content)
  19346. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19347. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19348. ASSERT_TRUE(res4);
  19349. EXPECT_EQ(200, res4->status);
  19350. EXPECT_EQ(content, res4->body);
  19351. EXPECT_FALSE(res4->has_header("Content-Range"));
  19352. svr.stop();
  19353. t.join();
  19354. std::remove(fname);
  19355. }
  19356. TEST(ETagTest, IfRangeWithDate) {
  19357. using namespace httplib;
  19358. // Create a test file
  19359. const char *fname = "if_range_date_testfile.txt";
  19360. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19361. {
  19362. std::ofstream ofs(fname);
  19363. ofs << content;
  19364. ASSERT_TRUE(ofs.good());
  19365. }
  19366. Server svr;
  19367. svr.set_mount_point("/static", ".");
  19368. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19369. svr.wait_until_ready();
  19370. Client cli(HOST, PORT);
  19371. // First request: get Last-Modified
  19372. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19373. ASSERT_TRUE(res1);
  19374. ASSERT_EQ(200, res1->status);
  19375. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19376. std::string last_modified = res1->get_header_value("Last-Modified");
  19377. // Range request with matching If-Range (date): should get 206
  19378. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19379. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19380. ASSERT_TRUE(res2);
  19381. EXPECT_EQ(206, res2->status);
  19382. EXPECT_EQ("FGHIJ", res2->body);
  19383. // Range request with old If-Range date: should get 200 (full content)
  19384. Headers h3 = {{"Range", "bytes=5-9"},
  19385. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19386. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19387. ASSERT_TRUE(res3);
  19388. EXPECT_EQ(200, res3->status);
  19389. EXPECT_EQ(content, res3->body);
  19390. // Range request with future If-Range date: should get 206
  19391. Headers h4 = {{"Range", "bytes=0-4"},
  19392. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19393. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19394. ASSERT_TRUE(res4);
  19395. EXPECT_EQ(206, res4->status);
  19396. EXPECT_EQ("ABCDE", res4->body);
  19397. svr.stop();
  19398. t.join();
  19399. std::remove(fname);
  19400. }
  19401. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19402. using namespace httplib;
  19403. const char *fname = "etag_malformed.txt";
  19404. const char *content = "malformed-etag";
  19405. {
  19406. std::ofstream ofs(fname);
  19407. ofs << content;
  19408. ASSERT_TRUE(ofs.good());
  19409. }
  19410. Server svr;
  19411. svr.set_mount_point("/static", ".");
  19412. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19413. svr.wait_until_ready();
  19414. Client cli(HOST, PORT);
  19415. // baseline: should get 200 and an ETag
  19416. auto res1 = cli.Get("/static/etag_malformed.txt");
  19417. ASSERT_TRUE(res1);
  19418. ASSERT_EQ(200, res1->status);
  19419. ASSERT_TRUE(res1->has_header("ETag"));
  19420. // Malformed ETag value (missing quotes) should be treated as non-matching
  19421. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19422. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19423. ASSERT_TRUE(res_bad);
  19424. EXPECT_EQ(200, res_bad->status);
  19425. // Whitespace-only header value should be considered invalid / non-matching
  19426. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19427. "Host: localhost\r\n"
  19428. "If-None-Match: \r\n"
  19429. "Connection: close\r\n"
  19430. "\r\n";
  19431. std::string out;
  19432. ASSERT_TRUE(send_request(5, raw_req, &out));
  19433. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19434. svr.stop();
  19435. t.join();
  19436. std::remove(fname);
  19437. }
  19438. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19439. using namespace httplib;
  19440. const char *fname = "ims_invalid_format.txt";
  19441. const char *content = "ims-bad-format";
  19442. {
  19443. std::ofstream ofs(fname);
  19444. ofs << content;
  19445. ASSERT_TRUE(ofs.good());
  19446. }
  19447. Server svr;
  19448. svr.set_mount_point("/static", ".");
  19449. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19450. svr.wait_until_ready();
  19451. Client cli(HOST, PORT);
  19452. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19453. ASSERT_TRUE(res1);
  19454. ASSERT_EQ(200, res1->status);
  19455. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19456. // If-Modified-Since with invalid format should not result in 304
  19457. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19458. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19459. ASSERT_TRUE(res_bad);
  19460. EXPECT_EQ(200, res_bad->status);
  19461. // If-Range with invalid date format should be treated as mismatch -> full
  19462. // content (200)
  19463. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19464. {"If-Range", "invalid-date"}};
  19465. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19466. ASSERT_TRUE(res_ifrange);
  19467. EXPECT_EQ(200, res_ifrange->status);
  19468. svr.stop();
  19469. t.join();
  19470. std::remove(fname);
  19471. }
  19472. TEST(ETagTest, IfRangeWithMalformedETag) {
  19473. using namespace httplib;
  19474. const char *fname = "ifrange_malformed.txt";
  19475. const std::string content = "0123456789";
  19476. {
  19477. std::ofstream ofs(fname);
  19478. ofs << content;
  19479. ASSERT_TRUE(ofs.good());
  19480. }
  19481. Server svr;
  19482. svr.set_mount_point("/static", ".");
  19483. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19484. svr.wait_until_ready();
  19485. Client cli(HOST, PORT);
  19486. // First request: get ETag
  19487. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19488. ASSERT_TRUE(res1);
  19489. ASSERT_EQ(200, res1->status);
  19490. ASSERT_TRUE(res1->has_header("ETag"));
  19491. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19492. // full content (200)
  19493. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19494. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19495. ASSERT_TRUE(res2);
  19496. EXPECT_EQ(200, res2->status);
  19497. EXPECT_EQ(content, res2->body);
  19498. svr.stop();
  19499. t.join();
  19500. std::remove(fname);
  19501. }
  19502. TEST(ETagTest, ExtremeLargeDateValues) {
  19503. using namespace httplib;
  19504. const char *fname = "ims_extreme_date.txt";
  19505. const char *content = "ims-extreme-date";
  19506. {
  19507. std::ofstream ofs(fname);
  19508. ofs << content;
  19509. ASSERT_TRUE(ofs.good());
  19510. }
  19511. Server svr;
  19512. svr.set_mount_point("/static", ".");
  19513. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19514. svr.wait_until_ready();
  19515. Client cli(HOST, PORT);
  19516. auto res1 = cli.Get(std::string("/static/") + fname);
  19517. ASSERT_TRUE(res1);
  19518. ASSERT_EQ(200, res1->status);
  19519. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19520. // Extremely large year that may overflow date parsing routines.
  19521. Headers h_large_date = {
  19522. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19523. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19524. ASSERT_TRUE(res_bad);
  19525. // Expect server to treat this as invalid/mismatch and return full content
  19526. EXPECT_EQ(200, res_bad->status);
  19527. // If-Range with extremely large date should be treated as mismatch -> full
  19528. // content (200)
  19529. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19530. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19531. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19532. ASSERT_TRUE(res_ifrange);
  19533. EXPECT_EQ(200, res_ifrange->status);
  19534. svr.stop();
  19535. t.join();
  19536. std::remove(fname);
  19537. }
  19538. TEST(ETagTest, NegativeFileModificationTime) {
  19539. using namespace httplib;
  19540. const char *fname = "ims_negative_mtime.txt";
  19541. const std::string content = "negative-mtime";
  19542. {
  19543. std::ofstream ofs(fname);
  19544. ofs << content;
  19545. ASSERT_TRUE(ofs.good());
  19546. }
  19547. // Try to set file mtime to a negative value. This may fail on some
  19548. // platforms/filesystems; if it fails, the test will still verify server
  19549. // behaves safely by performing a regular conditional request.
  19550. #if defined(__APPLE__) || defined(__linux__)
  19551. bool set_negative = false;
  19552. do {
  19553. struct timeval times[2];
  19554. // access time: now
  19555. times[0].tv_sec = time(nullptr);
  19556. times[0].tv_usec = 0;
  19557. // modification time: negative (e.g., -1)
  19558. times[1].tv_sec = -1;
  19559. times[1].tv_usec = 0;
  19560. if (utimes(fname, times) == 0) { set_negative = true; }
  19561. } while (0);
  19562. #else
  19563. bool set_negative = false;
  19564. #endif
  19565. Server svr;
  19566. svr.set_mount_point("/static", ".");
  19567. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19568. svr.wait_until_ready();
  19569. Client cli(HOST, PORT);
  19570. auto res1 = cli.Get(std::string("/static/") + fname);
  19571. ASSERT_TRUE(res1);
  19572. ASSERT_EQ(200, res1->status);
  19573. bool has_last_modified = res1->has_header("Last-Modified");
  19574. std::string last_modified;
  19575. if (has_last_modified) {
  19576. last_modified = res1->get_header_value("Last-Modified");
  19577. }
  19578. if (set_negative) {
  19579. // If we successfully set a negative mtime, ensure server returns a
  19580. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19581. // with an old date and ensure server handles it without crash.
  19582. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19583. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19584. ASSERT_TRUE(res2);
  19585. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19586. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19587. } else {
  19588. // Could not set negative mtime on this platform; fall back to verifying
  19589. // that normal invalid/malformed dates are treated safely (non-304).
  19590. Headers h_bad_date = {
  19591. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19592. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19593. ASSERT_TRUE(res_bad);
  19594. EXPECT_EQ(200, res_bad->status);
  19595. }
  19596. svr.stop();
  19597. t.join();
  19598. std::remove(fname);
  19599. }
  19600. //==============================================================================
  19601. // Integration Tests with Server
  19602. //==============================================================================
  19603. class SSEIntegrationTest : public ::testing::Test {
  19604. protected:
  19605. void SetUp() override {
  19606. stop_server_.store(false);
  19607. events_.clear();
  19608. server_ = httplib::detail::make_unique<Server>();
  19609. setup_server();
  19610. start_server();
  19611. }
  19612. void TearDown() override {
  19613. stop_server_.store(true);
  19614. event_cv_.notify_all();
  19615. server_->stop();
  19616. if (server_thread_.joinable()) { server_thread_.join(); }
  19617. }
  19618. void setup_server() {
  19619. // Simple SSE endpoint
  19620. server_->Get("/events", [this](const Request &req, Response &res) {
  19621. auto last_id = req.get_header_value("Last-Event-ID");
  19622. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19623. res.set_chunked_content_provider(
  19624. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19625. std::unique_lock<std::mutex> lock(event_mutex_);
  19626. if (event_cv_.wait_for(
  19627. lock, std::chrono::milliseconds(200), [this] {
  19628. return !events_.empty() || stop_server_.load();
  19629. })) {
  19630. if (stop_server_.load()) { return false; }
  19631. if (!events_.empty()) {
  19632. std::string event = events_.front();
  19633. events_.erase(events_.begin());
  19634. sink.write(event.data(), event.size());
  19635. return true;
  19636. }
  19637. }
  19638. return !stop_server_.load();
  19639. });
  19640. });
  19641. // Endpoint that returns error
  19642. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19643. res.status = 500;
  19644. res.set_content("Internal Server Error", "text/plain");
  19645. });
  19646. // Endpoint for custom event types
  19647. server_->Get("/custom-events", [](const Request &, Response &res) {
  19648. res.set_chunked_content_provider(
  19649. "text/event-stream", [](size_t offset, DataSink &sink) {
  19650. if (offset == 0) {
  19651. std::string event = "event: update\ndata: updated\n\n"
  19652. "event: delete\ndata: deleted\n\n";
  19653. sink.write(event.data(), event.size());
  19654. }
  19655. return false; // End stream after sending
  19656. });
  19657. });
  19658. }
  19659. void start_server() {
  19660. port_ = server_->bind_to_any_port(HOST);
  19661. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19662. // Wait for server to start
  19663. while (!server_->is_running()) {
  19664. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19665. }
  19666. }
  19667. int get_port() const { return port_; }
  19668. void send_event(const std::string &event) {
  19669. std::lock_guard<std::mutex> lock(event_mutex_);
  19670. events_.push_back(event);
  19671. event_cv_.notify_all();
  19672. }
  19673. std::unique_ptr<Server> server_;
  19674. std::thread server_thread_;
  19675. std::mutex event_mutex_;
  19676. std::condition_variable event_cv_;
  19677. std::vector<std::string> events_;
  19678. std::atomic<bool> stop_server_{false};
  19679. std::string last_received_event_id_;
  19680. int port_ = 0;
  19681. };
  19682. //==============================================================================
  19683. // SSE Parsing Tests
  19684. //==============================================================================
  19685. class SSEParsingTest : public SSEIntegrationTest {
  19686. protected:
  19687. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19688. // A trailing sentinel event tells when the whole stream has been parsed.
  19689. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19690. auto body = stream + "event: end\ndata: end\n\n";
  19691. server_->Get("/parse", [body](const Request &, Response &res) {
  19692. res.set_content(body, "text/event-stream");
  19693. });
  19694. return collect("/parse");
  19695. }
  19696. // Runs SSEClient against path until an "end" event arrives and returns the
  19697. // messages dispatched before it
  19698. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19699. Client client(HOST, get_port());
  19700. sse::SSEClient sse(client, path);
  19701. std::mutex mutex;
  19702. std::condition_variable cv;
  19703. std::vector<sse::SSEMessage> messages;
  19704. auto done = false;
  19705. sse.on_message([&](const sse::SSEMessage &msg) {
  19706. std::lock_guard<std::mutex> lock(mutex);
  19707. // Ignore a replay from a reconnect that races with stop()
  19708. if (!done) { messages.push_back(msg); }
  19709. });
  19710. sse.on_event("end", [&](const sse::SSEMessage &) {
  19711. std::lock_guard<std::mutex> lock(mutex);
  19712. done = true;
  19713. cv.notify_all();
  19714. });
  19715. sse.set_reconnect_interval(100);
  19716. sse.start_async();
  19717. {
  19718. std::unique_lock<std::mutex> lock(mutex);
  19719. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19720. }
  19721. sse.stop();
  19722. EXPECT_TRUE(done);
  19723. return messages;
  19724. }
  19725. };
  19726. TEST_F(SSEParsingTest, SingleLineData) {
  19727. auto msgs = parse("data: hello\n\n");
  19728. ASSERT_EQ(msgs.size(), 1u);
  19729. EXPECT_EQ(msgs[0].data, "hello");
  19730. EXPECT_EQ(msgs[0].event, "message");
  19731. }
  19732. TEST_F(SSEParsingTest, MultiLineData) {
  19733. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19734. ASSERT_EQ(msgs.size(), 1u);
  19735. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19736. }
  19737. TEST_F(SSEParsingTest, CustomEventType) {
  19738. auto msgs = parse("event: update\ndata: payload\n\n");
  19739. ASSERT_EQ(msgs.size(), 1u);
  19740. EXPECT_EQ(msgs[0].event, "update");
  19741. EXPECT_EQ(msgs[0].data, "payload");
  19742. }
  19743. TEST_F(SSEParsingTest, EventIdHandling) {
  19744. auto msgs = parse("id: 12345\ndata: test\n\n");
  19745. ASSERT_EQ(msgs.size(), 1u);
  19746. EXPECT_EQ(msgs[0].id, "12345");
  19747. }
  19748. TEST_F(SSEParsingTest, EmptyEventId) {
  19749. auto msgs = parse("id:\ndata: test\n\n");
  19750. ASSERT_EQ(msgs.size(), 1u);
  19751. EXPECT_EQ(msgs[0].id, "");
  19752. }
  19753. TEST_F(SSEParsingTest, CommentsIgnored) {
  19754. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19755. ASSERT_EQ(msgs.size(), 1u);
  19756. EXPECT_EQ(msgs[0].data, "hello");
  19757. EXPECT_EQ(msgs[0].event, "message");
  19758. }
  19759. TEST_F(SSEParsingTest, ColonInValue) {
  19760. auto msgs = parse("data: hello:world:test\n\n");
  19761. ASSERT_EQ(msgs.size(), 1u);
  19762. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19763. }
  19764. TEST_F(SSEParsingTest, FieldNameOnly) {
  19765. // A line without a colon is a field name with an empty value
  19766. auto msgs = parse("data\n\n");
  19767. ASSERT_EQ(msgs.size(), 1u);
  19768. EXPECT_EQ(msgs[0].data, "");
  19769. }
  19770. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19771. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19772. ASSERT_EQ(msgs.size(), 1u);
  19773. EXPECT_EQ(msgs[0].event, "update");
  19774. EXPECT_EQ(msgs[0].data, "hello");
  19775. }
  19776. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19777. auto msgs = parse("data\r\n\r\n");
  19778. ASSERT_EQ(msgs.size(), 1u);
  19779. EXPECT_EQ(msgs[0].data, "");
  19780. }
  19781. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19782. auto msgs = parse("event: update\rdata: hello\r\r");
  19783. ASSERT_EQ(msgs.size(), 1u);
  19784. EXPECT_EQ(msgs[0].event, "update");
  19785. EXPECT_EQ(msgs[0].data, "hello");
  19786. }
  19787. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19788. // Chunk boundaries fall inside every \r\n and right before the first one
  19789. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19790. "\n\r", "\nevent: end\ndata: end\n\n"};
  19791. server_->Get("/split", [chunks](const Request &, Response &res) {
  19792. auto i = std::make_shared<size_t>(0);
  19793. res.set_chunked_content_provider(
  19794. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19795. if (*i == chunks.size()) {
  19796. sink.done();
  19797. } else {
  19798. sink.write(chunks[*i].data(), chunks[*i].size());
  19799. (*i)++;
  19800. }
  19801. return true;
  19802. });
  19803. });
  19804. auto msgs = collect("/split");
  19805. ASSERT_EQ(msgs.size(), 1u);
  19806. EXPECT_EQ(msgs[0].event, "update");
  19807. EXPECT_EQ(msgs[0].data, "hello");
  19808. }
  19809. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19810. // Only a BOM at the start of the stream is ignored
  19811. auto msgs = parse("\xEF\xBB\xBF"
  19812. "data: first\n\n"
  19813. "\xEF\xBB\xBF"
  19814. "data: second\n\n");
  19815. ASSERT_EQ(msgs.size(), 1u);
  19816. EXPECT_EQ(msgs[0].data, "first");
  19817. }
  19818. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19819. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19820. ASSERT_EQ(msgs.size(), 1u);
  19821. EXPECT_EQ(msgs[0].data, "hello");
  19822. EXPECT_EQ(msgs[0].event, "message");
  19823. }
  19824. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19825. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19826. ASSERT_EQ(msgs.size(), 2u);
  19827. EXPECT_EQ(msgs[0].data, "hello");
  19828. EXPECT_EQ(msgs[1].data, "hello");
  19829. }
  19830. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19831. // An event without data is not dispatched, and its type must not leak
  19832. // into the next event
  19833. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19834. ASSERT_EQ(msgs.size(), 1u);
  19835. EXPECT_EQ(msgs[0].event, "message");
  19836. EXPECT_EQ(msgs[0].data, "hello");
  19837. }
  19838. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19839. // The first connection sends only an id; the second echoes back the
  19840. // Last-Event-ID it was reconnected with
  19841. std::atomic<int> connection_count{0};
  19842. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19843. if (connection_count++ == 0) {
  19844. res.set_content("id: 42\n\n", "text/event-stream");
  19845. } else {
  19846. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19847. "\n\nevent: end\ndata: end\n\n",
  19848. "text/event-stream");
  19849. }
  19850. });
  19851. auto msgs = collect("/id-only");
  19852. ASSERT_EQ(msgs.size(), 1u);
  19853. EXPECT_EQ(msgs[0].data, "42");
  19854. }
  19855. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19856. // The first connection sets an id and then clears it with an empty one; the
  19857. // second reports whether it was reconnected with a Last-Event-ID
  19858. std::atomic<int> connection_count{0};
  19859. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19860. if (connection_count++ == 0) {
  19861. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19862. "text/event-stream");
  19863. } else {
  19864. res.set_content(
  19865. std::string("data: ") +
  19866. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19867. "\n\nevent: end\ndata: end\n\n",
  19868. "text/event-stream");
  19869. }
  19870. });
  19871. auto msgs = collect("/id-clear");
  19872. ASSERT_EQ(msgs.size(), 3u);
  19873. EXPECT_EQ(msgs[0].id, "1");
  19874. EXPECT_EQ(msgs[1].id, "");
  19875. EXPECT_EQ(msgs[2].data, "not sent");
  19876. }
  19877. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19878. // The first connection sets an id and then sends ids that cannot be carried
  19879. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19880. // with
  19881. std::atomic<int> connection_count{0};
  19882. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19883. if (connection_count++ == 0) {
  19884. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19885. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19886. "text/event-stream");
  19887. } else {
  19888. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19889. "\n\nevent: end\ndata: end\n\n",
  19890. "text/event-stream");
  19891. }
  19892. });
  19893. auto msgs = collect("/id-unsendable");
  19894. ASSERT_EQ(msgs.size(), 1u);
  19895. EXPECT_EQ(msgs[0].data, "42");
  19896. }
  19897. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19898. auto msgs = parse("event: notification\nid: evt-42\n"
  19899. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19900. ASSERT_EQ(msgs.size(), 1u);
  19901. EXPECT_EQ(msgs[0].event, "notification");
  19902. EXPECT_EQ(msgs[0].id, "evt-42");
  19903. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19904. }
  19905. TEST(SSEMessageTest, Clear) {
  19906. sse::SSEMessage msg;
  19907. msg.event = "custom";
  19908. msg.data = "some data";
  19909. msg.id = "123";
  19910. msg.clear();
  19911. EXPECT_EQ(msg.event, "message");
  19912. EXPECT_EQ(msg.data, "");
  19913. EXPECT_EQ(msg.id, "");
  19914. }
  19915. //==============================================================================
  19916. // SSE Integration Tests
  19917. //==============================================================================
  19918. // Test: Successful connection and on_open callback
  19919. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19920. // Add a simple endpoint that sends one event and closes
  19921. server_->Get("/simple-event", [](const Request &, Response &res) {
  19922. res.set_chunked_content_provider(
  19923. "text/event-stream", [](size_t offset, DataSink &sink) {
  19924. if (offset == 0) {
  19925. std::string event = "data: hello\n\n";
  19926. sink.write(event.data(), event.size());
  19927. }
  19928. return false; // Close stream after sending
  19929. });
  19930. });
  19931. Client client("localhost", get_port());
  19932. sse::SSEClient sse(client, "/simple-event");
  19933. std::atomic<bool> open_called{false};
  19934. std::atomic<bool> message_received{false};
  19935. sse.on_open([&open_called]() { open_called.store(true); });
  19936. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19937. if (msg.data == "hello") { message_received.store(true); }
  19938. });
  19939. sse.set_reconnect_interval(100);
  19940. sse.set_max_reconnect_attempts(1);
  19941. // Start async
  19942. sse.start_async();
  19943. // Wait for message to be processed
  19944. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19945. sse.stop();
  19946. EXPECT_TRUE(open_called.load());
  19947. EXPECT_TRUE(message_received.load());
  19948. }
  19949. // Test: on_message callback
  19950. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19951. // Endpoint that sends multiple events then closes
  19952. server_->Get("/multi-event", [](const Request &, Response &res) {
  19953. res.set_chunked_content_provider(
  19954. "text/event-stream", [](size_t offset, DataSink &sink) {
  19955. if (offset == 0) {
  19956. std::string events = "data: message1\n\ndata: message2\n\n";
  19957. sink.write(events.data(), events.size());
  19958. }
  19959. return false;
  19960. });
  19961. });
  19962. Client client("localhost", get_port());
  19963. sse::SSEClient sse(client, "/multi-event");
  19964. std::vector<std::string> received_messages;
  19965. std::mutex messages_mutex;
  19966. sse.on_message([&](const sse::SSEMessage &msg) {
  19967. std::lock_guard<std::mutex> lock(messages_mutex);
  19968. received_messages.push_back(msg.data);
  19969. });
  19970. sse.set_reconnect_interval(100);
  19971. sse.set_max_reconnect_attempts(1);
  19972. sse.start_async();
  19973. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19974. sse.stop();
  19975. std::lock_guard<std::mutex> lock(messages_mutex);
  19976. EXPECT_GE(received_messages.size(), 2u);
  19977. if (received_messages.size() >= 2) {
  19978. EXPECT_EQ(received_messages[0], "message1");
  19979. EXPECT_EQ(received_messages[1], "message2");
  19980. }
  19981. }
  19982. // Test: on_event for specific types
  19983. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19984. Client client("localhost", get_port());
  19985. sse::SSEClient sse(client, "/custom-events");
  19986. std::atomic<bool> update_received{false};
  19987. std::atomic<bool> delete_received{false};
  19988. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19989. if (msg.data == "updated") { update_received.store(true); }
  19990. });
  19991. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19992. if (msg.data == "deleted") { delete_received.store(true); }
  19993. });
  19994. sse.set_max_reconnect_attempts(1);
  19995. sse.start_async();
  19996. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19997. sse.stop();
  19998. EXPECT_TRUE(update_received.load());
  19999. EXPECT_TRUE(delete_received.load());
  20000. }
  20001. // Test: on_error callback on connection failure
  20002. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20003. // Connect to a non-existent port
  20004. Client client("localhost", 59999);
  20005. sse::SSEClient sse(client, "/events");
  20006. std::atomic<bool> error_called{false};
  20007. Error received_error = Error::Success;
  20008. sse.on_error([&](Error err) {
  20009. error_called.store(true);
  20010. received_error = err;
  20011. });
  20012. sse.set_reconnect_interval(50);
  20013. sse.set_max_reconnect_attempts(1);
  20014. sse.start_async();
  20015. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20016. sse.stop();
  20017. EXPECT_TRUE(error_called.load());
  20018. EXPECT_NE(received_error, Error::Success);
  20019. }
  20020. // Test: Last-Event-ID header sent on reconnect
  20021. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20022. // Endpoint that sends event with ID
  20023. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20024. res.set_chunked_content_provider(
  20025. "text/event-stream", [](size_t offset, DataSink &sink) {
  20026. if (offset == 0) {
  20027. std::string event = "id: evt-123\ndata: test\n\n";
  20028. sink.write(event.data(), event.size());
  20029. }
  20030. return false;
  20031. });
  20032. });
  20033. Client client("localhost", get_port());
  20034. sse::SSEClient sse(client, "/event-with-id");
  20035. std::atomic<bool> id_received{false};
  20036. sse.on_message([&](const sse::SSEMessage &msg) {
  20037. if (!msg.id.empty()) { id_received.store(true); }
  20038. });
  20039. sse.set_reconnect_interval(100);
  20040. sse.set_max_reconnect_attempts(1);
  20041. sse.start_async();
  20042. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20043. sse.stop();
  20044. EXPECT_TRUE(id_received.load());
  20045. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20046. }
  20047. // Test: Manual stop
  20048. TEST_F(SSEIntegrationTest, ManualStop) {
  20049. // Endpoint that sends one event and stays open briefly
  20050. std::atomic<bool> handler_running{true};
  20051. server_->Get("/stay-open", [&handler_running](const Request &,
  20052. Response &res) {
  20053. res.set_chunked_content_provider(
  20054. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20055. if (offset == 0) {
  20056. std::string event = "data: connected\n\n";
  20057. sink.write(event.data(), event.size());
  20058. }
  20059. // Keep connection open while handler_running is true
  20060. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20061. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20062. }
  20063. return false;
  20064. });
  20065. });
  20066. Client client("localhost", get_port());
  20067. sse::SSEClient sse(client, "/stay-open");
  20068. std::atomic<bool> connected{false};
  20069. sse.on_open([&connected]() { connected.store(true); });
  20070. sse.set_reconnect_interval(100);
  20071. sse.set_max_reconnect_attempts(1);
  20072. sse.start_async();
  20073. // Wait for connection to establish
  20074. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20075. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20076. }
  20077. EXPECT_TRUE(connected.load());
  20078. EXPECT_TRUE(sse.is_connected());
  20079. // Signal handler to stop
  20080. handler_running.store(false);
  20081. // Stop SSE client
  20082. sse.stop();
  20083. EXPECT_FALSE(sse.is_connected());
  20084. }
  20085. // Test: SSEClient with custom headers
  20086. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20087. // Setup a server endpoint that checks for custom header
  20088. std::atomic<bool> header_received{false};
  20089. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20090. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20091. header_received.store(true);
  20092. }
  20093. res.set_chunked_content_provider("text/event-stream",
  20094. [](size_t, DataSink &) { return false; });
  20095. });
  20096. Client client("localhost", get_port());
  20097. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20098. sse::SSEClient sse(client, "/header-check", headers);
  20099. sse.set_max_reconnect_attempts(1);
  20100. sse.start_async();
  20101. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20102. sse.stop();
  20103. EXPECT_TRUE(header_received.load());
  20104. }
  20105. // Test: Reconnect interval configuration
  20106. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20107. Client client("localhost", get_port());
  20108. sse::SSEClient sse(client, "/events");
  20109. auto &result = sse.set_reconnect_interval(500);
  20110. // Builder pattern should return reference to self
  20111. EXPECT_EQ(&result, &sse);
  20112. }
  20113. // Test: Max reconnect attempts
  20114. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20115. // Connect to non-existent port to force reconnects
  20116. Client client("localhost", 59998);
  20117. sse::SSEClient sse(client, "/events");
  20118. std::atomic<int> error_count{0};
  20119. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20120. sse.set_reconnect_interval(50);
  20121. sse.set_max_reconnect_attempts(2);
  20122. auto start = std::chrono::steady_clock::now();
  20123. sse.start(); // Blocking call
  20124. auto end = std::chrono::steady_clock::now();
  20125. // Should have stopped after 2 failed attempts
  20126. EXPECT_GE(error_count.load(), 2);
  20127. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20128. auto duration =
  20129. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20130. #ifdef _WIN32
  20131. // Windows is much slower for socket connection failures
  20132. EXPECT_LT(duration.count(), 7000);
  20133. #else
  20134. EXPECT_LT(duration.count(), 1000);
  20135. #endif
  20136. }
  20137. // Test: Multi-line data in integration
  20138. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20139. // Endpoint with multi-line data
  20140. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20141. res.set_chunked_content_provider(
  20142. "text/event-stream", [](size_t offset, DataSink &sink) {
  20143. if (offset == 0) {
  20144. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20145. sink.write(event.data(), event.size());
  20146. }
  20147. return false;
  20148. });
  20149. });
  20150. Client client("localhost", get_port());
  20151. sse::SSEClient sse(client, "/multiline-data");
  20152. std::string received_data;
  20153. std::mutex data_mutex;
  20154. sse.on_message([&](const sse::SSEMessage &msg) {
  20155. std::lock_guard<std::mutex> lock(data_mutex);
  20156. received_data = msg.data;
  20157. });
  20158. sse.set_reconnect_interval(100);
  20159. sse.set_max_reconnect_attempts(1);
  20160. sse.start_async();
  20161. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20162. sse.stop();
  20163. std::lock_guard<std::mutex> lock(data_mutex);
  20164. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20165. }
  20166. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20167. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20168. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20169. DataSink &sink) {
  20170. if (offset == 0) {
  20171. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20172. sink.write(events.data(), events.size());
  20173. }
  20174. return false;
  20175. });
  20176. });
  20177. Client client("localhost", get_port());
  20178. sse::SSEClient sse(client, "/empty-data-lines");
  20179. std::mutex mutex;
  20180. std::condition_variable cv;
  20181. std::vector<std::string> received;
  20182. sse.on_message([&](const sse::SSEMessage &msg) {
  20183. std::lock_guard<std::mutex> lock(mutex);
  20184. received.push_back(msg.data);
  20185. cv.notify_all();
  20186. });
  20187. sse.set_max_reconnect_attempts(1);
  20188. sse.start_async();
  20189. {
  20190. std::unique_lock<std::mutex> lock(mutex);
  20191. cv.wait_for(lock, std::chrono::seconds(2),
  20192. [&] { return received.size() >= 3; });
  20193. }
  20194. sse.stop();
  20195. ASSERT_GE(received.size(), 3u);
  20196. EXPECT_EQ(received[0], "");
  20197. EXPECT_EQ(received[1], "\nhello");
  20198. EXPECT_EQ(received[2], "");
  20199. }
  20200. // Test: Auto-reconnect after server disconnection
  20201. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20202. std::atomic<int> connection_count{0};
  20203. std::atomic<int> message_count{0};
  20204. // Endpoint that sends one event and closes, forcing reconnect
  20205. server_->Get("/reconnect-test",
  20206. [&connection_count](const Request &, Response &res) {
  20207. connection_count.fetch_add(1);
  20208. res.set_chunked_content_provider(
  20209. "text/event-stream", [](size_t offset, DataSink &sink) {
  20210. if (offset == 0) {
  20211. std::string event = "data: hello\n\n";
  20212. sink.write(event.data(), event.size());
  20213. }
  20214. return false; // Close connection after sending
  20215. });
  20216. });
  20217. Client client("localhost", get_port());
  20218. sse::SSEClient sse(client, "/reconnect-test");
  20219. sse.on_message([&message_count](const sse::SSEMessage &) {
  20220. message_count.fetch_add(1);
  20221. });
  20222. sse.set_reconnect_interval(100);
  20223. sse.set_max_reconnect_attempts(3);
  20224. sse.start_async();
  20225. // Wait long enough for multiple reconnects
  20226. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20227. sse.stop();
  20228. // Should have connected multiple times (initial + reconnects)
  20229. EXPECT_GE(connection_count.load(), 2);
  20230. // Should have received messages from multiple connections
  20231. EXPECT_GE(message_count.load(), 2);
  20232. }
  20233. // Test: A retry field that is not all ASCII digits is ignored
  20234. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20235. std::atomic<int> connection_count{0};
  20236. server_->Get("/bad-retry",
  20237. [&connection_count](const Request &, Response &res) {
  20238. connection_count.fetch_add(1);
  20239. res.set_chunked_content_provider(
  20240. "text/event-stream", [](size_t offset, DataSink &sink) {
  20241. if (offset == 0) {
  20242. std::string event = "retry: -1\ndata: hello\n\n";
  20243. sink.write(event.data(), event.size());
  20244. }
  20245. return false;
  20246. });
  20247. });
  20248. Client client("localhost", get_port());
  20249. sse::SSEClient sse(client, "/bad-retry");
  20250. sse.set_reconnect_interval(10000);
  20251. sse.start_async();
  20252. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20253. sse.stop();
  20254. EXPECT_EQ(connection_count.load(), 1);
  20255. }
  20256. // Test: A retry field of all ASCII digits sets the reconnection time
  20257. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20258. std::mutex mutex;
  20259. std::condition_variable cv;
  20260. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20261. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20262. {
  20263. std::lock_guard<std::mutex> lock(mutex);
  20264. connected_at.push_back(std::chrono::steady_clock::now());
  20265. cv.notify_all();
  20266. }
  20267. res.set_chunked_content_provider(
  20268. "text/event-stream", [](size_t offset, DataSink &sink) {
  20269. if (offset == 0) {
  20270. std::string event = "retry: 0\ndata: hello\n\n";
  20271. sink.write(event.data(), event.size());
  20272. }
  20273. return false;
  20274. });
  20275. });
  20276. Client client("localhost", get_port());
  20277. sse::SSEClient sse(client, "/zero-retry");
  20278. sse.set_reconnect_interval(10000);
  20279. sse.start_async();
  20280. {
  20281. std::unique_lock<std::mutex> lock(mutex);
  20282. cv.wait_for(lock, std::chrono::seconds(5),
  20283. [&] { return connected_at.size() >= 2; });
  20284. }
  20285. sse.stop();
  20286. // The server-supplied interval is applied, but never below 100ms, so
  20287. // "retry: 0" does not cause a busy reconnect loop
  20288. std::lock_guard<std::mutex> lock(mutex);
  20289. ASSERT_GE(connected_at.size(), 2u);
  20290. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20291. connected_at[1] - connected_at[0])
  20292. .count();
  20293. EXPECT_GE(interval_ms, 100);
  20294. }
  20295. // Test: Last-Event-ID sent on reconnect
  20296. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20297. std::atomic<int> connection_count{0};
  20298. std::vector<std::string> received_last_event_ids;
  20299. std::mutex id_mutex;
  20300. // Endpoint that checks Last-Event-ID header and sends event with ID
  20301. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20302. int conn = connection_count.fetch_add(1);
  20303. // Capture the Last-Event-ID header from each connection
  20304. {
  20305. std::lock_guard<std::mutex> lock(id_mutex);
  20306. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20307. }
  20308. res.set_chunked_content_provider(
  20309. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20310. if (offset == 0) {
  20311. std::string event =
  20312. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20313. sink.write(event.data(), event.size());
  20314. }
  20315. return false;
  20316. });
  20317. });
  20318. Client client("localhost", get_port());
  20319. sse::SSEClient sse(client, "/reconnect-with-id");
  20320. sse.set_reconnect_interval(100);
  20321. sse.set_max_reconnect_attempts(3);
  20322. sse.start_async();
  20323. // Wait for at least 2 connections
  20324. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20325. sse.stop();
  20326. // Verify behavior
  20327. std::lock_guard<std::mutex> lock(id_mutex);
  20328. EXPECT_GE(received_last_event_ids.size(), 2u);
  20329. // First connection should have no Last-Event-ID
  20330. if (!received_last_event_ids.empty()) {
  20331. EXPECT_EQ(received_last_event_ids[0], "");
  20332. }
  20333. // Second connection should have Last-Event-ID from first connection
  20334. if (received_last_event_ids.size() >= 2) {
  20335. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20336. }
  20337. }
  20338. // Test: set_headers updates headers used on reconnect
  20339. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20340. std::vector<std::string> received_tokens;
  20341. std::mutex token_mutex;
  20342. // Endpoint that captures Authorization header
  20343. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20344. {
  20345. std::lock_guard<std::mutex> lock(token_mutex);
  20346. received_tokens.push_back(req.get_header_value("Authorization"));
  20347. }
  20348. res.set_chunked_content_provider(
  20349. "text/event-stream", [](size_t offset, DataSink &sink) {
  20350. if (offset == 0) {
  20351. std::string event = "data: hello\n\n";
  20352. sink.write(event.data(), event.size());
  20353. }
  20354. return false; // Close connection to trigger reconnect
  20355. });
  20356. });
  20357. Client client("localhost", get_port());
  20358. Headers headers = {{"Authorization", "Bearer old-token"}};
  20359. sse::SSEClient sse(client, "/auth-check", headers);
  20360. // Update headers on each successful connection
  20361. sse.on_open(
  20362. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20363. sse.set_reconnect_interval(100);
  20364. sse.set_max_reconnect_attempts(3);
  20365. sse.start_async();
  20366. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20367. sse.stop();
  20368. std::lock_guard<std::mutex> lock(token_mutex);
  20369. ASSERT_GE(received_tokens.size(), 2u);
  20370. // First connection uses original header
  20371. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20372. // Second connection uses updated header from set_headers
  20373. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20374. }
  20375. // Test: 401 allows reconnection (so on_error can refresh headers)
  20376. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20377. std::atomic<int> connection_count{0};
  20378. // Endpoint: returns 401 on first attempt, 200 on second
  20379. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20380. int conn = connection_count.fetch_add(1);
  20381. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20382. res.status = StatusCode::Unauthorized_401;
  20383. res.set_content("Unauthorized", "text/plain");
  20384. return;
  20385. }
  20386. res.set_chunked_content_provider(
  20387. "text/event-stream", [](size_t offset, DataSink &sink) {
  20388. if (offset == 0) {
  20389. std::string event = "data: authenticated\n\n";
  20390. sink.write(event.data(), event.size());
  20391. }
  20392. return false;
  20393. });
  20394. });
  20395. Client client("localhost", get_port());
  20396. Headers headers = {{"Authorization", "Bearer expired"}};
  20397. sse::SSEClient sse(client, "/auth-retry", headers);
  20398. std::atomic<bool> message_received{false};
  20399. // Refresh token on error
  20400. sse.on_error(
  20401. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20402. sse.on_message([&](const sse::SSEMessage &msg) {
  20403. if (msg.data == "authenticated") { message_received.store(true); }
  20404. });
  20405. sse.set_reconnect_interval(100);
  20406. sse.set_max_reconnect_attempts(3);
  20407. sse.start_async();
  20408. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20409. sse.stop();
  20410. // Should have reconnected after 401 and succeeded with new token
  20411. EXPECT_GE(connection_count.load(), 2);
  20412. EXPECT_TRUE(message_received.load());
  20413. }
  20414. TEST(Issue2318Test, EmptyHostString) {
  20415. {
  20416. httplib::Client cli_empty("", PORT);
  20417. auto res = cli_empty.Get("/");
  20418. ASSERT_FALSE(res);
  20419. EXPECT_EQ(httplib::Error::Connection, res.error());
  20420. }
  20421. {
  20422. httplib::Client cli(" ", PORT);
  20423. auto res = cli.Get("/");
  20424. ASSERT_FALSE(res);
  20425. EXPECT_EQ(httplib::Error::Connection, res.error());
  20426. }
  20427. }
  20428. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20429. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20430. Server svr;
  20431. // Set a small payload limit (1KB)
  20432. svr.set_payload_max_length(1024);
  20433. svr.Post("/test", [&](const Request &req, Response &res) {
  20434. res.set_content("Body size: " + std::to_string(req.body.size()),
  20435. "text/plain");
  20436. });
  20437. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20438. auto se = detail::scope_exit([&] {
  20439. svr.stop();
  20440. listen_thread.join();
  20441. });
  20442. svr.wait_until_ready();
  20443. // Create data that compresses well but exceeds limit when decompressed
  20444. // 8KB of repeated null bytes compresses to a very small size
  20445. std::string original_data(8 * 1024, '\0');
  20446. // Compress the data using gzip
  20447. std::string compressed_data;
  20448. detail::gzip_compressor compressor;
  20449. compressor.compress(original_data.data(), original_data.size(), true,
  20450. [&](const char *data, size_t size) {
  20451. compressed_data.append(data, size);
  20452. return true;
  20453. });
  20454. // Verify compression worked (compressed should be much smaller)
  20455. ASSERT_LT(compressed_data.size(), original_data.size());
  20456. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20457. // Send compressed data with Content-Encoding: gzip
  20458. Client cli(HOST, PORT);
  20459. Headers headers = {{"Content-Encoding", "gzip"}};
  20460. auto res =
  20461. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20462. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20464. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20465. }
  20466. #endif
  20467. // ============================================================================
  20468. // OpenSSL-Specific Tests
  20469. // ============================================================================
  20470. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20471. X509 *readCertificate(const std::string &strFileName) {
  20472. std::ifstream inStream(strFileName);
  20473. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20474. std::istreambuf_iterator<char>());
  20475. if (strCertPEM.empty()) return (nullptr);
  20476. BIO *pbCert = BIO_new(BIO_s_mem());
  20477. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20478. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20479. BIO_free(pbCert);
  20480. return (pCert);
  20481. }
  20482. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20483. std::ifstream inStream(strFileName);
  20484. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20485. std::istreambuf_iterator<char>());
  20486. if (strPrivateKeyPEM.empty()) return (nullptr);
  20487. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20488. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20489. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20490. BIO_free(pbPrivKey);
  20491. return (pPrivateKey);
  20492. }
  20493. TEST(BindServerTest, UpdateCerts) {
  20494. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20495. int port = svr.bind_to_any_port("0.0.0.0");
  20496. ASSERT_TRUE(svr.is_valid());
  20497. ASSERT_TRUE(port > 0);
  20498. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20499. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20500. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20501. ASSERT_TRUE(cert != nullptr);
  20502. ASSERT_TRUE(ca_cert != nullptr);
  20503. ASSERT_TRUE(key != nullptr);
  20504. X509_STORE *cert_store = X509_STORE_new();
  20505. X509_STORE_add_cert(cert_store, ca_cert);
  20506. // svr.update_certs(cert, key, cert_store); // deprecated
  20507. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20508. CLIENT_CA_CERT_FILE);
  20509. ASSERT_TRUE(svr.is_valid());
  20510. svr.stop();
  20511. X509_STORE_free(cert_store);
  20512. X509_free(cert);
  20513. X509_free(ca_cert);
  20514. EVP_PKEY_free(key);
  20515. }
  20516. // Test that update_certs() updates client CA list correctly
  20517. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20518. // Start with file-based constructor
  20519. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20520. ASSERT_TRUE(svr.is_valid());
  20521. // Initially no client CA list should be set
  20522. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20523. ASSERT_TRUE(ssl_ctx != nullptr);
  20524. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20525. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20526. EXPECT_EQ(0, count_before);
  20527. // Now update with client CA (PEM string)
  20528. std::string cert_pem, key_pem, ca_pem;
  20529. read_file(SERVER_CERT_FILE, cert_pem);
  20530. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20531. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20532. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20533. ASSERT_TRUE(svr.is_valid());
  20534. // Now client CA list should be set
  20535. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20536. ASSERT_TRUE(ca_list_after != nullptr);
  20537. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20538. }
  20539. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20540. // Test that the file-path SSLServer constructor properly sets the client CA
  20541. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20542. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20543. ASSERT_TRUE(svr.is_valid());
  20544. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20545. ASSERT_TRUE(ssl_ctx != nullptr);
  20546. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20547. ASSERT_TRUE(ca_list != nullptr);
  20548. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20549. }
  20550. #endif
  20551. // ============================================================================
  20552. // MbedTLS-Specific Tests
  20553. // ============================================================================
  20554. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20555. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20556. using namespace httplib::tls;
  20557. // Track if callback was invoked
  20558. bool callback_invoked = false;
  20559. // The callback receives void* ctx which is actually MbedTlsContext*
  20560. // We can access the mbedtls_ssl_config via the context
  20561. auto setup_callback = [&callback_invoked](void *ctx) {
  20562. callback_invoked = true;
  20563. // Cast to MbedTlsContext* to access the ssl config
  20564. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20565. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20566. // Use static variables to hold certificate data (simplified for test)
  20567. static mbedtls_x509_crt own_cert;
  20568. static mbedtls_pk_context own_key;
  20569. static mbedtls_x509_crt ca_chain;
  20570. static bool initialized = false;
  20571. if (!initialized) {
  20572. mbedtls_x509_crt_init(&own_cert);
  20573. mbedtls_pk_init(&own_key);
  20574. mbedtls_x509_crt_init(&ca_chain);
  20575. // Load server certificate
  20576. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20577. return false;
  20578. }
  20579. // Load server private key.
  20580. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20581. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20582. #if MBEDTLS_VERSION_MAJOR == 3
  20583. ,
  20584. mbedtls_ctr_drbg_random, nullptr
  20585. #endif
  20586. ) != 0) {
  20587. return false;
  20588. }
  20589. // Load CA chain for client verification
  20590. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20591. return false;
  20592. }
  20593. initialized = true;
  20594. }
  20595. // Configure the SSL config
  20596. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20597. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20598. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20599. // Set minimum TLS version using mbedTLS native API
  20600. #if MBEDTLS_VERSION_MAJOR >= 3
  20601. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20602. #else
  20603. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20604. MBEDTLS_SSL_MINOR_VERSION_3);
  20605. #endif
  20606. return true;
  20607. };
  20608. SSLServer svr(setup_callback);
  20609. ASSERT_TRUE(svr.is_valid());
  20610. ASSERT_TRUE(callback_invoked);
  20611. svr.Get("/test", [&](const Request &req, Response &res) {
  20612. res.set_content("test", "text/plain");
  20613. auto cert = req.peer_cert();
  20614. ASSERT_TRUE(static_cast<bool>(cert));
  20615. auto common_name = cert.subject_cn();
  20616. EXPECT_EQ("Common Name", common_name);
  20617. });
  20618. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20619. auto se = detail::scope_exit([&] {
  20620. svr.stop();
  20621. t.join();
  20622. ASSERT_FALSE(svr.is_running());
  20623. });
  20624. svr.wait_until_ready();
  20625. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20626. cli.enable_server_certificate_verification(false);
  20627. cli.set_connection_timeout(30);
  20628. auto res = cli.Get("/test");
  20629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20630. ASSERT_EQ(StatusCode::OK_200, res->status);
  20631. }
  20632. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20633. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20634. // keep-alive SSL session, which reads through that config in
  20635. // mbedtls_ssl_close_notify.
  20636. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20637. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20638. ASSERT_TRUE(svr.is_valid());
  20639. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20640. res.set_content("test", "text/plain");
  20641. });
  20642. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20643. auto se = detail::scope_exit([&] {
  20644. svr.stop();
  20645. t.join();
  20646. ASSERT_FALSE(svr.is_running());
  20647. });
  20648. svr.wait_until_ready();
  20649. {
  20650. SSLClient cli(HOST, PORT);
  20651. cli.enable_server_certificate_verification(false);
  20652. cli.set_keep_alive(true);
  20653. auto res = cli.Get("/test");
  20654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20655. ASSERT_EQ(StatusCode::OK_200, res->status);
  20656. // cli is destructed here with the keep-alive SSL session still open.
  20657. }
  20658. }
  20659. #endif
  20660. // WebSocket Tests
  20661. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20662. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20663. // defining the meaning of these bits has been negotiated.
  20664. auto make_frame = [](uint8_t first_byte) {
  20665. std::string frame;
  20666. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20667. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20668. frame += "Hello";
  20669. return frame;
  20670. };
  20671. // RSV1 set (0x40)
  20672. {
  20673. detail::BufferStream strm;
  20674. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20675. ws::Opcode opcode;
  20676. std::string payload;
  20677. bool fin;
  20678. EXPECT_EQ(
  20679. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20680. ws::impl::FrameRead::Fail);
  20681. }
  20682. // RSV2 set (0x20)
  20683. {
  20684. detail::BufferStream strm;
  20685. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20686. ws::Opcode opcode;
  20687. std::string payload;
  20688. bool fin;
  20689. EXPECT_EQ(
  20690. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20691. ws::impl::FrameRead::Fail);
  20692. }
  20693. // RSV3 set (0x10)
  20694. {
  20695. detail::BufferStream strm;
  20696. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20697. ws::Opcode opcode;
  20698. std::string payload;
  20699. bool fin;
  20700. EXPECT_EQ(
  20701. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20702. ws::impl::FrameRead::Fail);
  20703. }
  20704. // No RSV bits set - should succeed
  20705. {
  20706. detail::BufferStream strm;
  20707. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20708. ws::Opcode opcode;
  20709. std::string payload;
  20710. bool fin;
  20711. EXPECT_EQ(
  20712. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20713. ws::impl::FrameRead::Ok);
  20714. EXPECT_EQ(ws::Opcode::Text, opcode);
  20715. EXPECT_EQ("Hello", payload);
  20716. EXPECT_TRUE(fin);
  20717. }
  20718. }
  20719. TEST(WebSocketTest, ControlFrameValidation) {
  20720. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20721. // payload length <= 125.
  20722. // Ping with FIN=0 - must be rejected
  20723. {
  20724. detail::BufferStream strm;
  20725. std::string frame;
  20726. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20727. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20728. strm.write(frame.data(), frame.size());
  20729. ws::Opcode opcode;
  20730. std::string payload;
  20731. bool fin;
  20732. EXPECT_EQ(
  20733. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20734. ws::impl::FrameRead::Fail);
  20735. }
  20736. // Close with FIN=0 - must be rejected
  20737. {
  20738. detail::BufferStream strm;
  20739. std::string frame;
  20740. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20741. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20742. strm.write(frame.data(), frame.size());
  20743. ws::Opcode opcode;
  20744. std::string payload;
  20745. bool fin;
  20746. EXPECT_EQ(
  20747. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20748. ws::impl::FrameRead::Fail);
  20749. }
  20750. // Ping with payload_len=126 (extended length) - must be rejected
  20751. {
  20752. detail::BufferStream strm;
  20753. std::string frame;
  20754. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20755. frame += static_cast<char>(126); // payload_len=126 (>125)
  20756. frame += static_cast<char>(0x00); // extended length high byte
  20757. frame += static_cast<char>(126); // extended length low byte
  20758. frame += std::string(126, 'x');
  20759. strm.write(frame.data(), frame.size());
  20760. ws::Opcode opcode;
  20761. std::string payload;
  20762. bool fin;
  20763. EXPECT_EQ(
  20764. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20765. ws::impl::FrameRead::Fail);
  20766. }
  20767. // Ping with FIN=1 and payload_len=125 - should succeed
  20768. {
  20769. detail::BufferStream strm;
  20770. std::string frame;
  20771. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20772. frame += static_cast<char>(125); // payload_len=125
  20773. frame += std::string(125, 'x');
  20774. strm.write(frame.data(), frame.size());
  20775. ws::Opcode opcode;
  20776. std::string payload;
  20777. bool fin;
  20778. EXPECT_EQ(
  20779. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20780. ws::impl::FrameRead::Ok);
  20781. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20782. EXPECT_EQ(125u, payload.size());
  20783. EXPECT_TRUE(fin);
  20784. }
  20785. }
  20786. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20787. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20788. // length MUST be 0.
  20789. // MSB set - must be rejected
  20790. {
  20791. detail::BufferStream strm;
  20792. std::string frame;
  20793. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20794. frame += static_cast<char>(127); // 64-bit extended length
  20795. frame += static_cast<char>(0x80); // MSB set (invalid)
  20796. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20797. strm.write(frame.data(), frame.size());
  20798. ws::Opcode opcode;
  20799. std::string payload;
  20800. bool fin;
  20801. EXPECT_EQ(
  20802. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20803. ws::impl::FrameRead::Fail);
  20804. }
  20805. // MSB clear - should pass length parsing (will be rejected by max_len,
  20806. // but that's a different check; use a small length to verify)
  20807. {
  20808. detail::BufferStream strm;
  20809. std::string frame;
  20810. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20811. frame += static_cast<char>(127); // 64-bit extended length
  20812. frame += std::string(7, '\0'); // high bytes = 0
  20813. frame += static_cast<char>(0x03); // length = 3
  20814. frame += "abc";
  20815. strm.write(frame.data(), frame.size());
  20816. ws::Opcode opcode;
  20817. std::string payload;
  20818. bool fin;
  20819. EXPECT_EQ(
  20820. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20821. ws::impl::FrameRead::Ok);
  20822. EXPECT_EQ(ws::Opcode::Text, opcode);
  20823. EXPECT_EQ("abc", payload);
  20824. }
  20825. }
  20826. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20827. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20828. // Valid UTF-8
  20829. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20830. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20831. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20832. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20833. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20834. // Invalid UTF-8
  20835. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20836. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20837. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20838. EXPECT_FALSE(
  20839. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20840. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20841. }
  20842. TEST(WebSocketTest, ConnectAndDisconnect) {
  20843. Server svr;
  20844. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20845. std::string msg;
  20846. while (ws.read(msg)) {}
  20847. });
  20848. auto port = svr.bind_to_any_port(HOST);
  20849. std::thread t([&]() { svr.listen_after_bind(); });
  20850. svr.wait_until_ready();
  20851. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20852. auto res = client.connect();
  20853. ASSERT_TRUE(res);
  20854. EXPECT_EQ(Error::Success, res.error());
  20855. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20856. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20857. EXPECT_TRUE(client.is_open());
  20858. client.close();
  20859. EXPECT_FALSE(client.is_open());
  20860. svr.stop();
  20861. t.join();
  20862. }
  20863. TEST(WebSocketTest, ValidURL) {
  20864. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20865. EXPECT_TRUE(ws1.is_valid());
  20866. ws::WebSocketClient ws2("ws://example.com/path");
  20867. EXPECT_TRUE(ws2.is_valid());
  20868. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20869. EXPECT_TRUE(ws3.is_valid());
  20870. #ifdef CPPHTTPLIB_SSL_ENABLED
  20871. ws::WebSocketClient wss1("wss://example.com/path");
  20872. EXPECT_TRUE(wss1.is_valid());
  20873. ws::WebSocketClient wss2("wss://example.com:443/path");
  20874. EXPECT_TRUE(wss2.is_valid());
  20875. #endif
  20876. }
  20877. TEST(WebSocketTest, InvalidURL) {
  20878. // No scheme
  20879. ws::WebSocketClient ws1("localhost:8080/path");
  20880. EXPECT_FALSE(ws1.is_valid());
  20881. // No path
  20882. ws::WebSocketClient ws2("ws://localhost:8080");
  20883. EXPECT_FALSE(ws2.is_valid());
  20884. // Empty string
  20885. ws::WebSocketClient ws3("");
  20886. EXPECT_FALSE(ws3.is_valid());
  20887. // Missing host
  20888. ws::WebSocketClient ws4("ws://:8080/path");
  20889. EXPECT_FALSE(ws4.is_valid());
  20890. // Port number overflow — should not crash
  20891. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20892. EXPECT_FALSE(ws5.is_valid());
  20893. // Port out of range
  20894. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20895. EXPECT_FALSE(ws6.is_valid());
  20896. }
  20897. TEST(WebSocketTest, UnsupportedScheme) {
  20898. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20899. ws::WebSocketClient ws1("http://localhost:8080/path");
  20900. EXPECT_FALSE(ws1.is_valid());
  20901. ws::WebSocketClient ws2("https://localhost:8080/path");
  20902. EXPECT_FALSE(ws2.is_valid());
  20903. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20904. EXPECT_FALSE(ws3.is_valid());
  20905. #else
  20906. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20907. std::invalid_argument);
  20908. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20909. std::invalid_argument);
  20910. #endif
  20911. }
  20912. TEST(WebSocketTest, ConnectWhenInvalid) {
  20913. ws::WebSocketClient ws("not a valid url");
  20914. EXPECT_FALSE(ws.is_valid());
  20915. auto res = ws.connect();
  20916. EXPECT_FALSE(res);
  20917. EXPECT_EQ(Error::Connection, res.error());
  20918. EXPECT_EQ(-1, res.status());
  20919. }
  20920. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20921. // Grab a port that is free, then close it again so nothing listens there
  20922. Server svr;
  20923. auto port = svr.bind_to_any_port(HOST);
  20924. svr.stop();
  20925. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20926. auto res = client.connect();
  20927. ASSERT_FALSE(res);
  20928. EXPECT_EQ(Error::Connection, res.error());
  20929. EXPECT_EQ(-1, res.status());
  20930. }
  20931. TEST(WebSocketTest, DefaultPort) {
  20932. ws::WebSocketClient ws1("ws://example.com/path");
  20933. EXPECT_TRUE(ws1.is_valid());
  20934. // ws:// defaults to port 80 (verified by successful parse)
  20935. #ifdef CPPHTTPLIB_SSL_ENABLED
  20936. ws::WebSocketClient ws2("wss://example.com/path");
  20937. EXPECT_TRUE(ws2.is_valid());
  20938. // wss:// defaults to port 443 (verified by successful parse)
  20939. #endif
  20940. }
  20941. TEST(WebSocketTest, IPv6LiteralAddress) {
  20942. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20943. EXPECT_TRUE(ws1.is_valid());
  20944. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20945. EXPECT_TRUE(ws2.is_valid());
  20946. }
  20947. TEST(WebSocketTest, ComplexPath) {
  20948. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20949. EXPECT_TRUE(ws1.is_valid());
  20950. ws::WebSocketClient ws2("ws://localhost:8080/");
  20951. EXPECT_TRUE(ws2.is_valid());
  20952. }
  20953. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20954. Server svr;
  20955. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20956. std::string msg;
  20957. while (ws.read(msg)) {}
  20958. });
  20959. auto port = svr.bind_to_any_port(HOST);
  20960. std::thread t([&]() { svr.listen_after_bind(); });
  20961. svr.wait_until_ready();
  20962. auto another_host = "example.com";
  20963. auto wrong_ip = "192.0.2.1";
  20964. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20965. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20966. ASSERT_TRUE(client.connect());
  20967. EXPECT_TRUE(client.is_open());
  20968. client.close();
  20969. svr.stop();
  20970. t.join();
  20971. }
  20972. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20973. Server svr;
  20974. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20975. std::string msg;
  20976. while (ws.read(msg)) {}
  20977. });
  20978. auto port = svr.bind_to_any_port(HOST);
  20979. std::thread t([&]() { svr.listen_after_bind(); });
  20980. svr.wait_until_ready();
  20981. auto wrong_ip = "192.0.2.1";
  20982. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20983. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20984. client.set_connection_timeout(1);
  20985. client.set_read_timeout(1);
  20986. client.set_write_timeout(1);
  20987. EXPECT_FALSE(client.connect());
  20988. EXPECT_FALSE(client.is_open());
  20989. svr.stop();
  20990. t.join();
  20991. }
  20992. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20993. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20994. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20995. // (RFC 6761) is only a map key and the Host header value.
  20996. auto host = "target.invalid";
  20997. Server svr;
  20998. std::string received_host;
  20999. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21000. received_host = req.get_header_value("Host");
  21001. std::string msg;
  21002. while (ws.read(msg)) {}
  21003. });
  21004. auto port = svr.bind_to_any_port(HOST);
  21005. std::thread t([&]() { svr.listen_after_bind(); });
  21006. // ASSERT_* below returns from the test body, which would leave t joinable
  21007. // and make ~thread call std::terminate.
  21008. auto se = detail::scope_exit([&] {
  21009. svr.stop();
  21010. if (t.joinable()) { t.join(); }
  21011. });
  21012. svr.wait_until_ready();
  21013. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21014. std::to_string(port) + "/ws");
  21015. client.set_hostname_addr_map({{host, HOST}});
  21016. ASSERT_TRUE(client.connect());
  21017. EXPECT_TRUE(client.is_open());
  21018. client.close();
  21019. svr.stop();
  21020. t.join();
  21021. // The mapping only redirects the connection; the identity stays host_.
  21022. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21023. }
  21024. class WebSocketIntegrationTest : public ::testing::Test {
  21025. protected:
  21026. void SetUp() override {
  21027. server_ = httplib::detail::make_unique<Server>();
  21028. setup_server();
  21029. start_server();
  21030. }
  21031. void TearDown() override {
  21032. server_->stop();
  21033. if (server_thread_.joinable()) { server_thread_.join(); }
  21034. }
  21035. void setup_server() {
  21036. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21037. std::string msg;
  21038. ws::ReadResult ret;
  21039. while ((ret = ws.read(msg))) {
  21040. if (ret == ws::Binary) {
  21041. ws.send(msg.data(), msg.size());
  21042. } else {
  21043. ws.send(msg);
  21044. }
  21045. }
  21046. });
  21047. server_->WebSocket("/ws-echo-string",
  21048. [](const Request &, ws::WebSocket &ws) {
  21049. std::string msg;
  21050. while (ws.read(msg)) {
  21051. ws.send("echo: " + msg);
  21052. }
  21053. });
  21054. server_->WebSocket(
  21055. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21056. // Echo back request metadata
  21057. ws.send("path:" + req.path);
  21058. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21059. std::string msg;
  21060. while (ws.read(msg)) {}
  21061. });
  21062. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21063. std::string msg;
  21064. ws.read(msg); // wait for a message
  21065. ws.close();
  21066. });
  21067. server_->WebSocket("/ws-close-status",
  21068. [](const Request &, ws::WebSocket &ws) {
  21069. std::string msg;
  21070. ws.read(msg); // wait for a message
  21071. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21072. });
  21073. server_->WebSocket(
  21074. "/ws-subprotocol",
  21075. [](const Request &, ws::WebSocket &ws) {
  21076. std::string msg;
  21077. while (ws.read(msg)) {
  21078. ws.send(msg);
  21079. }
  21080. },
  21081. [](const std::vector<std::string> &protocols) -> std::string {
  21082. for (const auto &p : protocols) {
  21083. if (p == "graphql-ws") { return p; }
  21084. }
  21085. return "";
  21086. });
  21087. server_->WebSocket(
  21088. "/ws-subprotocol-unoffered",
  21089. [](const Request &, ws::WebSocket &ws) {
  21090. std::string msg;
  21091. while (ws.read(msg)) {
  21092. ws.send(msg);
  21093. }
  21094. },
  21095. [](const std::vector<std::string> &) -> std::string {
  21096. return "admin";
  21097. });
  21098. }
  21099. void start_server() {
  21100. port_ = server_->bind_to_any_port(HOST);
  21101. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21102. server_->wait_until_ready();
  21103. }
  21104. std::unique_ptr<Server> server_;
  21105. std::thread server_thread_;
  21106. int port_ = 0;
  21107. };
  21108. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21109. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21110. "/ws-echo");
  21111. ASSERT_TRUE(client.connect());
  21112. ASSERT_TRUE(client.is_open());
  21113. ASSERT_TRUE(client.send("Hello WebSocket"));
  21114. std::string msg;
  21115. EXPECT_EQ(ws::Text, client.read(msg));
  21116. EXPECT_EQ("Hello WebSocket", msg);
  21117. client.close();
  21118. }
  21119. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21120. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21121. "/ws-echo");
  21122. ASSERT_TRUE(client.connect());
  21123. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21124. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21125. std::string msg;
  21126. EXPECT_EQ(ws::Binary, client.read(msg));
  21127. EXPECT_EQ(binary_data, msg);
  21128. client.close();
  21129. }
  21130. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21131. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21132. "/ws-echo");
  21133. ASSERT_TRUE(client.connect());
  21134. for (int i = 0; i < 10; i++) {
  21135. auto text = "message " + std::to_string(i);
  21136. ASSERT_TRUE(client.send(text));
  21137. std::string msg;
  21138. ASSERT_TRUE(client.read(msg));
  21139. EXPECT_EQ(text, msg);
  21140. }
  21141. client.close();
  21142. }
  21143. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21144. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21145. "/ws-close");
  21146. ASSERT_TRUE(client.connect());
  21147. // Send a message to trigger the server to close
  21148. ASSERT_TRUE(client.send("trigger close"));
  21149. // The server will close, so read should return false
  21150. std::string msg;
  21151. EXPECT_FALSE(client.read(msg));
  21152. EXPECT_FALSE(client.is_open());
  21153. }
  21154. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21155. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21156. "/ws-echo");
  21157. ASSERT_TRUE(client.connect());
  21158. // 128KB message
  21159. std::string large_data(128 * 1024, 'X');
  21160. ASSERT_TRUE(client.send(large_data));
  21161. std::string msg;
  21162. ASSERT_TRUE(client.read(msg));
  21163. EXPECT_EQ(large_data, msg);
  21164. client.close();
  21165. }
  21166. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21167. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21168. "/ws-echo");
  21169. ASSERT_TRUE(client.connect());
  21170. const int num_threads = 4;
  21171. std::vector<std::thread> threads;
  21172. std::atomic<int> send_count{0};
  21173. for (int t = 0; t < num_threads; t++) {
  21174. threads.emplace_back([&client, &send_count, t]() {
  21175. for (int i = 0; i < 5; i++) {
  21176. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21177. if (client.send(text)) { send_count++; }
  21178. }
  21179. });
  21180. }
  21181. for (auto &th : threads) {
  21182. th.join();
  21183. }
  21184. int received = 0;
  21185. std::string msg;
  21186. while (received < send_count.load()) {
  21187. if (!client.read(msg)) { break; }
  21188. received++;
  21189. }
  21190. EXPECT_EQ(send_count.load(), received);
  21191. client.close();
  21192. }
  21193. TEST_F(WebSocketIntegrationTest, ReadString) {
  21194. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21195. "/ws-echo-string");
  21196. ASSERT_TRUE(client.connect());
  21197. ASSERT_TRUE(client.send("hello"));
  21198. std::string msg;
  21199. ASSERT_TRUE(client.read(msg));
  21200. EXPECT_EQ("echo: hello", msg);
  21201. ASSERT_TRUE(client.send("world"));
  21202. ASSERT_TRUE(client.read(msg));
  21203. EXPECT_EQ("echo: world", msg);
  21204. client.close();
  21205. }
  21206. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21207. Headers headers = {{"X-Test-Header", "test-value"}};
  21208. ws::WebSocketClient client(
  21209. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21210. ASSERT_TRUE(client.connect());
  21211. std::string msg;
  21212. ASSERT_TRUE(client.read(msg));
  21213. EXPECT_EQ("path:/ws-request-info", msg);
  21214. ASSERT_TRUE(client.read(msg));
  21215. EXPECT_EQ("header:test-value", msg);
  21216. client.close();
  21217. }
  21218. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21219. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21220. "/ws-echo");
  21221. client.set_read_timeout(1, 0); // 1 second
  21222. ASSERT_TRUE(client.connect());
  21223. // Don't send anything — server echo handler waits for a message, so read()
  21224. // should time out. The connection survives it: nothing was consumed.
  21225. std::string msg;
  21226. EXPECT_EQ(client.read(msg), ws::Timeout);
  21227. EXPECT_TRUE(client.is_open());
  21228. // And it is still usable afterwards.
  21229. EXPECT_TRUE(client.send("after timeout"));
  21230. EXPECT_EQ(client.read(msg), ws::Text);
  21231. EXPECT_EQ(msg, "after timeout");
  21232. }
  21233. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21234. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21235. "/ws-echo");
  21236. client.set_read_timeout(1, 0);
  21237. ASSERT_TRUE(client.connect());
  21238. ASSERT_TRUE(client.send("first"));
  21239. std::string msg;
  21240. ASSERT_EQ(client.read(msg), ws::Text);
  21241. ASSERT_EQ(msg, "first");
  21242. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21243. // not be used with a read timeout: it would reprocess the previous message.
  21244. EXPECT_EQ(client.read(msg), ws::Timeout);
  21245. EXPECT_EQ(msg, "first");
  21246. }
  21247. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21248. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21249. "/ws-echo");
  21250. ASSERT_TRUE(client.connect());
  21251. // Setting it once the connection is open reaches the live stream, not just
  21252. // the seed for the next connect().
  21253. client.set_read_timeout(1, 0);
  21254. std::string msg;
  21255. EXPECT_EQ(client.read(msg), ws::Timeout);
  21256. EXPECT_TRUE(client.is_open());
  21257. }
  21258. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21259. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21260. "/ws-echo");
  21261. client.set_read_timeout(5, 0);
  21262. ASSERT_TRUE(client.connect());
  21263. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21264. // The server should reject it and close the connection.
  21265. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21266. client.send(oversized);
  21267. // The server's read() should have failed due to payload limit,
  21268. // so our read() should return false (connection closed).
  21269. std::string msg;
  21270. EXPECT_FALSE(client.read(msg));
  21271. }
  21272. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21273. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21274. "/ws-echo");
  21275. client.set_read_timeout(10, 0);
  21276. ASSERT_TRUE(client.connect());
  21277. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21278. // This should succeed.
  21279. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21280. ASSERT_TRUE(client.send(at_limit));
  21281. std::string msg;
  21282. ASSERT_TRUE(client.read(msg));
  21283. EXPECT_EQ(at_limit.size(), msg.size());
  21284. client.close();
  21285. }
  21286. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21287. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21288. "/nonexistent");
  21289. auto res = client.connect();
  21290. EXPECT_FALSE(res);
  21291. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21292. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21293. EXPECT_FALSE(client.is_open());
  21294. }
  21295. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21296. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21297. "/ws-echo");
  21298. ASSERT_TRUE(client.connect());
  21299. ASSERT_TRUE(client.send(""));
  21300. std::string msg;
  21301. EXPECT_EQ(ws::Text, client.read(msg));
  21302. EXPECT_EQ("", msg);
  21303. client.close();
  21304. }
  21305. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21306. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21307. "/ws-echo");
  21308. // First connection
  21309. ASSERT_TRUE(client.connect());
  21310. ASSERT_TRUE(client.send("first"));
  21311. std::string msg;
  21312. ASSERT_TRUE(client.read(msg));
  21313. EXPECT_EQ("first", msg);
  21314. client.close();
  21315. EXPECT_FALSE(client.is_open());
  21316. // Reconnect using the same client object
  21317. ASSERT_TRUE(client.connect());
  21318. ASSERT_TRUE(client.is_open());
  21319. ASSERT_TRUE(client.send("second"));
  21320. ASSERT_TRUE(client.read(msg));
  21321. EXPECT_EQ("second", msg);
  21322. client.close();
  21323. }
  21324. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21325. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21326. "/ws-close-status");
  21327. ASSERT_TRUE(client.connect());
  21328. // Trigger the server to close with GoingAway status
  21329. ASSERT_TRUE(client.send("trigger"));
  21330. // read() should return false after receiving the close frame
  21331. std::string msg;
  21332. EXPECT_FALSE(client.read(msg));
  21333. EXPECT_FALSE(client.is_open());
  21334. }
  21335. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21336. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21337. "/ws-echo");
  21338. ASSERT_TRUE(client.connect());
  21339. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21340. EXPECT_FALSE(client.is_open());
  21341. }
  21342. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21343. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21344. ws::WebSocketClient client(
  21345. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21346. ASSERT_TRUE(client.connect());
  21347. // Server should have selected graphql-ws
  21348. EXPECT_EQ("graphql-ws", client.subprotocol());
  21349. client.close();
  21350. }
  21351. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21352. Headers headers;
  21353. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21354. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21355. ws::WebSocketClient client(
  21356. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21357. ASSERT_TRUE(client.connect());
  21358. // The offer on the second field line counts too, so graphql-ws is selected
  21359. EXPECT_EQ("graphql-ws", client.subprotocol());
  21360. client.close();
  21361. }
  21362. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21363. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21364. ws::WebSocketClient client(
  21365. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21366. ASSERT_TRUE(client.connect());
  21367. // Server should not have selected any subprotocol
  21368. EXPECT_TRUE(client.subprotocol().empty());
  21369. client.close();
  21370. }
  21371. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21372. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21373. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21374. "/ws-subprotocol-unoffered",
  21375. headers);
  21376. ASSERT_TRUE(client.connect());
  21377. EXPECT_TRUE(client.subprotocol().empty());
  21378. client.close();
  21379. }
  21380. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21381. // Connect without requesting any subprotocol
  21382. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21383. "/ws-subprotocol");
  21384. ASSERT_TRUE(client.connect());
  21385. EXPECT_TRUE(client.subprotocol().empty());
  21386. client.close();
  21387. }
  21388. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21389. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21390. "/ws-echo");
  21391. client.set_tcp_nodelay(true);
  21392. client.set_connection_timeout(3, 0);
  21393. bool socket_options_called = false;
  21394. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21395. ASSERT_TRUE(client.connect());
  21396. ASSERT_TRUE(client.is_open());
  21397. EXPECT_TRUE(socket_options_called);
  21398. ASSERT_TRUE(client.send("hello"));
  21399. std::string msg;
  21400. auto result = client.read(msg);
  21401. EXPECT_EQ(result, ws::ReadResult::Text);
  21402. EXPECT_EQ(msg, "hello");
  21403. client.close();
  21404. }
  21405. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21406. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21407. "/ws-echo");
  21408. client.set_connection_timeout(std::chrono::seconds(3));
  21409. client.set_write_timeout(std::chrono::seconds(3));
  21410. // A sub-second remainder exercises the seconds/microseconds split.
  21411. client.set_read_timeout(std::chrono::milliseconds(1500));
  21412. ASSERT_TRUE(client.connect());
  21413. auto start = std::chrono::steady_clock::now();
  21414. std::string msg;
  21415. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21416. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21417. std::chrono::steady_clock::now() - start)
  21418. .count();
  21419. // Above 1s so that dropping the microseconds half of the split fails here.
  21420. // Ignoring the setter altogether would not reach this line at all: a client
  21421. // waits forever by default.
  21422. EXPECT_GE(elapsed, 1400);
  21423. EXPECT_LT(elapsed, 30000);
  21424. }
  21425. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21426. Server svr;
  21427. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21428. if (!req.has_header("Authorization")) {
  21429. res.status = StatusCode::Unauthorized_401;
  21430. res.set_content("Unauthorized", "text/plain");
  21431. return Server::HandlerResponse::Handled;
  21432. }
  21433. return Server::HandlerResponse::Unhandled;
  21434. });
  21435. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21436. std::string msg;
  21437. while (ws.read(msg)) {
  21438. ws.send(msg);
  21439. }
  21440. });
  21441. auto port = svr.bind_to_any_port("localhost");
  21442. std::thread t([&]() { svr.listen_after_bind(); });
  21443. svr.wait_until_ready();
  21444. // Without Authorization header - should be rejected before upgrade
  21445. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21446. EXPECT_FALSE(client1.connect());
  21447. // The rejection is framed like any other HTTP response
  21448. {
  21449. Client cli("localhost", port);
  21450. Headers headers = {{"Upgrade", "websocket"},
  21451. {"Connection", "Upgrade"},
  21452. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21453. {"Sec-WebSocket-Version", "13"}};
  21454. auto res = cli.Get("/ws", headers);
  21455. ASSERT_TRUE(res);
  21456. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21457. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21458. EXPECT_EQ("Unauthorized", res->body);
  21459. }
  21460. // With Authorization header - should succeed
  21461. Headers headers = {{"Authorization", "Bearer token123"}};
  21462. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21463. headers);
  21464. ASSERT_TRUE(client2.connect());
  21465. ASSERT_TRUE(client2.send("hello"));
  21466. std::string msg;
  21467. ASSERT_TRUE(client2.read(msg));
  21468. EXPECT_EQ("hello", msg);
  21469. client2.close();
  21470. svr.stop();
  21471. t.join();
  21472. }
  21473. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21474. Server svr;
  21475. std::atomic<int> pre_request_calls{0};
  21476. std::atomic<bool> route_matched{false};
  21477. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21478. pre_request_calls++;
  21479. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21480. if (req.get_header_value("Authorization") != "Bearer token123") {
  21481. res.status = StatusCode::Unauthorized_401;
  21482. res.set_content("Unauthorized", "text/plain");
  21483. return Server::HandlerResponse::Handled;
  21484. }
  21485. return Server::HandlerResponse::Unhandled;
  21486. });
  21487. std::atomic<bool> handler_called{false};
  21488. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21489. handler_called = true;
  21490. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21491. });
  21492. auto port = svr.bind_to_any_port("localhost");
  21493. std::thread t([&]() { svr.listen_after_bind(); });
  21494. svr.wait_until_ready();
  21495. // Without Authorization header - should be rejected before upgrade
  21496. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21497. "/ws/1");
  21498. EXPECT_FALSE(client1.connect());
  21499. EXPECT_FALSE(handler_called);
  21500. EXPECT_EQ(1, pre_request_calls);
  21501. EXPECT_TRUE(route_matched);
  21502. // The rejection is an ordinary HTTP response, not a protocol switch
  21503. {
  21504. Client cli("localhost", port);
  21505. Headers headers = {{"Upgrade", "websocket"},
  21506. {"Connection", "Upgrade"},
  21507. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21508. {"Sec-WebSocket-Version", "13"}};
  21509. auto res = cli.Get("/ws/1", headers);
  21510. ASSERT_TRUE(res);
  21511. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21512. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21513. EXPECT_EQ("Unauthorized", res->body);
  21514. }
  21515. EXPECT_FALSE(handler_called);
  21516. // With Authorization header - should succeed
  21517. Headers headers = {{"Authorization", "Bearer token123"}};
  21518. ws::WebSocketClient client2(
  21519. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21520. ASSERT_TRUE(client2.connect());
  21521. std::string msg;
  21522. ASSERT_TRUE(client2.read(msg));
  21523. EXPECT_EQ("/ws/:id 2", msg);
  21524. EXPECT_TRUE(handler_called);
  21525. client2.close();
  21526. svr.stop();
  21527. t.join();
  21528. }
  21529. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21530. Server svr;
  21531. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21532. // A read timeout is how a handler gets control back. Without it, a handler
  21533. // parked in read() can never write on the connection it is reading.
  21534. ws.set_read_timeout(std::chrono::milliseconds(100));
  21535. std::string msg;
  21536. while (ws.is_open()) {
  21537. auto r = ws.read(msg);
  21538. if (r == httplib::ws::Timeout) {
  21539. ws.send("tick");
  21540. continue;
  21541. }
  21542. if (r == httplib::ws::Fail) { break; }
  21543. ws.send(msg);
  21544. }
  21545. });
  21546. auto port = svr.bind_to_any_port("localhost");
  21547. std::thread t([&]() { svr.listen_after_bind(); });
  21548. svr.wait_until_ready();
  21549. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21550. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21551. ASSERT_TRUE(client.connect());
  21552. // The client sends nothing, so anything it receives came out of the
  21553. // handler's timeout path.
  21554. std::string msg;
  21555. ASSERT_EQ(client.read(msg), ws::Text);
  21556. EXPECT_EQ("tick", msg);
  21557. client.close();
  21558. svr.stop();
  21559. t.join();
  21560. }
  21561. // Stream::read may return fewer bytes than asked for. This is that contract at
  21562. // its worst -- one byte per call -- which is what a frame header straddling a
  21563. // read buffer's boundary looks like to the frame parser.
  21564. class WsByteAtATimeStream : public Stream {
  21565. public:
  21566. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21567. bool is_readable() const override { return true; }
  21568. bool wait_readable() const override { return true; }
  21569. bool wait_writable() const override { return true; }
  21570. ssize_t read(char *ptr, size_t size) override {
  21571. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21572. *ptr = data_[pos_++];
  21573. return 1;
  21574. }
  21575. ssize_t write(const char *, size_t size) override {
  21576. return static_cast<ssize_t>(size);
  21577. }
  21578. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21579. ip = "127.0.0.1";
  21580. port = 0;
  21581. }
  21582. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21583. ip = "127.0.0.1";
  21584. port = 0;
  21585. }
  21586. socket_t socket() const override { return INVALID_SOCKET; }
  21587. time_t duration() const override { return 0; }
  21588. private:
  21589. std::string data_;
  21590. size_t pos_ = 0;
  21591. };
  21592. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21593. // The payload uses the 16-bit extended length, so the header, the length
  21594. // and the mask key are all multi-byte fields here. Each used to be read
  21595. // with a single read() call, which fails as soon as one is split. The
  21596. // payload is also a little over one read chunk, so it is read in two.
  21597. std::string body;
  21598. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21599. body += static_cast<char>(i % 251);
  21600. }
  21601. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21602. std::string frame;
  21603. frame += static_cast<char>(0x81); // FIN + Text
  21604. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21605. frame += static_cast<char>(body.size() >> 8);
  21606. frame += static_cast<char>(body.size() & 0xff);
  21607. for (size_t i = 0; i < 4; i++) {
  21608. frame += static_cast<char>(mask[i]);
  21609. }
  21610. for (size_t i = 0; i < body.size(); i++) {
  21611. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21612. }
  21613. WsByteAtATimeStream strm(frame);
  21614. ws::Opcode opcode;
  21615. std::string payload;
  21616. bool fin = false;
  21617. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21618. /*expect_masked=*/true, body.size()),
  21619. ws::impl::FrameRead::Ok);
  21620. EXPECT_TRUE(fin);
  21621. EXPECT_EQ(opcode, ws::Opcode::Text);
  21622. EXPECT_EQ(payload, body);
  21623. }
  21624. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21625. // The header announces the largest payload allowed, and only 3 bytes of it
  21626. // ever arrive.
  21627. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21628. std::string frame;
  21629. frame += static_cast<char>(0x82); // FIN + Binary
  21630. frame += static_cast<char>(127); // 64-bit length follows
  21631. for (int shift = 56; shift >= 0; shift -= 8) {
  21632. frame += static_cast<char>((len >> shift) & 0xff);
  21633. }
  21634. frame += "abc";
  21635. detail::BufferStream strm;
  21636. strm.write(frame.data(), frame.size());
  21637. ws::Opcode opcode;
  21638. std::string payload;
  21639. bool fin;
  21640. EXPECT_EQ(
  21641. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21642. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21643. ws::impl::FrameRead::Fail);
  21644. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21645. }
  21646. TEST(WebSocketTest, QueryStringInHandshake) {
  21647. Server svr;
  21648. std::mutex mtx;
  21649. std::string received_target;
  21650. std::string received_token;
  21651. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21652. {
  21653. std::lock_guard<std::mutex> lock(mtx);
  21654. received_target = req.target;
  21655. if (req.has_param("token")) {
  21656. received_token = req.get_param_value("token");
  21657. }
  21658. }
  21659. std::string msg;
  21660. while (ws.read(msg)) {
  21661. ws.send(msg);
  21662. }
  21663. });
  21664. auto port = svr.bind_to_any_port("localhost");
  21665. std::thread t([&]() { svr.listen_after_bind(); });
  21666. svr.wait_until_ready();
  21667. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21668. "/ws?token=ABC&session=123");
  21669. ASSERT_TRUE(client.connect());
  21670. // Round-trip ensures the handler has run and captured the request.
  21671. ASSERT_TRUE(client.send("hello"));
  21672. std::string msg;
  21673. ASSERT_TRUE(client.read(msg));
  21674. EXPECT_EQ("hello", msg);
  21675. client.close();
  21676. {
  21677. std::lock_guard<std::mutex> lock(mtx);
  21678. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21679. EXPECT_EQ("ABC", received_token);
  21680. }
  21681. svr.stop();
  21682. t.join();
  21683. }
  21684. // Run a handshake against a throwaway server and hand the request the server
  21685. // received back to the caller, so tests can assert on the headers the client
  21686. // actually put on the wire.
  21687. static void capture_websocket_handshake_request(
  21688. const Headers &client_headers,
  21689. std::function<void(const Request &, int port)> verify) {
  21690. Server svr;
  21691. std::mutex mtx;
  21692. Request received;
  21693. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21694. {
  21695. std::lock_guard<std::mutex> lock(mtx);
  21696. received = req;
  21697. }
  21698. std::string msg;
  21699. while (ws.read(msg)) {
  21700. ws.send(msg);
  21701. }
  21702. });
  21703. auto port = svr.bind_to_any_port("localhost");
  21704. std::thread t([&]() { svr.listen_after_bind(); });
  21705. auto se = detail::scope_exit([&] {
  21706. svr.stop();
  21707. t.join();
  21708. });
  21709. svr.wait_until_ready();
  21710. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21711. client_headers);
  21712. ASSERT_TRUE(client.connect());
  21713. ASSERT_TRUE(client.send("hello"));
  21714. std::string msg;
  21715. ASSERT_TRUE(client.read(msg));
  21716. client.close();
  21717. {
  21718. std::lock_guard<std::mutex> lock(mtx);
  21719. verify(received, port);
  21720. }
  21721. }
  21722. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21723. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21724. // Non-default port must be present in the Host header. Default ports
  21725. // (80/443) are omitted; that logic is covered by
  21726. // MakeHostAndPortStringTest.
  21727. EXPECT_EQ("localhost:" + std::to_string(port),
  21728. req.get_header_value("Host"));
  21729. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21730. req.get_header_value("User-Agent"));
  21731. EXPECT_FALSE(req.has_header("Accept"));
  21732. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21733. EXPECT_FALSE(req.has_header("Content-Length"));
  21734. });
  21735. }
  21736. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21737. capture_websocket_handshake_request(
  21738. {{"Host", "example.com"},
  21739. {"User-Agent", "custom-agent"},
  21740. {"X-Custom", "value"}},
  21741. [](const Request &req, int) {
  21742. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21743. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21744. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21745. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21746. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21747. });
  21748. }
  21749. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21750. capture_websocket_handshake_request(
  21751. {{"Upgrade", "bogus"},
  21752. {"Connection", "close"},
  21753. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21754. {"Sec-WebSocket-Version", "8"}},
  21755. [](const Request &req, int) {
  21756. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21757. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21758. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21759. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21760. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21761. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21762. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21763. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21764. req.get_header_value("Sec-WebSocket-Key"));
  21765. });
  21766. }
  21767. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21768. // A header the client refuses to send must abort the handshake before any
  21769. // part of it reaches the wire; a lone request line would otherwise sit in
  21770. // the peer's buffer as a truncated request.
  21771. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21772. ASSERT_NE(INVALID_SOCKET, srv);
  21773. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21774. sockaddr_in addr{};
  21775. addr.sin_family = AF_INET;
  21776. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21777. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21778. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21779. ASSERT_EQ(0, ::listen(srv, 1));
  21780. sockaddr_in bound{};
  21781. socklen_t bound_len = sizeof(bound);
  21782. ASSERT_EQ(
  21783. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21784. auto port = ntohs(bound.sin_port);
  21785. ssize_t received = -1;
  21786. std::thread t([&] {
  21787. // Bound every blocking call so a regression fails the test with a bad
  21788. // value instead of hanging the suite.
  21789. fd_set rfds;
  21790. FD_ZERO(&rfds);
  21791. FD_SET(srv, &rfds);
  21792. timeval tv{5, 0};
  21793. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21794. 0) {
  21795. return;
  21796. }
  21797. sockaddr_in cli_addr{};
  21798. socklen_t cli_len = sizeof(cli_addr);
  21799. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21800. if (cli == INVALID_SOCKET) { return; }
  21801. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21802. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21803. char buf[4096];
  21804. received = ::recv(cli, buf, sizeof(buf), 0);
  21805. });
  21806. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21807. // connect() has already shut the socket down by the time it returns false,
  21808. // so the peer sees EOF without waiting for the client to be destroyed.
  21809. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21810. {{"X-Bad", "a\r\nInjected: 1"}});
  21811. EXPECT_FALSE(client.connect());
  21812. t.join();
  21813. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21814. EXPECT_EQ(0, received);
  21815. }
  21816. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21817. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21818. // contains "upgrade" as a substring is a different token and must not
  21819. // start a WebSocket handshake.
  21820. auto make_request = [](const std::vector<std::string> &connection_values) {
  21821. Request req;
  21822. req.method = "GET";
  21823. req.headers.emplace("Upgrade", "websocket");
  21824. for (const auto &value : connection_values) {
  21825. req.headers.emplace("Connection", value);
  21826. }
  21827. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21828. req.headers.emplace("Sec-WebSocket-Version", "13");
  21829. return req;
  21830. };
  21831. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21832. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21833. EXPECT_TRUE(
  21834. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21835. EXPECT_TRUE(
  21836. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21837. EXPECT_TRUE(
  21838. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21839. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21840. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21841. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21842. EXPECT_FALSE(
  21843. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21844. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21845. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21846. }
  21847. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21848. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21849. // asks recipients to match each protocol-name case-insensitively, and RFC
  21850. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21851. // client naming websocket alongside another protocol, or on a second field
  21852. // line, is offering websocket; a value that merely contains "websocket" as a
  21853. // substring is a different protocol name and is not.
  21854. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21855. Request req;
  21856. req.method = "GET";
  21857. for (const auto &value : upgrade_values) {
  21858. req.headers.emplace("Upgrade", value);
  21859. }
  21860. req.headers.emplace("Connection", "Upgrade");
  21861. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21862. req.headers.emplace("Sec-WebSocket-Version", "13");
  21863. return req;
  21864. };
  21865. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21866. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21867. EXPECT_TRUE(
  21868. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21869. EXPECT_TRUE(
  21870. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21871. EXPECT_TRUE(
  21872. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21873. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21874. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21875. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21876. EXPECT_FALSE(
  21877. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21878. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21879. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21880. }
  21881. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21882. Server svr;
  21883. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21884. auto port = svr.bind_to_any_port("localhost");
  21885. std::thread t([&]() { svr.listen_after_bind(); });
  21886. auto se = detail::scope_exit([&] {
  21887. svr.stop();
  21888. t.join();
  21889. });
  21890. svr.wait_until_ready();
  21891. Headers headers = {{"Upgrade", "websocket"},
  21892. {"Connection", "notupgrade"},
  21893. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21894. {"Sec-WebSocket-Version", "13"}};
  21895. Client cli("localhost", port);
  21896. auto res = cli.Get("/ws", headers);
  21897. // The route exists only as a WebSocket route, so a request that fails the
  21898. // handshake check falls through to ordinary routing.
  21899. ASSERT_TRUE(res);
  21900. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21901. }
  21902. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21903. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21904. // Connection value is the only thing left for the client to reject.
  21905. Server svr;
  21906. svr.Get("/ws", [](const Request &req, Response &res) {
  21907. res.status = StatusCode::SwitchingProtocol_101;
  21908. res.set_header("Upgrade", "websocket");
  21909. res.set_header("Connection", "notupgrade");
  21910. res.set_header("Sec-WebSocket-Accept",
  21911. detail::websocket_accept_key(
  21912. req.get_header_value("Sec-WebSocket-Key")));
  21913. });
  21914. auto port = svr.bind_to_any_port("localhost");
  21915. std::thread t([&]() { svr.listen_after_bind(); });
  21916. auto se = detail::scope_exit([&] {
  21917. svr.stop();
  21918. t.join();
  21919. });
  21920. svr.wait_until_ready();
  21921. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21922. auto res = client.connect();
  21923. EXPECT_FALSE(res);
  21924. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21925. EXPECT_FALSE(client.is_open());
  21926. }
  21927. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21928. Server svr;
  21929. svr.Get("/ws", [](const Request &req, Response &res) {
  21930. res.status = StatusCode::SwitchingProtocol_101;
  21931. res.set_header("Upgrade", "websocket");
  21932. res.set_header("Connection", "Upgrade");
  21933. res.set_header("Sec-WebSocket-Accept",
  21934. detail::websocket_accept_key(
  21935. req.get_header_value("Sec-WebSocket-Key")));
  21936. res.set_header("Sec-WebSocket-Protocol", "admin");
  21937. });
  21938. auto port = svr.bind_to_any_port("localhost");
  21939. std::thread t([&]() { svr.listen_after_bind(); });
  21940. auto se = detail::scope_exit([&] {
  21941. svr.stop();
  21942. t.join();
  21943. });
  21944. svr.wait_until_ready();
  21945. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21946. // Server selects a subprotocol the client never offered
  21947. {
  21948. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21949. ws::WebSocketClient client(url, headers);
  21950. auto res = client.connect();
  21951. EXPECT_FALSE(res);
  21952. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21953. EXPECT_FALSE(client.is_open());
  21954. EXPECT_TRUE(client.subprotocol().empty());
  21955. }
  21956. // Client offered none but the server named one anyway
  21957. {
  21958. ws::WebSocketClient client(url);
  21959. auto res = client.connect();
  21960. EXPECT_FALSE(res);
  21961. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21962. EXPECT_FALSE(client.is_open());
  21963. EXPECT_TRUE(client.subprotocol().empty());
  21964. }
  21965. }
  21966. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21967. // The socket path doubles as the URL host, so it must not contain '/'.
  21968. const char *shard = getenv("GTEST_SHARD_INDEX");
  21969. const std::string sock_path =
  21970. shard ? std::string("httplib-ws-") + shard + ".sock"
  21971. : std::string("httplib-ws.sock");
  21972. std::remove(sock_path.c_str());
  21973. Server svr;
  21974. std::mutex mtx;
  21975. std::string received_host;
  21976. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21977. {
  21978. std::lock_guard<std::mutex> lock(mtx);
  21979. received_host = req.get_header_value("Host");
  21980. }
  21981. std::string msg;
  21982. while (ws.read(msg)) {
  21983. ws.send(msg);
  21984. }
  21985. });
  21986. svr.set_address_family(AF_UNIX);
  21987. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21988. auto se = detail::scope_exit([&] {
  21989. svr.stop();
  21990. t.join();
  21991. std::remove(sock_path.c_str());
  21992. });
  21993. svr.wait_until_ready();
  21994. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21995. client.set_address_family(AF_UNIX);
  21996. ASSERT_TRUE(client.connect());
  21997. ASSERT_TRUE(client.send("hello"));
  21998. std::string msg;
  21999. ASSERT_TRUE(client.read(msg));
  22000. client.close();
  22001. {
  22002. std::lock_guard<std::mutex> lock(mtx);
  22003. // There is no host:port for a Unix socket, so the same "localhost"
  22004. // placeholder the HTTP client uses is expected.
  22005. EXPECT_EQ("localhost", received_host);
  22006. }
  22007. }
  22008. // Two threads must never parse WebSocket frames from the same stream.
  22009. // close() used to read the peer's Close reply with its own frame read, so it
  22010. // raced a reader thread that was in the middle of a payload: the payload loop
  22011. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22012. // so bytes taken by close() were replaced with bytes from further along the
  22013. // stream. The message kept its length and silently changed content.
  22014. //
  22015. // The raw peer below sends a frame header plus part of the payload, waits for
  22016. // the handler to call close(), and only then sends the rest. Whichever thread
  22017. // would win the race for those bytes, the message must arrive intact, because
  22018. // close() must not touch the stream while read() owns it.
  22019. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22020. #ifndef _WIN32
  22021. signal(SIGPIPE, SIG_IGN);
  22022. #endif
  22023. const size_t payload_len = 120; // fits the 7-bit length field
  22024. const size_t prefix_len = 8;
  22025. const int attempts = 8;
  22026. std::string expected(payload_len, '\0');
  22027. for (size_t i = 0; i < payload_len; i++) {
  22028. expected[i] = static_cast<char>('a' + i % 26);
  22029. }
  22030. std::atomic<bool> peer_stalled{false};
  22031. std::atomic<bool> handler_done{false};
  22032. std::mutex received_mutex;
  22033. std::vector<std::string> received;
  22034. // Bound every wait, so a regression fails the test instead of hanging the
  22035. // suite.
  22036. auto wait_for = [](const std::atomic<bool> &flag) {
  22037. for (int i = 0; i < 500 && !flag; i++) {
  22038. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22039. }
  22040. };
  22041. Server svr;
  22042. svr.set_websocket_ping_interval(0);
  22043. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22044. std::thread reader([&]() {
  22045. std::string msg;
  22046. while (ws.read(msg)) {
  22047. std::lock_guard<std::mutex> guard(received_mutex);
  22048. received.push_back(msg);
  22049. }
  22050. });
  22051. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22052. // inside read_websocket_frame() when close() runs.
  22053. wait_for(peer_stalled);
  22054. ws.close();
  22055. reader.join();
  22056. handler_done = true;
  22057. });
  22058. auto port = svr.bind_to_any_port("127.0.0.1");
  22059. std::thread t([&]() { svr.listen_after_bind(); });
  22060. auto se = detail::scope_exit([&] {
  22061. svr.stop();
  22062. t.join();
  22063. });
  22064. svr.wait_until_ready();
  22065. auto send_bytes = [](socket_t s, const std::string &data) {
  22066. #ifdef _WIN32
  22067. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22068. #else
  22069. auto n = ::send(s, data.data(), data.size(), 0);
  22070. #endif
  22071. return n == static_cast<decltype(n)>(data.size());
  22072. };
  22073. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22074. // Every length used here fits the 7-bit length field.
  22075. auto masked_header = [](uint8_t first_byte, size_t len) {
  22076. std::string h;
  22077. h += static_cast<char>(first_byte);
  22078. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22079. h.append(4, '\0'); // mask key
  22080. return h;
  22081. };
  22082. for (int attempt = 0; attempt < attempts; attempt++) {
  22083. peer_stalled = false;
  22084. handler_done = false;
  22085. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22086. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22087. auto se_sock = detail::scope_exit([&] {
  22088. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22089. });
  22090. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22091. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22092. sockaddr_in addr{};
  22093. addr.sin_family = AF_INET;
  22094. addr.sin_port = htons(static_cast<uint16_t>(port));
  22095. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22096. ASSERT_EQ(
  22097. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22098. << "attempt " << attempt;
  22099. ASSERT_TRUE(send_bytes(sock,
  22100. "GET /ws HTTP/1.1\r\n"
  22101. "Host: 127.0.0.1\r\n"
  22102. "Upgrade: websocket\r\n"
  22103. "Connection: Upgrade\r\n"
  22104. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22105. "Sec-WebSocket-Version: 13\r\n"
  22106. "\r\n"))
  22107. << "attempt " << attempt;
  22108. std::string response;
  22109. while (response.find("\r\n\r\n") == std::string::npos) {
  22110. char buf[512];
  22111. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22112. if (n <= 0) { break; }
  22113. response.append(buf, static_cast<size_t>(n));
  22114. }
  22115. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22116. << "attempt " << attempt;
  22117. // Send the header of a Binary message but only the first prefix_len bytes
  22118. // of its payload, leaving the reader thread stalled inside the payload.
  22119. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22120. expected.substr(0, prefix_len)))
  22121. << "attempt " << attempt;
  22122. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22123. peer_stalled = true;
  22124. // Let close() send its Close frame and park in its own read before the
  22125. // rest of the payload arrives, so both threads are waiting for it.
  22126. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22127. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22128. close_frame += static_cast<char>(0x03); // status 1000
  22129. close_frame += static_cast<char>(0xE8);
  22130. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22131. << "attempt " << attempt;
  22132. // Closing the peer releases the reader thread even on the buggy path,
  22133. // where it waits for bytes another thread already consumed.
  22134. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22135. detail::close_socket(sock);
  22136. sock = INVALID_SOCKET;
  22137. wait_for(handler_done);
  22138. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22139. }
  22140. std::lock_guard<std::mutex> guard(received_mutex);
  22141. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22142. << "a message in flight when close() ran was dropped";
  22143. for (size_t i = 0; i < received.size(); i++) {
  22144. EXPECT_EQ(expected, received[i]) << "message " << i;
  22145. }
  22146. }
  22147. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22148. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22149. protected:
  22150. void SetUp() override {
  22151. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22152. SERVER_PRIVATE_KEY_FILE);
  22153. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22154. std::string msg;
  22155. ws::ReadResult ret;
  22156. while ((ret = ws.read(msg))) {
  22157. if (ret == ws::Binary) {
  22158. ws.send(msg.data(), msg.size());
  22159. } else {
  22160. ws.send(msg);
  22161. }
  22162. }
  22163. });
  22164. port_ = server_->bind_to_any_port(HOST);
  22165. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22166. server_->wait_until_ready();
  22167. }
  22168. void TearDown() override {
  22169. server_->stop();
  22170. if (server_thread_.joinable()) { server_thread_.join(); }
  22171. }
  22172. std::unique_ptr<SSLServer> server_;
  22173. std::thread server_thread_;
  22174. int port_ = 0;
  22175. };
  22176. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22177. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22178. "/ws-echo");
  22179. client.enable_server_certificate_verification(false);
  22180. ASSERT_TRUE(client.connect());
  22181. ASSERT_TRUE(client.is_open());
  22182. ASSERT_TRUE(client.send("Hello WSS"));
  22183. std::string msg;
  22184. EXPECT_EQ(ws::Text, client.read(msg));
  22185. EXPECT_EQ("Hello WSS", msg);
  22186. client.close();
  22187. }
  22188. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22189. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22190. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22191. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22192. // client (without calling close() first) is the only path that runs
  22193. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22194. // bug exactly.
  22195. //
  22196. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22197. // when linked against an instrumented libssl; run under Valgrind to catch it
  22198. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22199. // suite (the freed session otherwise stalls on the close handshake) — this test
  22200. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22201. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22202. {
  22203. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22204. "/ws-echo");
  22205. client.enable_server_certificate_verification(false);
  22206. client.set_read_timeout(2, 0);
  22207. client.set_write_timeout(2, 0);
  22208. ASSERT_TRUE(client.connect());
  22209. ASSERT_TRUE(client.is_open());
  22210. ASSERT_TRUE(client.send("still open"));
  22211. // Intentionally do NOT call client.close(): leaving scope runs
  22212. // shutdown_and_close() with the WebSocket still open, which must send the
  22213. // close frame while the TLS session is still alive.
  22214. }
  22215. }
  22216. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22217. // shutdown_and_close() at the start of connect(), reproducing the same
  22218. // use-after-free within the test body rather than at scope exit. The second
  22219. // connect must succeed and echo, proving the close handshake ran over a live
  22220. // session. See the note above about memory-tool requirements.
  22221. TEST_F(WebSocketSSLIntegrationTest,
  22222. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22223. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22224. "/ws-echo");
  22225. client.enable_server_certificate_verification(false);
  22226. client.set_read_timeout(2, 0);
  22227. client.set_write_timeout(2, 0);
  22228. ASSERT_TRUE(client.connect());
  22229. ASSERT_TRUE(client.is_open());
  22230. ASSERT_TRUE(client.send("still open"));
  22231. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22232. // the still-open connection, which must not touch a freed TLS session.
  22233. ASSERT_TRUE(client.connect());
  22234. ASSERT_TRUE(client.is_open());
  22235. ASSERT_TRUE(client.send("after reconnect"));
  22236. std::string msg;
  22237. EXPECT_EQ(ws::Text, client.read(msg));
  22238. EXPECT_EQ("after reconnect", msg);
  22239. client.close();
  22240. }
  22241. #endif
  22242. #ifdef CPPHTTPLIB_SSL_ENABLED
  22243. class WebSocketSSLCATest : public ::testing::Test {
  22244. protected:
  22245. void SetUp() override {
  22246. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22247. SERVER_PRIVATE_KEY_FILE);
  22248. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22249. std::string msg;
  22250. while (ws.read(msg)) {
  22251. ws.send(msg);
  22252. }
  22253. });
  22254. port_ = server_->bind_to_any_port("127.0.0.1");
  22255. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22256. server_->wait_until_ready();
  22257. }
  22258. void TearDown() override {
  22259. server_->stop();
  22260. if (server_thread_.joinable()) { server_thread_.join(); }
  22261. }
  22262. std::string url() const {
  22263. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22264. }
  22265. std::unique_ptr<SSLServer> server_;
  22266. std::thread server_thread_;
  22267. int port_ = 0;
  22268. };
  22269. // A custom CA loaded as PEM verifies the server with full certificate
  22270. // verification enabled
  22271. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22272. ws::WebSocketClient client(url());
  22273. std::string cert;
  22274. read_file(SERVER_CERT2_FILE, cert);
  22275. client.load_ca_cert_store(cert.c_str(), cert.size());
  22276. ASSERT_TRUE(client.connect());
  22277. ASSERT_TRUE(client.send("hello"));
  22278. std::string msg;
  22279. EXPECT_EQ(ws::Text, client.read(msg));
  22280. EXPECT_EQ("hello", msg);
  22281. client.close();
  22282. }
  22283. // A custom CA that does not cover the server must fail verification (the
  22284. // custom CA is exclusive; system certs are not loaded alongside it)
  22285. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22286. ws::WebSocketClient client(url());
  22287. std::string cert;
  22288. read_file(CLIENT_CA_CERT_FILE, cert);
  22289. client.load_ca_cert_store(cert.c_str(), cert.size());
  22290. auto res = client.connect();
  22291. ASSERT_FALSE(res);
  22292. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22293. EXPECT_EQ(-1, res.status());
  22294. EXPECT_NE(0u, res.ssl_backend_error());
  22295. }
  22296. // The same CA as a file path rather than PEM in memory
  22297. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22298. ws::WebSocketClient client(url());
  22299. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22300. ASSERT_TRUE(client.connect());
  22301. ASSERT_TRUE(client.send("hello"));
  22302. std::string msg;
  22303. EXPECT_EQ(ws::Text, client.read(msg));
  22304. EXPECT_EQ("hello", msg);
  22305. client.close();
  22306. }
  22307. // ...and a CA file that does not cover the server still fails, so it is the
  22308. // path above that decides the outcome
  22309. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22310. ws::WebSocketClient client(url());
  22311. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22312. ASSERT_FALSE(client.connect());
  22313. }
  22314. // Regression test: reconnecting with a native custom CA store used to reuse
  22315. // a store handle the previous TLS context had already freed (use-after-free
  22316. // under the OpenSSL backend). The context now lives as long as the client.
  22317. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22318. ws::WebSocketClient client(url());
  22319. std::string cert;
  22320. read_file(SERVER_CERT2_FILE, cert);
  22321. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22322. ASSERT_TRUE(client.connect());
  22323. client.close();
  22324. ASSERT_TRUE(client.connect());
  22325. ASSERT_TRUE(client.send("again"));
  22326. std::string msg;
  22327. EXPECT_EQ(ws::Text, client.read(msg));
  22328. EXPECT_EQ("again", msg);
  22329. client.close();
  22330. }
  22331. // Regression test: a certificate with a trusted chain but no identity match
  22332. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22333. // verification entirely for IP hosts, so this connection succeeded there.
  22334. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22335. // chain verification while the identity check must still fail.
  22336. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22337. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22338. ASSERT_TRUE(svr.is_valid());
  22339. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22340. std::string msg;
  22341. while (ws.read(msg)) {
  22342. ws.send(msg);
  22343. }
  22344. });
  22345. auto port = svr.bind_to_any_port("127.0.0.1");
  22346. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22347. auto se = detail::scope_exit([&] {
  22348. svr.stop();
  22349. t.join();
  22350. });
  22351. svr.wait_until_ready();
  22352. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22353. "/echo");
  22354. std::string cert;
  22355. read_file(SERVER_CERT_FILE, cert);
  22356. client.load_ca_cert_store(cert.c_str(), cert.size());
  22357. ASSERT_FALSE(client.connect());
  22358. }
  22359. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22360. // SNI, so nothing binds the host name to the TLS session. These bind the
  22361. // server to "localhost" instead, the only shape that exercises the SNI and
  22362. // hostname-verification path with certificate verification left enabled.
  22363. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22364. protected:
  22365. void Start(const char *cert_file) {
  22366. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22367. SERVER_PRIVATE_KEY_FILE);
  22368. ASSERT_TRUE(server_->is_valid());
  22369. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22370. std::string msg;
  22371. while (ws.read(msg)) {
  22372. ws.send(msg);
  22373. }
  22374. });
  22375. port_ = server_->bind_to_any_port("localhost");
  22376. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22377. server_->wait_until_ready();
  22378. }
  22379. void TearDown() override {
  22380. if (server_) { server_->stop(); }
  22381. if (server_thread_.joinable()) { server_thread_.join(); }
  22382. }
  22383. std::string url() const {
  22384. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22385. }
  22386. std::unique_ptr<SSLServer> server_;
  22387. std::thread server_thread_;
  22388. int port_ = 0;
  22389. };
  22390. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22391. // out and the connection is usable
  22392. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22393. Start(SERVER_CERT2_FILE);
  22394. ws::WebSocketClient client(url());
  22395. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22396. ASSERT_TRUE(client.connect());
  22397. ASSERT_TRUE(client.send("hello"));
  22398. std::string msg;
  22399. EXPECT_EQ(ws::Text, client.read(msg));
  22400. EXPECT_EQ("hello", msg);
  22401. client.close();
  22402. }
  22403. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22404. // while the identity check must still reject "localhost"
  22405. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22406. Start(SERVER_CERT_FILE);
  22407. ws::WebSocketClient client(url());
  22408. client.set_ca_cert_path(SERVER_CERT_FILE);
  22409. auto res = client.connect();
  22410. ASSERT_FALSE(res);
  22411. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22412. EXPECT_EQ(-1, res.status());
  22413. }
  22414. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22415. // disabled: the chain is still checked, only the identity check is skipped
  22416. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22417. Start(SERVER_CERT_FILE);
  22418. ws::WebSocketClient client(url());
  22419. client.set_ca_cert_path(SERVER_CERT_FILE);
  22420. client.enable_server_hostname_verification(false);
  22421. ASSERT_TRUE(client.connect());
  22422. ASSERT_TRUE(client.send("hello"));
  22423. std::string msg;
  22424. EXPECT_EQ(ws::Text, client.read(msg));
  22425. EXPECT_EQ("hello", msg);
  22426. client.close();
  22427. }
  22428. // A CA that did not sign the server certificate fails the chain, even though
  22429. // the name would match
  22430. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22431. Start(SERVER_CERT2_FILE);
  22432. ws::WebSocketClient client(url());
  22433. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22434. ASSERT_FALSE(client.connect());
  22435. }
  22436. // With verification disabled, neither the chain nor the name is checked
  22437. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22438. Start(SERVER_CERT_FILE);
  22439. ws::WebSocketClient client(url());
  22440. client.enable_server_certificate_verification(false);
  22441. ASSERT_TRUE(client.connect());
  22442. ASSERT_TRUE(client.send("hello"));
  22443. std::string msg;
  22444. EXPECT_EQ(ws::Text, client.read(msg));
  22445. EXPECT_EQ("hello", msg);
  22446. client.close();
  22447. }
  22448. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22449. protected:
  22450. void SetUp() override {
  22451. server_ = httplib::detail::make_unique<SSLServer>(
  22452. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22453. ASSERT_TRUE(server_->is_valid());
  22454. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22455. std::string msg;
  22456. while (ws.read(msg)) {
  22457. ws.send(msg);
  22458. }
  22459. });
  22460. port_ = server_->bind_to_any_port("localhost");
  22461. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22462. server_->wait_until_ready();
  22463. }
  22464. void TearDown() override {
  22465. server_->stop();
  22466. if (server_thread_.joinable()) { server_thread_.join(); }
  22467. }
  22468. std::string url() const {
  22469. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22470. }
  22471. void ConnectWithClientCert(const std::string &client_cert_file,
  22472. const std::string &client_private_key_file,
  22473. const char *private_key_password) {
  22474. std::string cert_pem, key_pem;
  22475. read_file(client_cert_file, cert_pem);
  22476. read_file(client_private_key_file, key_pem);
  22477. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22478. key_pem.c_str(), key_pem.size(),
  22479. private_key_password};
  22480. ws::WebSocketClient client(url(), pem);
  22481. ASSERT_TRUE(client.is_valid());
  22482. client.enable_server_certificate_verification(false);
  22483. ASSERT_TRUE(client.connect());
  22484. ASSERT_TRUE(client.send("hello"));
  22485. std::string msg;
  22486. EXPECT_EQ(ws::Text, client.read(msg));
  22487. EXPECT_EQ("hello", msg);
  22488. client.close();
  22489. }
  22490. std::unique_ptr<SSLServer> server_;
  22491. std::thread server_thread_;
  22492. int port_ = 0;
  22493. };
  22494. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22495. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22496. }
  22497. // Control for the tests above: the fixture's server really does require a
  22498. // client certificate, so it is the PEM the constructor installed that decides
  22499. // the outcome.
  22500. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22501. ws::WebSocketClient client(url());
  22502. ASSERT_TRUE(client.is_valid());
  22503. client.enable_server_certificate_verification(false);
  22504. EXPECT_FALSE(client.connect());
  22505. }
  22506. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22507. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22508. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22509. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22510. }
  22511. #endif
  22512. #if !defined(_WIN32)
  22513. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22514. auto secret_dir = std::string("./symlink_test_secret");
  22515. auto served_dir = std::string("./symlink_test_served");
  22516. auto secret_file = secret_dir + "/secret.txt";
  22517. auto symlink_path = served_dir + "/escape";
  22518. // Setup: create directories and files
  22519. mkdir(secret_dir.c_str(), 0755);
  22520. mkdir(served_dir.c_str(), 0755);
  22521. {
  22522. std::ofstream ofs(secret_file);
  22523. ofs << "SECRET_DATA";
  22524. }
  22525. // Create symlink using absolute path so it resolves correctly
  22526. #ifdef PATH_MAX
  22527. char abs_secret[PATH_MAX];
  22528. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22529. #else
  22530. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22531. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22532. ASSERT_NE(nullptr, abs_secret);
  22533. #endif
  22534. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22535. auto se = detail::scope_exit([&] {
  22536. unlink(symlink_path.c_str());
  22537. unlink(secret_file.c_str());
  22538. rmdir(served_dir.c_str());
  22539. rmdir(secret_dir.c_str());
  22540. });
  22541. Server svr;
  22542. svr.set_mount_point("/", served_dir);
  22543. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22544. auto se2 = detail::scope_exit([&] {
  22545. svr.stop();
  22546. listen_thread.join();
  22547. });
  22548. svr.wait_until_ready();
  22549. Client cli("localhost", PORT);
  22550. // Symlink pointing outside base dir should be blocked
  22551. auto res = cli.Get("/escape/secret.txt");
  22552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22553. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22554. }
  22555. #endif
  22556. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22557. // "GET /smuggled" request), reads the first response, and only then sends the
  22558. // embedded request as the body. Returns how many times /smuggled ran.
  22559. //
  22560. // The body is sent AFTER receiving the first response (as in the original
  22561. // PoC) so that the stream_line_reader cannot buffer it together with the
  22562. // headers of the first request.
  22563. static int count_smuggled_requests(const std::string &outer_head,
  22564. std::string &first_response) {
  22565. Server svr;
  22566. svr.set_mount_point("/", "./www");
  22567. std::atomic<int> smuggled_count(0);
  22568. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22569. smuggled_count++;
  22570. res.set_content("oops", "text/plain");
  22571. });
  22572. svr.Post("/post", [&](const Request &req, Response &res) {
  22573. res.set_content(req.body, "text/plain");
  22574. });
  22575. auto port = svr.bind_to_any_port("localhost");
  22576. thread t = thread([&] { svr.listen_after_bind(); });
  22577. auto se = detail::scope_exit([&] {
  22578. svr.stop();
  22579. t.join();
  22580. });
  22581. svr.wait_until_ready();
  22582. auto error = Error::Success;
  22583. auto sock = detail::create_client_socket(
  22584. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22585. /*connection_timeout_sec=*/2, 0,
  22586. /*read_timeout_sec=*/2, 0,
  22587. /*write_timeout_sec=*/2, 0, std::string(), error);
  22588. EXPECT_NE(INVALID_SOCKET, sock);
  22589. if (sock == INVALID_SOCKET) { return -1; }
  22590. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22591. // The "smuggled" request will be sent as the body of the outer request
  22592. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22593. "Host: localhost\r\n"
  22594. "Connection: close\r\n"
  22595. "\r\n";
  22596. auto head = outer_head;
  22597. auto len = std::to_string(smuggled.size());
  22598. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22599. pos = head.find("{len}", pos + len.size())) {
  22600. head.replace(pos, 5, len);
  22601. }
  22602. // Step 1: Send only the outer request headers (no body yet)
  22603. auto sent = send(sock, head.data(), head.size(), 0);
  22604. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22605. // Step 2: Read the first response
  22606. char buf[4096];
  22607. for (;;) {
  22608. auto n = recv(sock, buf, sizeof(buf), 0);
  22609. if (n <= 0) break;
  22610. first_response.append(buf, static_cast<size_t>(n));
  22611. // Stop once we have a complete response (headers + body)
  22612. auto hdr_end = first_response.find("\r\n\r\n");
  22613. if (hdr_end != std::string::npos) {
  22614. // Check for Content-Length to know when the body is complete
  22615. auto cl_pos = first_response.find("Content-Length:");
  22616. if (cl_pos != std::string::npos) {
  22617. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22618. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22619. auto cl = std::stoul(
  22620. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22621. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22622. } else {
  22623. break; // No Content-Length, assume headers-only response
  22624. }
  22625. }
  22626. }
  22627. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22628. // vulnerable server the keep-alive loop reads this as a second request. The
  22629. // server may already have closed the connection, so the result is ignored.
  22630. send(sock, smuggled.data(), smuggled.size(), 0);
  22631. // Half-close so that a server which drained the body sees EOF and closes,
  22632. // instead of the read below waiting for the read timeout.
  22633. #ifdef _WIN32
  22634. ::shutdown(sock, SD_SEND);
  22635. #else
  22636. ::shutdown(sock, SHUT_WR);
  22637. #endif
  22638. // Step 4: Read until the server closes the connection
  22639. for (;;) {
  22640. auto n = recv(sock, buf, sizeof(buf), 0);
  22641. if (n <= 0) break;
  22642. }
  22643. return smuggled_count.load();
  22644. }
  22645. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22646. // A GET request with Content-Length to a static file handler must have its
  22647. // body drained before the keep-alive connection is reused. Otherwise the
  22648. // unread body bytes are interpreted as the next HTTP request.
  22649. std::string first_response;
  22650. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22651. "Host: localhost\r\n"
  22652. "Content-Length: {len}\r\n"
  22653. "\r\n",
  22654. first_response));
  22655. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22656. }
  22657. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22658. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22659. // be answered with 400 and the connection closed. Treating it as "no body"
  22660. // leaves the body to be parsed as the next request.
  22661. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22662. const char *targets[] = {
  22663. "GET /file", // handler that never reads the body
  22664. "GET /not-found", // no handler matches (404)
  22665. "POST /post", // handler that reads the body
  22666. };
  22667. for (auto target : targets) {
  22668. for (auto value : values) {
  22669. std::string first_response;
  22670. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22671. " HTTP/1.1\r\n"
  22672. "Host: localhost\r\n"
  22673. "Content-Length: " +
  22674. value + "\r\n\r\n",
  22675. first_response))
  22676. << target << " with Content-Length: " << value;
  22677. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22678. << target << " with Content-Length: " << value;
  22679. }
  22680. }
  22681. }
  22682. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22683. // A 400 for an unparseable request line leaves the rest of the message
  22684. // unread, so the connection must be closed rather than reused.
  22685. std::string first_response;
  22686. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22687. "Host: localhost\r\n"
  22688. "Content-Length: {len}\r\n"
  22689. "\r\n",
  22690. first_response));
  22691. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22692. }
  22693. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22694. // Same as above for a header block that fails to parse.
  22695. std::string first_response;
  22696. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22697. "Host: localhost\r\n"
  22698. "Bad Header\r\n"
  22699. "Content-Length: {len}\r\n"
  22700. "\r\n",
  22701. first_response));
  22702. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22703. }
  22704. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22705. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22706. // server must not read another request on that connection, even when the
  22707. // request had no body to drain.
  22708. std::string first_response;
  22709. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22710. "Host: localhost\r\n"
  22711. "\r\n",
  22712. first_response));
  22713. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22714. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22715. }
  22716. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22717. // A content reader that stops early leaves the stream inside the body.
  22718. // Draining the whole Content-Length from there, or reading the body again,
  22719. // reads into the next request, and whatever follows is parsed as a request
  22720. // of its own.
  22721. Server svr;
  22722. std::atomic<int> smuggled_count(0);
  22723. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22724. svr.Post("/upload", [](const Request &req, Response &res,
  22725. const ContentReader &content_reader) {
  22726. // Stop at the last chunk, so the whole body has been read however it
  22727. // arrives.
  22728. auto length = req.get_header_value_u64("Content-Length");
  22729. size_t total = 0;
  22730. auto consumed = content_reader([&](const char *, size_t n) {
  22731. total += n;
  22732. return total < length;
  22733. });
  22734. EXPECT_FALSE(consumed);
  22735. if (req.has_param("retry")) {
  22736. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22737. }
  22738. // Replace the 400 the aborted read set, which would close the connection.
  22739. res.set_redirect("/done");
  22740. });
  22741. auto port = svr.bind_to_any_port(HOST);
  22742. thread t = thread([&] { svr.listen_after_bind(); });
  22743. auto se = detail::scope_exit([&] {
  22744. svr.stop();
  22745. t.join();
  22746. });
  22747. svr.wait_until_ready();
  22748. // A front end sees the second request as a POST whose body is the GET. The
  22749. // first body is as long as the POST's headers, so draining it again reads
  22750. // exactly those and leaves the GET to be parsed next.
  22751. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22752. "Host: localhost\r\n"
  22753. "\r\n";
  22754. std::string second_head = "POST /post HTTP/1.1\r\n"
  22755. "Host: localhost\r\n"
  22756. "Content-Length: " +
  22757. std::to_string(inner.size()) +
  22758. "\r\n"
  22759. "\r\n";
  22760. for (auto target : {"/upload", "/upload?retry"}) {
  22761. smuggled_count = 0;
  22762. std::string request = "POST " + std::string(target) +
  22763. " HTTP/1.1\r\n"
  22764. "Host: localhost\r\n"
  22765. "Content-Length: " +
  22766. std::to_string(second_head.size()) +
  22767. "\r\n"
  22768. "\r\n" +
  22769. std::string(second_head.size(), 'A') + second_head +
  22770. inner;
  22771. std::string response;
  22772. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22773. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22774. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22775. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22776. EXPECT_EQ(0, smuggled_count.load()) << target;
  22777. }
  22778. }
  22779. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22780. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22781. // must be rejected with 400 Bad Request.
  22782. Server svr;
  22783. svr.Post("/test", [&](const Request &, Response &res) {
  22784. res.set_content("ok", "text/plain");
  22785. });
  22786. thread t = thread([&] { svr.listen(HOST, PORT); });
  22787. auto se = detail::scope_exit([&] {
  22788. svr.stop();
  22789. t.join();
  22790. ASSERT_FALSE(svr.is_running());
  22791. });
  22792. svr.wait_until_ready();
  22793. // Exact "chunked"
  22794. {
  22795. auto req = "POST /test HTTP/1.1\r\n"
  22796. "Host: localhost\r\n"
  22797. "Content-Length: 5\r\n"
  22798. "Transfer-Encoding: chunked\r\n"
  22799. "Connection: close\r\n"
  22800. "\r\n"
  22801. "hello";
  22802. std::string response;
  22803. ASSERT_TRUE(send_request(1, req, &response));
  22804. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22805. response.substr(0, response.find("\r\n")));
  22806. }
  22807. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22808. {
  22809. auto req = "POST /test HTTP/1.1\r\n"
  22810. "Host: localhost\r\n"
  22811. "Content-Length: 5\r\n"
  22812. "Transfer-Encoding: gzip, chunked\r\n"
  22813. "Connection: close\r\n"
  22814. "\r\n"
  22815. "hello";
  22816. std::string response;
  22817. ASSERT_TRUE(send_request(1, req, &response));
  22818. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22819. response.substr(0, response.find("\r\n")));
  22820. }
  22821. }
  22822. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22823. Server svr;
  22824. svr.Post("/test", [&](const Request &, Response &res) {
  22825. res.set_content("ok", "text/plain");
  22826. });
  22827. thread t = thread([&] { svr.listen(HOST, PORT); });
  22828. auto se = detail::scope_exit([&] {
  22829. svr.stop();
  22830. t.join();
  22831. ASSERT_FALSE(svr.is_running());
  22832. });
  22833. svr.wait_until_ready();
  22834. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22835. // length cannot be determined, so the server must answer 400 and close
  22836. // rather than treat the request as bodyless and leave the body in the
  22837. // socket for the next request to pick up.
  22838. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22839. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22840. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22841. std::string response;
  22842. ASSERT_TRUE(send_request(1, req, &response));
  22843. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22844. response.substr(0, response.find("\r\n")))
  22845. << transfer_encoding;
  22846. }
  22847. // RFC 9110 5.3: the codings may also be split across several
  22848. // Transfer-Encoding lines, which combine in the order they were received.
  22849. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22850. // just like the single-line "chunked, gzip" above.
  22851. {
  22852. auto req = "POST /test HTTP/1.1\r\n"
  22853. "Host: localhost\r\n"
  22854. "Transfer-Encoding: chunked\r\n"
  22855. "Transfer-Encoding: gzip\r\n"
  22856. "\r\n"
  22857. "0\r\n\r\n";
  22858. std::string response;
  22859. ASSERT_TRUE(send_request(1, req, &response));
  22860. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22861. response.substr(0, response.find("\r\n")));
  22862. }
  22863. // A sequence ending in chunked stays valid.
  22864. auto req = "POST /test HTTP/1.1\r\n"
  22865. "Host: localhost\r\n"
  22866. "Transfer-Encoding: gzip, chunked\r\n"
  22867. "Connection: close\r\n"
  22868. "\r\n"
  22869. "0\r\n\r\n";
  22870. std::string response;
  22871. ASSERT_TRUE(send_request(1, req, &response));
  22872. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22873. // ...including when it is spread over several lines.
  22874. auto split_req = "POST /test HTTP/1.1\r\n"
  22875. "Host: localhost\r\n"
  22876. "Transfer-Encoding: gzip\r\n"
  22877. "Transfer-Encoding: chunked\r\n"
  22878. "Connection: close\r\n"
  22879. "\r\n"
  22880. "0\r\n\r\n";
  22881. std::string split_response;
  22882. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22883. EXPECT_EQ("HTTP/1.1 200 OK",
  22884. split_response.substr(0, split_response.find("\r\n")));
  22885. }
  22886. // Regression for issue #2450: a DELETE without Content-Length on a
  22887. // keep-alive connection must not let the post-response drain consume the
  22888. // next request's bytes.
  22889. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22890. Server svr;
  22891. std::atomic<int> delete_count(0);
  22892. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22893. delete_count++;
  22894. res.status = StatusCode::NoContent_204;
  22895. });
  22896. auto port = svr.bind_to_any_port(HOST);
  22897. thread t = thread([&] { svr.listen_after_bind(); });
  22898. auto se = detail::scope_exit([&] {
  22899. svr.stop();
  22900. t.join();
  22901. });
  22902. svr.wait_until_ready();
  22903. auto error = Error::Success;
  22904. auto sock = detail::create_client_socket(
  22905. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22906. /*connection_timeout_sec=*/2, 0,
  22907. /*read_timeout_sec=*/2, 0,
  22908. /*write_timeout_sec=*/2, 0, std::string(), error);
  22909. ASSERT_NE(INVALID_SOCKET, sock);
  22910. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22911. auto send_request_and_read_response = [&](const std::string &req,
  22912. std::string &out) -> bool {
  22913. auto sent = send(sock, req.data(), req.size(), 0);
  22914. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22915. char buf[4096];
  22916. for (;;) {
  22917. auto n = recv(sock, buf, sizeof(buf), 0);
  22918. if (n <= 0) { return !out.empty(); }
  22919. out.append(buf, static_cast<size_t>(n));
  22920. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22921. }
  22922. };
  22923. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22924. "Host: localhost\r\n"
  22925. "\r\n";
  22926. std::string resp1;
  22927. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22928. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22929. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22930. "Host: localhost\r\n"
  22931. "Connection: close\r\n"
  22932. "\r\n";
  22933. std::string resp2;
  22934. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22935. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22936. EXPECT_EQ(2, delete_count.load());
  22937. }
  22938. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22939. Server svr;
  22940. svr.Post("/ingest", [&](const Request &, Response &res,
  22941. const ContentReader &content_reader) {
  22942. auto consumed = content_reader([](const char *, size_t) { return false; });
  22943. EXPECT_FALSE(consumed);
  22944. res.status = StatusCode::Conflict_409;
  22945. res.set_header("Connection", "close");
  22946. });
  22947. auto port = svr.bind_to_any_port(HOST);
  22948. thread t = thread([&] { svr.listen_after_bind(); });
  22949. auto se = detail::scope_exit([&] {
  22950. svr.stop();
  22951. t.join();
  22952. });
  22953. svr.wait_until_ready();
  22954. auto error = Error::Success;
  22955. auto sock = detail::create_client_socket(
  22956. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22957. /*connection_timeout_sec=*/2, 0,
  22958. /*read_timeout_sec=*/1, 0,
  22959. /*write_timeout_sec=*/2, 0, std::string(), error);
  22960. ASSERT_NE(INVALID_SOCKET, sock);
  22961. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22962. std::string request = "POST /ingest HTTP/1.1\r\n"
  22963. "Host: localhost\r\n"
  22964. "Transfer-Encoding: chunked\r\n"
  22965. "\r\n"
  22966. "4\r\n"
  22967. "data\r\n";
  22968. auto sent = send(sock, request.data(), request.size(), 0);
  22969. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22970. std::string response;
  22971. ssize_t received = 0;
  22972. do {
  22973. char buf[4096];
  22974. received = recv(sock, buf, sizeof(buf), 0);
  22975. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22976. } while (received > 0);
  22977. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22978. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22979. EXPECT_EQ(0, received);
  22980. }
  22981. namespace no_proxy_test {
  22982. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22983. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22984. // calling listen().
  22985. class ScopedServer {
  22986. public:
  22987. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22988. ~ScopedServer() {
  22989. svr_.stop();
  22990. if (th_.joinable()) { th_.join(); }
  22991. }
  22992. Server &svr() { return svr_; }
  22993. int port() const { return port_; }
  22994. void listen() {
  22995. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22996. svr_.wait_until_ready();
  22997. }
  22998. private:
  22999. Server svr_;
  23000. std::thread th_;
  23001. int port_ = 0;
  23002. };
  23003. class ProxyAndTargetServers {
  23004. public:
  23005. ProxyAndTargetServers() {
  23006. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23007. proxy_hits_++;
  23008. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23009. res.set_content("via-proxy", "text/plain");
  23010. });
  23011. target_.Get(".*", [this](const Request &req, Response &res) {
  23012. target_hits_++;
  23013. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23014. res.set_content("direct", "text/plain");
  23015. });
  23016. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23017. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23018. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23019. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23020. proxy_mock_.wait_until_ready();
  23021. target_.wait_until_ready();
  23022. }
  23023. ~ProxyAndTargetServers() {
  23024. proxy_mock_.stop();
  23025. target_.stop();
  23026. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23027. if (target_thread_.joinable()) { target_thread_.join(); }
  23028. }
  23029. Server &proxy_mock() { return proxy_mock_; }
  23030. Server &target() { return target_; }
  23031. int proxy_port() const { return proxy_port_; }
  23032. int target_port() const { return target_port_; }
  23033. int proxy_hits() const { return proxy_hits_.load(); }
  23034. int target_hits() const { return target_hits_.load(); }
  23035. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23036. void reset_counters() {
  23037. proxy_hits_ = 0;
  23038. target_hits_ = 0;
  23039. last_had_proxy_authz_ = false;
  23040. }
  23041. private:
  23042. Server proxy_mock_;
  23043. Server target_;
  23044. std::thread proxy_thread_;
  23045. std::thread target_thread_;
  23046. int proxy_port_ = 0;
  23047. int target_port_ = 0;
  23048. std::atomic<int> proxy_hits_{0};
  23049. std::atomic<int> target_hits_{0};
  23050. std::atomic<bool> last_had_proxy_authz_{false};
  23051. };
  23052. inline std::unique_ptr<Client> make_client(const std::string &host,
  23053. ProxyAndTargetServers &s) {
  23054. auto cli = detail::make_unique<Client>(host, s.target_port());
  23055. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23056. cli->set_proxy("127.0.0.1", s.proxy_port());
  23057. return cli;
  23058. }
  23059. } // namespace no_proxy_test
  23060. using no_proxy_test::make_client;
  23061. using no_proxy_test::ProxyAndTargetServers;
  23062. TEST(NoProxyTest, ExactHostnameBypasses) {
  23063. ProxyAndTargetServers s;
  23064. auto cli = make_client("example.com", s);
  23065. cli->set_no_proxy({"example.com"});
  23066. auto res = cli->Get("/");
  23067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23068. EXPECT_EQ(0, s.proxy_hits());
  23069. EXPECT_EQ(1, s.target_hits());
  23070. }
  23071. TEST(NoProxyTest, SubdomainBypasses) {
  23072. ProxyAndTargetServers s;
  23073. auto cli = make_client("foo.example.com", s);
  23074. cli->set_no_proxy({"example.com"});
  23075. auto res = cli->Get("/");
  23076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23077. EXPECT_EQ(0, s.proxy_hits());
  23078. EXPECT_EQ(1, s.target_hits());
  23079. }
  23080. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23081. // Regression guard: "evilexample.com" must not be considered a subdomain
  23082. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23083. // check would let traffic bypass the proxy and leak credentials direct
  23084. // to the attacker host.
  23085. ProxyAndTargetServers s;
  23086. auto cli = make_client("evilexample.com", s);
  23087. cli->set_no_proxy({"example.com"});
  23088. auto res = cli->Get("/");
  23089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23090. EXPECT_GE(s.proxy_hits(), 1);
  23091. EXPECT_EQ(0, s.target_hits());
  23092. }
  23093. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23094. ProxyAndTargetServers s;
  23095. auto cli = make_client("example.com.evil.com", s);
  23096. cli->set_no_proxy({"example.com"});
  23097. auto res = cli->Get("/");
  23098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23099. EXPECT_GE(s.proxy_hits(), 1);
  23100. EXPECT_EQ(0, s.target_hits());
  23101. }
  23102. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23103. ProxyAndTargetServers s;
  23104. auto cli = make_client("example.com", s);
  23105. cli->set_no_proxy({".example.com"});
  23106. auto res = cli->Get("/");
  23107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23108. EXPECT_EQ(0, s.proxy_hits());
  23109. EXPECT_EQ(1, s.target_hits());
  23110. }
  23111. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23112. ProxyAndTargetServers s;
  23113. auto cli = make_client("Example.COM", s);
  23114. cli->set_no_proxy({"EXAMPLE.com"});
  23115. auto res = cli->Get("/");
  23116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23117. EXPECT_EQ(0, s.proxy_hits());
  23118. EXPECT_EQ(1, s.target_hits());
  23119. }
  23120. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23121. ProxyAndTargetServers s;
  23122. auto cli = make_client("example.com.", s);
  23123. cli->set_no_proxy({"example.com"});
  23124. auto res = cli->Get("/");
  23125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23126. EXPECT_EQ(0, s.proxy_hits());
  23127. EXPECT_EQ(1, s.target_hits());
  23128. }
  23129. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23130. // Trailing dots must be normalized on BOTH sides — host and entry.
  23131. // An implementation that only strips the host-side trailing dot would
  23132. // fail to match host "example.com" against entry "example.com." because
  23133. // a literal substring search would compare 11 chars against 12.
  23134. ProxyAndTargetServers s;
  23135. auto cli = make_client("example.com", s);
  23136. cli->set_no_proxy({"example.com."});
  23137. auto res = cli->Get("/");
  23138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23139. EXPECT_EQ(0, s.proxy_hits());
  23140. EXPECT_EQ(1, s.target_hits());
  23141. }
  23142. TEST(NoProxyTest, WildcardBypassesEverything) {
  23143. ProxyAndTargetServers s;
  23144. auto cli = make_client("anything.invalid.test", s);
  23145. cli->set_no_proxy({"*"});
  23146. auto res = cli->Get("/");
  23147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23148. EXPECT_EQ(0, s.proxy_hits());
  23149. EXPECT_EQ(1, s.target_hits());
  23150. }
  23151. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23152. ProxyAndTargetServers s;
  23153. Client cli("127.0.0.1", s.target_port());
  23154. cli.set_proxy("127.0.0.1", s.proxy_port());
  23155. cli.set_no_proxy({"127.0.0.1"});
  23156. auto res = cli.Get("/");
  23157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23158. EXPECT_EQ(0, s.proxy_hits());
  23159. EXPECT_EQ(1, s.target_hits());
  23160. }
  23161. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23162. ProxyAndTargetServers s;
  23163. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23164. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23165. cli.set_proxy("127.0.0.1", s.proxy_port());
  23166. cli.set_no_proxy({"::1"});
  23167. auto res = cli.Get("/");
  23168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23169. EXPECT_EQ(0, s.proxy_hits());
  23170. EXPECT_EQ(1, s.target_hits());
  23171. }
  23172. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23173. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23174. // must still be recognized as IPv6 for CIDR matching. Implementations
  23175. // that detect IPv6 only when the host begins with '[' would parse the
  23176. // host as a hostname and miss the match.
  23177. ProxyAndTargetServers s;
  23178. Client cli("fe80::1", s.target_port());
  23179. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23180. cli.set_proxy("127.0.0.1", s.proxy_port());
  23181. cli.set_no_proxy({"fe80::/10"});
  23182. auto res = cli.Get("/");
  23183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23184. EXPECT_EQ(0, s.proxy_hits());
  23185. EXPECT_EQ(1, s.target_hits());
  23186. }
  23187. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23188. ProxyAndTargetServers s;
  23189. Client cli("::1", s.target_port());
  23190. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23191. cli.set_proxy("127.0.0.1", s.proxy_port());
  23192. cli.set_no_proxy({"[::1]"});
  23193. auto res = cli.Get("/");
  23194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23195. EXPECT_EQ(0, s.proxy_hits());
  23196. EXPECT_EQ(1, s.target_hits());
  23197. }
  23198. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23199. ProxyAndTargetServers s;
  23200. Client cli("fe80::1", s.target_port());
  23201. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23202. cli.set_proxy("127.0.0.1", s.proxy_port());
  23203. cli.set_no_proxy({"[fe80::]/10"});
  23204. auto res = cli.Get("/");
  23205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23206. EXPECT_EQ(0, s.proxy_hits());
  23207. EXPECT_EQ(1, s.target_hits());
  23208. }
  23209. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23210. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23211. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23212. // tricks via address-family conversion.
  23213. ProxyAndTargetServers s;
  23214. Client cli("::ffff:127.0.0.1", s.target_port());
  23215. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23216. cli.set_proxy("127.0.0.1", s.proxy_port());
  23217. cli.set_no_proxy({"127.0.0.1"});
  23218. auto res = cli.Get("/");
  23219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23220. EXPECT_GE(s.proxy_hits(), 1);
  23221. EXPECT_EQ(0, s.target_hits());
  23222. }
  23223. TEST(NoProxyTest, IPv4CidrMatch) {
  23224. ProxyAndTargetServers s;
  23225. Client cli("127.0.0.1", s.target_port());
  23226. cli.set_proxy("127.0.0.1", s.proxy_port());
  23227. cli.set_no_proxy({"127.0.0.0/8"});
  23228. auto res = cli.Get("/");
  23229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23230. EXPECT_EQ(0, s.proxy_hits());
  23231. EXPECT_EQ(1, s.target_hits());
  23232. }
  23233. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23234. ProxyAndTargetServers s;
  23235. Client cli("127.0.0.1", s.target_port());
  23236. cli.set_proxy("127.0.0.1", s.proxy_port());
  23237. cli.set_no_proxy({"10.0.0.0/8"});
  23238. auto res = cli.Get("/");
  23239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23240. EXPECT_GE(s.proxy_hits(), 1);
  23241. EXPECT_EQ(0, s.target_hits());
  23242. }
  23243. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23244. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23245. // IPv4 target matches.
  23246. ProxyAndTargetServers s;
  23247. Client cli("127.0.0.1", s.target_port());
  23248. cli.set_proxy("127.0.0.1", s.proxy_port());
  23249. cli.set_no_proxy({"0.0.0.0/0"});
  23250. auto res = cli.Get("/");
  23251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23252. EXPECT_EQ(0, s.proxy_hits());
  23253. EXPECT_EQ(1, s.target_hits());
  23254. }
  23255. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23256. ProxyAndTargetServers s;
  23257. Client cli("127.0.0.1", s.target_port());
  23258. cli.set_proxy("127.0.0.1", s.proxy_port());
  23259. cli.set_no_proxy({"127.0.0.1"});
  23260. auto res = cli.Get("/");
  23261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23262. EXPECT_EQ(0, s.proxy_hits());
  23263. EXPECT_EQ(1, s.target_hits());
  23264. }
  23265. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23266. ProxyAndTargetServers s;
  23267. Client cli("127.0.0.1", s.target_port());
  23268. cli.set_proxy("127.0.0.1", s.proxy_port());
  23269. cli.set_no_proxy({"127.0.0.0/33"});
  23270. auto res = cli.Get("/");
  23271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23272. EXPECT_GE(s.proxy_hits(), 1);
  23273. EXPECT_EQ(0, s.target_hits());
  23274. }
  23275. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23276. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23277. ProxyAndTargetServers s;
  23278. Client cli("127.0.0.1", s.target_port());
  23279. cli.set_proxy("127.0.0.1", s.proxy_port());
  23280. cli.set_no_proxy({"127.0.0.1/"});
  23281. auto res = cli.Get("/");
  23282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23283. EXPECT_GE(s.proxy_hits(), 1);
  23284. EXPECT_EQ(0, s.target_hits());
  23285. }
  23286. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23287. ProxyAndTargetServers s;
  23288. auto cli = make_client("internal.corp", s);
  23289. cli->set_proxy_basic_auth("u", "p");
  23290. cli->set_no_proxy({"internal.corp"});
  23291. auto res = cli->Get("/");
  23292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23293. EXPECT_EQ(1, s.target_hits());
  23294. EXPECT_EQ(0, s.proxy_hits());
  23295. EXPECT_FALSE(s.last_had_proxy_authz())
  23296. << "Proxy-Authorization must not be sent direct to the target";
  23297. }
  23298. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23299. ProxyAndTargetServers s;
  23300. auto cli = make_client("public.example", s);
  23301. cli->set_proxy_basic_auth("u", "p");
  23302. cli->set_no_proxy({"internal.corp"}); // does not match
  23303. auto res = cli->Get("/");
  23304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23305. EXPECT_GE(s.proxy_hits(), 1);
  23306. EXPECT_TRUE(s.last_had_proxy_authz());
  23307. }
  23308. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23309. std::atomic<int> hits{0};
  23310. std::atomic<int> hits_with_authz{0};
  23311. no_proxy_test::ScopedServer proxy_mock;
  23312. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23313. hits++;
  23314. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23315. if (req.target.find("/redir") != std::string::npos) {
  23316. res.set_redirect("http://other.example/landed");
  23317. } else {
  23318. res.set_content("via-proxy", "text/plain");
  23319. }
  23320. });
  23321. proxy_mock.listen();
  23322. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23323. hits = 0;
  23324. hits_with_authz = 0;
  23325. Client cli("public.example", 80);
  23326. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23327. cli.set_proxy_basic_auth(c.first, c.second);
  23328. cli.set_follow_location(true);
  23329. // The redirect to another host goes through the proxy as well
  23330. auto res = cli.Get("/redir");
  23331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23332. EXPECT_EQ(2, hits.load());
  23333. EXPECT_EQ(2, hits_with_authz.load());
  23334. }
  23335. }
  23336. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23337. ProxyAndTargetServers s;
  23338. auto cli = make_client("anything.test", s);
  23339. auto res = cli->Get("/");
  23340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23341. EXPECT_GE(s.proxy_hits(), 1);
  23342. EXPECT_EQ(0, s.target_hits());
  23343. }
  23344. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23345. ProxyAndTargetServers s;
  23346. auto cli = make_client("example.com", s);
  23347. cli->set_no_proxy({"example.com:8080"});
  23348. auto res = cli->Get("/");
  23349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23350. EXPECT_GE(s.proxy_hits(), 1);
  23351. EXPECT_EQ(0, s.target_hits());
  23352. }
  23353. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23354. ProxyAndTargetServers s;
  23355. auto cli = make_client("anything.test", s);
  23356. cli->set_no_proxy({"", " ", "\t"});
  23357. auto res = cli->Get("/");
  23358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23359. EXPECT_GE(s.proxy_hits(), 1);
  23360. EXPECT_EQ(0, s.target_hits());
  23361. }
  23362. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23363. // An entry with leading/trailing whitespace must still match — env-style
  23364. // values are commonly pasted with stray spaces and an implementation
  23365. // that feeds the raw token directly to inet_pton would fail to match
  23366. // valid CIDRs because of the spaces.
  23367. ProxyAndTargetServers s;
  23368. Client cli("127.0.0.1", s.target_port());
  23369. cli.set_proxy("127.0.0.1", s.proxy_port());
  23370. cli.set_no_proxy({" 127.0.0.0/8 "});
  23371. auto res = cli.Get("/");
  23372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23373. EXPECT_EQ(0, s.proxy_hits());
  23374. EXPECT_EQ(1, s.target_hits());
  23375. }
  23376. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23377. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23378. // go direct and must NOT carry Proxy-Authorization.
  23379. std::atomic<int> proxy_hits{0};
  23380. std::atomic<int> target_hits{0};
  23381. std::atomic<bool> target_saw_authz{false};
  23382. no_proxy_test::ScopedServer proxy_mock, target;
  23383. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23384. proxy_hits++;
  23385. res.status = 302;
  23386. res.set_header("Location", "http://127.0.0.1:" +
  23387. std::to_string(target.port()) + "/landed");
  23388. });
  23389. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23390. target_hits++;
  23391. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23392. res.set_content("direct", "text/plain");
  23393. });
  23394. proxy_mock.listen();
  23395. target.listen();
  23396. Client cli("public.example", target.port());
  23397. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23398. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23399. cli.set_proxy_basic_auth("u", "p");
  23400. cli.set_no_proxy({"127.0.0.1"});
  23401. cli.set_follow_location(true);
  23402. auto res = cli.Get("/redir");
  23403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23404. EXPECT_GE(proxy_hits.load(), 1);
  23405. EXPECT_GE(target_hits.load(), 1);
  23406. EXPECT_FALSE(target_saw_authz.load());
  23407. }
  23408. #ifdef CPPHTTPLIB_SSL_ENABLED
  23409. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23410. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23411. // proxy creds would be sent to the (possibly hostile) origin.
  23412. std::atomic<int> target_hits{0};
  23413. std::atomic<bool> target_saw_proxy_authz{false};
  23414. no_proxy_test::ScopedServer target;
  23415. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23416. target_hits++;
  23417. if (req.has_header("Proxy-Authorization")) {
  23418. target_saw_proxy_authz = true;
  23419. }
  23420. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23421. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23422. "nonce=\"abc\", algorithm=MD5");
  23423. });
  23424. target.listen();
  23425. // The proxy address is set to the target's port: the bypass MUST kick in;
  23426. // if it doesn't, the test still routes "via proxy" to the same server and
  23427. // the Proxy-Authorization assertion below catches the leak.
  23428. Client cli("evil.example", target.port());
  23429. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23430. cli.set_proxy("127.0.0.1", target.port());
  23431. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23432. cli.set_no_proxy({"evil.example"});
  23433. auto res = cli.Get("/x");
  23434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23435. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23436. EXPECT_EQ(1, target_hits.load());
  23437. EXPECT_FALSE(target_saw_proxy_authz.load());
  23438. }
  23439. #endif
  23440. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23441. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23442. std::atomic<int> proxy_hits{0};
  23443. std::atomic<int> bypass_hits{0};
  23444. std::atomic<bool> proxy_saw_c_url{false};
  23445. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23446. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23447. proxy_hits++;
  23448. if (req.path.find("/start") != std::string::npos) {
  23449. res.status = 302;
  23450. res.set_header("Location", "http://127.0.0.1:" +
  23451. std::to_string(bypass_server.port()) +
  23452. "/middle");
  23453. return;
  23454. }
  23455. if (req.path.find("/end") != std::string::npos) {
  23456. proxy_saw_c_url = true;
  23457. res.set_content("c-via-proxy", "text/plain");
  23458. return;
  23459. }
  23460. res.set_content("unexpected", "text/plain");
  23461. });
  23462. // public.example's "advertised" port is arbitrary (the request never lands
  23463. // there — it goes through the proxy), but use a dynamic value to stay
  23464. // friendly with sharded parallel runs.
  23465. int public_port = bypass_server.port();
  23466. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23467. bypass_hits++;
  23468. res.status = 302;
  23469. res.set_header("Location", "http://public.example:" +
  23470. std::to_string(public_port) + "/end");
  23471. });
  23472. proxy_mock.listen();
  23473. bypass_server.listen();
  23474. Client cli("public.example", public_port);
  23475. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23476. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23477. cli.set_no_proxy({"127.0.0.1"});
  23478. cli.set_follow_location(true);
  23479. auto res = cli.Get("/start");
  23480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23481. EXPECT_EQ(StatusCode::OK_200, res->status);
  23482. EXPECT_EQ("c-via-proxy", res->body);
  23483. EXPECT_GE(proxy_hits.load(), 2);
  23484. EXPECT_GE(bypass_hits.load(), 1);
  23485. EXPECT_TRUE(proxy_saw_c_url.load());
  23486. }
  23487. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23488. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23489. // request reconnects to the correct endpoint.
  23490. std::atomic<int> proxy_hits{0};
  23491. std::atomic<int> target_hits{0};
  23492. no_proxy_test::ScopedServer proxy_mock, target;
  23493. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23494. proxy_hits++;
  23495. res.set_content("via-proxy", "text/plain");
  23496. });
  23497. target.svr().Get(".*", [&](const Request &, Response &res) {
  23498. target_hits++;
  23499. res.set_content("direct", "text/plain");
  23500. });
  23501. proxy_mock.listen();
  23502. target.listen();
  23503. Client cli("public.example", target.port());
  23504. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23505. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23506. cli.set_keep_alive(true);
  23507. auto res1 = cli.Get("/a");
  23508. ASSERT_TRUE(res1);
  23509. EXPECT_EQ("via-proxy", res1->body);
  23510. EXPECT_EQ(1, proxy_hits.load());
  23511. EXPECT_EQ(0, target_hits.load());
  23512. cli.set_no_proxy({"public.example"});
  23513. auto res2 = cli.Get("/b");
  23514. ASSERT_TRUE(res2);
  23515. EXPECT_EQ("direct", res2->body);
  23516. EXPECT_EQ(1, proxy_hits.load());
  23517. EXPECT_EQ(1, target_hits.load());
  23518. }
  23519. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23520. namespace proxy_tunnel_test {
  23521. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23522. class ScopedSSLServer {
  23523. public:
  23524. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23525. port_ = svr_.bind_to_any_port("127.0.0.1");
  23526. }
  23527. ~ScopedSSLServer() {
  23528. svr_.stop();
  23529. if (th_.joinable()) { th_.join(); }
  23530. }
  23531. SSLServer &svr() { return svr_; }
  23532. int port() const { return port_; }
  23533. void listen() {
  23534. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23535. svr_.wait_until_ready();
  23536. }
  23537. private:
  23538. SSLServer svr_;
  23539. std::thread th_;
  23540. int port_ = 0;
  23541. };
  23542. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23543. class ScopedConnectProxy {
  23544. public:
  23545. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23546. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23547. if (listen_fd_ < 0) { return; }
  23548. int yes = 1;
  23549. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23550. sockaddr_in a{};
  23551. a.sin_family = AF_INET;
  23552. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23553. a.sin_port = 0;
  23554. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23555. return;
  23556. }
  23557. socklen_t alen = sizeof(a);
  23558. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23559. 0) {
  23560. return;
  23561. }
  23562. port_ = ntohs(a.sin_port);
  23563. if (::listen(listen_fd_, 1) != 0) { return; }
  23564. th_ = std::thread([this] { run(); });
  23565. }
  23566. ~ScopedConnectProxy() {
  23567. stop_ = true;
  23568. if (listen_fd_ >= 0) {
  23569. ::shutdown(listen_fd_, SHUT_RDWR);
  23570. ::close(listen_fd_);
  23571. }
  23572. if (th_.joinable()) { th_.join(); }
  23573. }
  23574. int port() const { return port_; }
  23575. int connect_hits() const { return connect_hits_.load(); }
  23576. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23577. std::string connect_request() const {
  23578. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23579. return connect_request_;
  23580. }
  23581. private:
  23582. void run() {
  23583. while (!stop_.load()) {
  23584. fd_set rfds;
  23585. FD_ZERO(&rfds);
  23586. FD_SET(listen_fd_, &rfds);
  23587. timeval tv{0, 100 * 1000};
  23588. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23589. if (sel <= 0) { continue; }
  23590. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23591. if (client_fd < 0) { continue; }
  23592. std::string req;
  23593. char buf[2048];
  23594. while (req.find("\r\n\r\n") == std::string::npos) {
  23595. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23596. if (n <= 0) { break; }
  23597. req.append(buf, static_cast<size_t>(n));
  23598. }
  23599. if (req.compare(0, 7, "CONNECT") != 0) {
  23600. ::close(client_fd);
  23601. continue;
  23602. }
  23603. connect_hits_++;
  23604. {
  23605. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23606. connect_request_ = req;
  23607. }
  23608. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23609. ::send(client_fd, ok, std::strlen(ok), 0);
  23610. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23611. sockaddr_in o{};
  23612. o.sin_family = AF_INET;
  23613. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23614. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23615. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23616. 0) {
  23617. ::close(client_fd);
  23618. ::close(origin_fd);
  23619. continue;
  23620. }
  23621. auto forward = [](int from, int to) {
  23622. char b[8192];
  23623. for (;;) {
  23624. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23625. if (n <= 0) { break; }
  23626. ssize_t off = 0;
  23627. while (off < n) {
  23628. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23629. if (s <= 0) {
  23630. off = n;
  23631. break;
  23632. }
  23633. off += s;
  23634. }
  23635. }
  23636. ::shutdown(to, SHUT_WR);
  23637. };
  23638. std::thread t1([&] { forward(client_fd, origin_fd); });
  23639. std::thread t2([&] { forward(origin_fd, client_fd); });
  23640. t1.join();
  23641. t2.join();
  23642. ::close(client_fd);
  23643. ::close(origin_fd);
  23644. }
  23645. }
  23646. int forward_port_ = -1;
  23647. int listen_fd_ = -1;
  23648. int port_ = 0;
  23649. std::thread th_;
  23650. std::atomic<bool> stop_{false};
  23651. std::atomic<int> connect_hits_{0};
  23652. mutable std::mutex connect_request_mutex_;
  23653. std::string connect_request_;
  23654. };
  23655. // Sends one request through the CONNECT proxy to the TLS origin with a
  23656. // credential configured for each hop, and checks that each credential reaches
  23657. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23658. // origin's (every header in origin_headers) on the tunnelled request.
  23659. void CredentialsStayWithTheirHop(
  23660. const std::function<void(SSLClient &)> &set_credentials,
  23661. const std::string &scheme,
  23662. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23663. std::atomic<int> origin_hits{0};
  23664. std::atomic<bool> origin_saw_proxy_authz{false};
  23665. std::atomic<bool> origin_saw_headers{false};
  23666. ScopedSSLServer origin;
  23667. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23668. origin_hits++;
  23669. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23670. origin_saw_headers =
  23671. std::all_of(origin_headers.begin(), origin_headers.end(),
  23672. [&](const std::string &h) { return req.has_header(h); });
  23673. res.set_content("ok", "text/plain");
  23674. });
  23675. origin.listen();
  23676. ScopedConnectProxy proxy(origin.port());
  23677. ASSERT_NE(0, proxy.port());
  23678. // Pinned to 127.0.0.1 for the same reason as the test below.
  23679. SSLClient cli("127.0.0.1", origin.port());
  23680. cli.enable_server_certificate_verification(false);
  23681. cli.set_proxy("127.0.0.1", proxy.port());
  23682. set_credentials(cli);
  23683. auto res = cli.Get("/x");
  23684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23685. EXPECT_EQ(StatusCode::OK_200, res->status);
  23686. EXPECT_EQ(1, origin_hits.load());
  23687. EXPECT_EQ(1, proxy.connect_hits());
  23688. EXPECT_TRUE(origin_saw_headers.load());
  23689. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23690. << "Proxy-Authorization must not be sent inside the tunnel";
  23691. auto connect_req = proxy.connect_request();
  23692. EXPECT_NE(std::string::npos,
  23693. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23694. for (const auto &h : origin_headers) {
  23695. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23696. << h << " must not be sent to the proxy on CONNECT";
  23697. }
  23698. }
  23699. } // namespace proxy_tunnel_test
  23700. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23701. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23702. [](SSLClient &cli) {
  23703. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23704. cli.set_basic_auth("origin-user", "origin-pass");
  23705. },
  23706. "Basic");
  23707. }
  23708. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23709. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23710. [](SSLClient &cli) {
  23711. cli.set_proxy_bearer_token_auth("proxy-token");
  23712. cli.set_bearer_token_auth("origin-token");
  23713. },
  23714. "Bearer");
  23715. }
  23716. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23717. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23718. [](SSLClient &cli) {
  23719. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23720. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23721. {"Cookie", "sid=origin-session"},
  23722. {"X-Api-Key", "origin-key"}});
  23723. },
  23724. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23725. }
  23726. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23727. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23728. // retry; otherwise proxy creds would be sent to the origin.
  23729. std::atomic<int> origin_hits{0};
  23730. std::atomic<bool> origin_saw_proxy_authz{false};
  23731. proxy_tunnel_test::ScopedSSLServer origin;
  23732. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23733. origin_hits++;
  23734. if (req.has_header("Proxy-Authorization")) {
  23735. origin_saw_proxy_authz = true;
  23736. }
  23737. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23738. res.set_header("Proxy-Authenticate",
  23739. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23740. "algorithm=MD5");
  23741. });
  23742. origin.listen();
  23743. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23744. ASSERT_NE(0, proxy.port());
  23745. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23746. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23747. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23748. // and answer with its own status, making this test flaky.
  23749. SSLClient cli("127.0.0.1", origin.port());
  23750. cli.enable_server_certificate_verification(false);
  23751. cli.set_proxy("127.0.0.1", proxy.port());
  23752. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23753. auto res = cli.Get("/x");
  23754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23755. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23756. EXPECT_EQ(1, origin_hits.load());
  23757. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23758. EXPECT_EQ(1, proxy.connect_hits());
  23759. }
  23760. #endif