test.cc 918 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291
  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. auto res = cli.Get("/");
  12329. EXPECT_FALSE(res);
  12330. EXPECT_EQ(Error::Connection, res.error());
  12331. }
  12332. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12333. httplib::Client cli("http://www.google.com:80abc");
  12334. ASSERT_FALSE(cli.is_valid());
  12335. }
  12336. #ifdef CPPHTTPLIB_SSL_ENABLED
  12337. TEST(HostAndPortPropertiesTest, SSL) {
  12338. httplib::SSLClient cli("www.google.com");
  12339. ASSERT_EQ("www.google.com", cli.host());
  12340. ASSERT_EQ(443, cli.port());
  12341. }
  12342. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12343. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12344. std::string cert;
  12345. read_file(CA_CERT_FILE, cert);
  12346. httplib::SSLClient httplib_client("www.google.com");
  12347. // Load CA store first time
  12348. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12349. // Load CA store second time (update)
  12350. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12351. // Verify client is still valid and can make connections
  12352. httplib_client.enable_server_certificate_verification(true);
  12353. auto res = httplib_client.Get("/");
  12354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12355. // Google may return 200 or 301 depending on various factors
  12356. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12357. res->status == StatusCode::MovedPermanently_301);
  12358. }
  12359. TEST(SSLClientTest, ServerNameIndication_Online) {
  12360. auto host = "httpbingo.org";
  12361. auto path = std::string{"/get"};
  12362. SSLClient cli(host, 443);
  12363. auto res = cli.Get(path);
  12364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12365. ASSERT_EQ(StatusCode::OK_200, res->status);
  12366. }
  12367. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12368. // Use a site that will cause SSL verification failure due to self-signed cert
  12369. SSLClient cli("self-signed.badssl.com", 443);
  12370. cli.enable_server_certificate_verification(true);
  12371. auto res = cli.Get("/");
  12372. ASSERT_TRUE(!res);
  12373. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12374. // Verify backend error is captured for SSLServerVerification
  12375. // This occurs when certificate verification fails
  12376. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12377. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12378. EXPECT_NE(0UL, res.ssl_backend_error());
  12379. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12380. // For OpenSSL, ssl_error is 0 for verification errors
  12381. EXPECT_EQ(0, res.ssl_error());
  12382. #if !defined(_WIN32) || \
  12383. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12384. // On non-Windows or when Windows Schannel is disabled, the error comes
  12385. // from OpenSSL's verification
  12386. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12387. res.ssl_backend_error());
  12388. #endif
  12389. #endif
  12390. }
  12391. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12392. // Use a site where hostname doesn't match the certificate
  12393. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12394. SSLClient cli("wrong.host.badssl.com", 443);
  12395. cli.enable_server_certificate_verification(true);
  12396. cli.enable_server_hostname_verification(true);
  12397. auto res = cli.Get("/");
  12398. ASSERT_TRUE(!res);
  12399. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12400. // Verify backend error is captured for hostname verification failure
  12401. EXPECT_NE(0UL, res.ssl_backend_error());
  12402. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12403. // For OpenSSL, ssl_error is 0 for verification errors
  12404. EXPECT_EQ(0, res.ssl_error());
  12405. #if !defined(_WIN32) || \
  12406. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12407. // On non-Windows or when Windows Schannel is disabled, the error comes
  12408. // from OpenSSL's hostname verification
  12409. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12410. res.ssl_backend_error());
  12411. #endif
  12412. #endif
  12413. }
  12414. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12415. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12416. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12417. SSLClient cli("www.google.com", 443);
  12418. cli.enable_server_certificate_verification(true);
  12419. auto res = cli.Get("/");
  12420. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12421. }
  12422. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12423. SSLClient cli("www.google.com", 443);
  12424. cli.enable_server_certificate_verification(true);
  12425. cli.enable_windows_certificate_verification(false);
  12426. auto res = cli.Get("/");
  12427. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12428. }
  12429. // The server sends an intermediate cross-signed by a root Windows trusts,
  12430. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12431. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12432. SSLClient cli("accounts.spotify.com", 443);
  12433. auto res = cli.Get("/");
  12434. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12435. << " ssl_backend_error=" << res.ssl_backend_error();
  12436. }
  12437. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12438. // policy status, which no backend reports for a self-signed certificate.
  12439. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12440. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12441. ASSERT_TRUE(svr.is_valid());
  12442. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12443. auto se = detail::scope_exit([&] {
  12444. svr.stop();
  12445. t.join();
  12446. ASSERT_FALSE(svr.is_running());
  12447. });
  12448. svr.wait_until_ready();
  12449. SSLClient cli("127.0.0.1", PORT);
  12450. cli.set_connection_timeout(30);
  12451. auto res = cli.Get("/");
  12452. ASSERT_FALSE(res);
  12453. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12454. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12455. }
  12456. #endif
  12457. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12458. Client cli("https://google.com");
  12459. auto res = cli.Get("/");
  12460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12461. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12462. }
  12463. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12464. SSLClient cli("google.com");
  12465. cli.set_ca_cert_path(CA_CERT_FILE);
  12466. auto res = cli.Get("/");
  12467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12468. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12469. }
  12470. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12471. SSLClient cli("google.com");
  12472. cli.enable_server_certificate_verification(true);
  12473. cli.set_ca_cert_path("hello");
  12474. auto res = cli.Get("/");
  12475. ASSERT_TRUE(!res);
  12476. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12477. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12478. // should be set
  12479. EXPECT_EQ(0, res.ssl_error());
  12480. // Verify backend error is captured for SSLLoadingCerts
  12481. // This error occurs when loading CA certificates fails
  12482. EXPECT_NE(0UL, res.ssl_backend_error());
  12483. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12484. // OpenSSL specific error codes:
  12485. // > openssl errstr 0x80000002
  12486. // error:80000002:system library::No such file or directory
  12487. // > openssl errstr 0xA000126
  12488. // error:0A000126:SSL routines::unexpected eof while reading
  12489. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12490. res.ssl_backend_error() == 0xA000126);
  12491. #endif
  12492. }
  12493. TEST(SSLClientTest, ServerCertificateVerification4) {
  12494. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12495. ASSERT_TRUE(svr.is_valid());
  12496. svr.Get("/test", [&](const Request &, Response &res) {
  12497. res.set_content("test", "text/plain");
  12498. svr.stop();
  12499. ASSERT_TRUE(true);
  12500. });
  12501. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12502. auto se = detail::scope_exit([&] {
  12503. t.join();
  12504. ASSERT_FALSE(svr.is_running());
  12505. });
  12506. svr.wait_until_ready();
  12507. SSLClient cli("127.0.0.1", PORT);
  12508. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12509. cli.enable_server_certificate_verification(true);
  12510. cli.set_connection_timeout(30);
  12511. auto res = cli.Get("/test");
  12512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12513. ASSERT_EQ(StatusCode::OK_200, res->status);
  12514. }
  12515. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12516. std::string cert;
  12517. read_file(CA_CERT_FILE, cert);
  12518. SSLClient cli("google.com");
  12519. cli.load_ca_cert_store(cert.data(), cert.size());
  12520. const auto res = cli.Get("/");
  12521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12522. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12523. }
  12524. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12525. // clang-format off
  12526. static constexpr char cert[] =
  12527. "GlobalSign Root CA\n"
  12528. "==================\n"
  12529. "-----BEGIN CERTIFICATE-----\n"
  12530. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12531. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12532. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12533. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12534. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12535. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12536. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12537. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12538. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12539. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12540. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12541. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12542. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12543. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12544. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12545. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12546. "-----END CERTIFICATE-----\n";
  12547. // clang-format on
  12548. SSLClient cli("google.com");
  12549. cli.load_ca_cert_store(cert, sizeof(cert));
  12550. const auto res = cli.Get("/");
  12551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12552. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12553. }
  12554. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12555. SSLClient cli("www.youtube.com");
  12556. cli.set_ca_cert_path(CA_CERT_FILE);
  12557. cli.enable_server_certificate_verification(true);
  12558. cli.set_follow_location(true);
  12559. auto res = cli.Get("/");
  12560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12561. ASSERT_EQ(StatusCode::OK_200, res->status);
  12562. }
  12563. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12564. SSLClient cli("wWw.YouTube.Com");
  12565. cli.set_ca_cert_path(CA_CERT_FILE);
  12566. cli.enable_server_certificate_verification(true);
  12567. cli.enable_server_hostname_verification(true);
  12568. cli.set_follow_location(true);
  12569. auto res = cli.Get("/");
  12570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12571. ASSERT_EQ(StatusCode::OK_200, res->status);
  12572. }
  12573. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12574. SSLClient cli("gOoGlE.COm");
  12575. cli.enable_server_certificate_verification(true);
  12576. cli.enable_server_hostname_verification(true);
  12577. cli.set_follow_location(true);
  12578. auto res = cli.Get("/");
  12579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12580. ASSERT_EQ(StatusCode::OK_200, res->status);
  12581. }
  12582. TEST(SSLClientTest, Issue2004_Online) {
  12583. Client client("https://google.com");
  12584. client.set_follow_location(true);
  12585. auto res = client.Get("/");
  12586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12587. ASSERT_EQ(StatusCode::OK_200, res->status);
  12588. auto body = res->body;
  12589. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12590. }
  12591. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12592. // Create SSLClient with invalid cert/key to make is_valid() return false
  12593. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12594. "nonexistent_key.pem");
  12595. // is_valid() should be false due to cert loading failure
  12596. ASSERT_FALSE(cli.is_valid());
  12597. auto res = cli.Get("/");
  12598. ASSERT_FALSE(res);
  12599. EXPECT_EQ(Error::SSLConnection, res.error());
  12600. }
  12601. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12602. // Test for Issue #2251: SSL error not properly reported when client cert
  12603. // and key paths are swapped or mismatched
  12604. // This simulates the scenario where user accidentally swaps the cert and key
  12605. // files
  12606. // Using client cert file as private key and vice versa (completely wrong)
  12607. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12608. // Should fail validation due to cert/key mismatch
  12609. ASSERT_FALSE(cli.is_valid());
  12610. // Attempt to make a request should fail with proper error
  12611. auto res = cli.Get("/");
  12612. ASSERT_FALSE(res);
  12613. EXPECT_EQ(Error::SSLConnection, res.error());
  12614. // SSL error should be recorded in the Result object (this is the key fix for
  12615. // Issue #2251)
  12616. auto backend_error = res.ssl_backend_error();
  12617. EXPECT_NE(0u, backend_error);
  12618. }
  12619. // Tests cert/key mismatch detection at the TLS context level
  12620. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12621. // Test that using mismatched cert/key causes connection failure.
  12622. // We verify this at the SSLClient level rather than through internal
  12623. // TLS API functions.
  12624. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12625. cli.enable_server_certificate_verification(false);
  12626. cli.set_connection_timeout(2);
  12627. // The mismatch should cause a connection or handshake error
  12628. auto res = cli.Get("/test");
  12629. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12630. // Either way, the request should fail
  12631. EXPECT_FALSE(res);
  12632. }
  12633. #endif
  12634. #if 0
  12635. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12636. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12637. ASSERT_TRUE(cli != nullptr);
  12638. cli->set_address_family(AF_INET6);
  12639. cli->set_interface("en0");
  12640. auto res = cli->Get("/get");
  12641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12642. ASSERT_EQ(StatusCode::OK_200, res->status);
  12643. }
  12644. #endif
  12645. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12646. #ifdef CPPHTTPLIB_SSL_ENABLED
  12647. void ClientCertPresent(
  12648. const std::string &client_cert_file,
  12649. const std::string &client_private_key_file,
  12650. const std::string &client_encrypted_private_key_pass = std::string()) {
  12651. using namespace httplib::tls;
  12652. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12653. CLIENT_CA_CERT_DIR);
  12654. ASSERT_TRUE(svr.is_valid());
  12655. svr.Get("/test", [&](const Request &req, Response &res) {
  12656. res.set_content("test", "text/plain");
  12657. auto cert = req.peer_cert();
  12658. ASSERT_TRUE(static_cast<bool>(cert));
  12659. std::string common_name = cert.subject_cn();
  12660. EXPECT_EQ("Common Name", common_name);
  12661. });
  12662. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12663. auto se = detail::scope_exit([&] {
  12664. svr.stop();
  12665. t.join();
  12666. ASSERT_FALSE(svr.is_running());
  12667. });
  12668. svr.wait_until_ready();
  12669. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12670. client_encrypted_private_key_pass);
  12671. cli.enable_server_certificate_verification(false);
  12672. cli.set_connection_timeout(30);
  12673. auto res = cli.Get("/test");
  12674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12675. ASSERT_EQ(StatusCode::OK_200, res->status);
  12676. }
  12677. TEST(SSLClientServerTest, ClientCertPresent) {
  12678. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12679. }
  12680. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12681. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12682. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12683. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12684. }
  12685. // PEM memory-based constructor tests (works with all TLS backends)
  12686. void PemMemoryClientCertPresent(
  12687. const std::string &client_cert_file,
  12688. const std::string &client_private_key_file,
  12689. const std::string &client_encrypted_private_key_pass = std::string()) {
  12690. // Read PEM files into memory
  12691. std::string server_cert_pem, server_key_pem;
  12692. std::string client_ca_pem;
  12693. std::string client_cert_pem, client_key_pem;
  12694. read_file(SERVER_CERT_FILE, server_cert_pem);
  12695. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12696. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12697. read_file(client_cert_file, client_cert_pem);
  12698. read_file(client_private_key_file, client_key_pem);
  12699. // Create server with PEM memory
  12700. SSLServer::PemMemory server_pem = {
  12701. server_cert_pem.c_str(),
  12702. server_cert_pem.size(),
  12703. server_key_pem.c_str(),
  12704. server_key_pem.size(),
  12705. client_ca_pem.c_str(),
  12706. client_ca_pem.size(),
  12707. nullptr // no password for server key
  12708. };
  12709. SSLServer svr(server_pem);
  12710. ASSERT_TRUE(svr.is_valid());
  12711. svr.Get("/test", [&](const Request &, Response &res) {
  12712. res.set_content("test", "text/plain");
  12713. });
  12714. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12715. auto se = detail::scope_exit([&] {
  12716. svr.stop();
  12717. t.join();
  12718. ASSERT_FALSE(svr.is_running());
  12719. });
  12720. svr.wait_until_ready();
  12721. // Create client with PEM memory
  12722. const char *password = client_encrypted_private_key_pass.empty()
  12723. ? nullptr
  12724. : client_encrypted_private_key_pass.c_str();
  12725. SSLClient::PemMemory client_pem = {
  12726. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12727. client_key_pem.size(), password};
  12728. SSLClient cli(HOST, PORT, client_pem);
  12729. cli.enable_server_certificate_verification(false);
  12730. cli.set_connection_timeout(30);
  12731. auto res = cli.Get("/test");
  12732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12733. ASSERT_EQ(StatusCode::OK_200, res->status);
  12734. }
  12735. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12736. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12737. }
  12738. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12739. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12740. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12741. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12742. }
  12743. TEST(SSLClientServerTest, ClientCertMissing) {
  12744. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12745. CLIENT_CA_CERT_DIR);
  12746. ASSERT_TRUE(svr.is_valid());
  12747. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12748. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12749. auto se = detail::scope_exit([&] {
  12750. svr.stop();
  12751. t.join();
  12752. ASSERT_FALSE(svr.is_running());
  12753. });
  12754. svr.wait_until_ready();
  12755. SSLClient cli(HOST, PORT);
  12756. cli.set_connection_timeout(30);
  12757. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12758. // the chain check on Windows, so the result does not depend on the order.
  12759. cli.enable_server_hostname_verification(false);
  12760. auto res = cli.Get("/test");
  12761. ASSERT_TRUE(!res);
  12762. // When client cert is missing and server requires it, connection fails
  12763. // Error type depends on backend implementation
  12764. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12765. res.error() == Error::SSLConnection);
  12766. // Verify backend error is captured
  12767. // Note: This test may have different error codes depending on the exact
  12768. // verification failure
  12769. EXPECT_NE(0UL, res.ssl_backend_error());
  12770. }
  12771. TEST(SSLClientServerTest, TrustDirOptional) {
  12772. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12773. ASSERT_TRUE(svr.is_valid());
  12774. svr.Get("/test", [&](const Request &, Response &res) {
  12775. res.set_content("test", "text/plain");
  12776. });
  12777. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12778. auto se = detail::scope_exit([&] {
  12779. svr.stop();
  12780. t.join();
  12781. ASSERT_FALSE(svr.is_running());
  12782. });
  12783. svr.wait_until_ready();
  12784. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12785. cli.enable_server_certificate_verification(false);
  12786. cli.set_connection_timeout(30);
  12787. auto res = cli.Get("/test");
  12788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12789. ASSERT_EQ(StatusCode::OK_200, res->status);
  12790. }
  12791. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12792. class NoListenSSLServer : public SSLServer {
  12793. public:
  12794. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12795. const char *client_ca_cert_file_path,
  12796. const char *client_ca_cert_dir_path = nullptr)
  12797. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12798. client_ca_cert_dir_path),
  12799. stop_(false) {}
  12800. std::atomic_bool stop_;
  12801. private:
  12802. bool process_and_close_socket(socket_t /*sock*/) override {
  12803. // Don't create SSL context
  12804. while (!stop_.load()) {
  12805. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12806. }
  12807. return true;
  12808. }
  12809. };
  12810. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12811. CLIENT_CA_CERT_FILE);
  12812. ASSERT_TRUE(svr.is_valid());
  12813. svr.Get("/test", [&](const Request &, Response &res) {
  12814. res.set_content("test", "text/plain");
  12815. });
  12816. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12817. auto se = detail::scope_exit([&] {
  12818. svr.stop_ = true;
  12819. svr.stop();
  12820. t.join();
  12821. ASSERT_FALSE(svr.is_running());
  12822. });
  12823. svr.wait_until_ready();
  12824. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12825. cli.enable_server_certificate_verification(false);
  12826. cli.set_connection_timeout(1);
  12827. auto res = cli.Get("/test");
  12828. ASSERT_TRUE(!res);
  12829. EXPECT_EQ(Error::SSLConnection, res.error());
  12830. // Timeout results in WantRead error code (maps to backend-specific value)
  12831. EXPECT_NE(0, res.ssl_error());
  12832. }
  12833. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12834. // Test SSLServer with client certificate verification using the standard
  12835. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12836. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12837. CLIENT_CA_CERT_DIR);
  12838. ASSERT_TRUE(svr.is_valid());
  12839. svr.Get("/test", [&](const Request &req, Response &res) {
  12840. res.set_content("test", "text/plain");
  12841. auto cert = req.peer_cert();
  12842. ASSERT_TRUE(static_cast<bool>(cert));
  12843. auto common_name = cert.subject_cn();
  12844. EXPECT_EQ("Common Name", common_name);
  12845. });
  12846. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12847. auto se = detail::scope_exit([&] {
  12848. svr.stop();
  12849. t.join();
  12850. ASSERT_FALSE(svr.is_running());
  12851. });
  12852. svr.wait_until_ready();
  12853. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12854. cli.enable_server_certificate_verification(false);
  12855. cli.set_connection_timeout(30);
  12856. auto res = cli.Get("/test");
  12857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12858. ASSERT_EQ(StatusCode::OK_200, res->status);
  12859. }
  12860. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12861. // Verifies that wildcard matching and exact matching work consistently
  12862. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12863. using namespace httplib::tls;
  12864. // We need a running server to test against
  12865. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12866. ASSERT_TRUE(svr.is_valid());
  12867. svr.Get("/test", [](const Request &, Response &res) {
  12868. res.set_content("ok", "text/plain");
  12869. });
  12870. thread t([&]() { svr.listen(HOST, PORT); });
  12871. auto se = detail::scope_exit([&] {
  12872. svr.stop();
  12873. t.join();
  12874. });
  12875. svr.wait_until_ready();
  12876. bool verify_callback_called = false;
  12877. bool verify_result_wrong = false;
  12878. SSLClient cli(HOST, PORT);
  12879. cli.enable_server_certificate_verification(true);
  12880. cli.set_ca_cert_path(CA_CERT_FILE);
  12881. cli.set_connection_timeout(5);
  12882. // Note: Test certificate has CN="Common Name", not "localhost"
  12883. bool verify_result_cn = false;
  12884. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12885. verify_callback_called = true;
  12886. if (!ctx.cert) return false;
  12887. // Test 1: "Common Name" should match (our test server cert CN)
  12888. verify_result_cn = ctx.check_hostname("Common Name");
  12889. // Test 2: wrong hostname should not match
  12890. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12891. return true; // Accept for the purpose of this test
  12892. });
  12893. auto res = cli.Get("/test");
  12894. // The request may succeed or fail depending on cert configuration
  12895. // but the callback should have been called
  12896. ASSERT_TRUE(verify_callback_called)
  12897. << "Verify callback should have been called";
  12898. // CN="Common Name" should match our test certificate
  12899. //
  12900. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12901. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12902. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12903. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12904. // <openssl/base.h>, which is included transitively when
  12905. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12906. #if defined(OPENSSL_IS_BORINGSSL)
  12907. EXPECT_FALSE(verify_result_cn)
  12908. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12909. #else
  12910. EXPECT_TRUE(verify_result_cn)
  12911. << "verify_hostname should match 'Common Name' (certificate CN)";
  12912. #endif
  12913. // Wrong hostname should not match
  12914. EXPECT_FALSE(verify_result_wrong)
  12915. << "verify_hostname should not match 'wronghost.example.com'";
  12916. }
  12917. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12918. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12919. // X509_check_ip behavior and must hold for every backend.
  12920. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12921. using namespace httplib::tls;
  12922. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12923. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12924. ASSERT_TRUE(svr.is_valid());
  12925. svr.Get("/test", [](const Request &, Response &res) {
  12926. res.set_content("ok", "text/plain");
  12927. });
  12928. thread t([&]() { svr.listen(HOST, PORT); });
  12929. auto se = detail::scope_exit([&] {
  12930. svr.stop();
  12931. t.join();
  12932. });
  12933. svr.wait_until_ready();
  12934. bool verify_callback_called = false;
  12935. bool ip_matched_via_cn = true;
  12936. SSLClient cli(HOST, PORT);
  12937. cli.enable_server_certificate_verification(true);
  12938. cli.set_ca_cert_path(CA_CERT_FILE);
  12939. cli.set_connection_timeout(5);
  12940. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12941. verify_callback_called = true;
  12942. if (!ctx.cert) return false;
  12943. // The IP appears only in the CN, so it must NOT be accepted.
  12944. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12945. return true; // Accept for the purpose of this test
  12946. });
  12947. cli.Get("/test");
  12948. ASSERT_TRUE(verify_callback_called)
  12949. << "Verify callback should have been called";
  12950. EXPECT_FALSE(ip_matched_via_cn)
  12951. << "An IP host must not be authenticated via the certificate CN";
  12952. }
  12953. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12954. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12955. using namespace httplib::tls;
  12956. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12957. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12958. ASSERT_TRUE(svr.is_valid());
  12959. svr.Get("/test", [](const Request &, Response &res) {
  12960. res.set_content("ok", "text/plain");
  12961. });
  12962. thread t([&]() { svr.listen(HOST, PORT); });
  12963. auto se = detail::scope_exit([&] {
  12964. svr.stop();
  12965. t.join();
  12966. });
  12967. svr.wait_until_ready();
  12968. bool verify_callback_called = false;
  12969. bool san_matched = false;
  12970. bool wrong_ipv6_matched = true;
  12971. bool cn_ipv6_matched = true;
  12972. SSLClient cli(HOST, PORT);
  12973. cli.enable_server_certificate_verification(true);
  12974. cli.set_ca_cert_path(CA_CERT_FILE);
  12975. cli.set_connection_timeout(5);
  12976. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12977. verify_callback_called = true;
  12978. if (!ctx.cert) return false;
  12979. // Matches the IPv6 iPAddress SAN.
  12980. san_matched = ctx.check_hostname("2001:db8::1");
  12981. // A different IPv6 address must not match.
  12982. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12983. // "::1" lives only in the CN, so it must not be accepted.
  12984. cn_ipv6_matched = ctx.check_hostname("::1");
  12985. return true; // Accept for the purpose of this test
  12986. });
  12987. cli.Get("/test");
  12988. ASSERT_TRUE(verify_callback_called)
  12989. << "Verify callback should have been called";
  12990. EXPECT_TRUE(san_matched)
  12991. << "verify_hostname should match an IPv6 iPAddress SAN";
  12992. EXPECT_FALSE(wrong_ipv6_matched)
  12993. << "verify_hostname should not match a non-matching IPv6 address";
  12994. EXPECT_FALSE(cn_ipv6_matched)
  12995. << "An IPv6 host must not be authenticated via the certificate CN";
  12996. }
  12997. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12998. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12999. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13000. using namespace httplib::tls;
  13001. // SANs: DNS:a.zz, IP:42.46.122.122
  13002. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13003. ASSERT_TRUE(svr.is_valid());
  13004. svr.Get("/test", [](const Request &, Response &res) {
  13005. res.set_content("ok", "text/plain");
  13006. });
  13007. auto port = svr.bind_to_any_port(HOST);
  13008. thread t([&]() { svr.listen_after_bind(); });
  13009. auto se = detail::scope_exit([&] {
  13010. svr.stop();
  13011. t.join();
  13012. });
  13013. svr.wait_until_ready();
  13014. bool verify_callback_called = false;
  13015. bool dns_san_matched = false;
  13016. bool ip_san_matched = false;
  13017. bool ip_matched_via_dns_san = true;
  13018. bool dns_matched_via_ip_san = true;
  13019. SSLClient cli(HOST, port);
  13020. cli.enable_server_certificate_verification(true);
  13021. cli.set_ca_cert_path(CA_CERT_FILE);
  13022. cli.set_connection_timeout(5);
  13023. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13024. verify_callback_called = true;
  13025. if (!ctx.cert) return false;
  13026. dns_san_matched = ctx.check_hostname("a.zz");
  13027. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13028. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13029. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13030. return true; // Accept for the purpose of this test
  13031. });
  13032. cli.Get("/test");
  13033. ASSERT_TRUE(verify_callback_called)
  13034. << "Verify callback should have been called";
  13035. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13036. EXPECT_TRUE(ip_san_matched)
  13037. << "verify_hostname should match an iPAddress SAN";
  13038. EXPECT_FALSE(ip_matched_via_dns_san)
  13039. << "An IP host must not be authenticated via a dNSName SAN";
  13040. EXPECT_FALSE(dns_matched_via_ip_san)
  13041. << "A DNS host must not be authenticated via an iPAddress SAN";
  13042. }
  13043. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13044. // "www.*.example.test" names one host and not every host under example.test.
  13045. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13046. using namespace httplib::tls;
  13047. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13048. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13049. ASSERT_TRUE(svr.is_valid());
  13050. svr.Get("/test", [](const Request &, Response &res) {
  13051. res.set_content("ok", "text/plain");
  13052. });
  13053. auto port = svr.bind_to_any_port(HOST);
  13054. thread t([&]() { svr.listen_after_bind(); });
  13055. auto se = detail::scope_exit([&] {
  13056. svr.stop();
  13057. t.join();
  13058. });
  13059. svr.wait_until_ready();
  13060. bool verify_callback_called = false;
  13061. bool leftmost_wildcard_matched = false;
  13062. bool wildcard_spanned_labels = true;
  13063. bool inner_wildcard_matched = true;
  13064. SSLClient cli(HOST, port);
  13065. cli.enable_server_certificate_verification(true);
  13066. cli.set_ca_cert_path(CA_CERT_FILE);
  13067. cli.set_connection_timeout(5);
  13068. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13069. verify_callback_called = true;
  13070. if (!ctx.cert) return false;
  13071. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13072. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13073. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13074. return true; // Accept for the purpose of this test
  13075. });
  13076. cli.Get("/test");
  13077. ASSERT_TRUE(verify_callback_called)
  13078. << "Verify callback should have been called";
  13079. EXPECT_TRUE(leftmost_wildcard_matched)
  13080. << "A leftmost wildcard should match a single label";
  13081. EXPECT_FALSE(wildcard_spanned_labels)
  13082. << "A wildcard label must not match more than one label";
  13083. EXPECT_FALSE(inner_wildcard_matched)
  13084. << "A wildcard outside the leftmost label must not be honoured";
  13085. }
  13086. // sans() must report each SAN entry under its own type.
  13087. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13088. using namespace httplib::tls;
  13089. // SANs: DNS:a.zz, IP:42.46.122.122
  13090. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13091. ASSERT_TRUE(svr.is_valid());
  13092. svr.Get("/test", [](const Request &, Response &res) {
  13093. res.set_content("ok", "text/plain");
  13094. });
  13095. auto port = svr.bind_to_any_port(HOST);
  13096. thread t([&]() { svr.listen_after_bind(); });
  13097. auto se = detail::scope_exit([&] {
  13098. svr.stop();
  13099. t.join();
  13100. });
  13101. svr.wait_until_ready();
  13102. bool verify_callback_called = false;
  13103. std::vector<SanEntry> sans;
  13104. SSLClient cli(HOST, port);
  13105. cli.enable_server_certificate_verification(true);
  13106. cli.set_ca_cert_path(CA_CERT_FILE);
  13107. cli.set_connection_timeout(5);
  13108. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13109. verify_callback_called = true;
  13110. if (!ctx.cert) return false;
  13111. sans = ctx.sans();
  13112. return true; // Accept for the purpose of this test
  13113. });
  13114. cli.Get("/test");
  13115. ASSERT_TRUE(verify_callback_called)
  13116. << "Verify callback should have been called";
  13117. auto has_san = [&](SanType type, const std::string &value) {
  13118. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13119. return san.type == type && san.value == value;
  13120. });
  13121. };
  13122. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13123. << "sans() should report the dNSName SAN";
  13124. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13125. << "sans() should report the iPAddress SAN";
  13126. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13127. << "sans() must not report the dNSName SAN as an address";
  13128. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13129. << "sans() must not report the iPAddress SAN as a DNS name";
  13130. }
  13131. #endif
  13132. // mbedTLS-specific callback constructor test
  13133. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13134. #ifdef CPPHTTPLIB_SSL_ENABLED
  13135. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13136. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13137. ASSERT_TRUE(svr.is_valid());
  13138. // Set up a handler to verify client certificate is present
  13139. bool client_cert_verified = false;
  13140. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13141. // Verify that client certificate was provided
  13142. client_cert_verified = true;
  13143. res.set_content("success", "text/plain");
  13144. });
  13145. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13146. auto se = detail::scope_exit([&] {
  13147. svr.stop();
  13148. t.join();
  13149. ASSERT_FALSE(svr.is_running());
  13150. });
  13151. svr.wait_until_ready();
  13152. // Client with certificate
  13153. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13154. cli.enable_server_certificate_verification(false);
  13155. cli.set_connection_timeout(30);
  13156. auto res = cli.Get("/test");
  13157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13158. ASSERT_EQ(StatusCode::OK_200, res->status);
  13159. ASSERT_TRUE(client_cert_verified);
  13160. EXPECT_EQ("success", res->body);
  13161. }
  13162. #endif
  13163. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13164. // backends
  13165. #ifdef CPPHTTPLIB_SSL_ENABLED
  13166. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13167. using namespace httplib::tls;
  13168. // Test that when client CA cert file is provided,
  13169. // the server properly requests and validates client certificates
  13170. // Create a server with client authentication
  13171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13172. ASSERT_TRUE(svr.is_valid());
  13173. bool handler_called = false;
  13174. svr.Get("/test", [&](const Request &req, Response &res) {
  13175. handler_called = true;
  13176. // Verify that a client certificate was provided
  13177. auto cert = req.peer_cert();
  13178. ASSERT_TRUE(static_cast<bool>(cert));
  13179. // Get the issuer name
  13180. std::string issuer_str = cert.issuer_name();
  13181. ASSERT_FALSE(issuer_str.empty());
  13182. // The client certificate should be issued by our test CA
  13183. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13184. res.set_content("authenticated", "text/plain");
  13185. });
  13186. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13187. auto se = detail::scope_exit([&] {
  13188. svr.stop();
  13189. t.join();
  13190. ASSERT_FALSE(svr.is_running());
  13191. });
  13192. svr.wait_until_ready();
  13193. // Connect with a client certificate issued by the CA
  13194. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13195. cli.enable_server_certificate_verification(false);
  13196. cli.set_connection_timeout(30);
  13197. auto res = cli.Get("/test");
  13198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13199. ASSERT_EQ(StatusCode::OK_200, res->status);
  13200. ASSERT_TRUE(handler_called);
  13201. EXPECT_EQ("authenticated", res->body);
  13202. }
  13203. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13204. using namespace httplib::tls;
  13205. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13206. ASSERT_TRUE(svr.is_valid());
  13207. svr.Get("/test", [](const Request &, Response &res) {
  13208. res.set_content("ok", "text/plain");
  13209. });
  13210. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13211. auto se = detail::scope_exit([&] {
  13212. svr.stop();
  13213. t.join();
  13214. });
  13215. svr.wait_until_ready();
  13216. SSLClient cli(HOST, PORT);
  13217. cli.enable_server_certificate_verification(false);
  13218. cli.set_connection_timeout(30);
  13219. bool cert_checked = false;
  13220. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13221. if (ctx.cert) {
  13222. auto sans = ctx.sans();
  13223. // Test certificate may or may not have SANs - just verify the API
  13224. // works If SANs exist, verify the types are valid
  13225. for (const auto &san : sans) {
  13226. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13227. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13228. san.type == SanType::OTHER);
  13229. EXPECT_FALSE(san.value.empty());
  13230. }
  13231. cert_checked = true;
  13232. }
  13233. return true;
  13234. });
  13235. auto res = cli.Get("/test");
  13236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13237. EXPECT_TRUE(cert_checked);
  13238. }
  13239. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13240. using namespace httplib::tls;
  13241. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13242. ASSERT_TRUE(svr.is_valid());
  13243. svr.Get("/test", [](const Request &, Response &res) {
  13244. res.set_content("ok", "text/plain");
  13245. });
  13246. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13247. auto se = detail::scope_exit([&] {
  13248. svr.stop();
  13249. t.join();
  13250. });
  13251. svr.wait_until_ready();
  13252. SSLClient cli(HOST, PORT);
  13253. cli.enable_server_certificate_verification(false);
  13254. cli.set_connection_timeout(30);
  13255. bool validity_checked = false;
  13256. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13257. if (ctx.cert) {
  13258. time_t not_before = 0, not_after = 0;
  13259. bool result = ctx.validity(not_before, not_after);
  13260. EXPECT_TRUE(result);
  13261. // Verify that not_before < now < not_after for a valid cert
  13262. time_t now = time(nullptr);
  13263. EXPECT_LT(not_before, now);
  13264. EXPECT_GT(not_after, now);
  13265. validity_checked = true;
  13266. }
  13267. return true;
  13268. });
  13269. auto res = cli.Get("/test");
  13270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13271. EXPECT_TRUE(validity_checked);
  13272. }
  13273. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13274. using namespace httplib::tls;
  13275. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13276. ASSERT_TRUE(svr.is_valid());
  13277. svr.Get("/test", [](const Request &, Response &res) {
  13278. res.set_content("ok", "text/plain");
  13279. });
  13280. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13281. auto se = detail::scope_exit([&] {
  13282. svr.stop();
  13283. t.join();
  13284. });
  13285. svr.wait_until_ready();
  13286. SSLClient cli(HOST, PORT);
  13287. cli.enable_server_certificate_verification(false);
  13288. cli.set_connection_timeout(30);
  13289. bool serial_checked = false;
  13290. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13291. if (ctx.cert) {
  13292. std::string serial = ctx.serial();
  13293. EXPECT_FALSE(serial.empty());
  13294. // Serial should be a hex string
  13295. for (char c : serial) {
  13296. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13297. (c >= 'a' && c <= 'f'));
  13298. }
  13299. serial_checked = true;
  13300. }
  13301. return true;
  13302. });
  13303. auto res = cli.Get("/test");
  13304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13305. EXPECT_TRUE(serial_checked);
  13306. }
  13307. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13308. // Test 1: Valid CA file - no error should be recorded
  13309. {
  13310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13311. CLIENT_CA_CERT_FILE);
  13312. ASSERT_TRUE(svr.is_valid());
  13313. // With valid setup, last_ssl_error should be 0
  13314. EXPECT_EQ(0, svr.ssl_last_error());
  13315. }
  13316. // Test 2: Invalid CA file content
  13317. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13318. {
  13319. // Create a temporary file with completely invalid content
  13320. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13321. {
  13322. std::ofstream ofs(temp_invalid_ca);
  13323. ofs << "This is not a certificate file at all\n";
  13324. ofs << "Just plain text content\n";
  13325. }
  13326. // Create server with invalid CA file
  13327. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13328. // Clean up temporary file
  13329. std::remove(temp_invalid_ca);
  13330. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13331. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13332. // Note: SSL_CTX_load_verify_locations typically fails first,
  13333. // but our error handling code path is still exercised
  13334. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13335. }
  13336. }
  13337. TEST(VerifyCallbackTest, VerifyContextFields) {
  13338. using namespace httplib::tls;
  13339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13340. ASSERT_TRUE(svr.is_valid());
  13341. svr.Get("/test", [](const Request &, Response &res) {
  13342. res.set_content("ok", "text/plain");
  13343. });
  13344. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13345. auto se = detail::scope_exit([&] {
  13346. svr.stop();
  13347. t.join();
  13348. });
  13349. svr.wait_until_ready();
  13350. SSLClient cli(HOST, PORT);
  13351. cli.enable_server_certificate_verification(false);
  13352. cli.set_connection_timeout(30);
  13353. int callback_count = 0;
  13354. bool saw_leaf_cert = false;
  13355. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13356. if (ctx.cert) {
  13357. callback_count++;
  13358. // We should see at least one certificate (the leaf)
  13359. std::string cn = ctx.subject_cn();
  13360. if (!cn.empty()) { saw_leaf_cert = true; }
  13361. // Verify context fields are populated
  13362. EXPECT_NE(ctx.session, nullptr);
  13363. EXPECT_GE(ctx.depth, 0);
  13364. }
  13365. return true;
  13366. });
  13367. auto res = cli.Get("/test");
  13368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13369. EXPECT_GT(callback_count, 0);
  13370. EXPECT_TRUE(saw_leaf_cert);
  13371. }
  13372. // A verifier belongs to the client that set it, not to the thread that set it.
  13373. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13374. using namespace httplib::tls;
  13375. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13376. ASSERT_TRUE(svr.is_valid());
  13377. svr.Get("/test", [](const Request &, Response &res) {
  13378. res.set_content("ok", "text/plain");
  13379. });
  13380. auto port = svr.bind_to_any_port(HOST);
  13381. thread t([&]() { svr.listen_after_bind(); });
  13382. auto se = detail::scope_exit([&] {
  13383. svr.stop();
  13384. t.join();
  13385. });
  13386. svr.wait_until_ready();
  13387. auto rejecting_calls = 0;
  13388. SSLClient rejecting(HOST, port);
  13389. rejecting.enable_server_certificate_verification(false);
  13390. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13391. rejecting_calls++;
  13392. return false;
  13393. });
  13394. auto accepting_calls = 0;
  13395. SSLClient accepting(HOST, port);
  13396. accepting.enable_server_certificate_verification(false);
  13397. // Set on another thread than the requests below.
  13398. thread([&]() {
  13399. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13400. accepting_calls++;
  13401. return true;
  13402. });
  13403. }).join();
  13404. // Requested on another thread than the verifier was set on.
  13405. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13406. EXPECT_GT(rejecting_calls, 0);
  13407. auto res = accepting.Get("/test");
  13408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13409. EXPECT_GT(accepting_calls, 0);
  13410. }
  13411. // VerifyContext::session is the same handle the other tls:: functions take.
  13412. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13413. using namespace httplib::tls;
  13414. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13415. ASSERT_TRUE(svr.is_valid());
  13416. svr.Get("/test", [](const Request &, Response &res) {
  13417. res.set_content("ok", "text/plain");
  13418. });
  13419. auto port = svr.bind_to_any_port(HOST);
  13420. thread t([&]() { svr.listen_after_bind(); });
  13421. auto se = detail::scope_exit([&] {
  13422. svr.stop();
  13423. t.join();
  13424. });
  13425. svr.wait_until_ready();
  13426. SSLClient cli(HOST, port);
  13427. cli.enable_server_certificate_verification(false);
  13428. session_t verifier_session = nullptr;
  13429. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13430. verifier_session = ctx.session;
  13431. return true;
  13432. });
  13433. session_t session_verifier_session = nullptr;
  13434. cli.set_session_verifier([&](session_t session) {
  13435. session_verifier_session = session;
  13436. return SSLVerifierResponse::NoDecisionMade;
  13437. });
  13438. auto res = cli.Get("/test");
  13439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13440. EXPECT_NE(nullptr, verifier_session);
  13441. EXPECT_EQ(session_verifier_session, verifier_session);
  13442. }
  13443. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13444. using httplib::tls::TlsError;
  13445. // Test that verify_error_to_string returns empty for success
  13446. std::string success_str = TlsError::verify_error_to_string(0);
  13447. EXPECT_TRUE(success_str.empty());
  13448. // Test that verify_error_to_string returns non-empty for error codes
  13449. // Using a common error code (certificate expired)
  13450. std::string error_str =
  13451. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13452. EXPECT_FALSE(error_str.empty());
  13453. }
  13454. TEST(SessionVerifierTest, CertificateAccepted) {
  13455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13456. ASSERT_TRUE(svr.is_valid());
  13457. svr.Get("/test", [](const Request &, Response &res) {
  13458. res.set_content("ok", "text/plain");
  13459. });
  13460. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13461. auto se = detail::scope_exit([&] {
  13462. svr.stop();
  13463. t.join();
  13464. });
  13465. svr.wait_until_ready();
  13466. SSLClient cli(HOST, PORT);
  13467. cli.enable_server_certificate_verification(false);
  13468. cli.set_connection_timeout(30);
  13469. bool callback_called = false;
  13470. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13471. EXPECT_NE(session, nullptr);
  13472. callback_called = true;
  13473. return SSLVerifierResponse::CertificateAccepted;
  13474. });
  13475. auto res = cli.Get("/test");
  13476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13477. EXPECT_EQ(200, res->status);
  13478. EXPECT_TRUE(callback_called);
  13479. }
  13480. TEST(SessionVerifierTest, CertificateRejected) {
  13481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13482. ASSERT_TRUE(svr.is_valid());
  13483. svr.Get("/test", [](const Request &, Response &res) {
  13484. res.set_content("ok", "text/plain");
  13485. });
  13486. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13487. auto se = detail::scope_exit([&] {
  13488. svr.stop();
  13489. t.join();
  13490. });
  13491. svr.wait_until_ready();
  13492. SSLClient cli(HOST, PORT);
  13493. cli.enable_server_certificate_verification(false);
  13494. cli.set_connection_timeout(30);
  13495. bool callback_called = false;
  13496. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13497. EXPECT_NE(session, nullptr);
  13498. callback_called = true;
  13499. return SSLVerifierResponse::CertificateRejected;
  13500. });
  13501. auto res = cli.Get("/test");
  13502. EXPECT_FALSE(res);
  13503. EXPECT_TRUE(callback_called);
  13504. }
  13505. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13506. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13507. ASSERT_TRUE(svr.is_valid());
  13508. svr.Get("/test", [](const Request &, Response &res) {
  13509. res.set_content("ok", "text/plain");
  13510. });
  13511. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13512. auto se = detail::scope_exit([&] {
  13513. svr.stop();
  13514. t.join();
  13515. });
  13516. svr.wait_until_ready();
  13517. // NoDecisionMade with verification disabled should succeed (no default check)
  13518. SSLClient cli(HOST, PORT);
  13519. cli.enable_server_certificate_verification(false);
  13520. cli.set_connection_timeout(30);
  13521. bool callback_called = false;
  13522. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13523. EXPECT_NE(session, nullptr);
  13524. callback_called = true;
  13525. return SSLVerifierResponse::NoDecisionMade;
  13526. });
  13527. auto res = cli.Get("/test");
  13528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13529. EXPECT_EQ(200, res->status);
  13530. EXPECT_TRUE(callback_called);
  13531. }
  13532. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13534. ASSERT_TRUE(svr.is_valid());
  13535. svr.Get("/test", [](const Request &, Response &res) {
  13536. res.set_content("ok", "text/plain");
  13537. });
  13538. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13539. auto se = detail::scope_exit([&] {
  13540. svr.stop();
  13541. t.join();
  13542. });
  13543. svr.wait_until_ready();
  13544. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13545. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13546. // so we only check that the request fails, not whether the callback was
  13547. // called.
  13548. SSLClient cli(HOST, PORT);
  13549. cli.enable_server_certificate_verification(true);
  13550. cli.set_connection_timeout(30);
  13551. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13552. EXPECT_NE(session, nullptr);
  13553. return SSLVerifierResponse::NoDecisionMade;
  13554. });
  13555. auto res = cli.Get("/test");
  13556. EXPECT_FALSE(res);
  13557. }
  13558. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13559. // Test SSL server using PemMemory constructor with client CA certificates
  13560. // Read PEM files
  13561. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13562. read_file(SERVER_CERT_FILE, server_cert_pem);
  13563. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13564. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13565. // Create SSLServer with PemMemory constructor including client CA
  13566. SSLServer::PemMemory server_pem = {
  13567. server_cert_pem.c_str(),
  13568. server_cert_pem.size(),
  13569. server_key_pem.c_str(),
  13570. server_key_pem.size(),
  13571. client_ca_pem.c_str(),
  13572. client_ca_pem.size(),
  13573. nullptr // no password for server key
  13574. };
  13575. SSLServer svr(server_pem);
  13576. ASSERT_TRUE(svr.is_valid());
  13577. // No SSL error should be recorded for valid setup
  13578. EXPECT_EQ(0, svr.ssl_last_error());
  13579. // Set up server endpoints
  13580. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13581. res.set_content("ok", "text/plain");
  13582. });
  13583. // Start server in a thread
  13584. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13585. svr.wait_until_ready();
  13586. // Connect with client certificate (using constructor with paths)
  13587. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13588. cli.enable_server_certificate_verification(false);
  13589. auto res = cli.Get("/test-pem-ca");
  13590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13591. EXPECT_EQ(200, res->status);
  13592. EXPECT_EQ("ok", res->body);
  13593. svr.stop();
  13594. server_thread.join();
  13595. }
  13596. #endif
  13597. #ifdef _WIN32
  13598. TEST(CleanupTest, WSACleanup) {
  13599. int ret = WSACleanup();
  13600. ASSERT_EQ(0, ret);
  13601. }
  13602. #endif
  13603. #ifndef CPPHTTPLIB_SSL_ENABLED
  13604. TEST(NoSSLSupport, SimpleInterface) {
  13605. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13606. }
  13607. #endif
  13608. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13609. TEST(InvalidScheme, SimpleInterface) {
  13610. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13611. }
  13612. #endif
  13613. TEST(NoScheme, SimpleInterface) {
  13614. Client cli("yahoo.com:80");
  13615. ASSERT_TRUE(cli.is_valid());
  13616. }
  13617. TEST(SendAPI, SimpleInterface_Online) {
  13618. Client cli("http://yahoo.com");
  13619. Request req;
  13620. req.method = "GET";
  13621. req.path = "/";
  13622. auto res = cli.send(req);
  13623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13624. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13625. }
  13626. TEST(SendAPI, WithParamsInRequest) {
  13627. Server svr;
  13628. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13629. EXPECT_TRUE(req.has_param("test"));
  13630. EXPECT_EQ("test_value", req.get_param_value("test"));
  13631. });
  13632. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13633. auto se = detail::scope_exit([&] {
  13634. svr.stop();
  13635. t.join();
  13636. ASSERT_FALSE(svr.is_running());
  13637. });
  13638. svr.wait_until_ready();
  13639. Client cli(HOST, PORT);
  13640. {
  13641. Request req;
  13642. req.method = "GET";
  13643. req.path = "/";
  13644. req.params.emplace("test", "test_value");
  13645. auto res = cli.send(req);
  13646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13647. }
  13648. {
  13649. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13651. }
  13652. }
  13653. TEST(ClientImplMethods, GetSocketTest) {
  13654. httplib::Server svr;
  13655. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13656. res.status = StatusCode::OK_200;
  13657. });
  13658. auto port = svr.bind_to_any_port("127.0.0.1");
  13659. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13660. auto se = detail::scope_exit([&] {
  13661. svr.stop();
  13662. thread.join();
  13663. ASSERT_FALSE(svr.is_running());
  13664. });
  13665. svr.wait_until_ready();
  13666. {
  13667. httplib::Client cli("127.0.0.1", port);
  13668. cli.set_keep_alive(true);
  13669. // Use the behavior of cpp-httplib of opening the connection
  13670. // only when the first request happens. If that changes,
  13671. // this test would be obsolete.
  13672. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13673. // This also implicitly tests the server. But other tests would fail much
  13674. // earlier than this one to be considered.
  13675. auto res = cli.Get("/");
  13676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13677. EXPECT_EQ(StatusCode::OK_200, res->status);
  13678. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13679. }
  13680. }
  13681. #ifdef CPPHTTPLIB_SSL_ENABLED
  13682. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13683. Client cli("http://yahoo.com");
  13684. auto res = cli.Get("/");
  13685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13686. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13687. cli.set_follow_location(true);
  13688. res = cli.Get("/");
  13689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13690. EXPECT_EQ(StatusCode::OK_200, res->status);
  13691. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13692. }
  13693. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13694. Client cli("https://yahoo.com");
  13695. auto res = cli.Get("/");
  13696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13697. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13698. cli.set_follow_location(true);
  13699. res = cli.Get("/");
  13700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13701. EXPECT_EQ(StatusCode::OK_200, res->status);
  13702. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13703. }
  13704. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13705. Client cli("https://yahoo.com");
  13706. auto res = cli.Get("/");
  13707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13708. ASSERT_FALSE(!res);
  13709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13710. ASSERT_FALSE(res == nullptr);
  13711. ASSERT_TRUE(res != nullptr);
  13712. EXPECT_EQ(Error::Success, res.error());
  13713. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13714. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13715. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13716. cli.set_follow_location(true);
  13717. res = cli.Get("/");
  13718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13719. EXPECT_EQ(Error::Success, res.error());
  13720. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13721. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13722. EXPECT_EQ(StatusCode::OK_200, res->status);
  13723. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13724. }
  13725. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13726. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13727. Client cli("https://cdnjs.cloudflare.com");
  13728. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13729. Headers{{"Accept-Encoding", "br"}});
  13730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13731. EXPECT_EQ(StatusCode::OK_200, res->status);
  13732. EXPECT_EQ(287630U, res->body.size());
  13733. EXPECT_EQ("application/javascript; charset=utf-8",
  13734. res->get_header_value("Content-Type"));
  13735. }
  13736. #endif
  13737. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13738. #undef REDIR_HOST // Silence compiler warning
  13739. #define REDIR_HOST "https://httpbingo.org"
  13740. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13741. Client cli(REDIR_HOST);
  13742. cli.set_follow_location(true);
  13743. auto res =
  13744. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13746. EXPECT_EQ(StatusCode::OK_200, res->status);
  13747. }
  13748. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13749. Client cli(REDIR_HOST);
  13750. cli.set_follow_location(true);
  13751. Params params;
  13752. params.emplace("url", "http://example.com");
  13753. params.emplace("status_code", "302");
  13754. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13756. EXPECT_EQ(StatusCode::OK_200, res->status);
  13757. }
  13758. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13759. Client cli(REDIR_HOST);
  13760. cli.set_follow_location(true);
  13761. Params params;
  13762. params.emplace("url", "http://example.com");
  13763. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13765. EXPECT_EQ(StatusCode::OK_200, res->status);
  13766. }
  13767. TEST(HttpToHttpsRedirectTest, CertFile) {
  13768. auto ssl_port = PORT + 1;
  13769. Server svr;
  13770. ASSERT_TRUE(svr.is_valid());
  13771. svr.Get("/index", [&](const Request &, Response &res) {
  13772. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13773. "/index");
  13774. svr.stop();
  13775. });
  13776. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13777. ASSERT_TRUE(ssl_svr.is_valid());
  13778. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13779. res.set_content("test", "text/plain");
  13780. ssl_svr.stop();
  13781. });
  13782. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13783. thread t2 =
  13784. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13785. auto se = detail::scope_exit([&] {
  13786. t2.join();
  13787. t.join();
  13788. ASSERT_FALSE(svr.is_running());
  13789. });
  13790. svr.wait_until_ready();
  13791. ssl_svr.wait_until_ready();
  13792. Client cli("127.0.0.1", PORT);
  13793. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13794. cli.enable_server_certificate_verification(true);
  13795. cli.set_follow_location(true);
  13796. cli.set_connection_timeout(30);
  13797. auto res = cli.Get("/index");
  13798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13799. ASSERT_EQ(StatusCode::OK_200, res->status);
  13800. }
  13801. TEST(SSLClientRedirectTest, CertFile) {
  13802. auto ssl_port = PORT + 1;
  13803. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13804. ASSERT_TRUE(ssl_svr1.is_valid());
  13805. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13806. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13807. "/index");
  13808. ssl_svr1.stop();
  13809. });
  13810. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13811. ASSERT_TRUE(ssl_svr2.is_valid());
  13812. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13813. res.set_content("test", "text/plain");
  13814. ssl_svr2.stop();
  13815. });
  13816. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13817. thread t2 =
  13818. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13819. auto se = detail::scope_exit([&] {
  13820. t2.join();
  13821. t.join();
  13822. ASSERT_FALSE(ssl_svr1.is_running());
  13823. });
  13824. ssl_svr1.wait_until_ready();
  13825. ssl_svr2.wait_until_ready();
  13826. SSLClient cli("127.0.0.1", PORT);
  13827. std::string cert;
  13828. read_file(SERVER_CERT2_FILE, cert);
  13829. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13830. cli.enable_server_certificate_verification(true);
  13831. cli.set_follow_location(true);
  13832. cli.set_connection_timeout(30);
  13833. auto res = cli.Get("/index");
  13834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13835. ASSERT_EQ(StatusCode::OK_200, res->status);
  13836. }
  13837. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  13838. // another port, so the client follows it with a new client.
  13839. static Result GetThroughTlsRedirectToDifferentPort(
  13840. const std::function<void(SSLClient &)> &setup,
  13841. const char *target_cert = SERVER_CERT2_FILE) {
  13842. auto ssl_port = PORT + 1;
  13843. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13844. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13845. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13846. "/index");
  13847. });
  13848. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  13849. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13850. res.set_content("test", "text/plain");
  13851. });
  13852. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  13853. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  13854. auto se = detail::scope_exit([&] {
  13855. ssl_svr2.stop();
  13856. ssl_svr1.stop();
  13857. t2.join();
  13858. t.join();
  13859. });
  13860. ssl_svr1.wait_until_ready();
  13861. ssl_svr2.wait_until_ready();
  13862. SSLClient cli("127.0.0.1", PORT);
  13863. cli.set_follow_location(true);
  13864. cli.set_connection_timeout(30);
  13865. setup(cli);
  13866. return cli.Get("/index");
  13867. }
  13868. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  13869. auto calls = 0;
  13870. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  13871. cli.enable_server_certificate_verification(false);
  13872. // Accept the first server only.
  13873. cli.set_session_verifier([&](tls::session_t) {
  13874. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  13875. : SSLVerifierResponse::CertificateRejected;
  13876. });
  13877. });
  13878. EXPECT_FALSE(res);
  13879. EXPECT_EQ(2, calls);
  13880. }
  13881. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  13882. std::string pinned;
  13883. auto res = GetThroughTlsRedirectToDifferentPort(
  13884. [&](SSLClient &cli) {
  13885. cli.enable_server_certificate_verification(false);
  13886. // Pin the first certificate seen.
  13887. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  13888. if (pinned.empty()) { pinned = ctx.serial(); }
  13889. return ctx.serial() == pinned;
  13890. });
  13891. },
  13892. // A certificate other than the first server's.
  13893. SERVER_CERT_FILE);
  13894. EXPECT_FALSE(res);
  13895. EXPECT_FALSE(pinned.empty());
  13896. }
  13897. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  13898. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  13899. std::string cert;
  13900. read_file(SERVER_CERT2_FILE, cert);
  13901. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13902. });
  13903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13904. EXPECT_EQ(StatusCode::OK_200, res->status);
  13905. }
  13906. #endif
  13907. #ifdef CPPHTTPLIB_SSL_ENABLED
  13908. // Test that set_ca_cert_store() skips system certs (consistent with
  13909. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13910. // should be trusted - system certs should NOT be loaded.
  13911. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13912. // Load a specific cert that is NOT a system CA cert
  13913. std::string cert;
  13914. read_file(SERVER_CERT2_FILE, cert);
  13915. SSLClient cli("google.com");
  13916. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13917. cli.enable_server_certificate_verification(true);
  13918. // This should FAIL because:
  13919. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13920. // 2. System certs should NOT be loaded when custom store is set
  13921. // If system certs WERE loaded, this would succeed
  13922. auto res = cli.Get("/");
  13923. ASSERT_FALSE(res);
  13924. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13925. }
  13926. // Same as above, but through the native store handle path. Regression test:
  13927. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13928. // merged system certs into the user-provided store.
  13929. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13930. std::string cert;
  13931. read_file(SERVER_CERT2_FILE, cert);
  13932. SSLClient cli("google.com");
  13933. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13934. cli.enable_server_certificate_verification(true);
  13935. auto res = cli.Get("/");
  13936. ASSERT_FALSE(res);
  13937. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13938. }
  13939. // A custom store set via the native handle must still verify a server whose
  13940. // cert it does contain.
  13941. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13942. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13943. ASSERT_TRUE(svr.is_valid());
  13944. svr.Get("/test", [&](const Request &, Response &res) {
  13945. res.set_content("test", "text/plain");
  13946. });
  13947. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13948. auto se = detail::scope_exit([&] {
  13949. svr.stop();
  13950. t.join();
  13951. ASSERT_FALSE(svr.is_running());
  13952. });
  13953. svr.wait_until_ready();
  13954. SSLClient cli("127.0.0.1", PORT);
  13955. std::string cert;
  13956. read_file(SERVER_CERT2_FILE, cert);
  13957. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13958. cli.enable_server_certificate_verification(true);
  13959. cli.set_connection_timeout(30);
  13960. auto res = cli.Get("/test");
  13961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13962. ASSERT_EQ(StatusCode::OK_200, res->status);
  13963. }
  13964. // CA certs loaded through the universal Client must be transferred to the
  13965. // client created internally for following an HTTPS redirect. Regression test:
  13966. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13967. // the CA data for redirect transfer.
  13968. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13969. auto ssl_port = PORT + 1;
  13970. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13971. ASSERT_TRUE(ssl_svr1.is_valid());
  13972. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13973. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13974. "/index");
  13975. });
  13976. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13977. ASSERT_TRUE(ssl_svr2.is_valid());
  13978. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13979. res.set_content("test", "text/plain");
  13980. });
  13981. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13982. thread t2 =
  13983. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13984. auto se = detail::scope_exit([&] {
  13985. ssl_svr2.stop();
  13986. ssl_svr1.stop();
  13987. t2.join();
  13988. t.join();
  13989. ASSERT_FALSE(ssl_svr1.is_running());
  13990. });
  13991. ssl_svr1.wait_until_ready();
  13992. ssl_svr2.wait_until_ready();
  13993. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13994. std::string cert;
  13995. read_file(SERVER_CERT2_FILE, cert);
  13996. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13997. cli.enable_server_certificate_verification(true);
  13998. cli.set_follow_location(true);
  13999. cli.set_connection_timeout(30);
  14000. auto res = cli.Get("/index");
  14001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14002. ASSERT_EQ(StatusCode::OK_200, res->status);
  14003. }
  14004. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14005. // so a host signed by a system CA verifies even though a custom CA is set
  14006. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14007. std::string cert;
  14008. read_file(SERVER_CERT2_FILE, cert);
  14009. SSLClient cli("google.com");
  14010. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14011. cli.enable_system_ca(true);
  14012. cli.enable_server_certificate_verification(true);
  14013. auto res = cli.Get("/");
  14014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14015. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14016. }
  14017. // The custom CA remains effective when combined with the system CA
  14018. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14019. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14020. ASSERT_TRUE(svr.is_valid());
  14021. svr.Get("/test", [&](const Request &, Response &res) {
  14022. res.set_content("test", "text/plain");
  14023. });
  14024. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14025. auto se = detail::scope_exit([&] {
  14026. svr.stop();
  14027. t.join();
  14028. ASSERT_FALSE(svr.is_running());
  14029. });
  14030. svr.wait_until_ready();
  14031. SSLClient cli("127.0.0.1", PORT);
  14032. std::string cert;
  14033. read_file(SERVER_CERT2_FILE, cert);
  14034. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14035. cli.enable_system_ca(true);
  14036. cli.enable_server_certificate_verification(true);
  14037. cli.set_connection_timeout(30);
  14038. auto res = cli.Get("/test");
  14039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14040. ASSERT_EQ(StatusCode::OK_200, res->status);
  14041. }
  14042. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14043. // skip chain verification entirely (only the certificate identity was
  14044. // checked), so a server presenting an untrusted certificate with a matching
  14045. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14046. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14047. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14048. ASSERT_TRUE(svr.is_valid());
  14049. svr.Get("/test", [&](const Request &, Response &res) {
  14050. res.set_content("test", "text/plain");
  14051. });
  14052. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14053. auto se = detail::scope_exit([&] {
  14054. svr.stop();
  14055. t.join();
  14056. ASSERT_FALSE(svr.is_running());
  14057. });
  14058. svr.wait_until_ready();
  14059. SSLClient cli("127.0.0.1", PORT);
  14060. std::string cert;
  14061. // A trusted CA that did not sign the server certificate. The server cert
  14062. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14063. // this connection.
  14064. read_file(CLIENT_CA_CERT_FILE, cert);
  14065. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14066. cli.enable_server_certificate_verification(true);
  14067. cli.set_connection_timeout(30);
  14068. auto res = cli.Get("/test");
  14069. ASSERT_FALSE(res);
  14070. }
  14071. // enable_system_ca(false) prevents system CA loading entirely
  14072. TEST(SSLClientTest, DisableSystemCa_Online) {
  14073. SSLClient cli("google.com");
  14074. cli.enable_system_ca(false);
  14075. cli.enable_server_certificate_verification(true);
  14076. auto res = cli.Get("/");
  14077. ASSERT_FALSE(res);
  14078. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14079. // itself when the CA chain is empty
  14080. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14081. res.error() == Error::SSLConnection);
  14082. }
  14083. // The universal Client forwards enable_system_ca()
  14084. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14085. std::string cert;
  14086. read_file(SERVER_CERT2_FILE, cert);
  14087. Client cli("https://google.com");
  14088. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14089. cli.enable_system_ca(true);
  14090. cli.enable_server_certificate_verification(true);
  14091. auto res = cli.Get("/");
  14092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14093. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14094. }
  14095. // The system CA policy must carry over to the client created internally for
  14096. // following a cross-host HTTPS redirect
  14097. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14098. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14099. ASSERT_TRUE(svr.is_valid());
  14100. svr.Get("/index", [&](const Request &, Response &res) {
  14101. res.set_redirect("https://www.google.com/");
  14102. });
  14103. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14104. auto se = detail::scope_exit([&] {
  14105. svr.stop();
  14106. t.join();
  14107. ASSERT_FALSE(svr.is_running());
  14108. });
  14109. svr.wait_until_ready();
  14110. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14111. std::string cert;
  14112. read_file(SERVER_CERT2_FILE, cert);
  14113. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14114. cli.enable_system_ca(true);
  14115. cli.enable_server_certificate_verification(true);
  14116. cli.set_follow_location(true);
  14117. cli.set_connection_timeout(30);
  14118. // Receiving any response proves the redirect client completed the TLS
  14119. // handshake with a system-CA-signed host
  14120. auto res = cli.Get("/index");
  14121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14122. }
  14123. TEST(MultipartFormDataTest, LargeData) {
  14124. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14125. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14126. const ContentReader &content_reader) {
  14127. if (req.is_multipart_form_data()) {
  14128. std::vector<FormData> items;
  14129. content_reader(
  14130. [&](const FormData &file) {
  14131. items.push_back(file);
  14132. return true;
  14133. },
  14134. [&](const char *data, size_t data_length) {
  14135. items.back().content.append(data, data_length);
  14136. return true;
  14137. });
  14138. EXPECT_TRUE(std::string(items[0].name) == "document");
  14139. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14140. EXPECT_TRUE(items[0].filename == "2MB_data");
  14141. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14142. EXPECT_TRUE(items[1].name == "hello");
  14143. EXPECT_TRUE(items[1].content == "world");
  14144. EXPECT_TRUE(items[1].filename == "");
  14145. EXPECT_TRUE(items[1].content_type == "");
  14146. } else {
  14147. std::string body;
  14148. content_reader([&](const char *data, size_t data_length) {
  14149. body.append(data, data_length);
  14150. return true;
  14151. });
  14152. }
  14153. });
  14154. auto port = svr.bind_to_any_port(HOST);
  14155. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14156. auto se = detail::scope_exit([&] {
  14157. svr.stop();
  14158. t.join();
  14159. ASSERT_FALSE(svr.is_running());
  14160. });
  14161. svr.wait_until_ready();
  14162. {
  14163. std::string data(1024 * 1024 * 2, '.');
  14164. std::stringstream buffer;
  14165. buffer << data;
  14166. SSLClient cli(HOST, port);
  14167. cli.enable_server_certificate_verification(false);
  14168. UploadFormDataItems items{
  14169. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14170. {"hello", "world", "", ""},
  14171. };
  14172. auto res = cli.Post("/post", items);
  14173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14174. ASSERT_EQ(StatusCode::OK_200, res->status);
  14175. }
  14176. }
  14177. TEST(MultipartFormDataTest, DataProviderItems) {
  14178. std::random_device seed_gen;
  14179. std::mt19937 random(seed_gen());
  14180. std::string rand1;
  14181. rand1.resize(1000);
  14182. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14183. std::string rand2;
  14184. rand2.resize(3000);
  14185. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14186. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14187. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14188. const ContentReader &content_reader) {
  14189. ASSERT_FALSE(req.is_multipart_form_data());
  14190. std::string body;
  14191. content_reader([&](const char *data, size_t data_length) {
  14192. body.append(data, data_length);
  14193. return true;
  14194. });
  14195. EXPECT_EQ(body, "");
  14196. });
  14197. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14198. const ContentReader &content_reader) {
  14199. ASSERT_TRUE(req.is_multipart_form_data());
  14200. std::vector<FormData> items;
  14201. content_reader(
  14202. [&](const FormData &file) {
  14203. items.push_back(file);
  14204. return true;
  14205. },
  14206. [&](const char *data, size_t data_length) {
  14207. items.back().content.append(data, data_length);
  14208. return true;
  14209. });
  14210. ASSERT_TRUE(items.size() == 2);
  14211. EXPECT_EQ(std::string(items[0].name), "name1");
  14212. EXPECT_EQ(items[0].content, "Testing123");
  14213. EXPECT_EQ(items[0].filename, "filename1");
  14214. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14215. EXPECT_EQ(items[1].name, "name2");
  14216. EXPECT_EQ(items[1].content, "Testing456");
  14217. EXPECT_EQ(items[1].filename, "");
  14218. EXPECT_EQ(items[1].content_type, "");
  14219. });
  14220. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14221. const ContentReader &content_reader) {
  14222. ASSERT_TRUE(req.is_multipart_form_data());
  14223. std::vector<FormData> items;
  14224. content_reader(
  14225. [&](const FormData &file) {
  14226. items.push_back(file);
  14227. return true;
  14228. },
  14229. [&](const char *data, size_t data_length) {
  14230. items.back().content.append(data, data_length);
  14231. return true;
  14232. });
  14233. ASSERT_TRUE(items.size() == 2);
  14234. EXPECT_EQ(items[0].name, "name3");
  14235. EXPECT_EQ(items[0].content, rand1);
  14236. EXPECT_EQ(items[0].filename, "filename3");
  14237. EXPECT_EQ(items[0].content_type, "");
  14238. EXPECT_EQ(items[1].name, "name4");
  14239. EXPECT_EQ(items[1].content, rand2);
  14240. EXPECT_EQ(items[1].filename, "filename4");
  14241. EXPECT_EQ(items[1].content_type, "");
  14242. });
  14243. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14244. const ContentReader &content_reader) {
  14245. ASSERT_TRUE(req.is_multipart_form_data());
  14246. std::vector<FormData> items;
  14247. content_reader(
  14248. [&](const FormData &file) {
  14249. items.push_back(file);
  14250. return true;
  14251. },
  14252. [&](const char *data, size_t data_length) {
  14253. items.back().content.append(data, data_length);
  14254. return true;
  14255. });
  14256. ASSERT_TRUE(items.size() == 4);
  14257. EXPECT_EQ(std::string(items[0].name), "name1");
  14258. EXPECT_EQ(items[0].content, "Testing123");
  14259. EXPECT_EQ(items[0].filename, "filename1");
  14260. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14261. EXPECT_EQ(items[1].name, "name2");
  14262. EXPECT_EQ(items[1].content, "Testing456");
  14263. EXPECT_EQ(items[1].filename, "");
  14264. EXPECT_EQ(items[1].content_type, "");
  14265. EXPECT_EQ(items[2].name, "name3");
  14266. EXPECT_EQ(items[2].content, rand1);
  14267. EXPECT_EQ(items[2].filename, "filename3");
  14268. EXPECT_EQ(items[2].content_type, "");
  14269. EXPECT_EQ(items[3].name, "name4");
  14270. EXPECT_EQ(items[3].content, rand2);
  14271. EXPECT_EQ(items[3].filename, "filename4");
  14272. EXPECT_EQ(items[3].content_type, "");
  14273. });
  14274. auto port = svr.bind_to_any_port("localhost");
  14275. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14276. auto se = detail::scope_exit([&] {
  14277. svr.stop();
  14278. t.join();
  14279. ASSERT_FALSE(svr.is_running());
  14280. });
  14281. svr.wait_until_ready();
  14282. {
  14283. SSLClient cli("localhost", port);
  14284. cli.enable_server_certificate_verification(false);
  14285. UploadFormDataItems items{
  14286. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14287. {"name2", "Testing456", "", ""}, // not a file
  14288. };
  14289. {
  14290. auto res = cli.Post("/post-none", {}, {}, {});
  14291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14292. ASSERT_EQ(StatusCode::OK_200, res->status);
  14293. }
  14294. FormDataProviderItems providers;
  14295. {
  14296. auto res =
  14297. cli.Post("/post-items", {}, items, providers); // empty providers
  14298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14299. ASSERT_EQ(StatusCode::OK_200, res->status);
  14300. }
  14301. providers.push_back({"name3",
  14302. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14303. // test the offset is given correctly at each step
  14304. if (!offset)
  14305. sink.os.write(rand1.data(), 30);
  14306. else if (offset == 30)
  14307. sink.os.write(rand1.data() + 30, 300);
  14308. else if (offset == 330)
  14309. sink.os.write(rand1.data() + 330, 670);
  14310. else if (offset == rand1.size())
  14311. sink.done();
  14312. return true;
  14313. },
  14314. "filename3",
  14315. {}});
  14316. providers.push_back({"name4",
  14317. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14318. // test the offset is given correctly at each step
  14319. if (!offset)
  14320. sink.os.write(rand2.data(), 2000);
  14321. else if (offset == 2000)
  14322. sink.os.write(rand2.data() + 2000, 1);
  14323. else if (offset == 2001)
  14324. sink.os.write(rand2.data() + 2001, 999);
  14325. else if (offset == rand2.size())
  14326. sink.done();
  14327. return true;
  14328. },
  14329. "filename4",
  14330. {}});
  14331. {
  14332. auto res = cli.Post("/post-providers", {}, {}, providers);
  14333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14334. ASSERT_EQ(StatusCode::OK_200, res->status);
  14335. }
  14336. {
  14337. auto res = cli.Post("/post-both", {}, items, providers);
  14338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14339. ASSERT_EQ(StatusCode::OK_200, res->status);
  14340. }
  14341. }
  14342. }
  14343. TEST(MultipartFormDataTest, BadHeader) {
  14344. Server svr;
  14345. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14346. res.set_content("ok", "text/plain");
  14347. });
  14348. thread t = thread([&] { svr.listen(HOST, PORT); });
  14349. auto se = detail::scope_exit([&] {
  14350. svr.stop();
  14351. t.join();
  14352. ASSERT_FALSE(svr.is_running());
  14353. });
  14354. svr.wait_until_ready();
  14355. const std::string body =
  14356. "This is the preamble. It is to be ignored, though it\r\n"
  14357. "is a handy place for composition agents to include an\r\n"
  14358. "explanatory note to non-MIME conformant readers.\r\n"
  14359. "\r\n"
  14360. "\r\n"
  14361. "--simple boundary\r\n"
  14362. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14363. ": BAD...\r\n"
  14364. "\r\n"
  14365. "value1\r\n"
  14366. "--simple boundary\r\n"
  14367. "Content-Disposition: form-data; name=\"field2\"; "
  14368. "filename=\"example.txt\"\r\n"
  14369. "\r\n"
  14370. "value2\r\n"
  14371. "--simple boundary--\r\n"
  14372. "This is the epilogue. It is also to be ignored.\r\n";
  14373. std::string content_type =
  14374. R"(multipart/form-data; boundary="simple boundary")";
  14375. Client cli(HOST, PORT);
  14376. auto res = cli.Post("/post", body, content_type.c_str());
  14377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14378. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14379. }
  14380. TEST(MultipartFormDataTest, WithPreamble) {
  14381. Server svr;
  14382. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14383. res.set_content("ok", "text/plain");
  14384. });
  14385. thread t = thread([&] { svr.listen(HOST, PORT); });
  14386. auto se = detail::scope_exit([&] {
  14387. svr.stop();
  14388. t.join();
  14389. ASSERT_FALSE(svr.is_running());
  14390. });
  14391. svr.wait_until_ready();
  14392. const std::string body =
  14393. "This is the preamble. It is to be ignored, though it\r\n"
  14394. "is a handy place for composition agents to include an\r\n"
  14395. "explanatory note to non-MIME conformant readers.\r\n"
  14396. "\r\n"
  14397. "\r\n"
  14398. "--simple boundary\r\n"
  14399. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14400. "\r\n"
  14401. "value1\r\n"
  14402. "--simple boundary\r\n"
  14403. "Content-Disposition: form-data; name=\"field2\"; "
  14404. "filename=\"example.txt\"\r\n"
  14405. "\r\n"
  14406. "value2\r\n"
  14407. "--simple boundary--\r\n"
  14408. "This is the epilogue. It is also to be ignored.\r\n";
  14409. std::string content_type =
  14410. R"(multipart/form-data; boundary="simple boundary")";
  14411. Client cli(HOST, PORT);
  14412. auto res = cli.Post("/post", body, content_type.c_str());
  14413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14414. EXPECT_EQ(StatusCode::OK_200, res->status);
  14415. }
  14416. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14417. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14418. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14419. const ContentReader &content_reader) {
  14420. if (req.is_multipart_form_data()) {
  14421. std::vector<FormData> items;
  14422. content_reader(
  14423. [&](const FormData &file) {
  14424. items.push_back(file);
  14425. return true;
  14426. },
  14427. [&](const char *data, size_t data_length) {
  14428. items.back().content.append(data, data_length);
  14429. return true;
  14430. });
  14431. EXPECT_TRUE(std::string(items[0].name) == "document");
  14432. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14433. EXPECT_TRUE(items[0].filename == "2MB_data");
  14434. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14435. EXPECT_TRUE(items[1].name == "hello");
  14436. EXPECT_TRUE(items[1].content == "world");
  14437. EXPECT_TRUE(items[1].filename == "");
  14438. EXPECT_TRUE(items[1].content_type == "");
  14439. } else {
  14440. std::string body;
  14441. content_reader([&](const char *data, size_t data_length) {
  14442. body.append(data, data_length);
  14443. return true;
  14444. });
  14445. }
  14446. });
  14447. auto port = svr.bind_to_any_port("localhost");
  14448. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14449. auto se = detail::scope_exit([&] {
  14450. svr.stop();
  14451. t.join();
  14452. ASSERT_FALSE(svr.is_running());
  14453. });
  14454. svr.wait_until_ready();
  14455. {
  14456. std::string data(1024 * 1024 * 2, '.');
  14457. std::stringstream buffer;
  14458. buffer << data;
  14459. SSLClient cli("localhost", port);
  14460. cli.enable_server_certificate_verification(false);
  14461. UploadFormDataItems items{
  14462. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14463. {"hello", "world", "", ""},
  14464. };
  14465. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14467. ASSERT_EQ(StatusCode::OK_200, res->status);
  14468. }
  14469. }
  14470. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14471. std::string data(1024 * 1024 * 2, '&');
  14472. std::stringstream buffer;
  14473. buffer << data;
  14474. Client cli("https://localhost:8080");
  14475. UploadFormDataItems items{
  14476. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14477. {"hello", "world", "", ""},
  14478. };
  14479. for (const char &c : " \t\r\n") {
  14480. auto res =
  14481. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14482. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14483. ASSERT_FALSE(res);
  14484. }
  14485. }
  14486. TEST(MultipartFormDataTest, PutFormData) {
  14487. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14488. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14489. const ContentReader &content_reader) {
  14490. if (req.is_multipart_form_data()) {
  14491. std::vector<FormData> items;
  14492. content_reader(
  14493. [&](const FormData &file) {
  14494. items.push_back(file);
  14495. return true;
  14496. },
  14497. [&](const char *data, size_t data_length) {
  14498. items.back().content.append(data, data_length);
  14499. return true;
  14500. });
  14501. EXPECT_TRUE(std::string(items[0].name) == "document");
  14502. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14503. EXPECT_TRUE(items[0].filename == "2MB_data");
  14504. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14505. EXPECT_TRUE(items[1].name == "hello");
  14506. EXPECT_TRUE(items[1].content == "world");
  14507. EXPECT_TRUE(items[1].filename == "");
  14508. EXPECT_TRUE(items[1].content_type == "");
  14509. } else {
  14510. std::string body;
  14511. content_reader([&](const char *data, size_t data_length) {
  14512. body.append(data, data_length);
  14513. return true;
  14514. });
  14515. }
  14516. });
  14517. auto port = svr.bind_to_any_port("localhost");
  14518. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14519. auto se = detail::scope_exit([&] {
  14520. svr.stop();
  14521. t.join();
  14522. ASSERT_FALSE(svr.is_running());
  14523. });
  14524. svr.wait_until_ready();
  14525. {
  14526. std::string data(1024 * 1024 * 2, '&');
  14527. std::stringstream buffer;
  14528. buffer << data;
  14529. SSLClient cli("localhost", port);
  14530. cli.enable_server_certificate_verification(false);
  14531. UploadFormDataItems items{
  14532. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14533. {"hello", "world", "", ""},
  14534. };
  14535. auto res = cli.Put("/put", items);
  14536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14537. ASSERT_EQ(StatusCode::OK_200, res->status);
  14538. }
  14539. }
  14540. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14542. svr.Put("/put_customboundary",
  14543. [&](const Request &req, const Response & /*res*/,
  14544. const ContentReader &content_reader) {
  14545. if (req.is_multipart_form_data()) {
  14546. std::vector<FormData> items;
  14547. content_reader(
  14548. [&](const FormData &file) {
  14549. items.push_back(file);
  14550. return true;
  14551. },
  14552. [&](const char *data, size_t data_length) {
  14553. items.back().content.append(data, data_length);
  14554. return true;
  14555. });
  14556. EXPECT_TRUE(std::string(items[0].name) == "document");
  14557. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14558. EXPECT_TRUE(items[0].filename == "2MB_data");
  14559. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14560. EXPECT_TRUE(items[1].name == "hello");
  14561. EXPECT_TRUE(items[1].content == "world");
  14562. EXPECT_TRUE(items[1].filename == "");
  14563. EXPECT_TRUE(items[1].content_type == "");
  14564. } else {
  14565. std::string body;
  14566. content_reader([&](const char *data, size_t data_length) {
  14567. body.append(data, data_length);
  14568. return true;
  14569. });
  14570. }
  14571. });
  14572. auto port = svr.bind_to_any_port("localhost");
  14573. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14574. auto se = detail::scope_exit([&] {
  14575. svr.stop();
  14576. t.join();
  14577. ASSERT_FALSE(svr.is_running());
  14578. });
  14579. svr.wait_until_ready();
  14580. {
  14581. std::string data(1024 * 1024 * 2, '&');
  14582. std::stringstream buffer;
  14583. buffer << data;
  14584. SSLClient cli("localhost", port);
  14585. cli.enable_server_certificate_verification(false);
  14586. UploadFormDataItems items{
  14587. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14588. {"hello", "world", "", ""},
  14589. };
  14590. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14592. ASSERT_EQ(StatusCode::OK_200, res->status);
  14593. }
  14594. }
  14595. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14596. std::string data(1024 * 1024 * 2, '&');
  14597. std::stringstream buffer;
  14598. buffer << data;
  14599. Client cli("https://localhost:8080");
  14600. cli.enable_server_certificate_verification(false);
  14601. UploadFormDataItems items{
  14602. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14603. {"hello", "world", "", ""},
  14604. };
  14605. for (const char &c : " \t\r\n") {
  14606. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14607. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14608. ASSERT_FALSE(res);
  14609. }
  14610. }
  14611. TEST(MultipartFormDataTest, AlternateFilename) {
  14612. auto handled = false;
  14613. Server svr;
  14614. svr.Post("/test", [&](const Request &req, Response &res) {
  14615. ASSERT_EQ(2u, req.form.files.size());
  14616. ASSERT_EQ(1u, req.form.fields.size());
  14617. // Test files
  14618. const auto &file1 = req.form.get_file("file1");
  14619. ASSERT_EQ("file1", file1.name);
  14620. ASSERT_EQ("A.txt", file1.filename);
  14621. ASSERT_EQ("text/plain", file1.content_type);
  14622. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14623. const auto &file2 = req.form.get_file("file2");
  14624. ASSERT_EQ("file2", file2.name);
  14625. ASSERT_EQ("a.html", file2.filename);
  14626. ASSERT_EQ("text/html", file2.content_type);
  14627. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14628. file2.content);
  14629. // Test text field
  14630. const auto &text = req.form.get_field("text");
  14631. ASSERT_EQ("text default", text);
  14632. res.set_content("ok", "text/plain");
  14633. handled = true;
  14634. });
  14635. thread t = thread([&] { svr.listen(HOST, PORT); });
  14636. auto se = detail::scope_exit([&] {
  14637. svr.stop();
  14638. t.join();
  14639. ASSERT_FALSE(svr.is_running());
  14640. ASSERT_TRUE(handled);
  14641. });
  14642. svr.wait_until_ready();
  14643. auto req = "POST /test HTTP/1.1\r\n"
  14644. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14645. "Content-Length: 399\r\n"
  14646. "\r\n"
  14647. "----------\r\n"
  14648. "Content-Disposition: form-data; name=\"text\"\r\n"
  14649. "\r\n"
  14650. "text default\r\n"
  14651. "----------\r\n"
  14652. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14653. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14654. "Content-Type: text/plain\r\n"
  14655. "\r\n"
  14656. "Content of a.txt.\r\n"
  14657. "\r\n"
  14658. "----------\r\n"
  14659. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14660. "\"a.html\"\r\n"
  14661. "Content-Type: text/html\r\n"
  14662. "\r\n"
  14663. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14664. "\r\n"
  14665. "------------\r\n";
  14666. ASSERT_TRUE(send_request(1, req));
  14667. }
  14668. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14669. auto handled = false;
  14670. Server svr;
  14671. svr.Post("/test", [&](const Request &req, Response &res) {
  14672. // Case-insensitive "utf-8''" prefix with a long value
  14673. const auto &file = req.form.get_file("file1");
  14674. ASSERT_EQ("file1", file.name);
  14675. // 8000 chars exercises both the Content-Disposition parser and the
  14676. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14677. // Prior to the fix, std::regex_match on this header would cause O(N)
  14678. // stack recursion in libstdc++, leading to SIGSEGV.
  14679. std::string expected_filename(8000, 'A');
  14680. ASSERT_EQ(expected_filename, file.filename);
  14681. res.set_content("ok", "text/plain");
  14682. handled = true;
  14683. });
  14684. thread t = thread([&] { svr.listen(HOST, PORT); });
  14685. auto se = detail::scope_exit([&] {
  14686. svr.stop();
  14687. t.join();
  14688. ASSERT_FALSE(svr.is_running());
  14689. ASSERT_TRUE(handled);
  14690. });
  14691. svr.wait_until_ready();
  14692. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14693. // Regression test for GHSA-qq6v-r583-3h69
  14694. std::string long_filename(8000, 'A');
  14695. std::string body = "----------\r\n"
  14696. "Content-Disposition: form-data; name=\"file1\"; "
  14697. "filename*=\"Utf-8''" +
  14698. long_filename +
  14699. "\"\r\n"
  14700. "\r\n"
  14701. "hello\r\n"
  14702. "------------\r\n";
  14703. auto req = "POST /test HTTP/1.1\r\n"
  14704. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14705. "Content-Length: " +
  14706. std::to_string(body.size()) + "\r\n\r\n" + body;
  14707. ASSERT_TRUE(send_request(1, req));
  14708. }
  14709. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14710. auto handled = false;
  14711. Server svr;
  14712. svr.Post("/test", [&](const Request &req, Response &) {
  14713. ASSERT_EQ(2u, req.form.fields.size());
  14714. const auto &text1 = req.form.get_field("text1");
  14715. ASSERT_EQ("text1", text1);
  14716. const auto &text2 = req.form.get_field("text2");
  14717. ASSERT_EQ("text2", text2);
  14718. handled = true;
  14719. });
  14720. thread t = thread([&] { svr.listen(HOST, PORT); });
  14721. auto se = detail::scope_exit([&] {
  14722. svr.stop();
  14723. t.join();
  14724. ASSERT_FALSE(svr.is_running());
  14725. ASSERT_TRUE(handled);
  14726. });
  14727. svr.wait_until_ready();
  14728. auto req = "POST /test HTTP/1.1\r\n"
  14729. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14730. "Content-Length: 146\r\n"
  14731. "\r\n----------\r\n"
  14732. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14733. "\r\n"
  14734. "text1"
  14735. "\r\n----------\r\n"
  14736. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14737. "\r\n"
  14738. "text2"
  14739. "\r\n------------";
  14740. std::string response;
  14741. ASSERT_TRUE(send_request(1, req, &response));
  14742. ASSERT_EQ("200", response.substr(9, 3));
  14743. }
  14744. TEST(MultipartFormDataTest, ContentLength) {
  14745. auto handled = false;
  14746. Server svr;
  14747. svr.Post("/test", [&](const Request &req, Response &) {
  14748. ASSERT_EQ(2u, req.form.fields.size());
  14749. const auto &text1 = req.form.get_field("text1");
  14750. ASSERT_EQ("text1", text1);
  14751. const auto &text2 = req.form.get_field("text2");
  14752. ASSERT_EQ("text2", text2);
  14753. handled = true;
  14754. });
  14755. thread t = thread([&] { svr.listen(HOST, PORT); });
  14756. auto se = detail::scope_exit([&] {
  14757. svr.stop();
  14758. t.join();
  14759. ASSERT_FALSE(svr.is_running());
  14760. ASSERT_TRUE(handled);
  14761. });
  14762. svr.wait_until_ready();
  14763. auto req = "POST /test HTTP/1.1\r\n"
  14764. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14765. "Content-Length: 167\r\n"
  14766. "\r\n----------\r\n"
  14767. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14768. "Content-Length: 5\r\n"
  14769. "\r\n"
  14770. "text1"
  14771. "\r\n----------\r\n"
  14772. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14773. "\r\n"
  14774. "text2"
  14775. "\r\n------------\r\n";
  14776. std::string response;
  14777. ASSERT_TRUE(send_request(1, req, &response));
  14778. ASSERT_EQ("200", response.substr(9, 3));
  14779. }
  14780. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14781. auto handled = false;
  14782. Server svr;
  14783. svr.Post("/test", [&](const Request &req, Response &) {
  14784. ASSERT_EQ(2u, req.form.fields.size());
  14785. const auto &text1 = req.form.get_field("text1");
  14786. ASSERT_EQ("text1", text1);
  14787. // TODO: Add header access for text fields if needed
  14788. const auto &text2 = req.form.get_field("text2");
  14789. ASSERT_EQ("text2", text2);
  14790. // TODO: Header access for text fields needs to be implemented
  14791. // auto &headers = it->second.headers;
  14792. // ASSERT_EQ(3U, headers.size());
  14793. // auto custom_header = headers.find("x-whatever");
  14794. // ASSERT_TRUE(custom_header != headers.end());
  14795. // ASSERT_NE("customvalue", custom_header->second);
  14796. // ASSERT_EQ("CustomValue", custom_header->second);
  14797. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14798. handled = true;
  14799. });
  14800. thread t = thread([&] { svr.listen(HOST, PORT); });
  14801. auto se = detail::scope_exit([&] {
  14802. svr.stop();
  14803. t.join();
  14804. ASSERT_FALSE(svr.is_running());
  14805. ASSERT_TRUE(handled);
  14806. });
  14807. svr.wait_until_ready();
  14808. auto req = "POST /test HTTP/1.1\r\n"
  14809. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14810. "Content-Length: 232\r\n"
  14811. "\r\n----------\r\n"
  14812. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14813. "Content-Length: 5\r\n"
  14814. "X-Test: 1\r\n"
  14815. "\r\n"
  14816. "text1"
  14817. "\r\n----------\r\n"
  14818. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14819. "Content-Type: text/plain\r\n"
  14820. "X-Whatever: CustomValue\r\n"
  14821. "\r\n"
  14822. "text2"
  14823. "\r\n------------\r\n"
  14824. "That should be disregarded. Not even read";
  14825. std::string response;
  14826. ASSERT_TRUE(send_request(1, req, &response));
  14827. ASSERT_EQ("200", response.substr(9, 3));
  14828. }
  14829. TEST(MultipartFormDataTest, LargeHeader) {
  14830. auto handled = false;
  14831. Server svr;
  14832. svr.Post("/test", [&](const Request &req, Response &) {
  14833. ASSERT_EQ(1u, req.form.fields.size());
  14834. const auto &text = req.form.get_field("name1");
  14835. ASSERT_EQ("text1", text);
  14836. handled = true;
  14837. });
  14838. thread t = thread([&] { svr.listen(HOST, PORT); });
  14839. auto se = detail::scope_exit([&] {
  14840. svr.stop();
  14841. t.join();
  14842. ASSERT_FALSE(svr.is_running());
  14843. ASSERT_TRUE(handled);
  14844. });
  14845. svr.wait_until_ready();
  14846. auto boundary = std::string("cpp-httplib-multipart-data");
  14847. std::string content = "--" + boundary +
  14848. "\r\n"
  14849. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14850. "\r\n"
  14851. "text1\r\n"
  14852. "--" +
  14853. boundary + "--\r\n";
  14854. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14855. "Content-Type: multipart/form-data;boundary=" +
  14856. boundary +
  14857. "\r\n"
  14858. "Content-Length: " +
  14859. std::to_string(content.size()) +
  14860. "\r\n"
  14861. "Dummy-Header: ";
  14862. std::string header_suffix = "\r\n"
  14863. "\r\n";
  14864. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14865. size_t header_dummy_size =
  14866. read_buff_size -
  14867. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14868. auto header_dummy = std::string(header_dummy_size, '@');
  14869. auto req = header_prefix + header_dummy + header_suffix + content;
  14870. std::string response;
  14871. ASSERT_TRUE(send_request(1, req, &response));
  14872. ASSERT_EQ("200", response.substr(9, 3));
  14873. }
  14874. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14875. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14876. // (not chunked Transfer-Encoding) after the streaming refactor.
  14877. auto handled = false;
  14878. Server svr;
  14879. svr.Post("/upload", [&](const Request &req, Response &res) {
  14880. auto cl_it = req.headers.find("Content-Length");
  14881. EXPECT_TRUE(cl_it != req.headers.end());
  14882. auto te_it = req.headers.find("Transfer-Encoding");
  14883. EXPECT_TRUE(te_it == req.headers.end());
  14884. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14885. res.set_content("ok", "text/plain");
  14886. handled = true;
  14887. });
  14888. auto port = svr.bind_to_any_port(HOST);
  14889. auto t = thread([&] { svr.listen_after_bind(); });
  14890. auto se = detail::scope_exit([&] {
  14891. svr.stop();
  14892. t.join();
  14893. ASSERT_FALSE(svr.is_running());
  14894. ASSERT_TRUE(handled);
  14895. });
  14896. svr.wait_until_ready();
  14897. UploadFormDataItems items = {
  14898. {"field1", "hello", "", "text/plain"},
  14899. {"file1", "world", "test.txt", "application/octet-stream"},
  14900. };
  14901. Client cli(HOST, port);
  14902. auto res = cli.Post("/upload", {}, items);
  14903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14904. EXPECT_EQ(StatusCode::OK_200, res->status);
  14905. }
  14906. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14907. // Verify that make_multipart_content_provider coalesces many small segments
  14908. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14909. constexpr size_t kItemCount = 1000;
  14910. UploadFormDataItems items;
  14911. items.reserve(kItemCount);
  14912. for (size_t i = 0; i < kItemCount; i++) {
  14913. items.push_back(
  14914. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14915. }
  14916. const std::string boundary = "----test-boundary";
  14917. auto content_length = detail::get_multipart_content_length(items, boundary);
  14918. auto provider = detail::make_multipart_content_provider(items, boundary);
  14919. // Drive the provider the same way write_content_with_progress does
  14920. size_t write_count = 0;
  14921. size_t total_bytes = 0;
  14922. DataSink sink;
  14923. size_t offset = 0;
  14924. sink.write = [&](const char *d, size_t l) -> bool {
  14925. (void)d;
  14926. write_count++;
  14927. total_bytes += l;
  14928. offset += l;
  14929. return true;
  14930. };
  14931. sink.is_writable = []() -> bool { return true; };
  14932. while (offset < content_length) {
  14933. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14934. }
  14935. EXPECT_EQ(content_length, total_bytes);
  14936. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14937. // With buffering into 64KB blocks, write_count should be much smaller.
  14938. auto segment_count = 3 * kItemCount + 1;
  14939. EXPECT_LT(write_count, segment_count / 10);
  14940. }
  14941. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14942. // Integration test: send many UploadFormDataItems and verify the server
  14943. // receives all of them correctly (#2410).
  14944. constexpr size_t kItemCount = 500;
  14945. auto handled = false;
  14946. Server svr;
  14947. svr.Post("/upload", [&](const Request &req, Response &res) {
  14948. EXPECT_EQ(kItemCount, req.form.fields.size());
  14949. for (size_t i = 0; i < kItemCount; i++) {
  14950. auto key = "field" + std::to_string(i);
  14951. auto val = "value" + std::to_string(i);
  14952. auto it = req.form.fields.find(key);
  14953. if (it != req.form.fields.end()) {
  14954. EXPECT_EQ(val, it->second.content);
  14955. } else {
  14956. ADD_FAILURE() << "Missing field: " << key;
  14957. }
  14958. }
  14959. res.set_content("ok", "text/plain");
  14960. handled = true;
  14961. });
  14962. auto port = svr.bind_to_any_port(HOST);
  14963. auto t = thread([&] { svr.listen_after_bind(); });
  14964. auto se = detail::scope_exit([&] {
  14965. svr.stop();
  14966. t.join();
  14967. ASSERT_FALSE(svr.is_running());
  14968. ASSERT_TRUE(handled);
  14969. });
  14970. svr.wait_until_ready();
  14971. UploadFormDataItems items;
  14972. items.reserve(kItemCount);
  14973. for (size_t i = 0; i < kItemCount; i++) {
  14974. items.push_back(
  14975. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14976. }
  14977. Client cli(HOST, port);
  14978. auto res = cli.Post("/upload", items);
  14979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14980. EXPECT_EQ(StatusCode::OK_200, res->status);
  14981. }
  14982. TEST(MultipartFormDataTest, MakeFileProvider) {
  14983. // Verify make_file_provider sends a file's contents correctly.
  14984. const std::string file_content(4096, 'Z');
  14985. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14986. {
  14987. std::ofstream ofs(tmp_path, std::ios::binary);
  14988. ofs.write(file_content.data(),
  14989. static_cast<std::streamsize>(file_content.size()));
  14990. }
  14991. auto handled = false;
  14992. Server svr;
  14993. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14994. const ContentReader &content_reader) {
  14995. ASSERT_TRUE(req.is_multipart_form_data());
  14996. std::vector<FormData> items;
  14997. content_reader(
  14998. [&](const FormData &file) {
  14999. items.push_back(file);
  15000. return true;
  15001. },
  15002. [&](const char *data, size_t data_length) {
  15003. items.back().content.append(data, data_length);
  15004. return true;
  15005. });
  15006. ASSERT_EQ(1u, items.size());
  15007. EXPECT_EQ("myfile", items[0].name);
  15008. EXPECT_EQ("data.bin", items[0].filename);
  15009. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15010. EXPECT_EQ(file_content, items[0].content);
  15011. handled = true;
  15012. });
  15013. auto port = svr.bind_to_any_port(HOST);
  15014. auto t = thread([&] { svr.listen_after_bind(); });
  15015. auto se = detail::scope_exit([&] {
  15016. svr.stop();
  15017. t.join();
  15018. ASSERT_FALSE(svr.is_running());
  15019. ASSERT_TRUE(handled);
  15020. std::remove(tmp_path.c_str());
  15021. });
  15022. svr.wait_until_ready();
  15023. FormDataProviderItems providers;
  15024. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15025. "application/octet-stream"));
  15026. Client cli(HOST, port);
  15027. auto res = cli.Post("/upload", {}, {}, providers);
  15028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15029. EXPECT_EQ(StatusCode::OK_200, res->status);
  15030. }
  15031. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15032. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15033. // (100) headers is rejected with a 400 Bad Request response.
  15034. Server svr;
  15035. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15036. res.set_content("ok", "text/plain");
  15037. });
  15038. thread t = thread([&] { svr.listen(HOST, PORT); });
  15039. auto se = detail::scope_exit([&] {
  15040. svr.stop();
  15041. t.join();
  15042. ASSERT_FALSE(svr.is_running());
  15043. });
  15044. svr.wait_until_ready();
  15045. // Build a multipart part with 101 custom headers (exceeding
  15046. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15047. std::stringstream body;
  15048. body << "--simpleboundary\r\n"
  15049. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15050. for (int i = 0; i < 101; i++) {
  15051. body << "X-Custom-Header-" << i << ": value\r\n";
  15052. }
  15053. body << "\r\n"
  15054. << "value1\r\n"
  15055. << "--simpleboundary--\r\n";
  15056. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15057. Client cli(HOST, PORT);
  15058. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15060. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15061. }
  15062. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15063. // A body that never contains the declared boundary must not be accumulated
  15064. // while the parser waits for it. Buffering it would also make every read
  15065. // rescan everything seen so far, which is quadratic in the body size.
  15066. Server svr;
  15067. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15068. res.set_content("ok", "text/plain");
  15069. });
  15070. auto port = svr.bind_to_any_port(HOST);
  15071. thread t = thread([&] { svr.listen_after_bind(); });
  15072. auto se = detail::scope_exit([&] {
  15073. svr.stop();
  15074. t.join();
  15075. ASSERT_FALSE(svr.is_running());
  15076. });
  15077. svr.wait_until_ready();
  15078. Client cli(HOST, port);
  15079. cli.set_read_timeout(60, 0);
  15080. cli.set_write_timeout(60, 0);
  15081. // '-' is the worst case: it matches the first character of the boundary, so
  15082. // every position has to be checked against it.
  15083. auto post_dashes = [&](size_t size) {
  15084. const std::string body(size, '-');
  15085. auto start = std::chrono::steady_clock::now();
  15086. auto res =
  15087. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15088. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15089. std::chrono::steady_clock::now() - start)
  15090. .count();
  15091. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15092. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15093. return ms;
  15094. };
  15095. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15096. // Windows.
  15097. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15098. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15099. // Comparing the two sizes rather than checking an absolute duration keeps
  15100. // this meaningful across build types and CI load, both of which move the
  15101. // absolute numbers by more than an order of magnitude. Four times the bytes
  15102. // costs about four times the time when parsing is linear, and about sixteen
  15103. // times when the body is buffered and rescanned.
  15104. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15105. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15106. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15107. << "ms, which suggests the body is being buffered and rescanned";
  15108. }
  15109. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15110. // A boundary can only be followed by CRLF or by "--", so anything else is
  15111. // malformed no matter what comes next. The parser must say so right away
  15112. // instead of buffering the rest of the declared body.
  15113. Server svr;
  15114. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15115. res.set_content("ok", "text/plain");
  15116. });
  15117. auto port = svr.bind_to_any_port(HOST);
  15118. thread t = thread([&] { svr.listen_after_bind(); });
  15119. auto se = detail::scope_exit([&] {
  15120. svr.stop();
  15121. t.join();
  15122. ASSERT_FALSE(svr.is_running());
  15123. });
  15124. svr.wait_until_ready();
  15125. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15126. // buffers instead of failing would still be waiting for the remaining bytes.
  15127. const std::string body = "--zzzz\r\n"
  15128. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15129. "\r\n"
  15130. "text1"
  15131. "\r\n--zzzzXX";
  15132. const std::string req = "POST /post HTTP/1.1\r\n"
  15133. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15134. "Content-Length: 1048576\r\n"
  15135. "\r\n" +
  15136. body;
  15137. std::string response;
  15138. ASSERT_TRUE(send_request(3, req, &response, port));
  15139. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15140. EXPECT_EQ("400", response.substr(9, 3));
  15141. }
  15142. // Posts a multipart body split into two writes, so that the server sees the
  15143. // split at whatever offset the caller chose, and expects the single "text1"
  15144. // field to come through.
  15145. static void expect_split_multipart_ok(const std::string &body1,
  15146. const std::string &body2) {
  15147. auto handled = false;
  15148. Server svr;
  15149. svr.Post("/post", [&](const Request &req, Response &) {
  15150. EXPECT_EQ(1u, req.form.fields.size());
  15151. EXPECT_EQ("text1", req.form.get_field("text1"));
  15152. handled = true;
  15153. });
  15154. auto port = svr.bind_to_any_port(HOST);
  15155. thread t = thread([&] { svr.listen_after_bind(); });
  15156. auto se = detail::scope_exit([&] {
  15157. svr.stop();
  15158. t.join();
  15159. ASSERT_FALSE(svr.is_running());
  15160. ASSERT_TRUE(handled);
  15161. });
  15162. svr.wait_until_ready();
  15163. // "Connection: close" makes the server close once it has answered, so the
  15164. // response drain ends immediately instead of idling until the read timeout.
  15165. const std::string head =
  15166. "POST /post HTTP/1.1\r\n"
  15167. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15168. "Connection: close\r\n"
  15169. "Content-Length: " +
  15170. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15171. std::string response;
  15172. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15173. ASSERT_GE(response.size(), 12u) << "no response";
  15174. EXPECT_EQ("200", response.substr(9, 3));
  15175. }
  15176. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15177. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15178. // ignored, including when it does not arrive in the same read as the
  15179. // close-delimiter itself.
  15180. expect_split_multipart_ok("--zzzz\r\n"
  15181. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15182. "\r\n"
  15183. "text1"
  15184. "\r\n--zzzz--",
  15185. "\r\nthis epilogue must be ignored\r\n");
  15186. }
  15187. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15188. // The initial boundary may be preceded by a preamble of any length and may
  15189. // straddle a read boundary. Discarding data while waiting for it must not
  15190. // throw away a partial boundary sitting at the end of the buffer.
  15191. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15192. "zz\r\n"
  15193. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15194. "\r\n"
  15195. "text1"
  15196. "\r\n--zzzz--\r\n");
  15197. }
  15198. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15199. // The received boundary was only checked for being non-empty, so it could be
  15200. // as long as a header is allowed to be. The parser scans the body for
  15201. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15202. // costs a nearly full comparison at nearly every position, making the
  15203. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15204. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15205. Server svr;
  15206. svr.Post("/post", [](const Request &req, Response &res) {
  15207. EXPECT_EQ(1u, req.form.fields.size());
  15208. EXPECT_EQ("text1", req.form.get_field("text1"));
  15209. res.set_content("ok", "text/plain");
  15210. });
  15211. auto port = svr.bind_to_any_port(HOST);
  15212. thread t = thread([&] { svr.listen_after_bind(); });
  15213. auto se = detail::scope_exit([&] {
  15214. svr.stop();
  15215. t.join();
  15216. ASSERT_FALSE(svr.is_running());
  15217. });
  15218. svr.wait_until_ready();
  15219. Client cli(HOST, port);
  15220. auto post_with_boundary_of_length = [&](size_t len) {
  15221. const std::string boundary(len, 'a');
  15222. const std::string body =
  15223. "--" + boundary +
  15224. "\r\n"
  15225. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15226. "\r\n"
  15227. "text1"
  15228. "\r\n--" +
  15229. boundary + "--\r\n";
  15230. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15231. };
  15232. auto res = post_with_boundary_of_length(70);
  15233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15234. EXPECT_EQ(StatusCode::OK_200, res->status);
  15235. res = post_with_boundary_of_length(71);
  15236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15237. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15238. }
  15239. TEST(MakeFileBodyTest, Basic) {
  15240. const std::string file_content(4096, 'Z');
  15241. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15242. {
  15243. std::ofstream ofs(tmp_path, std::ios::binary);
  15244. ofs.write(file_content.data(),
  15245. static_cast<std::streamsize>(file_content.size()));
  15246. }
  15247. auto handled = false;
  15248. Server svr;
  15249. svr.Post("/upload", [&](const Request &req, Response &res) {
  15250. EXPECT_EQ(file_content, req.body);
  15251. handled = true;
  15252. res.status = StatusCode::OK_200;
  15253. });
  15254. auto port = svr.bind_to_any_port(HOST);
  15255. auto t = thread([&] { svr.listen_after_bind(); });
  15256. auto se = detail::scope_exit([&] {
  15257. svr.stop();
  15258. t.join();
  15259. ASSERT_FALSE(svr.is_running());
  15260. ASSERT_TRUE(handled);
  15261. std::remove(tmp_path.c_str());
  15262. });
  15263. svr.wait_until_ready();
  15264. auto fb = make_file_body(tmp_path);
  15265. ASSERT_GT(fb.first, 0u);
  15266. Client cli(HOST, port);
  15267. auto res =
  15268. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15270. EXPECT_EQ(StatusCode::OK_200, res->status);
  15271. }
  15272. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15273. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15274. {
  15275. std::ofstream ofs(path, std::ios::binary);
  15276. const std::string content(100, 'A');
  15277. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15278. }
  15279. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15280. auto body = make_file_body(path);
  15281. ASSERT_EQ(100u, body.first);
  15282. ASSERT_TRUE(static_cast<bool>(body.second));
  15283. // Rewritten shorter after its length was measured - and, on a server, after
  15284. // that length has already gone out as Content-Length.
  15285. {
  15286. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15287. const std::string content(10, 'A');
  15288. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15289. }
  15290. std::string written;
  15291. DataSink sink;
  15292. sink.write = [&](const char *d, size_t l) {
  15293. written.append(d, l);
  15294. return true;
  15295. };
  15296. // The provider has to report failure. write_content_with_progress() advances
  15297. // its offset only by what was written, so a provider that returns true
  15298. // without completing the length it promised is called again straight away,
  15299. // and again.
  15300. EXPECT_FALSE(body.second(0, body.first, sink));
  15301. EXPECT_EQ(std::string(10, 'A'), written);
  15302. }
  15303. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15304. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15305. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15306. {
  15307. std::ofstream ofs(path, std::ios::binary);
  15308. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15309. }
  15310. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15311. auto body = make_file_body(path);
  15312. ASSERT_EQ(content.size(), body.first);
  15313. ASSERT_TRUE(static_cast<bool>(body.second));
  15314. std::string written;
  15315. DataSink sink;
  15316. sink.write = [&](const char *d, size_t l) {
  15317. written.append(d, l);
  15318. return true;
  15319. };
  15320. EXPECT_TRUE(body.second(0, body.first, sink));
  15321. EXPECT_EQ(content, written);
  15322. }
  15323. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15324. static constexpr unsigned int number_of_tasks{1000000};
  15325. std::atomic_uint count{0};
  15326. std::unique_ptr<TaskQueue> task_queue{
  15327. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15328. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15329. auto queued = task_queue->enqueue(
  15330. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15331. EXPECT_TRUE(queued);
  15332. }
  15333. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15334. task_queue->shutdown();
  15335. #else
  15336. EXPECT_NO_THROW(task_queue->shutdown());
  15337. #endif
  15338. EXPECT_EQ(number_of_tasks, count.load());
  15339. }
  15340. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15341. static constexpr unsigned int number_of_tasks{1000000};
  15342. static constexpr unsigned int qlimit{2};
  15343. unsigned int queued_count{0};
  15344. std::atomic_uint count{0};
  15345. std::unique_ptr<TaskQueue> task_queue{
  15346. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15347. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15348. if (task_queue->enqueue(
  15349. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15350. queued_count++;
  15351. }
  15352. }
  15353. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15354. task_queue->shutdown();
  15355. #else
  15356. EXPECT_NO_THROW(task_queue->shutdown());
  15357. #endif
  15358. EXPECT_EQ(queued_count, count.load());
  15359. EXPECT_TRUE(queued_count <= number_of_tasks);
  15360. EXPECT_TRUE(queued_count >= qlimit);
  15361. }
  15362. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15363. // Use a short idle timeout so a dynamic thread spawns, times out and
  15364. // exits during the test, and the pool keeps working afterwards.
  15365. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15366. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15367. /*idle_timeout_sec=*/1}};
  15368. std::atomic_uint count{0};
  15369. std::condition_variable cv;
  15370. std::mutex mtx;
  15371. bool release = false;
  15372. // Block the base thread so the second task spawns a dynamic thread.
  15373. EXPECT_TRUE(task_queue->enqueue([&] {
  15374. std::unique_lock<std::mutex> lock(mtx);
  15375. while (!release) {
  15376. cv.wait(lock);
  15377. }
  15378. count++;
  15379. }));
  15380. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15381. // Let the dynamic thread finish its task and exceed the idle timeout.
  15382. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15383. {
  15384. std::unique_lock<std::mutex> lock(mtx);
  15385. release = true;
  15386. }
  15387. cv.notify_all();
  15388. // The pool must still accept and run tasks after the dynamic thread exited.
  15389. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15390. task_queue->shutdown();
  15391. EXPECT_EQ(3u, count.load());
  15392. }
  15393. TEST(TaskQueueTest, MaxQueuedRequests) {
  15394. static constexpr unsigned int qlimit{3};
  15395. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15396. std::condition_variable sem_cv;
  15397. std::mutex sem_mtx;
  15398. int credits = 0;
  15399. bool queued;
  15400. /* Fill up the queue with tasks that will block until we give them credits to
  15401. * complete. */
  15402. for (unsigned int n = 0; n <= qlimit;) {
  15403. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15404. std::unique_lock<std::mutex> lock(sem_mtx);
  15405. while (credits <= 0) {
  15406. sem_cv.wait(lock);
  15407. }
  15408. /* Consume the credit and signal the test code if they are all gone. */
  15409. if (--credits == 0) { sem_cv.notify_one(); }
  15410. });
  15411. if (n < qlimit) {
  15412. /* The first qlimit enqueues must succeed. */
  15413. EXPECT_TRUE(queued);
  15414. } else {
  15415. /* The last one will succeed only when the worker thread
  15416. * starts and dequeues the first blocking task. Although
  15417. * not necessary for the correctness of this test, we sleep for
  15418. * a short while to avoid busy waiting. */
  15419. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15420. }
  15421. if (queued) { n++; }
  15422. }
  15423. /* Further enqueues must fail since the queue is full. */
  15424. for (auto i = 0; i < 4; i++) {
  15425. queued = task_queue->enqueue([] {});
  15426. EXPECT_FALSE(queued);
  15427. }
  15428. /* Give the credits to allow the previous tasks to complete. */
  15429. {
  15430. std::unique_lock<std::mutex> lock(sem_mtx);
  15431. credits += qlimit + 1;
  15432. }
  15433. sem_cv.notify_all();
  15434. /* Wait for all the credits to be consumed. */
  15435. {
  15436. std::unique_lock<std::mutex> lock(sem_mtx);
  15437. while (credits > 0) {
  15438. sem_cv.wait(lock);
  15439. }
  15440. }
  15441. /* Check that we are able again to enqueue at least qlimit tasks. */
  15442. for (unsigned int i = 0; i < qlimit; i++) {
  15443. queued = task_queue->enqueue([] {});
  15444. EXPECT_TRUE(queued);
  15445. }
  15446. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15447. task_queue->shutdown();
  15448. #else
  15449. EXPECT_NO_THROW(task_queue->shutdown());
  15450. #endif
  15451. }
  15452. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15453. Server svr;
  15454. std::string method;
  15455. std::string body;
  15456. auto has_content_length = false;
  15457. auto has_transfer_encoding = false;
  15458. std::atomic<int> bad_requests{0};
  15459. // Leftover body bytes get parsed as a malformed request and answered with
  15460. // 400
  15461. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15462. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15463. });
  15464. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15465. res.set_redirect("/down", StatusCode::SeeOther_303);
  15466. });
  15467. svr.Get("/down", [&](const Request &req, Response &res) {
  15468. method = req.method;
  15469. body = req.body;
  15470. has_content_length = req.has_header("Content-Length");
  15471. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15472. res.set_content("ok", "text/plain");
  15473. });
  15474. auto port = svr.bind_to_any_port(HOST);
  15475. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15476. auto se = detail::scope_exit([&] {
  15477. svr.stop();
  15478. thread.join();
  15479. ASSERT_FALSE(svr.is_running());
  15480. });
  15481. svr.wait_until_ready();
  15482. const std::string payload = "SECRET-BODY";
  15483. auto check = [&](Client &cli, const Result &res) {
  15484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15485. EXPECT_EQ(StatusCode::OK_200, res->status);
  15486. EXPECT_EQ("ok", res->body);
  15487. EXPECT_EQ("GET", method);
  15488. EXPECT_TRUE(body.empty());
  15489. EXPECT_FALSE(has_content_length);
  15490. EXPECT_FALSE(has_transfer_encoding);
  15491. // Nothing of the original body may be left on the connection
  15492. auto res2 = cli.Get("/down");
  15493. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15494. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15495. EXPECT_EQ("ok", res2->body);
  15496. EXPECT_EQ(0, bad_requests);
  15497. };
  15498. // With content length
  15499. {
  15500. Client cli(HOST, port);
  15501. cli.set_keep_alive(true);
  15502. cli.set_follow_location(true);
  15503. auto res = cli.Post(
  15504. "/up", payload.size(),
  15505. [&](size_t offset, size_t length, DataSink &sink) {
  15506. return sink.write(payload.data() + offset, length);
  15507. },
  15508. "text/plain");
  15509. check(cli, res);
  15510. }
  15511. // Without content length (chunked)
  15512. {
  15513. Client cli(HOST, port);
  15514. cli.set_keep_alive(true);
  15515. cli.set_follow_location(true);
  15516. auto res = cli.Post(
  15517. "/up",
  15518. [&](size_t /*offset*/, DataSink &sink) {
  15519. sink.write(payload.data(), payload.size());
  15520. sink.done();
  15521. return true;
  15522. },
  15523. "text/plain");
  15524. check(cli, res);
  15525. }
  15526. }
  15527. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15528. Server svr;
  15529. std::string target;
  15530. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15531. // Echo the still-encoded name back in the Location
  15532. const std::string prefix = "/start/";
  15533. res.status = StatusCode::Found_302;
  15534. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15535. });
  15536. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15537. target = req.target;
  15538. res.set_content("ok", "text/plain");
  15539. });
  15540. auto port = svr.bind_to_any_port(HOST);
  15541. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15542. auto se = detail::scope_exit([&] {
  15543. svr.stop();
  15544. thread.join();
  15545. ASSERT_FALSE(svr.is_running());
  15546. });
  15547. svr.wait_until_ready();
  15548. // Decoding the Location path would turn the first four into a path
  15549. // separator, a query delimiter, a fragment delimiter and a different
  15550. // percent-encoded octet. The rest must keep reaching the server as they are.
  15551. const std::vector<std::string> names = {
  15552. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15553. };
  15554. for (auto path_encode : {true, false}) {
  15555. Client cli(HOST, port);
  15556. cli.set_follow_location(true);
  15557. cli.set_path_encode(path_encode);
  15558. for (const auto &name : names) {
  15559. target.clear();
  15560. auto res = cli.Get("/start/" + name);
  15561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15562. EXPECT_EQ(StatusCode::OK_200, res->status);
  15563. EXPECT_EQ("/dest/" + name, target);
  15564. }
  15565. }
  15566. }
  15567. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15568. Server svr;
  15569. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15570. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15571. });
  15572. svr.Get("/hello", [](const Request &req, Response &res) {
  15573. res.set_content(req.get_param_value("key"), "text/plain");
  15574. });
  15575. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15576. auto se = detail::scope_exit([&] {
  15577. svr.stop();
  15578. thread.join();
  15579. ASSERT_FALSE(svr.is_running());
  15580. });
  15581. svr.wait_until_ready();
  15582. {
  15583. Client cli(HOST, PORT);
  15584. cli.set_follow_location(true);
  15585. auto res = cli.Get("/");
  15586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15587. EXPECT_EQ(StatusCode::OK_200, res->status);
  15588. EXPECT_EQ("val&key2=val2", res->body);
  15589. }
  15590. }
  15591. #endif
  15592. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15593. Server svr;
  15594. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15595. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15596. });
  15597. svr.Get("/hello", [](const Request &req, Response &res) {
  15598. res.set_content(req.get_param_value("key"), "text/plain");
  15599. });
  15600. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15601. auto se = detail::scope_exit([&] {
  15602. svr.stop();
  15603. thread.join();
  15604. ASSERT_FALSE(svr.is_running());
  15605. });
  15606. svr.wait_until_ready();
  15607. {
  15608. Client cli(HOST, PORT);
  15609. cli.set_follow_location(true);
  15610. auto res = cli.Get("/");
  15611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15612. EXPECT_EQ(StatusCode::OK_200, res->status);
  15613. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15614. }
  15615. }
  15616. TEST(RedirectTest, RedirectWithPlusInPath) {
  15617. Server svr;
  15618. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15619. res.set_redirect("/a+b");
  15620. });
  15621. // Route pattern uses regex; escape + as \\+
  15622. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15623. res.set_content(req.path, "text/plain");
  15624. });
  15625. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15626. auto se = detail::scope_exit([&] {
  15627. svr.stop();
  15628. thread.join();
  15629. ASSERT_FALSE(svr.is_running());
  15630. });
  15631. svr.wait_until_ready();
  15632. {
  15633. Client cli(HOST, PORT);
  15634. cli.set_follow_location(true);
  15635. auto res = cli.Get("/");
  15636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15637. EXPECT_EQ(StatusCode::OK_200, res->status);
  15638. EXPECT_EQ("/a+b", res->body);
  15639. }
  15640. }
  15641. TEST(RedirectTest, ResolveRelativeLocation) {
  15642. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15643. const std::vector<std::pair<std::string, std::string>> cases = {
  15644. {"g", "/b/c/g"},
  15645. {"./g", "/b/c/g"},
  15646. {"g/", "/b/c/g/"},
  15647. {"?y", "/b/c/d;p?y"},
  15648. {"g?y", "/b/c/g?y"},
  15649. {"#s", "/b/c/d;p?q#s"},
  15650. {"g#s", "/b/c/g#s"},
  15651. {"g?y#s", "/b/c/g?y#s"},
  15652. {";x", "/b/c/;x"},
  15653. {"g;x", "/b/c/g;x"},
  15654. {".", "/b/c/"},
  15655. {"./", "/b/c/"},
  15656. {"..", "/b/"},
  15657. {"../", "/b/"},
  15658. {"../g", "/b/g"},
  15659. {"../..", "/"},
  15660. {"../../", "/"},
  15661. {"../../g", "/g"},
  15662. {"../../../g", "/g"},
  15663. {"g.", "/b/c/g."},
  15664. {".g", "/b/c/.g"},
  15665. {"g..", "/b/c/g.."},
  15666. {"..g", "/b/c/..g"},
  15667. {"./../g", "/b/g"},
  15668. {"./g/.", "/b/c/g/"},
  15669. {"g/./h", "/b/c/g/h"},
  15670. {"g/../h", "/b/c/h"},
  15671. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15672. {"g;x=1/../y", "/b/c/y"},
  15673. {"g?y/./x", "/b/c/g?y/./x"},
  15674. {"g#s/../x", "/b/c/g#s/../x"},
  15675. // Not relative-path references, so left for parse_url.
  15676. {"/g", "/g"},
  15677. {"//g", "//g"},
  15678. {"http://g/x", "http://g/x"},
  15679. {"g:h", "g:h"},
  15680. };
  15681. for (const auto &c : cases) {
  15682. EXPECT_EQ(c.second,
  15683. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15684. << c.first;
  15685. }
  15686. }
  15687. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15688. Server svr;
  15689. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15690. res.set_redirect(req.get_param_value("to"));
  15691. });
  15692. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15693. res.set_content(req.target, "text/plain");
  15694. });
  15695. svr.Get("/other", [](const Request &req, Response &res) {
  15696. res.set_content(req.target, "text/plain");
  15697. });
  15698. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15699. auto se = detail::scope_exit([&] {
  15700. svr.stop();
  15701. thread.join();
  15702. ASSERT_FALSE(svr.is_running());
  15703. });
  15704. svr.wait_until_ready();
  15705. const std::vector<std::pair<std::string, std::string>> cases = {
  15706. {"next", "/dir/next"},
  15707. {"./next?x=1", "/dir/next?x=1"},
  15708. {"../other", "/other"},
  15709. };
  15710. for (const auto &c : cases) {
  15711. Client cli(HOST, PORT);
  15712. cli.set_follow_location(true);
  15713. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15714. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15715. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15716. EXPECT_EQ(c.second, res->body) << c.first;
  15717. }
  15718. }
  15719. #ifdef CPPHTTPLIB_SSL_ENABLED
  15720. TEST(RedirectTest, Issue2185_Online) {
  15721. SSLClient client("github.com");
  15722. client.set_follow_location(true);
  15723. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15724. "Coollab-Windows.zip");
  15725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15726. EXPECT_EQ(StatusCode::OK_200, res->status);
  15727. EXPECT_EQ(9920427U, res->body.size());
  15728. }
  15729. #endif
  15730. TEST(VulnerabilityTest, CRLFInjection) {
  15731. Server svr;
  15732. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15733. res.set_content("Hello 1", "text/plain");
  15734. });
  15735. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15736. res.set_content("Hello 2", "text/plain");
  15737. });
  15738. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15739. res.set_content("Hello 3", "text/plain");
  15740. });
  15741. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15742. res.set_content("Hello 4", "text/plain");
  15743. });
  15744. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15745. for (const auto &x : req.headers) {
  15746. auto key = x.first;
  15747. EXPECT_STRNE("evil", key.c_str());
  15748. }
  15749. });
  15750. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15751. auto se = detail::scope_exit([&] {
  15752. svr.stop();
  15753. thread.join();
  15754. ASSERT_FALSE(svr.is_running());
  15755. });
  15756. svr.wait_until_ready();
  15757. {
  15758. Client cli(HOST, PORT);
  15759. cli.Post("/test1", "A=B",
  15760. "application/x-www-form-urlencoded\r\nevil: hello1");
  15761. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15762. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15763. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15764. }
  15765. }
  15766. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15767. auto server_thread = std::thread([] {
  15768. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15769. default_socket_options(srv);
  15770. sockaddr_in addr{};
  15771. addr.sin_family = AF_INET;
  15772. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15773. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15774. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15775. ::listen(srv, 1);
  15776. sockaddr_in cli_addr{};
  15777. socklen_t cli_len = sizeof(cli_addr);
  15778. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15779. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15780. std::string buf_all;
  15781. char buf[2048];
  15782. ssize_t n;
  15783. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15784. buf_all.append(buf, static_cast<size_t>(n));
  15785. size_t pos;
  15786. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15787. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15788. auto e = request_block.find("\r\n");
  15789. if (e != std::string::npos) {
  15790. auto request_line = request_block.substr(0, e);
  15791. std::string msg =
  15792. "CRLF injection detected in request line: '" + request_line + "'";
  15793. EXPECT_FALSE(true) << msg;
  15794. }
  15795. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15796. ::send(cli,
  15797. #ifdef _WIN32
  15798. static_cast<const char *>(resp.c_str()),
  15799. static_cast<int>(resp.size()),
  15800. #else
  15801. resp.c_str(), resp.size(),
  15802. #endif
  15803. 0);
  15804. buf_all.erase(0, pos + 4);
  15805. }
  15806. }
  15807. detail::close_socket(cli);
  15808. detail::close_socket(srv);
  15809. });
  15810. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15811. auto cli = Client("127.0.0.1", PORT + 1);
  15812. auto headers = Headers{
  15813. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15814. {"Connection", "keep-alive"}};
  15815. auto res = cli.Get("/hi", headers);
  15816. EXPECT_FALSE(res);
  15817. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15818. server_thread.join();
  15819. }
  15820. // A request rejected before any byte reaches the socket must fail right away
  15821. // instead of waiting for a response the server will never send.
  15822. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15823. // The kernel completes the TCP handshake from the listen backlog, so the
  15824. // client connects, but nothing ever reads, responds or closes.
  15825. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15826. default_socket_options(srv);
  15827. sockaddr_in addr{};
  15828. addr.sin_family = AF_INET;
  15829. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15830. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15831. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15832. ASSERT_EQ(0, ::listen(srv, 8));
  15833. auto cli = Client("127.0.0.1", PORT + 1);
  15834. cli.set_read_timeout(10, 0);
  15835. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15836. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15837. std::chrono::steady_clock::now() - start)
  15838. .count();
  15839. };
  15840. {
  15841. Request req;
  15842. req.method = "GE T";
  15843. req.path = "/";
  15844. auto start = std::chrono::steady_clock::now();
  15845. auto res = cli.send(req);
  15846. EXPECT_FALSE(res);
  15847. EXPECT_EQ(Error::Write, res.error());
  15848. EXPECT_LT(elapsed_ms(start), 1000);
  15849. }
  15850. {
  15851. auto start = std::chrono::steady_clock::now();
  15852. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15853. EXPECT_FALSE(res);
  15854. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15855. EXPECT_LT(elapsed_ms(start), 1000);
  15856. }
  15857. EXPECT_FALSE(cli.is_socket_open());
  15858. detail::close_socket(srv);
  15859. }
  15860. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15861. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15862. default_socket_options(srv);
  15863. sockaddr_in addr{};
  15864. addr.sin_family = AF_INET;
  15865. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15866. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15867. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15868. ASSERT_EQ(0, ::listen(srv, 1));
  15869. std::string received;
  15870. auto server_thread = std::thread([&] {
  15871. auto sock = ::accept(srv, nullptr, nullptr);
  15872. if (sock == INVALID_SOCKET) { return; }
  15873. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15874. char buf[2048];
  15875. ssize_t n;
  15876. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15877. received.append(buf, static_cast<size_t>(n));
  15878. }
  15879. detail::close_socket(sock);
  15880. });
  15881. {
  15882. auto cli = Client("127.0.0.1", PORT + 1);
  15883. // "Z" sorts after the default headers, so writing straight to the socket
  15884. // would have sent the request line and those headers before the rejection.
  15885. auto handle =
  15886. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15887. EXPECT_FALSE(handle.is_valid());
  15888. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15889. }
  15890. server_thread.join();
  15891. detail::close_socket(srv);
  15892. EXPECT_TRUE(received.empty()) << received;
  15893. }
  15894. TEST(PathParamsTest, StaticMatch) {
  15895. const auto pattern = "/users/all";
  15896. detail::PathParamsMatcher matcher(pattern);
  15897. Request request;
  15898. request.path = "/users/all";
  15899. ASSERT_TRUE(matcher.match(request));
  15900. std::unordered_map<std::string, std::string> expected_params = {};
  15901. EXPECT_EQ(request.path_params, expected_params);
  15902. }
  15903. TEST(PathParamsTest, StaticMismatch) {
  15904. const auto pattern = "/users/all";
  15905. detail::PathParamsMatcher matcher(pattern);
  15906. Request request;
  15907. request.path = "/users/1";
  15908. ASSERT_FALSE(matcher.match(request));
  15909. }
  15910. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15911. const auto pattern = "/users/:id/subscriptions";
  15912. detail::PathParamsMatcher matcher(pattern);
  15913. Request request;
  15914. request.path = "/users/42/subscriptions";
  15915. ASSERT_TRUE(matcher.match(request));
  15916. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15917. EXPECT_EQ(request.path_params, expected_params);
  15918. }
  15919. TEST(PathParamsTest, SingleParamInTheEnd) {
  15920. const auto pattern = "/users/:id";
  15921. detail::PathParamsMatcher matcher(pattern);
  15922. Request request;
  15923. request.path = "/users/24";
  15924. ASSERT_TRUE(matcher.match(request));
  15925. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15926. EXPECT_EQ(request.path_params, expected_params);
  15927. }
  15928. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15929. const auto pattern = "/users/:id/";
  15930. detail::PathParamsMatcher matcher(pattern);
  15931. Request request;
  15932. request.path = "/users/42/";
  15933. ASSERT_TRUE(matcher.match(request));
  15934. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15935. EXPECT_EQ(request.path_params, expected_params);
  15936. }
  15937. TEST(PathParamsTest, EmptyParam) {
  15938. const auto pattern = "/users/:id/";
  15939. detail::PathParamsMatcher matcher(pattern);
  15940. Request request;
  15941. request.path = "/users//";
  15942. ASSERT_TRUE(matcher.match(request));
  15943. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15944. EXPECT_EQ(request.path_params, expected_params);
  15945. }
  15946. TEST(PathParamsTest, FragmentMismatch) {
  15947. const auto pattern = "/users/:id/";
  15948. detail::PathParamsMatcher matcher(pattern);
  15949. Request request;
  15950. request.path = "/admins/24/";
  15951. ASSERT_FALSE(matcher.match(request));
  15952. }
  15953. TEST(PathParamsTest, ExtraFragments) {
  15954. const auto pattern = "/users/:id";
  15955. detail::PathParamsMatcher matcher(pattern);
  15956. Request request;
  15957. request.path = "/users/42/subscriptions";
  15958. ASSERT_FALSE(matcher.match(request));
  15959. }
  15960. TEST(PathParamsTest, MissingTrailingParam) {
  15961. const auto pattern = "/users/:id";
  15962. detail::PathParamsMatcher matcher(pattern);
  15963. Request request;
  15964. request.path = "/users";
  15965. ASSERT_FALSE(matcher.match(request));
  15966. }
  15967. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15968. const auto pattern = "/users/:id/subscriptions";
  15969. detail::PathParamsMatcher matcher(pattern);
  15970. Request request;
  15971. request.path = "/users/subscriptions";
  15972. ASSERT_FALSE(matcher.match(request));
  15973. }
  15974. TEST(PathParamsTest, MultipleParams) {
  15975. const auto pattern = "/users/:userid/subscriptions/:subid";
  15976. detail::PathParamsMatcher matcher(pattern);
  15977. Request request;
  15978. request.path = "/users/42/subscriptions/2";
  15979. ASSERT_TRUE(matcher.match(request));
  15980. std::unordered_map<std::string, std::string> expected_params = {
  15981. {"userid", "42"}, {"subid", "2"}};
  15982. EXPECT_EQ(request.path_params, expected_params);
  15983. }
  15984. TEST(PathParamsTest, SequenceOfParams) {
  15985. const auto pattern = "/values/:x/:y/:z";
  15986. detail::PathParamsMatcher matcher(pattern);
  15987. Request request;
  15988. request.path = "/values/1/2/3";
  15989. ASSERT_TRUE(matcher.match(request));
  15990. std::unordered_map<std::string, std::string> expected_params = {
  15991. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15992. EXPECT_EQ(request.path_params, expected_params);
  15993. }
  15994. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15995. const auto pattern = "/prefix:suffix";
  15996. detail::PathParamsMatcher matcher(pattern);
  15997. Request request;
  15998. request.path = "/prefix:suffix";
  15999. ASSERT_TRUE(matcher.match(request));
  16000. const std::unordered_map<std::string, std::string> expected_params = {};
  16001. EXPECT_EQ(request.path_params, expected_params);
  16002. }
  16003. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16004. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16005. // calling thread's stack on a long enough path for a quantified pattern;
  16006. // RegexMatcher must refuse to run regex matching on paths beyond
  16007. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16008. detail::RegexMatcher matcher("/files/(.*)");
  16009. Request within_limit;
  16010. within_limit.path = "/files/" + std::string(10, 'A');
  16011. EXPECT_TRUE(matcher.match(within_limit));
  16012. Request over_limit;
  16013. over_limit.path =
  16014. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16015. EXPECT_FALSE(matcher.match(over_limit));
  16016. }
  16017. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16018. Server svr;
  16019. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16020. res.set_content("ok", "text/plain");
  16021. });
  16022. auto port = svr.bind_to_any_port(HOST);
  16023. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16024. auto se = detail::scope_exit([&] {
  16025. svr.stop();
  16026. thread.join();
  16027. ASSERT_FALSE(svr.is_running());
  16028. });
  16029. svr.wait_until_ready();
  16030. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16031. // request URI limit; this used to be able to crash the process.
  16032. std::string path =
  16033. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16034. std::string req = "GET " + path +
  16035. " HTTP/1.1\r\n"
  16036. "Host: " +
  16037. std::string(HOST) + ":" + std::to_string(port) +
  16038. "\r\n"
  16039. "Connection: close\r\n"
  16040. "\r\n";
  16041. std::string response;
  16042. ASSERT_TRUE(send_request(5, req, &response, port));
  16043. EXPECT_NE(std::string::npos, response.find("404"));
  16044. }
  16045. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16046. Server svr;
  16047. auto handler = [](const Request & /*req*/, Response &res) {
  16048. res.set_content("hit", "text/plain");
  16049. };
  16050. // No regex metacharacter, so this one is compared literally
  16051. svr.Get("/literal/route", handler);
  16052. // '.' is a regex metacharacter, so this one must keep regex semantics
  16053. svr.Get("/a.c", handler);
  16054. auto port = svr.bind_to_any_port(HOST);
  16055. std::thread t([&]() { svr.listen_after_bind(); });
  16056. auto se = detail::scope_exit([&] {
  16057. svr.stop();
  16058. t.join();
  16059. ASSERT_FALSE(svr.is_running());
  16060. });
  16061. svr.wait_until_ready();
  16062. Client cli(HOST, port);
  16063. struct {
  16064. const char *path;
  16065. int status;
  16066. } cases[] = {
  16067. {"/literal/route", StatusCode::OK_200},
  16068. {"/literal/routes", StatusCode::NotFound_404},
  16069. {"/literal/rout", StatusCode::NotFound_404},
  16070. {"/abc", StatusCode::OK_200},
  16071. {"/a.c", StatusCode::OK_200},
  16072. };
  16073. for (const auto &x : cases) {
  16074. auto res = cli.Get(x.path);
  16075. ASSERT_TRUE(res) << x.path;
  16076. EXPECT_EQ(x.status, res->status) << x.path;
  16077. }
  16078. }
  16079. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16080. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16081. // from exhausting the stack, so it must only constrain routes that actually
  16082. // run a regular expression. A literal route is matched by comparison and
  16083. // stays usable at any length.
  16084. Server svr;
  16085. const std::string pattern =
  16086. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16087. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16088. res.set_content("hit", "text/plain");
  16089. });
  16090. auto port = svr.bind_to_any_port(HOST);
  16091. std::thread t([&]() { svr.listen_after_bind(); });
  16092. auto se = detail::scope_exit([&] {
  16093. svr.stop();
  16094. t.join();
  16095. ASSERT_FALSE(svr.is_running());
  16096. });
  16097. svr.wait_until_ready();
  16098. Client cli(HOST, port);
  16099. auto res = cli.Get(pattern);
  16100. ASSERT_TRUE(res);
  16101. EXPECT_EQ(StatusCode::OK_200, res->status);
  16102. }
  16103. TEST(ParseUrlTest, VariousPatterns) {
  16104. {
  16105. detail::UrlComponents uc;
  16106. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16107. EXPECT_EQ("http", uc.scheme);
  16108. EXPECT_EQ("example.com", uc.host);
  16109. EXPECT_EQ("8080", uc.port);
  16110. EXPECT_EQ("/path", uc.path);
  16111. EXPECT_EQ("?q=1", uc.query);
  16112. }
  16113. {
  16114. detail::UrlComponents uc;
  16115. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16116. EXPECT_EQ("https", uc.scheme);
  16117. EXPECT_EQ("example.com", uc.host);
  16118. EXPECT_TRUE(uc.port.empty());
  16119. EXPECT_EQ("/path", uc.path);
  16120. }
  16121. {
  16122. detail::UrlComponents uc;
  16123. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16124. EXPECT_EQ("::1", uc.host);
  16125. EXPECT_EQ("8080", uc.port);
  16126. EXPECT_EQ("/path", uc.path);
  16127. }
  16128. {
  16129. detail::UrlComponents uc;
  16130. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16131. }
  16132. {
  16133. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16134. // the path while the connection still targets the bracketed host.
  16135. detail::UrlComponents uc;
  16136. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16137. }
  16138. {
  16139. detail::UrlComponents uc;
  16140. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16141. }
  16142. {
  16143. detail::UrlComponents uc;
  16144. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16145. EXPECT_EQ("::1", uc.host);
  16146. EXPECT_TRUE(uc.port.empty());
  16147. EXPECT_EQ("/path", uc.path);
  16148. }
  16149. {
  16150. detail::UrlComponents uc;
  16151. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16152. EXPECT_TRUE(uc.scheme.empty());
  16153. EXPECT_EQ("example.com", uc.host);
  16154. EXPECT_EQ("/path", uc.path);
  16155. EXPECT_EQ("?q=1", uc.query);
  16156. }
  16157. {
  16158. detail::UrlComponents uc;
  16159. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16160. EXPECT_TRUE(uc.host.empty());
  16161. EXPECT_EQ("/path", uc.path);
  16162. EXPECT_EQ("?q=1", uc.query);
  16163. }
  16164. {
  16165. detail::UrlComponents uc;
  16166. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16167. EXPECT_EQ("example.com", uc.host);
  16168. EXPECT_EQ("8080", uc.port);
  16169. }
  16170. {
  16171. // Unix socket path — must not be parsed as host
  16172. detail::UrlComponents uc;
  16173. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16174. EXPECT_TRUE(uc.host.empty());
  16175. }
  16176. {
  16177. detail::UrlComponents uc;
  16178. ASSERT_TRUE(detail::parse_url("", uc));
  16179. EXPECT_TRUE(uc.host.empty());
  16180. EXPECT_TRUE(uc.path.empty());
  16181. }
  16182. {
  16183. detail::UrlComponents uc;
  16184. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16185. }
  16186. {
  16187. detail::UrlComponents uc;
  16188. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16189. }
  16190. {
  16191. // Accepted by parse_url; callers restrict to http/https
  16192. detail::UrlComponents uc;
  16193. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16194. EXPECT_EQ("ftp", uc.scheme);
  16195. }
  16196. {
  16197. detail::UrlComponents uc;
  16198. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16199. }
  16200. {
  16201. detail::UrlComponents uc;
  16202. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16203. }
  16204. }
  16205. TEST(ParseUrlTest, FragmentHandling) {
  16206. {
  16207. detail::UrlComponents uc;
  16208. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16209. EXPECT_EQ("/path", uc.path);
  16210. EXPECT_TRUE(uc.query.empty());
  16211. }
  16212. {
  16213. detail::UrlComponents uc;
  16214. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16215. EXPECT_TRUE(uc.path.empty());
  16216. EXPECT_TRUE(uc.query.empty());
  16217. }
  16218. }
  16219. TEST(ParseUrlTest, UserinfoHandling) {
  16220. // Userinfo with @ but no colon — host includes @
  16221. detail::UrlComponents uc;
  16222. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16223. EXPECT_EQ("user@host.com", uc.host);
  16224. EXPECT_EQ("/path", uc.path);
  16225. }
  16226. TEST(ParseUrlTest, IPv6EdgeCases) {
  16227. {
  16228. detail::UrlComponents uc;
  16229. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16230. EXPECT_TRUE(uc.scheme.empty());
  16231. EXPECT_EQ("::1", uc.host);
  16232. EXPECT_EQ("8080", uc.port);
  16233. }
  16234. {
  16235. // Zone ID '%25' is not in [a-fA-F0-9:]
  16236. detail::UrlComponents uc;
  16237. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16238. }
  16239. }
  16240. TEST(ParseUrlTest, SchemeEdgeCases) {
  16241. {
  16242. detail::UrlComponents uc;
  16243. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16244. }
  16245. {
  16246. detail::UrlComponents uc;
  16247. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16248. }
  16249. {
  16250. detail::UrlComponents uc;
  16251. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16252. }
  16253. }
  16254. TEST(ParseUrlTest, PortEdgeCases) {
  16255. {
  16256. detail::UrlComponents uc;
  16257. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16258. EXPECT_TRUE(uc.port.empty());
  16259. EXPECT_EQ("/path", uc.path);
  16260. }
  16261. {
  16262. // parse_url accepts any port string; validation is done by parse_port
  16263. detail::UrlComponents uc;
  16264. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16265. EXPECT_EQ("abc", uc.port);
  16266. }
  16267. }
  16268. TEST(ParseUrlTest, WebSocketPatterns) {
  16269. {
  16270. detail::UrlComponents uc;
  16271. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16272. EXPECT_EQ("ws", uc.scheme);
  16273. EXPECT_EQ("echo.example.com", uc.host);
  16274. EXPECT_EQ("8080", uc.port);
  16275. EXPECT_EQ("/ws", uc.path);
  16276. }
  16277. {
  16278. detail::UrlComponents uc;
  16279. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16280. EXPECT_EQ("wss", uc.scheme);
  16281. EXPECT_EQ("echo.example.com", uc.host);
  16282. EXPECT_TRUE(uc.port.empty());
  16283. EXPECT_EQ("/ws", uc.path);
  16284. }
  16285. }
  16286. TEST(ParseUrlTest, QueryOnly) {
  16287. detail::UrlComponents uc;
  16288. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16289. EXPECT_TRUE(uc.host.empty());
  16290. EXPECT_TRUE(uc.path.empty());
  16291. EXPECT_EQ("?q=1&r=2", uc.query);
  16292. }
  16293. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16294. detail::UrlComponents uc;
  16295. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16296. EXPECT_TRUE(uc.scheme.empty());
  16297. EXPECT_EQ("example.com", uc.host);
  16298. EXPECT_EQ("443", uc.port);
  16299. EXPECT_EQ("/path", uc.path);
  16300. }
  16301. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16302. // If ipv6 regex working, regex match codepath is taken.
  16303. // else port will default to 80 in Client impl
  16304. int clientImplMagicPort = 80;
  16305. int port = 4321;
  16306. // above ports must be different to avoid false negative
  16307. EXPECT_NE(clientImplMagicPort, port);
  16308. std::string ipV6TestURL = "http://[ff06::c3]";
  16309. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16310. CLIENT_PRIVATE_KEY_FILE);
  16311. EXPECT_EQ(cli.port(), port);
  16312. }
  16313. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16314. auto file_path = "./www/dir/index.html";
  16315. auto dir_path = "./www/dir";
  16316. detail::FileStat stat_file(file_path);
  16317. EXPECT_TRUE(stat_file.is_file());
  16318. EXPECT_FALSE(stat_file.is_dir());
  16319. detail::FileStat stat_dir(dir_path);
  16320. EXPECT_FALSE(stat_dir.is_file());
  16321. EXPECT_TRUE(stat_dir.is_dir());
  16322. }
  16323. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16324. // IPv4 with default HTTP port (80)
  16325. EXPECT_EQ("example.com",
  16326. detail::make_host_and_port_string("example.com", 80, false));
  16327. // IPv4 with default HTTPS port (443)
  16328. EXPECT_EQ("example.com",
  16329. detail::make_host_and_port_string("example.com", 443, true));
  16330. // IPv4 with non-default HTTP port
  16331. EXPECT_EQ("example.com:8080",
  16332. detail::make_host_and_port_string("example.com", 8080, false));
  16333. // IPv4 with non-default HTTPS port
  16334. EXPECT_EQ("example.com:8443",
  16335. detail::make_host_and_port_string("example.com", 8443, true));
  16336. // IPv6 with default HTTP port (80)
  16337. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16338. // IPv6 with default HTTPS port (443)
  16339. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16340. // IPv6 with non-default HTTP port
  16341. EXPECT_EQ("[::1]:8080",
  16342. detail::make_host_and_port_string("::1", 8080, false));
  16343. // IPv6 with non-default HTTPS port
  16344. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16345. // IPv6 full address with default port
  16346. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16347. detail::make_host_and_port_string(
  16348. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16349. // IPv6 full address with non-default port
  16350. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16351. detail::make_host_and_port_string(
  16352. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16353. // IPv6 localhost with non-default port
  16354. EXPECT_EQ("[::1]:3000",
  16355. detail::make_host_and_port_string("::1", 3000, false));
  16356. // IPv6 with zone ID (link-local address) with default port
  16357. EXPECT_EQ("[fe80::1%eth0]",
  16358. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16359. // IPv6 with zone ID (link-local address) with non-default port
  16360. EXPECT_EQ("[fe80::1%eth0]:8080",
  16361. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16362. // Edge case: Port 443 with is_ssl=false (should add port)
  16363. EXPECT_EQ("example.com:443",
  16364. detail::make_host_and_port_string("example.com", 443, false));
  16365. // Edge case: Port 80 with is_ssl=true (should add port)
  16366. EXPECT_EQ("example.com:80",
  16367. detail::make_host_and_port_string("example.com", 80, true));
  16368. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16369. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16370. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16371. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16372. // Security fix: Already bracketed IPv6 should not get double brackets
  16373. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16374. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16375. EXPECT_EQ("[::1]:8080",
  16376. detail::make_host_and_port_string("[::1]", 8080, false));
  16377. EXPECT_EQ("[2001:db8::1]:8080",
  16378. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16379. EXPECT_EQ("[fe80::1%eth0]",
  16380. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16381. EXPECT_EQ("[fe80::1%eth0]:8080",
  16382. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16383. // Edge case: Empty host (should return as-is)
  16384. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16385. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16386. // This is a known limitation but shouldn't crash
  16387. EXPECT_EQ("[host:name]",
  16388. detail::make_host_and_port_string("host:name", 80, false));
  16389. // Port number edge cases (no validation, but should not crash)
  16390. EXPECT_EQ("example.com:0",
  16391. detail::make_host_and_port_string("example.com", 0, false));
  16392. EXPECT_EQ("example.com:-1",
  16393. detail::make_host_and_port_string("example.com", -1, false));
  16394. EXPECT_EQ("example.com:65535",
  16395. detail::make_host_and_port_string("example.com", 65535, false));
  16396. EXPECT_EQ("example.com:65536",
  16397. detail::make_host_and_port_string("example.com", 65536, false));
  16398. }
  16399. #ifdef CPPHTTPLIB_SSL_ENABLED
  16400. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16401. httplib::SSLClient cli("roblox.com", 443);
  16402. cli.set_follow_location(true);
  16403. auto res = cli.Get("/");
  16404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16405. EXPECT_EQ(StatusCode::OK_200, res->status);
  16406. }
  16407. #endif
  16408. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16409. Server svr;
  16410. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16411. EXPECT_EQ(res.status, 400);
  16412. });
  16413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16414. auto se = detail::scope_exit([&] {
  16415. svr.stop();
  16416. thread.join();
  16417. ASSERT_FALSE(svr.is_running());
  16418. });
  16419. svr.wait_until_ready();
  16420. Client cli(HOST, PORT);
  16421. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16422. }
  16423. TEST(InvalidHeaderCharsTest, is_field_name) {
  16424. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16425. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16426. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16427. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16428. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16429. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16430. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16431. EXPECT_FALSE(detail::fields::is_field_name(""));
  16432. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16433. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16434. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16435. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16436. }
  16437. TEST(InvalidHeaderCharsTest, is_field_value) {
  16438. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16439. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16440. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16441. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16442. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16443. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16444. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16445. EXPECT_TRUE(detail::fields::is_field_value(""));
  16446. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16447. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16448. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16449. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16450. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16451. }
  16452. TEST(InvalidHeaderCharsTest, OnServer) {
  16453. Server svr;
  16454. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16455. std::string header = "Not Set";
  16456. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16457. res.set_header(header, "value");
  16458. res.set_content("Page Content Page Content", "text/plain");
  16459. });
  16460. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16461. std::string header = "Not Set";
  16462. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16463. res.set_header("X-Test", header);
  16464. res.set_content("Page Content Page Content", "text/plain");
  16465. });
  16466. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16467. auto se = detail::scope_exit([&] {
  16468. svr.stop();
  16469. thread.join();
  16470. ASSERT_FALSE(svr.is_running());
  16471. });
  16472. svr.wait_until_ready();
  16473. Client cli(HOST, PORT);
  16474. {
  16475. auto res = cli.Get(
  16476. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16478. EXPECT_EQ("Page Content Page Content", res->body);
  16479. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16480. }
  16481. {
  16482. auto res = cli.Get(
  16483. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16485. EXPECT_EQ("Page Content Page Content", res->body);
  16486. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16487. }
  16488. }
  16489. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16490. auto handled = false;
  16491. Server svr;
  16492. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16493. thread t = thread([&] { svr.listen(HOST, PORT); });
  16494. auto se = detail::scope_exit([&] {
  16495. svr.stop();
  16496. t.join();
  16497. ASSERT_FALSE(svr.is_running());
  16498. ASSERT_FALSE(handled);
  16499. });
  16500. svr.wait_until_ready();
  16501. auto req = "POST /test HTTP/1.1\r\n"
  16502. "Content-Length: x\r\n"
  16503. "\r\n";
  16504. std::string response;
  16505. ASSERT_TRUE(send_request(1, req, &response));
  16506. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16507. response.substr(0, response.find("\r\n")));
  16508. }
  16509. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16510. // case-insensitive, and a server that receives a 100-continue expectation in
  16511. // an HTTP/1.0 request MUST ignore it.
  16512. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16513. std::string response;
  16514. ASSERT_TRUE(send_request(1, req, &response, port));
  16515. *got_100 = response.find("100 Continue") != std::string::npos;
  16516. }
  16517. class ExpectTokenTest : public ::testing::Test {
  16518. protected:
  16519. void SetUp() override {
  16520. svr_.Post("/p", [](const Request &, Response &res) {
  16521. res.set_content("ok", "text/plain");
  16522. });
  16523. port_ = svr_.bind_to_any_port(HOST);
  16524. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16525. svr_.wait_until_ready();
  16526. }
  16527. void TearDown() override {
  16528. svr_.stop();
  16529. if (thread_.joinable()) { thread_.join(); }
  16530. }
  16531. std::string request(const char *version, const char *expect_value) const {
  16532. return std::string("POST /p ") + version +
  16533. "\r\n"
  16534. "Host: localhost\r\n"
  16535. "Content-Length: 2\r\n"
  16536. "Connection: close\r\n"
  16537. "Expect: " +
  16538. expect_value +
  16539. "\r\n"
  16540. "\r\n"
  16541. "hi";
  16542. }
  16543. Server svr_;
  16544. int port_ = 0;
  16545. thread thread_;
  16546. };
  16547. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16548. bool got_100 = false;
  16549. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16550. EXPECT_TRUE(got_100);
  16551. }
  16552. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16553. bool got_100 = true;
  16554. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16555. EXPECT_FALSE(got_100);
  16556. }
  16557. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16558. bool got_100 = false;
  16559. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16560. EXPECT_TRUE(got_100);
  16561. }
  16562. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16563. bool got_100 = false;
  16564. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16565. EXPECT_TRUE(got_100);
  16566. }
  16567. // `100 Continue` is sent only when the server starts reading the body, so a
  16568. // request rejected before that never invites the client to send it. The
  16569. // requests below carry the expectation but withhold the body, as a client
  16570. // waiting for `100 Continue` would.
  16571. // A POST that expects `100 Continue` and withholds its two-byte body.
  16572. static std::string expect_headers_only(const std::string &path) {
  16573. return "POST " + path +
  16574. " HTTP/1.1\r\n"
  16575. "Host: localhost\r\n"
  16576. "Content-Length: 2\r\n"
  16577. "Expect: 100-continue\r\n"
  16578. "\r\n";
  16579. }
  16580. class ExpectLazyContinueTest : public ::testing::Test {
  16581. protected:
  16582. void SetUp() override {
  16583. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16584. if (req.path == "/pre-routing") {
  16585. res.status = StatusCode::Unauthorized_401;
  16586. return Server::HandlerResponse::Handled;
  16587. }
  16588. return Server::HandlerResponse::Unhandled;
  16589. });
  16590. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16591. if (req.matched_route == "/pre-request") {
  16592. res.status = StatusCode::Forbidden_403;
  16593. return Server::HandlerResponse::Handled;
  16594. }
  16595. return Server::HandlerResponse::Unhandled;
  16596. });
  16597. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16598. res.set_content("ok", "text/plain");
  16599. });
  16600. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16601. res.set_content("ok", "text/plain");
  16602. });
  16603. svr_.Post("/reader-used", [](const Request &, Response &res,
  16604. const ContentReader &content_reader) {
  16605. std::string body;
  16606. content_reader([&](const char *data, size_t len) {
  16607. body.append(data, len);
  16608. return true;
  16609. });
  16610. res.set_content(body, "text/plain");
  16611. });
  16612. svr_.Post("/reader-unused",
  16613. [](const Request &, Response &res, const ContentReader &) {
  16614. res.set_content("ignored", "text/plain");
  16615. });
  16616. port_ = svr_.bind_to_any_port(HOST);
  16617. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16618. svr_.wait_until_ready();
  16619. }
  16620. void TearDown() override {
  16621. svr_.stop();
  16622. if (thread_.joinable()) { thread_.join(); }
  16623. }
  16624. // Sends `req` and reads until the server closes the connection. Returns
  16625. // false if the read had to wait for the client-side timeout instead.
  16626. bool send_until_closed(const std::string &req, std::string *resp) const {
  16627. auto start = std::chrono::steady_clock::now();
  16628. if (!send_request(3, req, resp, port_)) { return false; }
  16629. auto elapsed = std::chrono::steady_clock::now() - start;
  16630. return elapsed < std::chrono::seconds(2);
  16631. }
  16632. // The final response comes without `100 Continue`, and the server closes
  16633. // the connection since the body may or may not follow.
  16634. void expect_final_without_interim(const std::string &path,
  16635. const char *status_line) const {
  16636. std::string resp;
  16637. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16638. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16639. EXPECT_EQ(0u, resp.find(status_line));
  16640. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16641. }
  16642. Server svr_;
  16643. int port_ = 0;
  16644. thread thread_;
  16645. };
  16646. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16647. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16648. }
  16649. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16650. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16651. }
  16652. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16653. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16654. }
  16655. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16656. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16657. }
  16658. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16659. // The body follows once `100 Continue` has had time to arrive.
  16660. auto req = expect_headers_only("/reader-used");
  16661. req.insert(req.size() - 2, "Connection: close\r\n");
  16662. std::string resp;
  16663. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16664. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16665. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16666. EXPECT_NE(std::string::npos, resp.find("hi"));
  16667. }
  16668. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16669. // Large enough for the client to add `Expect: 100-continue` itself.
  16670. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16671. std::atomic<bool> body_sent{false};
  16672. Client cli(HOST, port_);
  16673. auto res = cli.Post(
  16674. "/pre-request", length,
  16675. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16676. body_sent = true;
  16677. std::string chunk(len, 'x');
  16678. sink.write(chunk.data(), chunk.size());
  16679. return true;
  16680. },
  16681. "application/octet-stream");
  16682. ASSERT_TRUE(res);
  16683. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16684. EXPECT_FALSE(body_sent);
  16685. }
  16686. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16687. Server svr;
  16688. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16689. return StatusCode::ExpectationFailed_417;
  16690. });
  16691. svr.Post("/p", [](const Request &, Response &res) {
  16692. res.set_content("ok", "text/plain");
  16693. });
  16694. auto port = svr.bind_to_any_port(HOST);
  16695. thread t = thread([&] { svr.listen_after_bind(); });
  16696. auto se = detail::scope_exit([&] {
  16697. svr.stop();
  16698. t.join();
  16699. });
  16700. svr.wait_until_ready();
  16701. std::string resp;
  16702. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16703. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16704. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16705. // Exactly one response: the route handler must not run after the 417.
  16706. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16707. }
  16708. #ifndef _WIN32
  16709. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16710. static constexpr char reject[] = "Unauthorized";
  16711. static constexpr char accept[] = "Upload accepted";
  16712. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16713. Server svr;
  16714. svr.set_expect_100_continue_handler(
  16715. [](const Request & /*req*/, Response &res) {
  16716. res.status = StatusCode::Unauthorized_401;
  16717. res.set_content(reject, "text/plain");
  16718. return res.status;
  16719. });
  16720. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16721. res.set_content(accept, "text/plain");
  16722. });
  16723. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16724. auto se = detail::scope_exit([&] {
  16725. svr.stop();
  16726. thread.join();
  16727. ASSERT_FALSE(svr.is_running());
  16728. });
  16729. svr.wait_until_ready();
  16730. {
  16731. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16732. curl_easy_init(), &curl_easy_cleanup};
  16733. ASSERT_NE(curl, nullptr);
  16734. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16735. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16736. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16737. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16738. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16739. &curl_slist_free_all};
  16740. ASSERT_NE(list, nullptr);
  16741. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16742. struct read_data {
  16743. size_t read_size;
  16744. size_t total_size;
  16745. } data = {0, total_size};
  16746. using read_callback_t =
  16747. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16748. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16749. void *userdata) -> size_t {
  16750. read_data *d = (read_data *)userdata;
  16751. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16752. std::fill_n(ptr, size * nmemb, 'A');
  16753. d->read_size += size * nmemb;
  16754. return size * nmemb;
  16755. };
  16756. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16757. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16758. std::vector<char> buffer;
  16759. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16760. using write_callback_t =
  16761. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16762. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16763. void *userdata) -> size_t {
  16764. std::vector<char> *buf = (std::vector<char> *)userdata;
  16765. buf->reserve(buf->size() + size * nmemb + 1);
  16766. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16767. return size * nmemb;
  16768. };
  16769. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16770. {
  16771. const auto res = curl_easy_perform(curl.get());
  16772. ASSERT_EQ(res, CURLE_OK);
  16773. }
  16774. {
  16775. auto response_code = long{};
  16776. const auto res =
  16777. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16778. ASSERT_EQ(res, CURLE_OK);
  16779. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16780. }
  16781. {
  16782. auto dl = curl_off_t{};
  16783. const auto res =
  16784. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16785. ASSERT_EQ(res, CURLE_OK);
  16786. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16787. }
  16788. {
  16789. buffer.push_back('\0');
  16790. ASSERT_STRCASEEQ(buffer.data(), reject);
  16791. }
  16792. }
  16793. }
  16794. #endif
  16795. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16796. // Regression test for #2458.
  16797. //
  16798. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16799. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16800. // ticket can make the client socket spuriously readable during the
  16801. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16802. // the client withholds the body and then blocks reading a response that never
  16803. // comes, failing with `Failed to read connection`.
  16804. //
  16805. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16806. // within the timeout. This raw OpenSSL server deliberately never sends
  16807. // `100 Continue`; the client must still deliver the body and receive 200.
  16808. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16809. signal(SIGPIPE, SIG_IGN);
  16810. const auto port = PORT + 4;
  16811. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16812. ASSERT_NE(srv, INVALID_SOCKET);
  16813. int opt = 1;
  16814. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16815. sockaddr_in addr{};
  16816. addr.sin_family = AF_INET;
  16817. addr.sin_port = htons(static_cast<uint16_t>(port));
  16818. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16819. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16820. ASSERT_EQ(0, ::listen(srv, 1));
  16821. std::atomic<size_t> server_body_bytes{0};
  16822. auto server_thread = std::thread([&] {
  16823. sockaddr_in cli_addr{};
  16824. socklen_t cli_len = sizeof(cli_addr);
  16825. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16826. if (cli == INVALID_SOCKET) { return; }
  16827. // Bound the lifetime of the server side so a buggy client (which never
  16828. // sends the body) cannot make this thread block forever on join.
  16829. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16830. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16831. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16832. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16833. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16834. SSL *ssl = SSL_new(ctx);
  16835. SSL_set_fd(ssl, static_cast<int>(cli));
  16836. if (SSL_accept(ssl) > 0) {
  16837. // Read the request headers. Reading here also flushes the TLS 1.3
  16838. // session tickets to the client. Deliberately do NOT send
  16839. // `100 Continue`.
  16840. std::string buf;
  16841. char tmp[1024];
  16842. while (buf.find("\r\n\r\n") == std::string::npos) {
  16843. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16844. if (n <= 0) { break; }
  16845. buf.append(tmp, static_cast<size_t>(n));
  16846. }
  16847. // A correct client sends the body now; count what arrives.
  16848. auto pos = buf.find("\r\n\r\n");
  16849. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16850. while (body < 4096) {
  16851. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16852. if (n <= 0) { break; }
  16853. body += static_cast<size_t>(n);
  16854. }
  16855. server_body_bytes = body;
  16856. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16857. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16858. SSL_shutdown(ssl);
  16859. }
  16860. SSL_free(ssl);
  16861. detail::close_socket(cli);
  16862. SSL_CTX_free(ctx);
  16863. });
  16864. auto se = detail::scope_exit([&] {
  16865. server_thread.join();
  16866. detail::close_socket(srv);
  16867. });
  16868. SSLClient cli("127.0.0.1", port);
  16869. cli.enable_server_certificate_verification(false);
  16870. cli.set_connection_timeout(5, 0);
  16871. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16872. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16873. std::string body(4096, 'A');
  16874. auto res = cli.Put("/api/test", body, "application/json");
  16875. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16876. EXPECT_EQ(StatusCode::OK_200, res->status);
  16877. EXPECT_EQ(body.size(), server_body_bytes.load());
  16878. }
  16879. #endif
  16880. template <typename S, typename C>
  16881. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16882. svr.Get("/stream", [&](const Request &, Response &res) {
  16883. auto data = new std::string("01234567890123456789");
  16884. res.set_content_provider(
  16885. data->size(), "text/plain",
  16886. [&, data](size_t offset, size_t length, DataSink &sink) {
  16887. const size_t DATA_CHUNK_SIZE = 4;
  16888. const auto &d = *data;
  16889. std::this_thread::sleep_for(std::chrono::seconds(1));
  16890. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16891. return true;
  16892. },
  16893. [data](bool success) {
  16894. EXPECT_FALSE(success);
  16895. delete data;
  16896. });
  16897. });
  16898. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16899. auto i = new size_t(0);
  16900. res.set_content_provider(
  16901. "text/plain",
  16902. [i](size_t, DataSink &sink) {
  16903. if (*i < 5) {
  16904. std::this_thread::sleep_for(std::chrono::seconds(1));
  16905. sink.write("abcd", 4);
  16906. (*i)++;
  16907. } else {
  16908. sink.done();
  16909. }
  16910. return true;
  16911. },
  16912. [i](bool success) {
  16913. EXPECT_FALSE(success);
  16914. delete i;
  16915. });
  16916. });
  16917. svr.Get("/chunked", [&](const Request &, Response &res) {
  16918. auto i = new size_t(0);
  16919. res.set_chunked_content_provider(
  16920. "text/plain",
  16921. [i](size_t, DataSink &sink) {
  16922. if (*i < 5) {
  16923. std::this_thread::sleep_for(std::chrono::seconds(1));
  16924. sink.os << "abcd";
  16925. (*i)++;
  16926. } else {
  16927. sink.done();
  16928. }
  16929. return true;
  16930. },
  16931. [i](bool success) {
  16932. EXPECT_FALSE(success);
  16933. delete i;
  16934. });
  16935. });
  16936. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16937. auto se = detail::scope_exit([&] {
  16938. svr.stop();
  16939. listen_thread.join();
  16940. ASSERT_FALSE(svr.is_running());
  16941. });
  16942. svr.wait_until_ready();
  16943. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16944. {
  16945. auto start = std::chrono::steady_clock::now();
  16946. auto res = cli.Get("/stream");
  16947. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16948. std::chrono::steady_clock::now() - start)
  16949. .count();
  16950. ASSERT_FALSE(res);
  16951. EXPECT_EQ(Error::Read, res.error());
  16952. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16953. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16954. }
  16955. {
  16956. auto start = std::chrono::steady_clock::now();
  16957. auto res = cli.Get("/stream_without_length");
  16958. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16959. std::chrono::steady_clock::now() - start)
  16960. .count();
  16961. ASSERT_FALSE(res);
  16962. EXPECT_EQ(Error::Read, res.error());
  16963. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16964. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16965. }
  16966. {
  16967. auto start = std::chrono::steady_clock::now();
  16968. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16969. EXPECT_EQ("abcd", string(data, data_length));
  16970. return true;
  16971. });
  16972. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16973. std::chrono::steady_clock::now() - start)
  16974. .count();
  16975. ASSERT_FALSE(res);
  16976. EXPECT_EQ(Error::Read, res.error());
  16977. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16978. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16979. }
  16980. }
  16981. TEST(MaxTimeoutTest, ContentStream) {
  16982. time_t timeout = 2000;
  16983. time_t threshold = 200;
  16984. Server svr;
  16985. Client cli("localhost", PORT);
  16986. max_timeout_test(svr, cli, timeout, threshold);
  16987. }
  16988. #ifdef CPPHTTPLIB_SSL_ENABLED
  16989. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16990. time_t timeout = 2000;
  16991. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16993. SSLClient cli("localhost", PORT);
  16994. cli.enable_server_certificate_verification(false);
  16995. max_timeout_test(svr, cli, timeout, threshold);
  16996. }
  16997. #endif
  16998. class EventDispatcher {
  16999. public:
  17000. EventDispatcher() {}
  17001. bool wait_event(DataSink *sink) {
  17002. unique_lock<mutex> lk(m_);
  17003. int id = id_;
  17004. // Wait with timeout to prevent hanging if client disconnects
  17005. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17006. [&] { return cid_ == id; })) {
  17007. return false; // Timeout occurred
  17008. }
  17009. sink->write(message_.data(), message_.size());
  17010. return true;
  17011. }
  17012. void send_event(const string &message) {
  17013. lock_guard<mutex> lk(m_);
  17014. cid_ = id_++;
  17015. message_ = message;
  17016. cv_.notify_all();
  17017. }
  17018. private:
  17019. mutex m_;
  17020. condition_variable cv_;
  17021. atomic_int id_{0};
  17022. atomic_int cid_{-1};
  17023. string message_;
  17024. };
  17025. TEST(ClientInThreadTest, Issue2068) {
  17026. EventDispatcher ed;
  17027. Server svr;
  17028. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17029. res.set_chunked_content_provider("text/event-stream",
  17030. [&](size_t /*offset*/, DataSink &sink) {
  17031. return ed.wait_event(&sink);
  17032. });
  17033. });
  17034. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17035. svr.wait_until_ready();
  17036. thread event_thread([&] {
  17037. int id = 0;
  17038. while (svr.is_running()) {
  17039. this_thread::sleep_for(chrono::milliseconds(500));
  17040. std::stringstream ss;
  17041. ss << "data: " << id << "\n\n";
  17042. ed.send_event(ss.str());
  17043. id++;
  17044. }
  17045. });
  17046. auto se = detail::scope_exit([&] {
  17047. svr.stop();
  17048. listen_thread.join();
  17049. event_thread.join();
  17050. ASSERT_FALSE(svr.is_running());
  17051. });
  17052. {
  17053. auto client = detail::make_unique<Client>(HOST, PORT);
  17054. client->set_read_timeout(std::chrono::minutes(10));
  17055. std::atomic<bool> stop{false};
  17056. std::thread t([&] {
  17057. client->Get("/event1",
  17058. [&](const char *, size_t) -> bool { return !stop; });
  17059. });
  17060. std::this_thread::sleep_for(std::chrono::seconds(2));
  17061. stop = true;
  17062. client->stop();
  17063. t.join();
  17064. // Reset client after thread has finished
  17065. client.reset();
  17066. }
  17067. }
  17068. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17069. auto handled = false;
  17070. Server svr;
  17071. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17072. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17073. auto se = detail::scope_exit([&] {
  17074. svr.stop();
  17075. t.join();
  17076. ASSERT_FALSE(svr.is_running());
  17077. ASSERT_FALSE(handled);
  17078. });
  17079. svr.wait_until_ready();
  17080. // Two Content-Length headers with different values — must be rejected
  17081. auto req = "POST /test HTTP/1.1\r\n"
  17082. "Content-Length: 5\r\n"
  17083. "Content-Length: 10\r\n"
  17084. "\r\n"
  17085. "hello";
  17086. std::string response;
  17087. ASSERT_TRUE(send_request(1, req, &response));
  17088. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17089. response.substr(0, response.find("\r\n")));
  17090. }
  17091. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17092. auto handled = false;
  17093. Server svr;
  17094. svr.Post("/test", [&](const Request &, Response &res) {
  17095. handled = true;
  17096. res.set_content("ok", "text/plain");
  17097. });
  17098. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17099. auto se = detail::scope_exit([&] {
  17100. svr.stop();
  17101. t.join();
  17102. ASSERT_FALSE(svr.is_running());
  17103. ASSERT_TRUE(handled);
  17104. });
  17105. svr.wait_until_ready();
  17106. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17107. auto req = "POST /test HTTP/1.1\r\n"
  17108. "Content-Length: 5\r\n"
  17109. "Content-Length: 5\r\n"
  17110. "\r\n"
  17111. "hello";
  17112. std::string response;
  17113. ASSERT_TRUE(send_request(1, req, &response));
  17114. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17115. }
  17116. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17117. Server svr;
  17118. svr.Get("/test", [](const Request &, Response &res) {
  17119. res.set_content("ok", "text/plain");
  17120. });
  17121. auto port = svr.bind_to_any_port(HOST);
  17122. thread t = thread([&] { svr.listen_after_bind(); });
  17123. auto se = detail::scope_exit([&] {
  17124. svr.stop();
  17125. t.join();
  17126. ASSERT_FALSE(svr.is_running());
  17127. });
  17128. svr.wait_until_ready();
  17129. auto status_line = [&](const std::string &host_lines) {
  17130. std::string res;
  17131. send_request(
  17132. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17133. &res, port);
  17134. return res.substr(0, res.find("\r\n"));
  17135. };
  17136. const char *accepted[] = {
  17137. "Host: localhost\r\n",
  17138. "Host: a.example:8080\r\n",
  17139. "Host: my_service\r\n",
  17140. "Host: [::1]:8080\r\n",
  17141. "Host: [fe80::1%25eth0]\r\n",
  17142. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17143. };
  17144. for (auto host_lines : accepted) {
  17145. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17146. }
  17147. const char *rejected[] = {
  17148. "Host: a.example\r\nHost: b.example\r\n",
  17149. "Host: a.example\r\nHost: a.example\r\n",
  17150. "Host: a@b.example\r\n",
  17151. "Host: a.example/b\r\n",
  17152. "Host: a.example\\b\r\n",
  17153. "Host: a.example?b\r\n",
  17154. "Host: a.example#b\r\n",
  17155. "Host: a.example b.example\r\n",
  17156. };
  17157. for (auto host_lines : rejected) {
  17158. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17159. << host_lines;
  17160. }
  17161. }
  17162. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17163. Server svr;
  17164. svr.Get("/", [](const Request &req, Response &res) {
  17165. EXPECT_EQ(2U, req.trailers.size());
  17166. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17167. // Denied
  17168. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17169. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17170. // Accepted
  17171. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17172. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17173. EXPECT_TRUE(req.has_trailer("X-World"));
  17174. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17175. res.set_content("ok", "text/plain");
  17176. });
  17177. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17178. auto se = detail::scope_exit([&] {
  17179. svr.stop();
  17180. t.join();
  17181. ASSERT_FALSE(svr.is_running());
  17182. });
  17183. svr.wait_until_ready();
  17184. const std::string req = "GET / HTTP/1.1\r\n"
  17185. "Transfer-Encoding: chunked\r\n"
  17186. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17187. "\r\n"
  17188. "0\r\n"
  17189. "Content-Length: 10\r\n"
  17190. "Host: internal.local\r\n"
  17191. "Content-Type: malicious/content\r\n"
  17192. "Cookie: any\r\n"
  17193. "Set-Cookie: any\r\n"
  17194. "X-Forwarded-For: attacker.com\r\n"
  17195. "X-Real-Ip: 1.1.1.1\r\n"
  17196. "X-Hello: hello\r\n"
  17197. "X-World: world\r\n"
  17198. "\r\n";
  17199. std::string res;
  17200. ASSERT_TRUE(send_request(1, req, &res));
  17201. }
  17202. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17203. // several field lines, and the combined value is what has to be parsed. A
  17204. // Trailer field split across lines therefore declares every name it lists;
  17205. // reading only the first line silently drops the trailers the later lines
  17206. // declare. The prohibited-trailer filter still applies to every line.
  17207. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17208. Server svr;
  17209. size_t observed_trailer_count = 0;
  17210. std::string observed_hello;
  17211. std::string observed_world;
  17212. bool observed_content_length = true;
  17213. svr.Get("/", [&](const Request &req, Response &res) {
  17214. observed_trailer_count = req.trailers.size();
  17215. observed_hello = req.get_trailer_value("X-Hello");
  17216. observed_world = req.get_trailer_value("X-World");
  17217. observed_content_length = req.has_trailer("Content-Length");
  17218. res.set_content("ok", "text/plain");
  17219. });
  17220. auto port = svr.bind_to_any_port(HOST);
  17221. thread t = thread([&]() { svr.listen_after_bind(); });
  17222. auto se = detail::scope_exit([&] {
  17223. svr.stop();
  17224. t.join();
  17225. ASSERT_FALSE(svr.is_running());
  17226. });
  17227. svr.wait_until_ready();
  17228. const std::string req = "GET / HTTP/1.1\r\n"
  17229. "Transfer-Encoding: chunked\r\n"
  17230. "Trailer: X-Hello\r\n"
  17231. "Trailer: X-World, Content-Length\r\n"
  17232. "\r\n"
  17233. "0\r\n"
  17234. "X-Hello: hello\r\n"
  17235. "X-World: world\r\n"
  17236. "Content-Length: 10\r\n"
  17237. "\r\n";
  17238. std::string res;
  17239. ASSERT_TRUE(send_request(1, req, &res, port));
  17240. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17241. // Accepted: both field lines contribute to the declared set
  17242. EXPECT_EQ(2U, observed_trailer_count);
  17243. EXPECT_EQ(observed_hello, "hello");
  17244. EXPECT_EQ(observed_world, "world");
  17245. // Denied: a prohibited name stays prohibited on a later field line
  17246. EXPECT_FALSE(observed_content_length);
  17247. }
  17248. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17249. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17250. // unbounded run of fields that are never declared, because the counter would
  17251. // only advance for declared fields.
  17252. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17253. Server svr;
  17254. bool handler_called = false;
  17255. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17256. handler_called = true;
  17257. res.set_content("ok", "text/plain");
  17258. });
  17259. auto port = svr.bind_to_any_port(HOST);
  17260. thread t = thread([&]() { svr.listen_after_bind(); });
  17261. auto se = detail::scope_exit([&] {
  17262. svr.stop();
  17263. t.join();
  17264. ASSERT_FALSE(svr.is_running());
  17265. });
  17266. svr.wait_until_ready();
  17267. // Declare nothing, then send far more undeclared trailer fields than the
  17268. // header-count limit. Parsing must stop and reject the request rather than
  17269. // read every line.
  17270. std::string req = "GET / HTTP/1.1\r\n"
  17271. "Transfer-Encoding: chunked\r\n"
  17272. "\r\n"
  17273. "0\r\n";
  17274. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17275. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17276. }
  17277. req += "\r\n";
  17278. std::string res;
  17279. ASSERT_TRUE(send_request(1, req, &res, port));
  17280. // The request is rejected before the handler runs.
  17281. EXPECT_FALSE(handler_called);
  17282. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17283. }
  17284. // The set of declared trailer names is capped so a peer cannot grow it without
  17285. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17286. // declared past the cap is not honored, even if the field is actually sent.
  17287. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17288. Server svr;
  17289. // One name inside the cap and one past it, so the test tracks the cap rather
  17290. // than a fixed count.
  17291. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17292. const std::string within_cap_name = "X-T-0";
  17293. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17294. bool observed_within_cap = false;
  17295. bool observed_past_cap = false;
  17296. svr.Get("/", [&](const Request &req, Response &res) {
  17297. observed_within_cap = req.has_trailer(within_cap_name);
  17298. observed_past_cap = req.has_trailer(past_cap_name);
  17299. res.set_content("ok", "text/plain");
  17300. });
  17301. auto port = svr.bind_to_any_port(HOST);
  17302. thread t = thread([&]() { svr.listen_after_bind(); });
  17303. auto se = detail::scope_exit([&] {
  17304. svr.stop();
  17305. t.join();
  17306. ASSERT_FALSE(svr.is_running());
  17307. });
  17308. svr.wait_until_ready();
  17309. // Declare more trailer names than the cap in a single Trailer field, then
  17310. // actually send the first (within the cap) and the last (past it).
  17311. std::string trailer_decl = "Trailer: ";
  17312. for (int i = 0; i < declared_count; i++) {
  17313. if (i != 0) { trailer_decl += ", "; }
  17314. trailer_decl += "X-T-" + std::to_string(i);
  17315. }
  17316. trailer_decl += "\r\n";
  17317. const std::string req = "GET / HTTP/1.1\r\n"
  17318. "Transfer-Encoding: chunked\r\n" +
  17319. trailer_decl +
  17320. "\r\n"
  17321. "0\r\n" +
  17322. within_cap_name + ": a\r\n" + past_cap_name +
  17323. ": b\r\n"
  17324. "\r\n";
  17325. std::string res;
  17326. ASSERT_TRUE(send_request(1, req, &res, port));
  17327. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17328. // A name within the cap is honored; one declared past the cap is dropped.
  17329. EXPECT_TRUE(observed_within_cap);
  17330. EXPECT_FALSE(observed_past_cap);
  17331. }
  17332. // A direct client that is not listed in trusted_proxies must not be able to
  17333. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17334. // the peer address on the actual TCP connection determines whether the
  17335. // header is honored.
  17336. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17337. Server svr;
  17338. // Deliberately does NOT include the loopback address the test client
  17339. // actually connects from, so the direct connection is not a trusted proxy.
  17340. svr.set_trusted_proxies({"203.0.113.66"});
  17341. std::string observed_remote_addr;
  17342. svr.Get("/ip", [&](const Request &req, Response &res) {
  17343. observed_remote_addr = req.remote_addr;
  17344. res.set_content("ok", "text/plain");
  17345. });
  17346. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17347. auto se = detail::scope_exit([&] {
  17348. svr.stop();
  17349. t.join();
  17350. ASSERT_FALSE(svr.is_running());
  17351. });
  17352. svr.wait_until_ready();
  17353. Client cli(HOST, PORT);
  17354. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17356. EXPECT_EQ(StatusCode::OK_200, res->status);
  17357. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17358. // ignored entirely and the real connection-level address retained.
  17359. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17360. observed_remote_addr == "127.0.0.1");
  17361. }
  17362. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17363. Server svr;
  17364. std::string observed_remote_addr;
  17365. std::string observed_xff;
  17366. svr.Get("/ip", [&](const Request &req, Response &res) {
  17367. observed_remote_addr = req.remote_addr;
  17368. observed_xff = req.get_header_value("X-Forwarded-For");
  17369. res.set_content("ok", "text/plain");
  17370. });
  17371. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17372. auto se = detail::scope_exit([&] {
  17373. svr.stop();
  17374. t.join();
  17375. ASSERT_FALSE(svr.is_running());
  17376. });
  17377. svr.wait_until_ready();
  17378. Client cli(HOST, PORT);
  17379. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17381. EXPECT_EQ(StatusCode::OK_200, res->status);
  17382. EXPECT_EQ(observed_xff, "203.0.113.66");
  17383. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17384. observed_remote_addr == "127.0.0.1");
  17385. }
  17386. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17387. Server svr;
  17388. svr.set_trusted_proxies({"203.0.113.66"});
  17389. std::string observed_remote_addr;
  17390. std::string observed_xff;
  17391. svr.Get("/ip", [&](const Request &req, Response &res) {
  17392. observed_remote_addr = req.remote_addr;
  17393. observed_xff = req.get_header_value("X-Forwarded-For");
  17394. res.set_content("ok", "text/plain");
  17395. });
  17396. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17397. auto se = detail::scope_exit([&] {
  17398. svr.stop();
  17399. t.join();
  17400. ASSERT_FALSE(svr.is_running());
  17401. });
  17402. svr.wait_until_ready();
  17403. Client cli(HOST, PORT);
  17404. auto res = cli.Get("/ip");
  17405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17406. EXPECT_EQ(StatusCode::OK_200, res->status);
  17407. EXPECT_EQ(observed_xff, "");
  17408. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17409. observed_remote_addr == "127.0.0.1");
  17410. }
  17411. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17412. Server svr;
  17413. // Include the loopback address the test client actually connects from, so
  17414. // the direct connection itself is recognized as the trusted proxy hop.
  17415. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17416. std::string observed_remote_addr;
  17417. std::string observed_xff;
  17418. svr.Get("/ip", [&](const Request &req, Response &res) {
  17419. observed_remote_addr = req.remote_addr;
  17420. observed_xff = req.get_header_value("X-Forwarded-For");
  17421. res.set_content("ok", "text/plain");
  17422. });
  17423. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17424. auto se = detail::scope_exit([&] {
  17425. svr.stop();
  17426. t.join();
  17427. ASSERT_FALSE(svr.is_running());
  17428. });
  17429. svr.wait_until_ready();
  17430. Client cli(HOST, PORT);
  17431. auto res = cli.Get(
  17432. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17434. EXPECT_EQ(StatusCode::OK_200, res->status);
  17435. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17436. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17437. }
  17438. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17439. Server svr;
  17440. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17441. std::string observed_remote_addr;
  17442. std::string observed_xff;
  17443. svr.Get("/ip", [&](const Request &req, Response &res) {
  17444. observed_remote_addr = req.remote_addr;
  17445. observed_xff = req.get_header_value("X-Forwarded-For");
  17446. res.set_content("ok", "text/plain");
  17447. });
  17448. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17449. auto se = detail::scope_exit([&] {
  17450. svr.stop();
  17451. t.join();
  17452. ASSERT_FALSE(svr.is_running());
  17453. });
  17454. svr.wait_until_ready();
  17455. Client cli(HOST, PORT);
  17456. auto res = cli.Get(
  17457. "/ip",
  17458. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17460. EXPECT_EQ(StatusCode::OK_200, res->status);
  17461. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17462. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17463. }
  17464. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17465. Server svr;
  17466. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17467. std::string observed_remote_addr;
  17468. std::string observed_xff;
  17469. svr.Get("/ip", [&](const Request &req, Response &res) {
  17470. observed_remote_addr = req.remote_addr;
  17471. observed_xff = req.get_header_value("X-Forwarded-For");
  17472. res.set_content("ok", "text/plain");
  17473. });
  17474. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17475. auto se = detail::scope_exit([&] {
  17476. svr.stop();
  17477. t.join();
  17478. ASSERT_FALSE(svr.is_running());
  17479. });
  17480. svr.wait_until_ready();
  17481. Client cli(HOST, PORT);
  17482. auto res = cli.Get(
  17483. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17485. EXPECT_EQ(StatusCode::OK_200, res->status);
  17486. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17487. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17488. // and must not be selected.
  17489. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17490. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17491. }
  17492. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17493. Server svr;
  17494. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17495. std::string observed_remote_addr;
  17496. svr.Get("/ip", [&](const Request &req, Response &res) {
  17497. observed_remote_addr = req.remote_addr;
  17498. res.set_content("ok", "text/plain");
  17499. });
  17500. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17501. auto se = detail::scope_exit([&] {
  17502. svr.stop();
  17503. t.join();
  17504. ASSERT_FALSE(svr.is_running());
  17505. });
  17506. svr.wait_until_ready();
  17507. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17508. // a forged address and the trusted proxy's own address; the forged value must
  17509. // not win over the address the trusted proxy actually recorded.
  17510. Client cli(HOST, PORT);
  17511. auto res = cli.Get(
  17512. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17514. EXPECT_EQ(StatusCode::OK_200, res->status);
  17515. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17516. }
  17517. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17518. Server svr;
  17519. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17520. std::string observed_remote_addr;
  17521. std::string observed_xff;
  17522. svr.Get("/ip", [&](const Request &req, Response &res) {
  17523. observed_remote_addr = req.remote_addr;
  17524. observed_xff = req.get_header_value("X-Forwarded-For");
  17525. res.set_content("ok", "text/plain");
  17526. });
  17527. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17528. auto se = detail::scope_exit([&] {
  17529. svr.stop();
  17530. t.join();
  17531. ASSERT_FALSE(svr.is_running());
  17532. });
  17533. svr.wait_until_ready();
  17534. Client cli(HOST, PORT);
  17535. auto res = cli.Get(
  17536. "/ip",
  17537. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17539. EXPECT_EQ(StatusCode::OK_200, res->status);
  17540. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17541. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17542. }
  17543. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17544. Server svr;
  17545. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17546. std::string observed_remote_addr;
  17547. std::string observed_xff;
  17548. svr.Get("/ip", [&](const Request &req, Response &res) {
  17549. observed_remote_addr = req.remote_addr;
  17550. observed_xff = req.get_header_value("X-Forwarded-For");
  17551. res.set_content("ok", "text/plain");
  17552. });
  17553. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17554. auto se = detail::scope_exit([&] {
  17555. svr.stop();
  17556. t.join();
  17557. ASSERT_FALSE(svr.is_running());
  17558. });
  17559. svr.wait_until_ready();
  17560. std::string raw_req =
  17561. "GET /ip HTTP/1.1\r\n"
  17562. "Host: localhost\r\n"
  17563. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17564. "Connection: close\r\n"
  17565. "\r\n";
  17566. std::string out;
  17567. ASSERT_TRUE(send_request(5, raw_req, &out));
  17568. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17569. // Header parser trims surrounding whitespace of the header value
  17570. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17571. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17572. }
  17573. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17574. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17575. // their own X-Forwarded-For as a separate field line rather than extending the
  17576. // one the client sent, so every occurrence has to be taken into account.
  17577. // Reading only the first one hands back the address the client chose.
  17578. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17579. Server svr;
  17580. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17581. std::string observed_remote_addr;
  17582. size_t observed_xff_count = 0;
  17583. svr.Get("/ip", [&](const Request &req, Response &res) {
  17584. observed_remote_addr = req.remote_addr;
  17585. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17586. res.set_content("ok", "text/plain");
  17587. });
  17588. auto port = svr.bind_to_any_port(HOST);
  17589. thread t = thread([&]() { svr.listen_after_bind(); });
  17590. auto se = detail::scope_exit([&] {
  17591. svr.stop();
  17592. t.join();
  17593. ASSERT_FALSE(svr.is_running());
  17594. });
  17595. svr.wait_until_ready();
  17596. // The client supplies the first field line; the trusted proxy appends the
  17597. // address it observed as a second one.
  17598. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17599. "Host: localhost\r\n"
  17600. "X-Forwarded-For: 1.2.3.4\r\n"
  17601. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17602. "Connection: close\r\n"
  17603. "\r\n";
  17604. std::string out;
  17605. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17606. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17607. EXPECT_EQ(observed_xff_count, 2U);
  17608. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17609. // The same chain spread over one field line per hop derives the same client
  17610. // address, i.e. the split and the comma-joined representations agree.
  17611. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17612. "Host: localhost\r\n"
  17613. "X-Forwarded-For: 1.2.3.4\r\n"
  17614. "X-Forwarded-For: 198.51.100.23\r\n"
  17615. "X-Forwarded-For: 192.0.2.45\r\n"
  17616. "Connection: close\r\n"
  17617. "\r\n";
  17618. out.clear();
  17619. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17620. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17621. EXPECT_EQ(observed_xff_count, 3U);
  17622. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17623. }
  17624. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17625. // crash the server (it used to call front() on an empty vector inside
  17626. // get_client_ip). The connection-level remote address must be retained instead.
  17627. static void run_malformed_xff_test(const std::string &xff_value) {
  17628. Server svr;
  17629. svr.set_trusted_proxies({"192.0.2.45"});
  17630. std::string observed_remote_addr;
  17631. svr.Get("/ip", [&](const Request &req, Response &res) {
  17632. observed_remote_addr = req.remote_addr;
  17633. res.set_content("ok", "text/plain");
  17634. });
  17635. int port = 0;
  17636. thread t = thread([&]() {
  17637. port = svr.bind_to_any_port(HOST);
  17638. svr.listen_after_bind();
  17639. });
  17640. auto se = detail::scope_exit([&] {
  17641. svr.stop();
  17642. t.join();
  17643. ASSERT_FALSE(svr.is_running());
  17644. });
  17645. svr.wait_until_ready();
  17646. Client cli(HOST, port);
  17647. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17649. EXPECT_EQ(StatusCode::OK_200, res->status);
  17650. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17651. observed_remote_addr == "127.0.0.1");
  17652. }
  17653. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17654. run_malformed_xff_test("");
  17655. }
  17656. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17657. run_malformed_xff_test(",");
  17658. }
  17659. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17660. run_malformed_xff_test(", , ,");
  17661. }
  17662. // The same rule applies to Accept: a request whose acceptable types are spread
  17663. // over several field lines must be negotiated against all of them.
  17664. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17665. // case-insensitive connection options. Comparing the whole field value against
  17666. // one option misses a client that sends several of them, and misses every
  17667. // casing but the one written in the comparison.
  17668. //
  17669. // Sends req, reads the response, then reuses the same socket for a second
  17670. // request to find out whether the server kept the connection.
  17671. static void probe_connection_reuse(int port, const std::string &req,
  17672. bool *announced_close, bool *reusable) {
  17673. auto error = Error::Success;
  17674. auto sock = detail::create_client_socket(
  17675. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17676. /*connection_timeout_sec=*/5, 0,
  17677. /*read_timeout_sec=*/1, 0,
  17678. /*write_timeout_sec=*/5, 0, std::string(), error);
  17679. ASSERT_NE(sock, INVALID_SOCKET);
  17680. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17681. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17682. "Host: localhost\r\n"
  17683. "Connection: close\r\n"
  17684. "\r\n";
  17685. std::string first_response;
  17686. std::string second_response;
  17687. detail::process_client_socket(
  17688. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17689. [&](Stream &strm) {
  17690. if (strm.write(req.data(), req.size()) !=
  17691. static_cast<ssize_t>(req.size())) {
  17692. return false;
  17693. }
  17694. char buf[512];
  17695. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17696. // Headers plus the two-byte body of the handler below
  17697. while (reader.getline()) {
  17698. first_response += reader.ptr();
  17699. if (first_response.find("ok") != std::string::npos) { break; }
  17700. }
  17701. if (strm.write(second.data(), second.size()) !=
  17702. static_cast<ssize_t>(second.size())) {
  17703. return true;
  17704. }
  17705. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17706. while (reader2.getline()) {
  17707. second_response += reader2.ptr();
  17708. if (second_response.find("ok") != std::string::npos) { break; }
  17709. }
  17710. return true;
  17711. });
  17712. *announced_close =
  17713. first_response.find("Connection: close") != std::string::npos;
  17714. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17715. }
  17716. class ConnectionTokenTest : public ::testing::Test {
  17717. protected:
  17718. void SetUp() override {
  17719. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17720. res.set_content("ok", "text/plain");
  17721. });
  17722. port_ = svr_.bind_to_any_port(HOST);
  17723. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17724. svr_.wait_until_ready();
  17725. }
  17726. void TearDown() override {
  17727. svr_.stop();
  17728. if (thread_.joinable()) { thread_.join(); }
  17729. }
  17730. Server svr_;
  17731. int port_ = 0;
  17732. thread thread_;
  17733. };
  17734. // "close" alongside another option still closes the connection, and the
  17735. // response says so rather than leaving the peer to discover it.
  17736. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17737. bool announced_close = false;
  17738. bool reusable = true;
  17739. probe_connection_reuse(port_,
  17740. "GET /keepalive HTTP/1.1\r\n"
  17741. "Host: localhost\r\n"
  17742. "Connection: keep-alive, close\r\n"
  17743. "\r\n",
  17744. &announced_close, &reusable);
  17745. EXPECT_TRUE(announced_close);
  17746. EXPECT_FALSE(reusable);
  17747. }
  17748. // "close" split over two field lines is the same list, so it is honored too.
  17749. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17750. bool announced_close = false;
  17751. bool reusable = true;
  17752. probe_connection_reuse(port_,
  17753. "GET /keepalive HTTP/1.1\r\n"
  17754. "Host: localhost\r\n"
  17755. "Connection: keep-alive\r\n"
  17756. "Connection: close\r\n"
  17757. "\r\n",
  17758. &announced_close, &reusable);
  17759. EXPECT_TRUE(announced_close);
  17760. EXPECT_FALSE(reusable);
  17761. }
  17762. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17763. // keep-alive in the spelling everyone actually sends keeps its connection.
  17764. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17765. bool announced_close = false;
  17766. bool reusable = false;
  17767. probe_connection_reuse(port_,
  17768. "GET /keepalive HTTP/1.0\r\n"
  17769. "Host: localhost\r\n"
  17770. "Connection: keep-alive\r\n"
  17771. "\r\n",
  17772. &announced_close, &reusable);
  17773. EXPECT_FALSE(announced_close);
  17774. EXPECT_TRUE(reusable);
  17775. }
  17776. // A token the value merely contains is not the token itself.
  17777. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17778. bool announced_close = false;
  17779. bool reusable = false;
  17780. probe_connection_reuse(port_,
  17781. "GET /keepalive HTTP/1.1\r\n"
  17782. "Host: localhost\r\n"
  17783. "Connection: notclose\r\n"
  17784. "\r\n",
  17785. &announced_close, &reusable);
  17786. EXPECT_FALSE(announced_close);
  17787. EXPECT_TRUE(reusable);
  17788. }
  17789. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17790. Server svr;
  17791. std::vector<std::string> observed_types;
  17792. svr.Get("/", [&](const Request &req, Response &res) {
  17793. observed_types = req.accept_content_types;
  17794. res.set_content("ok", "text/plain");
  17795. });
  17796. auto port = svr.bind_to_any_port(HOST);
  17797. thread t = thread([&]() { svr.listen_after_bind(); });
  17798. auto se = detail::scope_exit([&] {
  17799. svr.stop();
  17800. t.join();
  17801. ASSERT_FALSE(svr.is_running());
  17802. });
  17803. svr.wait_until_ready();
  17804. Client cli(HOST, port);
  17805. Headers headers;
  17806. headers.emplace("Accept", "text/plain;q=0.5");
  17807. headers.emplace("Accept", "application/json");
  17808. auto res = cli.Get("/", headers);
  17809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17810. EXPECT_EQ(StatusCode::OK_200, res->status);
  17811. // Sorted by q-value, so the second field line's type comes first
  17812. ASSERT_EQ(2U, observed_types.size());
  17813. EXPECT_EQ("application/json", observed_types[0]);
  17814. EXPECT_EQ("text/plain", observed_types[1]);
  17815. }
  17816. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17817. // empty field line must not contribute a bare comma to the combined value.
  17818. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17819. Server svr;
  17820. std::vector<std::string> observed_types;
  17821. svr.Get("/", [&](const Request &req, Response &res) {
  17822. observed_types = req.accept_content_types;
  17823. res.set_content("ok", "text/plain");
  17824. });
  17825. auto port = svr.bind_to_any_port(HOST);
  17826. thread t = thread([&]() { svr.listen_after_bind(); });
  17827. auto se = detail::scope_exit([&] {
  17828. svr.stop();
  17829. t.join();
  17830. ASSERT_FALSE(svr.is_running());
  17831. });
  17832. svr.wait_until_ready();
  17833. // Empty first field line, then a real one
  17834. std::string raw_req = "GET / HTTP/1.1\r\n"
  17835. "Host: localhost\r\n"
  17836. "Accept:\r\n"
  17837. "Accept: application/json\r\n"
  17838. "Connection: close\r\n"
  17839. "\r\n";
  17840. std::string out;
  17841. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17842. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17843. ASSERT_EQ(1U, observed_types.size());
  17844. EXPECT_EQ("application/json", observed_types[0]);
  17845. }
  17846. // The skip in get_combined_header_value() is what keeps an empty field line
  17847. // from contributing a bare comma. Only a trailing empty field line exercises
  17848. // it: a leading one is already covered by the "combined is still empty" check,
  17849. // and parse_accept_header() now ignores the empty element either way, so the
  17850. // request-level test above can no longer tell the two apart.
  17851. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17852. Headers headers;
  17853. headers.emplace("Accept", "text/html");
  17854. headers.emplace("Accept", "");
  17855. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17856. headers.clear();
  17857. headers.emplace("Accept", "");
  17858. headers.emplace("Accept", "application/json");
  17859. EXPECT_EQ("application/json",
  17860. detail::get_combined_header_value(headers, "Accept"));
  17861. }
  17862. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17863. // An encoding offered on a later Accept-Encoding field line is still offered.
  17864. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17865. Server svr;
  17866. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17867. res.set_content(std::string(1024, 'x'), "text/plain");
  17868. });
  17869. auto port = svr.bind_to_any_port(HOST);
  17870. thread t = thread([&]() { svr.listen_after_bind(); });
  17871. auto se = detail::scope_exit([&] {
  17872. svr.stop();
  17873. t.join();
  17874. ASSERT_FALSE(svr.is_running());
  17875. });
  17876. svr.wait_until_ready();
  17877. Client cli(HOST, port);
  17878. cli.set_decompress(false);
  17879. Headers headers;
  17880. headers.emplace("Accept-Encoding", "identity");
  17881. headers.emplace("Accept-Encoding", "gzip");
  17882. auto res = cli.Get("/", headers);
  17883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17884. EXPECT_EQ(StatusCode::OK_200, res->status);
  17885. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17886. }
  17887. #endif
  17888. #ifndef _WIN32
  17889. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17890. Server svr;
  17891. svr.Post("/post", [&](const Request &req, Response &res) {
  17892. res.set_content(req.body, "text/plain");
  17893. });
  17894. svr.Put("/put", [&](const Request &req, Response &res) {
  17895. res.set_content(req.body, "text/plain");
  17896. });
  17897. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17898. res.set_content(req.body, "text/plain");
  17899. });
  17900. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17901. res.set_content(req.body, "text/plain");
  17902. });
  17903. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17904. auto se = detail::scope_exit([&] {
  17905. svr.stop();
  17906. t.join();
  17907. ASSERT_FALSE(svr.is_running());
  17908. });
  17909. svr.wait_until_ready();
  17910. std::string resp;
  17911. // POST without Content-Length
  17912. ASSERT_TRUE(send_request(5,
  17913. "POST /post HTTP/1.1\r\n"
  17914. "Host: localhost\r\n"
  17915. "Connection: close\r\n"
  17916. "\r\n",
  17917. &resp));
  17918. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17919. // PUT without Content-Length
  17920. resp.clear();
  17921. ASSERT_TRUE(send_request(5,
  17922. "PUT /put HTTP/1.1\r\n"
  17923. "Host: localhost\r\n"
  17924. "Connection: close\r\n"
  17925. "\r\n",
  17926. &resp));
  17927. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17928. // PATCH without Content-Length
  17929. resp.clear();
  17930. ASSERT_TRUE(send_request(5,
  17931. "PATCH /patch HTTP/1.1\r\n"
  17932. "Host: localhost\r\n"
  17933. "Connection: close\r\n"
  17934. "\r\n",
  17935. &resp));
  17936. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17937. // DELETE without Content-Length
  17938. resp.clear();
  17939. ASSERT_TRUE(send_request(5,
  17940. "DELETE /delete HTTP/1.1\r\n"
  17941. "Host: localhost\r\n"
  17942. "Connection: close\r\n"
  17943. "\r\n",
  17944. &resp));
  17945. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17946. }
  17947. #endif
  17948. //==============================================================================
  17949. // open_stream() Tests
  17950. //==============================================================================
  17951. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17952. std::string result;
  17953. char buf[8192];
  17954. ssize_t n;
  17955. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17956. result.append(buf, static_cast<size_t>(n));
  17957. }
  17958. return result;
  17959. }
  17960. // Mock stream for unit tests
  17961. class MockStream : public Stream {
  17962. public:
  17963. std::string data;
  17964. size_t pos = 0;
  17965. ssize_t error_after = -1; // -1 = no error
  17966. explicit MockStream(const std::string &d, ssize_t err = -1)
  17967. : data(d), error_after(err) {}
  17968. bool is_readable() const override { return true; }
  17969. bool wait_readable() const override { return true; }
  17970. bool wait_writable() const override { return true; }
  17971. ssize_t read(char *ptr, size_t size) override {
  17972. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17973. if (pos >= data.size()) return 0;
  17974. size_t limit =
  17975. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17976. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17977. std::memcpy(ptr, data.data() + pos, to_read);
  17978. pos += to_read;
  17979. return static_cast<ssize_t>(to_read);
  17980. }
  17981. ssize_t write(const char *, size_t) override { return -1; }
  17982. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17983. ip = "127.0.0.1";
  17984. port = 0;
  17985. }
  17986. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17987. ip = "127.0.0.1";
  17988. port = 0;
  17989. }
  17990. socket_t socket() const override { return INVALID_SOCKET; }
  17991. time_t duration() const override { return 0; }
  17992. };
  17993. TEST(StreamHandleTest, Basic) {
  17994. ClientImpl::StreamHandle handle;
  17995. EXPECT_FALSE(handle.is_valid());
  17996. handle.response = detail::make_unique<Response>();
  17997. handle.error = Error::Connection;
  17998. EXPECT_FALSE(handle.is_valid());
  17999. handle.error = Error::Success;
  18000. EXPECT_TRUE(handle.is_valid());
  18001. }
  18002. TEST(BodyReaderTest, Basic) {
  18003. MockStream stream("Hello, World!");
  18004. detail::BodyReader reader;
  18005. reader.stream = &stream;
  18006. reader.content_length = 13;
  18007. char buf[32];
  18008. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18009. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18010. EXPECT_TRUE(reader.eof);
  18011. }
  18012. TEST(BodyReaderTest, NoStream) {
  18013. detail::BodyReader reader;
  18014. char buf[32];
  18015. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18016. EXPECT_EQ(Error::Connection, reader.last_error);
  18017. }
  18018. TEST(BodyReaderTest, Error) {
  18019. MockStream stream("Hello, World!", 5);
  18020. detail::BodyReader reader;
  18021. reader.stream = &stream;
  18022. reader.content_length = 13;
  18023. char buf[32];
  18024. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18025. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18026. EXPECT_EQ(Error::Read, reader.last_error);
  18027. }
  18028. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18029. // Mock-based StreamHandle tests relying on private internals are removed.
  18030. class OpenStreamTest : public ::testing::Test {
  18031. protected:
  18032. void SetUp() override {
  18033. svr_.Get("/hello", [](const Request &, Response &res) {
  18034. res.set_content("Hello World!", "text/plain");
  18035. });
  18036. svr_.Get("/large", [](const Request &, Response &res) {
  18037. res.set_content(std::string(10000, 'X'), "text/plain");
  18038. });
  18039. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18040. res.set_content("Hello World!", "image/jpeg");
  18041. res.set_header("Content-Encoding", "UTF-8");
  18042. });
  18043. svr_.Get("/chunked", [](const Request &, Response &res) {
  18044. res.set_chunked_content_provider("text/plain",
  18045. [](size_t offset, DataSink &sink) {
  18046. if (offset < 15) {
  18047. sink.write("chunk", 5);
  18048. return true;
  18049. }
  18050. sink.done();
  18051. return true;
  18052. });
  18053. });
  18054. svr_.Get("/compressible", [](const Request &, Response &res) {
  18055. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18056. DataSink &sink) {
  18057. if (offset < 100 * 1024) {
  18058. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18059. sink.write(chunk.data(), chunk.size());
  18060. return true;
  18061. }
  18062. sink.done();
  18063. return true;
  18064. });
  18065. });
  18066. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18067. [](const Request & /*req*/, Response &res) {
  18068. auto i = new int(0);
  18069. res.set_header("Trailer", "Content-Length, X-Allowed");
  18070. res.set_chunked_content_provider(
  18071. "text/plain",
  18072. [i](size_t /*offset*/, DataSink &sink) {
  18073. switch (*i) {
  18074. case 0: sink.os << "123"; break;
  18075. case 1: sink.os << "456"; break;
  18076. case 2: sink.os << "789"; break;
  18077. case 3: {
  18078. sink.done_with_trailer(
  18079. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18080. } break;
  18081. }
  18082. (*i)++;
  18083. return true;
  18084. },
  18085. [i](bool success) {
  18086. EXPECT_TRUE(success);
  18087. delete i;
  18088. });
  18089. });
  18090. // Echo headers endpoint for header-related tests
  18091. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18092. std::string body;
  18093. for (const auto &h : req.headers) {
  18094. body.append(h.first);
  18095. body.push_back(':');
  18096. body.append(h.second);
  18097. body.push_back('\n');
  18098. }
  18099. res.set_content(body, "text/plain");
  18100. });
  18101. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18102. std::string body;
  18103. for (const auto &h : req.headers) {
  18104. body.append(h.first);
  18105. body.push_back(':');
  18106. body.append(h.second);
  18107. body.push_back('\n');
  18108. }
  18109. res.set_content(body, "text/plain");
  18110. });
  18111. port_ = svr_.bind_to_any_port("127.0.0.1");
  18112. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18113. svr_.wait_until_ready();
  18114. }
  18115. void TearDown() override {
  18116. svr_.stop();
  18117. if (thread_.joinable()) thread_.join();
  18118. }
  18119. Server svr_;
  18120. std::thread thread_;
  18121. int port_ = 0;
  18122. };
  18123. TEST_F(OpenStreamTest, Basic) {
  18124. Client cli("127.0.0.1", port_);
  18125. auto handle = cli.open_stream("GET", "/hello");
  18126. EXPECT_TRUE(handle.is_valid());
  18127. EXPECT_EQ("Hello World!", read_all(handle));
  18128. }
  18129. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18130. Client cli("127.0.0.1", port_);
  18131. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18132. ASSERT_TRUE(handle.is_valid());
  18133. EXPECT_EQ("Hello World!", read_all(handle));
  18134. }
  18135. TEST_F(OpenStreamTest, SmallBuffer) {
  18136. Client cli("127.0.0.1", port_);
  18137. auto handle = cli.open_stream("GET", "/hello");
  18138. std::string result;
  18139. char buf[4];
  18140. ssize_t n;
  18141. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18142. result.append(buf, static_cast<size_t>(n));
  18143. EXPECT_EQ("Hello World!", result);
  18144. }
  18145. TEST_F(OpenStreamTest, DefaultHeaders) {
  18146. Client cli("127.0.0.1", port_);
  18147. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18148. {
  18149. auto handle = cli.open_stream("GET", "/echo-headers");
  18150. ASSERT_TRUE(handle.is_valid());
  18151. auto body = read_all(handle);
  18152. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18153. std::string::npos);
  18154. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18155. std::string::npos);
  18156. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18157. }
  18158. // open_stream POST with body and no explicit content_type should NOT add
  18159. // text/plain Content-Type (behavior differs from non-streaming path), but
  18160. // should include Content-Length
  18161. {
  18162. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18163. ASSERT_TRUE(handle.is_valid());
  18164. auto body = read_all(handle);
  18165. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18166. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18167. }
  18168. // open_stream POST with explicit Content-Type should preserve it
  18169. {
  18170. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18171. {{"Content-Type", "application/custom"}},
  18172. "{}", "application/custom");
  18173. ASSERT_TRUE(handle.is_valid());
  18174. auto body = read_all(handle);
  18175. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18176. }
  18177. // User-specified User-Agent must not be overwritten for stream API
  18178. {
  18179. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18180. {{"User-Agent", "MyAgent/1.2"}});
  18181. ASSERT_TRUE(handle.is_valid());
  18182. auto body = read_all(handle);
  18183. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18184. }
  18185. }
  18186. TEST_F(OpenStreamTest, Large) {
  18187. Client cli("127.0.0.1", port_);
  18188. auto handle = cli.open_stream("GET", "/large");
  18189. EXPECT_EQ(10000u, read_all(handle).size());
  18190. }
  18191. TEST_F(OpenStreamTest, ConnectionError) {
  18192. Client cli("127.0.0.1", 9999);
  18193. auto handle = cli.open_stream("GET", "/hello");
  18194. EXPECT_FALSE(handle.is_valid());
  18195. }
  18196. TEST_F(OpenStreamTest, Chunked) {
  18197. Client cli("127.0.0.1", port_);
  18198. auto handle = cli.open_stream("GET", "/chunked");
  18199. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18200. "Transfer-Encoding") == "chunked");
  18201. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18202. }
  18203. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18204. Client cli("127.0.0.1", port_);
  18205. auto handle =
  18206. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18207. ASSERT_TRUE(handle.is_valid());
  18208. // Consume body to allow trailers to be received/parsed
  18209. auto body = read_all(handle);
  18210. // Explicitly parse trailers (ensure trailers are available for assertion)
  18211. handle.parse_trailers_if_needed();
  18212. EXPECT_EQ(std::string("123456789"), body);
  18213. // The response should include a Trailer header declaring both names
  18214. ASSERT_TRUE(handle.response);
  18215. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18216. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18217. handle.response->get_header_value("Trailer"));
  18218. // Prohibited trailer must not be present
  18219. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18220. // Allowed trailer should be present
  18221. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18222. EXPECT_EQ(std::string("yes"),
  18223. handle.response->get_trailer_value("X-Allowed"));
  18224. // Verify trailers are NOT present as regular headers
  18225. EXPECT_EQ(std::string(""),
  18226. handle.response->get_header_value("Content-Length"));
  18227. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18228. }
  18229. static std::thread serve_single_response(std::promise<int> &port_promise,
  18230. const std::string &response) {
  18231. return std::thread([&port_promise, response] {
  18232. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18233. default_socket_options(srv);
  18234. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18235. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18236. sockaddr_in addr{};
  18237. addr.sin_family = AF_INET;
  18238. addr.sin_port = htons(0); // Let OS assign a free port
  18239. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18240. int opt = 1;
  18241. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18242. #ifdef _WIN32
  18243. reinterpret_cast<const char *>(&opt),
  18244. #else
  18245. &opt,
  18246. #endif
  18247. sizeof(opt));
  18248. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18249. ::listen(srv, 1) != 0) {
  18250. port_promise.set_value(-1);
  18251. detail::close_socket(srv);
  18252. return;
  18253. }
  18254. socklen_t addr_len = sizeof(addr);
  18255. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18256. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18257. sockaddr_in cli_addr{};
  18258. socklen_t cli_len = sizeof(cli_addr);
  18259. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18260. if (cli != INVALID_SOCKET) {
  18261. // Read the complete HTTP request (until the blank line that terminates
  18262. // headers) before sending the response. If the server closes the socket
  18263. // while the client's request data is still unread in the kernel receive
  18264. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18265. // connection on both sides: it discards the client's receive buffer
  18266. // (which already holds our response) and causes any in-progress write on
  18267. // the client to fail with ECONNRESET. Reading all request data first
  18268. // ensures close() emits a graceful FIN.
  18269. {
  18270. char rbuf[256];
  18271. std::string req;
  18272. while (req.find("\r\n\r\n") == std::string::npos) {
  18273. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18274. if (n <= 0) { break; }
  18275. req.append(rbuf, static_cast<size_t>(n));
  18276. }
  18277. }
  18278. ::send(cli,
  18279. #ifdef _WIN32
  18280. static_cast<const char *>(response.c_str()),
  18281. static_cast<int>(response.size()),
  18282. #else
  18283. response.c_str(), response.size(),
  18284. #endif
  18285. 0);
  18286. detail::close_socket(cli);
  18287. }
  18288. detail::close_socket(srv);
  18289. });
  18290. }
  18291. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18292. #ifndef _WIN32
  18293. signal(SIGPIPE, SIG_IGN);
  18294. #endif
  18295. std::promise<int> port_promise;
  18296. auto port_future = port_promise.get_future();
  18297. auto server_thread =
  18298. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18299. "Content-Type: text/plain\r\n"
  18300. "Content-Length: not-a-number\r\n"
  18301. "Connection: close\r\n"
  18302. "\r\n"
  18303. "hello");
  18304. auto port = port_future.get();
  18305. ASSERT_GT(port, 0);
  18306. Client cli("127.0.0.1", port);
  18307. auto handle = cli.open_stream("GET", "/");
  18308. EXPECT_FALSE(handle.is_valid());
  18309. server_thread.join();
  18310. }
  18311. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18312. #ifndef _WIN32
  18313. signal(SIGPIPE, SIG_IGN);
  18314. #endif
  18315. std::promise<int> port_promise;
  18316. auto port_future = port_promise.get_future();
  18317. auto server_thread = serve_single_response(
  18318. port_promise, "HTTP/1.1 200 OK\r\n"
  18319. "Content-Type: text/plain\r\n"
  18320. "Content-Length: 99999999999999999999999999\r\n"
  18321. "Connection: close\r\n"
  18322. "\r\n"
  18323. "hello");
  18324. auto port = port_future.get();
  18325. ASSERT_GT(port, 0);
  18326. // Historically std::stoull would throw std::out_of_range here and crash
  18327. // the process, then parsing silently clamped to a bogus framing length and
  18328. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18329. // so the stream fails to open, matching the not-a-number case above. The
  18330. // process still must NOT terminate.
  18331. Client cli("127.0.0.1", port);
  18332. auto handle = cli.open_stream("GET", "/");
  18333. EXPECT_FALSE(handle.is_valid());
  18334. server_thread.join();
  18335. }
  18336. // Serves `response` to the single request `fn` makes with a fresh client.
  18337. template <typename Fn>
  18338. static void with_single_response(const std::string &response, Fn fn) {
  18339. #ifndef _WIN32
  18340. signal(SIGPIPE, SIG_IGN);
  18341. #endif
  18342. std::promise<int> port_promise;
  18343. auto port_future = port_promise.get_future();
  18344. auto server_thread = serve_single_response(port_promise, response);
  18345. auto se = detail::scope_exit([&] { server_thread.join(); });
  18346. auto port = port_future.get();
  18347. ASSERT_GT(port, 0);
  18348. Client cli("127.0.0.1", port);
  18349. fn(cli);
  18350. }
  18351. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18352. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18353. // the chunked coding and drop Content-Length, so a front-end that trusts
  18354. // Content-Length would disagree about where the body ends (response
  18355. // smuggling). The client must reject such a response.
  18356. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18357. for (const char *te : {"chunked", "gzip, chunked"}) {
  18358. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18359. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18360. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18361. "5\r\nhello\r\n0\r\n\r\n";
  18362. with_single_response(response, [&](Client &cli) {
  18363. auto res = cli.Get("/");
  18364. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18365. EXPECT_EQ(Error::Read, res.error()) << te;
  18366. });
  18367. with_single_response(response, [&](Client &cli) {
  18368. auto handle = cli.open_stream("GET", "/");
  18369. EXPECT_FALSE(handle.is_valid()) << te;
  18370. EXPECT_EQ(Error::Read, handle.error) << te;
  18371. });
  18372. }
  18373. }
  18374. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18375. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18376. // closing the connection (unlike a request, which must be rejected).
  18377. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18378. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18379. "Transfer-Encoding: chunked\r\n"
  18380. "Connection: close\r\n"
  18381. "\r\n"
  18382. "5\r\nhello\r\n0\r\n\r\n",
  18383. "HTTP/1.1 200 OK\r\n"
  18384. "Transfer-Encoding: gzip\r\n"
  18385. "Connection: close\r\n"
  18386. "\r\n"
  18387. "hello"}) {
  18388. with_single_response(response, [&](Client &cli) {
  18389. auto res = cli.Get("/");
  18390. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18391. EXPECT_EQ("hello", res->body);
  18392. });
  18393. with_single_response(response, [&](Client &cli) {
  18394. auto handle = cli.open_stream("GET", "/");
  18395. ASSERT_TRUE(handle.is_valid()) << response;
  18396. EXPECT_EQ("hello", read_all(handle));
  18397. });
  18398. }
  18399. }
  18400. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18401. // framing headers describe nothing to read and must not be rejected.
  18402. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18403. const std::string framing = "Content-Length: 5\r\n"
  18404. "Transfer-Encoding: chunked\r\n"
  18405. "Connection: close\r\n"
  18406. "\r\n";
  18407. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18408. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18409. });
  18410. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18411. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18412. });
  18413. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18414. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18415. with_single_response(response, [&](Client &cli) {
  18416. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18417. });
  18418. with_single_response(response, [&](Client &cli) {
  18419. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18420. });
  18421. }
  18422. }
  18423. // A payload max length of 0 means no limit, however the body is framed.
  18424. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18425. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18426. "Transfer-Encoding: chunked\r\n"
  18427. "\r\n"
  18428. "5\r\nhello\r\n0\r\n\r\n",
  18429. "HTTP/1.1 200 OK\r\n"
  18430. "Connection: close\r\n"
  18431. "\r\n"
  18432. "hello"}) {
  18433. with_single_response(response, [&](Client &cli) {
  18434. cli.set_payload_max_length(0);
  18435. auto res = cli.Get("/");
  18436. ASSERT_TRUE(res) << response;
  18437. EXPECT_EQ("hello", res->body) << response;
  18438. });
  18439. }
  18440. }
  18441. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18442. Server svr;
  18443. svr.set_payload_max_length(0);
  18444. svr.Post("/echo", [](const Request &req, Response &res) {
  18445. res.set_content(req.body, "text/plain");
  18446. });
  18447. auto port = svr.bind_to_any_port(HOST);
  18448. thread t = thread([&] { svr.listen_after_bind(); });
  18449. auto se = detail::scope_exit([&] {
  18450. svr.stop();
  18451. t.join();
  18452. ASSERT_FALSE(svr.is_running());
  18453. });
  18454. svr.wait_until_ready();
  18455. Client cli(HOST, port);
  18456. auto res = cli.Post(
  18457. "/echo",
  18458. [](size_t /*offset*/, DataSink &sink) {
  18459. sink.write("hello", 5);
  18460. sink.done();
  18461. return true;
  18462. },
  18463. "text/plain");
  18464. ASSERT_TRUE(res);
  18465. EXPECT_EQ(StatusCode::OK_200, res->status);
  18466. EXPECT_EQ("hello", res->body);
  18467. }
  18468. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18469. TEST_F(OpenStreamTest, Gzip) {
  18470. Client cli("127.0.0.1", port_);
  18471. auto handle = cli.open_stream("GET", "/compressible", {},
  18472. {{"Accept-Encoding", "gzip"}});
  18473. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18474. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18475. }
  18476. #endif
  18477. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18478. TEST_F(OpenStreamTest, Brotli) {
  18479. Client cli("127.0.0.1", port_);
  18480. auto handle =
  18481. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18482. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18483. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18484. }
  18485. #endif
  18486. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18487. TEST_F(OpenStreamTest, Zstd) {
  18488. Client cli("127.0.0.1", port_);
  18489. auto handle = cli.open_stream("GET", "/compressible", {},
  18490. {{"Accept-Encoding", "zstd"}});
  18491. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18492. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18493. }
  18494. #endif
  18495. #ifdef CPPHTTPLIB_SSL_ENABLED
  18496. class SSLOpenStreamTest : public ::testing::Test {
  18497. protected:
  18498. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18499. void SetUp() override {
  18500. svr_.Get("/hello", [](const Request &, Response &res) {
  18501. res.set_content("Hello SSL World!", "text/plain");
  18502. });
  18503. svr_.Get("/chunked", [](const Request &, Response &res) {
  18504. res.set_chunked_content_provider("text/plain",
  18505. [](size_t offset, DataSink &sink) {
  18506. if (offset < 15) {
  18507. sink.write("chunk", 5);
  18508. return true;
  18509. }
  18510. sink.done();
  18511. return true;
  18512. });
  18513. });
  18514. svr_.Post("/echo", [](const Request &req, Response &res) {
  18515. res.set_content(req.body, req.get_header_value("Content-Type"));
  18516. });
  18517. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18518. std::string body = req.body;
  18519. res.set_chunked_content_provider(
  18520. "text/plain", [body](size_t offset, DataSink &sink) {
  18521. if (offset < body.size()) {
  18522. sink.write(body.data() + offset, body.size() - offset);
  18523. }
  18524. sink.done();
  18525. return true;
  18526. });
  18527. });
  18528. port_ = svr_.bind_to_any_port("127.0.0.1");
  18529. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18530. svr_.wait_until_ready();
  18531. }
  18532. void TearDown() override {
  18533. svr_.stop();
  18534. if (thread_.joinable()) thread_.join();
  18535. }
  18536. SSLServer svr_;
  18537. std::thread thread_;
  18538. int port_ = 0;
  18539. };
  18540. TEST_F(SSLOpenStreamTest, Basic) {
  18541. SSLClient cli("127.0.0.1", port_);
  18542. cli.enable_server_certificate_verification(false);
  18543. auto handle = cli.open_stream("GET", "/hello");
  18544. ASSERT_TRUE(handle.is_valid());
  18545. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18546. }
  18547. TEST_F(SSLOpenStreamTest, Chunked) {
  18548. SSLClient cli("127.0.0.1", port_);
  18549. cli.enable_server_certificate_verification(false);
  18550. auto handle = cli.open_stream("GET", "/chunked");
  18551. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18552. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18553. "Transfer-Encoding") == "chunked");
  18554. auto body = read_all(handle);
  18555. EXPECT_EQ("chunkchunkchunk", body);
  18556. }
  18557. TEST_F(SSLOpenStreamTest, Post) {
  18558. SSLClient cli("127.0.0.1", port_);
  18559. cli.enable_server_certificate_verification(false);
  18560. auto handle =
  18561. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18562. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18563. EXPECT_EQ(200, handle.response->status);
  18564. auto body = read_all(handle);
  18565. EXPECT_EQ("Hello SSL POST", body);
  18566. }
  18567. TEST_F(SSLOpenStreamTest, PostChunked) {
  18568. SSLClient cli("127.0.0.1", port_);
  18569. cli.enable_server_certificate_verification(false);
  18570. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18571. "Chunked SSL Data", "text/plain");
  18572. ASSERT_TRUE(handle.is_valid());
  18573. EXPECT_EQ(200, handle.response->status);
  18574. auto body = read_all(handle);
  18575. EXPECT_EQ("Chunked SSL Data", body);
  18576. }
  18577. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18578. // Content-Length is terminated by the server closing the connection. When the
  18579. // SSL peer sends a close_notify after the body, the client must treat it as a
  18580. // clean EOF and return a successful response rather than an error.
  18581. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18583. ASSERT_TRUE(svr.is_valid());
  18584. svr.set_keep_alive_max_count(1);
  18585. const std::string expected_body = "Hello from connection-close response!";
  18586. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18587. res.set_content_provider("text/plain",
  18588. [&](size_t offset, DataSink &sink) -> bool {
  18589. if (offset < expected_body.size()) {
  18590. sink.write(expected_body.data() + offset,
  18591. expected_body.size() - offset);
  18592. }
  18593. sink.done();
  18594. return true;
  18595. });
  18596. });
  18597. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18598. auto se = detail::scope_exit([&] {
  18599. svr.stop();
  18600. listen_thread.join();
  18601. ASSERT_FALSE(svr.is_running());
  18602. });
  18603. svr.wait_until_ready();
  18604. SSLClient cli(HOST, PORT);
  18605. cli.enable_server_certificate_verification(false);
  18606. auto res = cli.Get("/no-content-length");
  18607. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18608. EXPECT_EQ(StatusCode::OK_200, res->status);
  18609. EXPECT_EQ(expected_body, res->body);
  18610. }
  18611. #endif // CPPHTTPLIB_SSL_ENABLED
  18612. //==============================================================================
  18613. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18614. // results for various scenarios.
  18615. //==============================================================================
  18616. TEST(ParityTest, GetVsOpenStream) {
  18617. Server svr;
  18618. const std::string path = "/parity";
  18619. const std::string content = "Parity test content: hello world";
  18620. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18621. res.set_content(content, "text/plain");
  18622. });
  18623. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18624. auto se = detail::scope_exit([&] {
  18625. svr.stop();
  18626. t.join();
  18627. ASSERT_FALSE(svr.is_running());
  18628. });
  18629. svr.wait_until_ready();
  18630. Client cli(HOST, PORT);
  18631. // Non-stream path
  18632. auto r1 = cli.Get(path);
  18633. ASSERT_TRUE(r1);
  18634. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18635. // Stream path
  18636. auto h = cli.open_stream("GET", path);
  18637. ASSERT_TRUE(h.is_valid());
  18638. EXPECT_EQ(r1->body, read_all(h));
  18639. }
  18640. // Helper to compress data with provided compressor type T
  18641. template <typename Compressor>
  18642. static std::string compress_payload_for_parity(const std::string &in) {
  18643. std::string out;
  18644. Compressor compressor;
  18645. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18646. [&](const char *data, size_t n) {
  18647. out.append(data, n);
  18648. return true;
  18649. });
  18650. EXPECT_TRUE(ok);
  18651. return out;
  18652. }
  18653. // Helper function for compression parity tests
  18654. template <typename Compressor>
  18655. static void test_compression_parity(const std::string &original,
  18656. const std::string &path,
  18657. const std::string &encoding) {
  18658. const std::string compressed =
  18659. compress_payload_for_parity<Compressor>(original);
  18660. Server svr;
  18661. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18662. res.set_content(compressed, "application/octet-stream");
  18663. res.set_header("Content-Encoding", encoding);
  18664. });
  18665. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18666. auto se = detail::scope_exit([&] {
  18667. svr.stop();
  18668. t.join();
  18669. ASSERT_FALSE(svr.is_running());
  18670. });
  18671. svr.wait_until_ready();
  18672. Client cli(HOST, PORT);
  18673. // Non-streaming
  18674. {
  18675. auto res = cli.Get(path);
  18676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18677. EXPECT_EQ(StatusCode::OK_200, res->status);
  18678. EXPECT_EQ(original, res->body);
  18679. }
  18680. // Streaming
  18681. {
  18682. auto h = cli.open_stream("GET", path);
  18683. ASSERT_TRUE(h.is_valid());
  18684. EXPECT_EQ(original, read_all(h));
  18685. }
  18686. }
  18687. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18688. TEST(ParityTest, Gzip) {
  18689. test_compression_parity<detail::gzip_compressor>(
  18690. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18691. }
  18692. #endif
  18693. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18694. TEST(ParityTest, Brotli) {
  18695. test_compression_parity<detail::brotli_compressor>(
  18696. "Hello, brotli parity test payload", "/parity-br", "br");
  18697. }
  18698. #endif
  18699. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18700. TEST(ParityTest, Zstd) {
  18701. test_compression_parity<detail::zstd_compressor>(
  18702. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18703. }
  18704. #endif
  18705. //==============================================================================
  18706. // New Stream API Tests
  18707. //==============================================================================
  18708. inline std::string read_body(httplib::stream::Result &result) {
  18709. std::string body;
  18710. while (result.next()) {
  18711. body.append(result.data(), result.size());
  18712. }
  18713. return body;
  18714. }
  18715. TEST(ClientConnectionTest, Basic) {
  18716. httplib::ClientConnection conn;
  18717. EXPECT_FALSE(conn.is_open());
  18718. conn.sock = 1;
  18719. EXPECT_TRUE(conn.is_open());
  18720. httplib::ClientConnection conn2(std::move(conn));
  18721. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18722. conn2.sock = INVALID_SOCKET;
  18723. }
  18724. // Unified test server for all stream::* tests
  18725. class StreamApiTest : public ::testing::Test {
  18726. protected:
  18727. void SetUp() override {
  18728. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18729. res.set_content("Hello World!", "text/plain");
  18730. });
  18731. svr_.Get("/echo-params",
  18732. [](const httplib::Request &req, httplib::Response &res) {
  18733. std::string r;
  18734. for (const auto &p : req.params) {
  18735. if (!r.empty()) r += "&";
  18736. r += p.first + "=" + p.second;
  18737. }
  18738. res.set_content(r, "text/plain");
  18739. });
  18740. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18741. res.set_content(req.body, req.get_header_value("Content-Type"));
  18742. });
  18743. svr_.Post("/echo-headers",
  18744. [](const httplib::Request &req, httplib::Response &res) {
  18745. std::string r;
  18746. for (const auto &h : req.headers)
  18747. r += h.first + ": " + h.second + "\n";
  18748. res.set_content(r, "text/plain");
  18749. });
  18750. svr_.Post("/echo-params",
  18751. [](const httplib::Request &req, httplib::Response &res) {
  18752. std::string r = "params:";
  18753. for (const auto &p : req.params)
  18754. r += p.first + "=" + p.second + ";";
  18755. res.set_content(r + " body:" + req.body, "text/plain");
  18756. });
  18757. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18758. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18759. });
  18760. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18761. res.set_content("PUT:" + req.body, "text/plain");
  18762. });
  18763. svr_.Patch("/echo",
  18764. [](const httplib::Request &req, httplib::Response &res) {
  18765. res.set_content("PATCH:" + req.body, "text/plain");
  18766. });
  18767. svr_.Delete(
  18768. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18769. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18770. "text/plain");
  18771. });
  18772. svr_.Get("/head-test",
  18773. [](const httplib::Request &, httplib::Response &res) {
  18774. res.set_content("body for HEAD", "text/plain");
  18775. });
  18776. svr_.Options("/options",
  18777. [](const httplib::Request &, httplib::Response &res) {
  18778. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18779. });
  18780. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18781. svr_.wait_until_ready();
  18782. }
  18783. void TearDown() override {
  18784. svr_.stop();
  18785. if (thread_.joinable()) thread_.join();
  18786. }
  18787. httplib::Server svr_;
  18788. std::thread thread_;
  18789. };
  18790. // stream::Get tests
  18791. TEST_F(StreamApiTest, GetBasic) {
  18792. httplib::Client cli(HOST, PORT);
  18793. auto result = httplib::stream::Get(cli, "/hello");
  18794. ASSERT_TRUE(result.is_valid());
  18795. EXPECT_EQ(200, result.status());
  18796. EXPECT_EQ("Hello World!", read_body(result));
  18797. }
  18798. TEST_F(StreamApiTest, GetWithParams) {
  18799. httplib::Client cli(HOST, PORT);
  18800. httplib::Params params{{"foo", "bar"}};
  18801. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18802. ASSERT_TRUE(result.is_valid());
  18803. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18804. }
  18805. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18806. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  18807. httplib::Client cli(HOST, PORT);
  18808. cli.set_payload_max_length(0);
  18809. auto result = httplib::stream::Get(cli, "/hello");
  18810. ASSERT_TRUE(result.is_valid());
  18811. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  18812. EXPECT_EQ("Hello World!", read_body(result));
  18813. }
  18814. #endif
  18815. TEST_F(StreamApiTest, GetConnectionError) {
  18816. httplib::Client cli(HOST, 9999);
  18817. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18818. }
  18819. TEST_F(StreamApiTest, Get404) {
  18820. httplib::Client cli(HOST, PORT);
  18821. auto result = httplib::stream::Get(cli, "/nonexistent");
  18822. EXPECT_TRUE(result.is_valid());
  18823. EXPECT_EQ(404, result.status());
  18824. }
  18825. // stream::Post tests
  18826. TEST_F(StreamApiTest, PostBasic) {
  18827. httplib::Client cli(HOST, PORT);
  18828. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18829. "application/json");
  18830. ASSERT_TRUE(result.is_valid());
  18831. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18832. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18833. }
  18834. TEST_F(StreamApiTest, PostWithHeaders) {
  18835. httplib::Client cli(HOST, PORT);
  18836. httplib::Headers headers{{"X-Custom", "value"}};
  18837. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18838. "text/plain");
  18839. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18840. }
  18841. TEST_F(StreamApiTest, PostWithParams) {
  18842. httplib::Client cli(HOST, PORT);
  18843. httplib::Params params{{"k", "v"}};
  18844. auto result =
  18845. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18846. auto body = read_body(result);
  18847. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18848. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18849. }
  18850. TEST_F(StreamApiTest, PostLarge) {
  18851. httplib::Client cli(HOST, PORT);
  18852. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18853. size_t total = 0;
  18854. while (result.next()) {
  18855. total += result.size();
  18856. }
  18857. EXPECT_EQ(100u * 1024u, total);
  18858. }
  18859. // stream::Put/Patch tests
  18860. TEST_F(StreamApiTest, PutAndPatch) {
  18861. httplib::Client cli(HOST, PORT);
  18862. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18863. EXPECT_EQ("PUT:test", read_body(put));
  18864. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18865. EXPECT_EQ("PATCH:test", read_body(patch));
  18866. }
  18867. // stream::Delete tests
  18868. TEST_F(StreamApiTest, Delete) {
  18869. httplib::Client cli(HOST, PORT);
  18870. auto del1 = httplib::stream::Delete(cli, "/resource");
  18871. EXPECT_EQ("Deleted", read_body(del1));
  18872. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18873. EXPECT_EQ("Deleted:data", read_body(del2));
  18874. }
  18875. // stream::Head/Options tests
  18876. TEST_F(StreamApiTest, HeadAndOptions) {
  18877. httplib::Client cli(HOST, PORT);
  18878. auto head = httplib::stream::Head(cli, "/head-test");
  18879. EXPECT_TRUE(head.is_valid());
  18880. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18881. auto opts = httplib::stream::Options(cli, "/options");
  18882. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18883. }
  18884. // SSL stream::* tests
  18885. #ifdef CPPHTTPLIB_SSL_ENABLED
  18886. class SSLStreamApiTest : public ::testing::Test {
  18887. protected:
  18888. void SetUp() override {
  18889. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18890. res.set_content("Hello SSL!", "text/plain");
  18891. });
  18892. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18893. res.set_content(req.body, "text/plain");
  18894. });
  18895. port_ = svr_.bind_to_any_port("127.0.0.1");
  18896. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18897. svr_.wait_until_ready();
  18898. }
  18899. void TearDown() override {
  18900. svr_.stop();
  18901. if (thread_.joinable()) thread_.join();
  18902. }
  18903. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18904. std::thread thread_;
  18905. int port_ = 0;
  18906. };
  18907. TEST_F(SSLStreamApiTest, GetAndPost) {
  18908. httplib::SSLClient cli("127.0.0.1", port_);
  18909. cli.enable_server_certificate_verification(false);
  18910. auto get = httplib::stream::Get(cli, "/hello");
  18911. EXPECT_EQ("Hello SSL!", read_body(get));
  18912. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18913. EXPECT_EQ("test", read_body(post));
  18914. }
  18915. #endif
  18916. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18917. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18918. // BodyReader
  18919. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18920. // Test that read timeout during streaming is detected
  18921. // Use a large content-length response where server delays mid-stream
  18922. Server svr;
  18923. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18924. // Send a large response with delay in the middle
  18925. res.set_content_provider(
  18926. 1000, // content_length
  18927. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18928. if (offset < 100) {
  18929. // Send first 100 bytes immediately
  18930. std::string data(100, 'A');
  18931. sink.write(data.c_str(), data.size());
  18932. return true;
  18933. }
  18934. // Then delay longer than client timeout
  18935. std::this_thread::sleep_for(std::chrono::seconds(3));
  18936. std::string data(900, 'B');
  18937. sink.write(data.c_str(), data.size());
  18938. return true;
  18939. });
  18940. });
  18941. auto port = 8091;
  18942. std::thread t([&]() { svr.listen("localhost", port); });
  18943. svr.wait_until_ready();
  18944. Client cli("localhost", port);
  18945. cli.set_read_timeout(1, 0); // 1 second timeout
  18946. auto handle = cli.open_stream("GET", "/slow-stream");
  18947. ASSERT_TRUE(handle.is_valid());
  18948. char buf[256];
  18949. ssize_t total = 0;
  18950. ssize_t n;
  18951. bool got_error = false;
  18952. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18953. total += n;
  18954. }
  18955. if (n < 0) {
  18956. got_error = true;
  18957. // Should be timeout or read error
  18958. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18959. handle.get_read_error() == Error::Read)
  18960. << "Actual error: " << to_string(handle.get_read_error());
  18961. }
  18962. // Either we got an error, or we got less data than expected
  18963. EXPECT_TRUE(got_error || total < 1000)
  18964. << "Expected timeout but got all " << total << " bytes";
  18965. svr.stop();
  18966. t.join();
  18967. }
  18968. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18969. // Test connection closed detection via BodyReader
  18970. Server svr;
  18971. std::atomic<bool> close_now{false};
  18972. svr.Get("/will-close", [&](const Request &, Response &res) {
  18973. res.set_content_provider(
  18974. 10000, // Large content_length that we won't fully send
  18975. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18976. if (offset < 100) {
  18977. std::string data(100, 'X');
  18978. sink.write(data.c_str(), data.size());
  18979. return true;
  18980. }
  18981. // Wait for signal then abort
  18982. while (!close_now) {
  18983. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18984. }
  18985. return false; // Abort - server will close connection
  18986. });
  18987. });
  18988. auto port = 8092;
  18989. std::thread t([&]() { svr.listen("localhost", port); });
  18990. svr.wait_until_ready();
  18991. Client cli("localhost", port);
  18992. auto handle = cli.open_stream("GET", "/will-close");
  18993. ASSERT_TRUE(handle.is_valid());
  18994. char buf[256];
  18995. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18996. EXPECT_GT(n, 0) << "First read should succeed";
  18997. // Signal server to close
  18998. close_now = true;
  18999. // Keep reading until error or EOF
  19000. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19001. // Keep reading
  19002. }
  19003. // Should get an error since content_length wasn't satisfied
  19004. if (n < 0) {
  19005. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19006. handle.get_read_error() == Error::Read)
  19007. << "Actual error: " << to_string(handle.get_read_error());
  19008. }
  19009. svr.stop();
  19010. t.join();
  19011. }
  19012. #ifdef CPPHTTPLIB_SSL_ENABLED
  19013. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19014. // Test that read timeout during SSL streaming is detected
  19015. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19016. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19017. res.set_content_provider(
  19018. 1000, "text/plain",
  19019. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19020. if (offset < 100) {
  19021. std::string data(100, 'A');
  19022. sink.write(data.c_str(), data.size());
  19023. return true;
  19024. }
  19025. std::this_thread::sleep_for(std::chrono::seconds(3));
  19026. std::string data(900, 'B');
  19027. sink.write(data.c_str(), data.size());
  19028. return true;
  19029. });
  19030. });
  19031. auto port = 8093;
  19032. std::thread t([&]() { svr.listen("localhost", port); });
  19033. svr.wait_until_ready();
  19034. SSLClient cli("localhost", port);
  19035. cli.enable_server_certificate_verification(false);
  19036. cli.set_read_timeout(1, 0); // 1 second timeout
  19037. auto handle = cli.open_stream("GET", "/slow-stream");
  19038. ASSERT_TRUE(handle.is_valid());
  19039. char buf[256];
  19040. ssize_t total = 0;
  19041. ssize_t n;
  19042. bool got_error = false;
  19043. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19044. total += n;
  19045. }
  19046. if (n < 0) {
  19047. got_error = true;
  19048. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19049. handle.get_read_error() == Error::Read)
  19050. << "Actual error: " << to_string(handle.get_read_error());
  19051. }
  19052. EXPECT_TRUE(got_error || total < 1000)
  19053. << "Expected timeout but got all " << total << " bytes";
  19054. svr.stop();
  19055. t.join();
  19056. }
  19057. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19058. // Test SSL connection closed detection
  19059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19060. std::atomic<bool> close_now{false};
  19061. svr.Get("/will-close", [&](const Request &, Response &res) {
  19062. res.set_content_provider(
  19063. 10000, "text/plain",
  19064. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19065. if (offset < 100) {
  19066. std::string data(100, 'X');
  19067. sink.write(data.c_str(), data.size());
  19068. return true;
  19069. }
  19070. while (!close_now) {
  19071. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19072. }
  19073. return false;
  19074. });
  19075. });
  19076. auto port = 8094;
  19077. std::thread t([&]() { svr.listen("localhost", port); });
  19078. svr.wait_until_ready();
  19079. SSLClient cli("localhost", port);
  19080. cli.enable_server_certificate_verification(false);
  19081. auto handle = cli.open_stream("GET", "/will-close");
  19082. ASSERT_TRUE(handle.is_valid());
  19083. char buf[256];
  19084. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19085. EXPECT_GT(n, 0);
  19086. // Signal server to close
  19087. close_now = true;
  19088. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19089. // Keep reading
  19090. }
  19091. if (n < 0) {
  19092. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19093. handle.get_read_error() == Error::Read)
  19094. << "Actual error: " << to_string(handle.get_read_error());
  19095. }
  19096. svr.stop();
  19097. t.join();
  19098. }
  19099. #endif
  19100. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19101. using namespace httplib;
  19102. // Create a test file
  19103. const char *fname = "etag_testfile.txt";
  19104. const char *content = "etag-content";
  19105. {
  19106. std::ofstream ofs(fname);
  19107. ofs << content;
  19108. ASSERT_TRUE(ofs.good());
  19109. }
  19110. Server svr;
  19111. svr.set_mount_point("/static", ".");
  19112. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19113. svr.wait_until_ready();
  19114. Client cli(HOST, PORT);
  19115. // First request: should get 200 with ETag header
  19116. auto res1 = cli.Get("/static/etag_testfile.txt");
  19117. ASSERT_TRUE(res1);
  19118. ASSERT_EQ(200, res1->status);
  19119. ASSERT_TRUE(res1->has_header("ETag"));
  19120. std::string etag = res1->get_header_value("ETag");
  19121. EXPECT_FALSE(etag.empty());
  19122. // Verify ETag format: W/"hex-hex"
  19123. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19124. EXPECT_EQ('W', etag[0]);
  19125. EXPECT_EQ('/', etag[1]);
  19126. EXPECT_EQ('"', etag[2]);
  19127. EXPECT_EQ('"', etag.back());
  19128. // Exact match: expect 304 Not Modified
  19129. Headers h2 = {{"If-None-Match", etag}};
  19130. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19131. ASSERT_TRUE(res2);
  19132. EXPECT_EQ(304, res2->status);
  19133. // Wildcard match: expect 304 Not Modified
  19134. Headers h3 = {{"If-None-Match", "*"}};
  19135. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19136. ASSERT_TRUE(res3);
  19137. EXPECT_EQ(304, res3->status);
  19138. // Non-matching ETag: expect 200
  19139. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19140. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19141. ASSERT_TRUE(res4);
  19142. EXPECT_EQ(200, res4->status);
  19143. // Multiple ETags with one matching: expect 304
  19144. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19145. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19146. ASSERT_TRUE(res5);
  19147. EXPECT_EQ(304, res5->status);
  19148. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19149. // that equivalent to the single comma-separated list above, so the match on
  19150. // the second line must still be found.
  19151. Headers h6;
  19152. h6.emplace("If-None-Match", "W/\"other\"");
  19153. h6.emplace("If-None-Match", etag);
  19154. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19155. ASSERT_TRUE(res6);
  19156. EXPECT_EQ(304, res6->status);
  19157. svr.stop();
  19158. t.join();
  19159. std::remove(fname);
  19160. }
  19161. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19162. using namespace httplib;
  19163. Server svr;
  19164. svr.set_mount_point("/static", ".");
  19165. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19166. svr.wait_until_ready();
  19167. Client cli(HOST, PORT);
  19168. // Send If-None-Match: * to a non-existent file
  19169. Headers h = {{"If-None-Match", "*"}};
  19170. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19172. EXPECT_EQ(404, res->status);
  19173. svr.stop();
  19174. t.join();
  19175. }
  19176. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19177. using namespace httplib;
  19178. // Create a test file
  19179. const char *fname = "etag_boundary_testfile.txt";
  19180. const char *content = "boundary-test";
  19181. {
  19182. std::ofstream ofs(fname);
  19183. ofs << content;
  19184. ASSERT_TRUE(ofs.good());
  19185. }
  19186. Server svr;
  19187. svr.set_mount_point("/static", ".");
  19188. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19189. svr.wait_until_ready();
  19190. Client cli(HOST, PORT);
  19191. // Get the actual ETag
  19192. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19193. ASSERT_TRUE(res1);
  19194. ASSERT_EQ(200, res1->status);
  19195. ASSERT_TRUE(res1->has_header("ETag"));
  19196. std::string etag = res1->get_header_value("ETag");
  19197. // Test 1: Very long ETag value (longer than actual ETag)
  19198. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19199. Headers h1 = {{"If-None-Match", "W/"
  19200. "\"very-long-etag-value-that-is-much-longer-"
  19201. "than-the-actual-etag-value\""}};
  19202. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19203. ASSERT_TRUE(res2);
  19204. EXPECT_EQ(200, res2->status); // Should not match
  19205. // Test 2: Long string followed by wildcard
  19206. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19207. // string)
  19208. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19209. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19210. ASSERT_TRUE(res3);
  19211. EXPECT_EQ(304, res3->status); // Should match on "*"
  19212. // Test 3: Wildcard followed by long string
  19213. // Should match on "*" immediately and return 304
  19214. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19215. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19216. ASSERT_TRUE(res4);
  19217. EXPECT_EQ(304, res4->status); // Should match on "*"
  19218. // Test 4: Multiple long non-matching values
  19219. // Should NOT match and return 200 (test that all comparisons are safe)
  19220. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19221. "W/\"second-long-non-matching-value\", "
  19222. "W/\"third-long-non-matching-value\""}};
  19223. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19224. ASSERT_TRUE(res5);
  19225. EXPECT_EQ(200, res5->status); // Should not match
  19226. // Test 5: Single character that is not "*" (edge case)
  19227. Headers h5 = {{"If-None-Match", "X"}};
  19228. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19229. ASSERT_TRUE(res6);
  19230. EXPECT_EQ(200, res6->status); // Should not match
  19231. svr.stop();
  19232. t.join();
  19233. std::remove(fname);
  19234. }
  19235. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19236. using namespace httplib;
  19237. // Create a test file
  19238. const char *fname = "ims_testfile.txt";
  19239. const char *content = "if-modified-since-test";
  19240. {
  19241. std::ofstream ofs(fname);
  19242. ofs << content;
  19243. ASSERT_TRUE(ofs.good());
  19244. }
  19245. Server svr;
  19246. svr.set_mount_point("/static", ".");
  19247. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19248. svr.wait_until_ready();
  19249. Client cli(HOST, PORT);
  19250. // First request: should get 200 with Last-Modified header
  19251. auto res1 = cli.Get("/static/ims_testfile.txt");
  19252. ASSERT_TRUE(res1);
  19253. ASSERT_EQ(200, res1->status);
  19254. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19255. std::string last_modified = res1->get_header_value("Last-Modified");
  19256. EXPECT_FALSE(last_modified.empty());
  19257. // If-Modified-Since with same time: expect 304
  19258. Headers h2 = {{"If-Modified-Since", last_modified}};
  19259. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19260. ASSERT_TRUE(res2);
  19261. EXPECT_EQ(304, res2->status);
  19262. // If-Modified-Since with future time: expect 304
  19263. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19264. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19265. ASSERT_TRUE(res3);
  19266. EXPECT_EQ(304, res3->status);
  19267. // If-Modified-Since with past time: expect 200
  19268. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19269. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19270. ASSERT_TRUE(res4);
  19271. EXPECT_EQ(200, res4->status);
  19272. // If-None-Match takes precedence over If-Modified-Since
  19273. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19274. ASSERT_TRUE(res1->has_header("ETag"));
  19275. std::string etag = res1->get_header_value("ETag");
  19276. Headers h5 = {{"If-None-Match", etag},
  19277. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19278. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19279. ASSERT_TRUE(res5);
  19280. EXPECT_EQ(304, res5->status);
  19281. svr.stop();
  19282. t.join();
  19283. std::remove(fname);
  19284. }
  19285. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19286. using namespace httplib;
  19287. Server svr;
  19288. // Endpoint that returns compressible content
  19289. svr.Get("/compressible", [](const Request &, Response &res) {
  19290. // Return a large enough body to trigger compression
  19291. std::string body(1000, 'a');
  19292. res.set_content(body, "text/plain");
  19293. });
  19294. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19295. svr.wait_until_ready();
  19296. Client cli(HOST, PORT);
  19297. // Request with gzip support: should get Vary header when compressed
  19298. cli.set_compress(true);
  19299. auto res1 = cli.Get("/compressible");
  19300. ASSERT_TRUE(res1);
  19301. EXPECT_EQ(200, res1->status);
  19302. // If Content-Encoding is set, Vary should also be set
  19303. if (res1->has_header("Content-Encoding")) {
  19304. EXPECT_TRUE(res1->has_header("Vary"));
  19305. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19306. }
  19307. // Request without Accept-Encoding header: should not have compression
  19308. Headers h_no_compress;
  19309. auto res2 = cli.Get("/compressible", h_no_compress);
  19310. ASSERT_TRUE(res2);
  19311. EXPECT_EQ(200, res2->status);
  19312. // Verify Vary header is present when compression is applied
  19313. // (the exact behavior depends on server configuration)
  19314. svr.stop();
  19315. t.join();
  19316. }
  19317. TEST(ETagTest, IfRangeWithETag) {
  19318. using namespace httplib;
  19319. // Create a test file with known content
  19320. const char *fname = "if_range_testfile.txt";
  19321. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19322. {
  19323. std::ofstream ofs(fname);
  19324. ofs << content;
  19325. ASSERT_TRUE(ofs.good());
  19326. }
  19327. Server svr;
  19328. svr.set_mount_point("/static", ".");
  19329. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19330. svr.wait_until_ready();
  19331. Client cli(HOST, PORT);
  19332. // First request: get ETag
  19333. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19334. ASSERT_TRUE(res1);
  19335. ASSERT_EQ(200, res1->status);
  19336. ASSERT_TRUE(res1->has_header("ETag"));
  19337. std::string etag = res1->get_header_value("ETag");
  19338. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19339. // Since our server generates weak ETags (W/"..."), If-Range with our
  19340. // ETag should NOT result in partial content - it should return full content.
  19341. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19342. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19343. ASSERT_TRUE(res2);
  19344. // Weak ETag in If-Range -> full content (200), not partial (206)
  19345. EXPECT_EQ(200, res2->status);
  19346. EXPECT_EQ(content, res2->body);
  19347. EXPECT_FALSE(res2->has_header("Content-Range"));
  19348. // Range request with non-matching If-Range (ETag): should get 200 (full
  19349. // content)
  19350. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19351. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19352. ASSERT_TRUE(res3);
  19353. EXPECT_EQ(200, res3->status);
  19354. EXPECT_EQ(content, res3->body);
  19355. EXPECT_FALSE(res3->has_header("Content-Range"));
  19356. // Range request with strong ETag (hypothetical - our server doesn't generate
  19357. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19358. // should return full content)
  19359. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19360. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19361. ASSERT_TRUE(res4);
  19362. EXPECT_EQ(200, res4->status);
  19363. EXPECT_EQ(content, res4->body);
  19364. EXPECT_FALSE(res4->has_header("Content-Range"));
  19365. svr.stop();
  19366. t.join();
  19367. std::remove(fname);
  19368. }
  19369. TEST(ETagTest, IfRangeWithDate) {
  19370. using namespace httplib;
  19371. // Create a test file
  19372. const char *fname = "if_range_date_testfile.txt";
  19373. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19374. {
  19375. std::ofstream ofs(fname);
  19376. ofs << content;
  19377. ASSERT_TRUE(ofs.good());
  19378. }
  19379. Server svr;
  19380. svr.set_mount_point("/static", ".");
  19381. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19382. svr.wait_until_ready();
  19383. Client cli(HOST, PORT);
  19384. // First request: get Last-Modified
  19385. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19386. ASSERT_TRUE(res1);
  19387. ASSERT_EQ(200, res1->status);
  19388. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19389. std::string last_modified = res1->get_header_value("Last-Modified");
  19390. // Range request with matching If-Range (date): should get 206
  19391. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19392. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19393. ASSERT_TRUE(res2);
  19394. EXPECT_EQ(206, res2->status);
  19395. EXPECT_EQ("FGHIJ", res2->body);
  19396. // Range request with old If-Range date: should get 200 (full content)
  19397. Headers h3 = {{"Range", "bytes=5-9"},
  19398. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19399. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19400. ASSERT_TRUE(res3);
  19401. EXPECT_EQ(200, res3->status);
  19402. EXPECT_EQ(content, res3->body);
  19403. // Range request with future If-Range date: should get 206
  19404. Headers h4 = {{"Range", "bytes=0-4"},
  19405. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19406. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19407. ASSERT_TRUE(res4);
  19408. EXPECT_EQ(206, res4->status);
  19409. EXPECT_EQ("ABCDE", res4->body);
  19410. svr.stop();
  19411. t.join();
  19412. std::remove(fname);
  19413. }
  19414. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19415. using namespace httplib;
  19416. const char *fname = "etag_malformed.txt";
  19417. const char *content = "malformed-etag";
  19418. {
  19419. std::ofstream ofs(fname);
  19420. ofs << content;
  19421. ASSERT_TRUE(ofs.good());
  19422. }
  19423. Server svr;
  19424. svr.set_mount_point("/static", ".");
  19425. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19426. svr.wait_until_ready();
  19427. Client cli(HOST, PORT);
  19428. // baseline: should get 200 and an ETag
  19429. auto res1 = cli.Get("/static/etag_malformed.txt");
  19430. ASSERT_TRUE(res1);
  19431. ASSERT_EQ(200, res1->status);
  19432. ASSERT_TRUE(res1->has_header("ETag"));
  19433. // Malformed ETag value (missing quotes) should be treated as non-matching
  19434. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19435. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19436. ASSERT_TRUE(res_bad);
  19437. EXPECT_EQ(200, res_bad->status);
  19438. // Whitespace-only header value should be considered invalid / non-matching
  19439. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19440. "Host: localhost\r\n"
  19441. "If-None-Match: \r\n"
  19442. "Connection: close\r\n"
  19443. "\r\n";
  19444. std::string out;
  19445. ASSERT_TRUE(send_request(5, raw_req, &out));
  19446. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19447. svr.stop();
  19448. t.join();
  19449. std::remove(fname);
  19450. }
  19451. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19452. using namespace httplib;
  19453. const char *fname = "ims_invalid_format.txt";
  19454. const char *content = "ims-bad-format";
  19455. {
  19456. std::ofstream ofs(fname);
  19457. ofs << content;
  19458. ASSERT_TRUE(ofs.good());
  19459. }
  19460. Server svr;
  19461. svr.set_mount_point("/static", ".");
  19462. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19463. svr.wait_until_ready();
  19464. Client cli(HOST, PORT);
  19465. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19466. ASSERT_TRUE(res1);
  19467. ASSERT_EQ(200, res1->status);
  19468. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19469. // If-Modified-Since with invalid format should not result in 304
  19470. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19471. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19472. ASSERT_TRUE(res_bad);
  19473. EXPECT_EQ(200, res_bad->status);
  19474. // If-Range with invalid date format should be treated as mismatch -> full
  19475. // content (200)
  19476. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19477. {"If-Range", "invalid-date"}};
  19478. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19479. ASSERT_TRUE(res_ifrange);
  19480. EXPECT_EQ(200, res_ifrange->status);
  19481. svr.stop();
  19482. t.join();
  19483. std::remove(fname);
  19484. }
  19485. TEST(ETagTest, IfRangeWithMalformedETag) {
  19486. using namespace httplib;
  19487. const char *fname = "ifrange_malformed.txt";
  19488. const std::string content = "0123456789";
  19489. {
  19490. std::ofstream ofs(fname);
  19491. ofs << content;
  19492. ASSERT_TRUE(ofs.good());
  19493. }
  19494. Server svr;
  19495. svr.set_mount_point("/static", ".");
  19496. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19497. svr.wait_until_ready();
  19498. Client cli(HOST, PORT);
  19499. // First request: get ETag
  19500. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19501. ASSERT_TRUE(res1);
  19502. ASSERT_EQ(200, res1->status);
  19503. ASSERT_TRUE(res1->has_header("ETag"));
  19504. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19505. // full content (200)
  19506. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19507. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19508. ASSERT_TRUE(res2);
  19509. EXPECT_EQ(200, res2->status);
  19510. EXPECT_EQ(content, res2->body);
  19511. svr.stop();
  19512. t.join();
  19513. std::remove(fname);
  19514. }
  19515. TEST(ETagTest, ExtremeLargeDateValues) {
  19516. using namespace httplib;
  19517. const char *fname = "ims_extreme_date.txt";
  19518. const char *content = "ims-extreme-date";
  19519. {
  19520. std::ofstream ofs(fname);
  19521. ofs << content;
  19522. ASSERT_TRUE(ofs.good());
  19523. }
  19524. Server svr;
  19525. svr.set_mount_point("/static", ".");
  19526. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19527. svr.wait_until_ready();
  19528. Client cli(HOST, PORT);
  19529. auto res1 = cli.Get(std::string("/static/") + fname);
  19530. ASSERT_TRUE(res1);
  19531. ASSERT_EQ(200, res1->status);
  19532. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19533. // Extremely large year that may overflow date parsing routines.
  19534. Headers h_large_date = {
  19535. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19536. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19537. ASSERT_TRUE(res_bad);
  19538. // Expect server to treat this as invalid/mismatch and return full content
  19539. EXPECT_EQ(200, res_bad->status);
  19540. // If-Range with extremely large date should be treated as mismatch -> full
  19541. // content (200)
  19542. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19543. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19544. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19545. ASSERT_TRUE(res_ifrange);
  19546. EXPECT_EQ(200, res_ifrange->status);
  19547. svr.stop();
  19548. t.join();
  19549. std::remove(fname);
  19550. }
  19551. TEST(ETagTest, NegativeFileModificationTime) {
  19552. using namespace httplib;
  19553. const char *fname = "ims_negative_mtime.txt";
  19554. const std::string content = "negative-mtime";
  19555. {
  19556. std::ofstream ofs(fname);
  19557. ofs << content;
  19558. ASSERT_TRUE(ofs.good());
  19559. }
  19560. // Try to set file mtime to a negative value. This may fail on some
  19561. // platforms/filesystems; if it fails, the test will still verify server
  19562. // behaves safely by performing a regular conditional request.
  19563. #if defined(__APPLE__) || defined(__linux__)
  19564. bool set_negative = false;
  19565. do {
  19566. struct timeval times[2];
  19567. // access time: now
  19568. times[0].tv_sec = time(nullptr);
  19569. times[0].tv_usec = 0;
  19570. // modification time: negative (e.g., -1)
  19571. times[1].tv_sec = -1;
  19572. times[1].tv_usec = 0;
  19573. if (utimes(fname, times) == 0) { set_negative = true; }
  19574. } while (0);
  19575. #else
  19576. bool set_negative = false;
  19577. #endif
  19578. Server svr;
  19579. svr.set_mount_point("/static", ".");
  19580. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19581. svr.wait_until_ready();
  19582. Client cli(HOST, PORT);
  19583. auto res1 = cli.Get(std::string("/static/") + fname);
  19584. ASSERT_TRUE(res1);
  19585. ASSERT_EQ(200, res1->status);
  19586. bool has_last_modified = res1->has_header("Last-Modified");
  19587. std::string last_modified;
  19588. if (has_last_modified) {
  19589. last_modified = res1->get_header_value("Last-Modified");
  19590. }
  19591. if (set_negative) {
  19592. // If we successfully set a negative mtime, ensure server returns a
  19593. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19594. // with an old date and ensure server handles it without crash.
  19595. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19596. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19597. ASSERT_TRUE(res2);
  19598. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19599. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19600. } else {
  19601. // Could not set negative mtime on this platform; fall back to verifying
  19602. // that normal invalid/malformed dates are treated safely (non-304).
  19603. Headers h_bad_date = {
  19604. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19605. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19606. ASSERT_TRUE(res_bad);
  19607. EXPECT_EQ(200, res_bad->status);
  19608. }
  19609. svr.stop();
  19610. t.join();
  19611. std::remove(fname);
  19612. }
  19613. //==============================================================================
  19614. // Integration Tests with Server
  19615. //==============================================================================
  19616. class SSEIntegrationTest : public ::testing::Test {
  19617. protected:
  19618. void SetUp() override {
  19619. stop_server_.store(false);
  19620. events_.clear();
  19621. server_ = httplib::detail::make_unique<Server>();
  19622. setup_server();
  19623. start_server();
  19624. }
  19625. void TearDown() override {
  19626. stop_server_.store(true);
  19627. event_cv_.notify_all();
  19628. server_->stop();
  19629. if (server_thread_.joinable()) { server_thread_.join(); }
  19630. }
  19631. void setup_server() {
  19632. // Simple SSE endpoint
  19633. server_->Get("/events", [this](const Request &req, Response &res) {
  19634. auto last_id = req.get_header_value("Last-Event-ID");
  19635. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19636. res.set_chunked_content_provider(
  19637. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19638. std::unique_lock<std::mutex> lock(event_mutex_);
  19639. if (event_cv_.wait_for(
  19640. lock, std::chrono::milliseconds(200), [this] {
  19641. return !events_.empty() || stop_server_.load();
  19642. })) {
  19643. if (stop_server_.load()) { return false; }
  19644. if (!events_.empty()) {
  19645. std::string event = events_.front();
  19646. events_.erase(events_.begin());
  19647. sink.write(event.data(), event.size());
  19648. return true;
  19649. }
  19650. }
  19651. return !stop_server_.load();
  19652. });
  19653. });
  19654. // Endpoint that returns error
  19655. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19656. res.status = 500;
  19657. res.set_content("Internal Server Error", "text/plain");
  19658. });
  19659. // Endpoint for custom event types
  19660. server_->Get("/custom-events", [](const Request &, Response &res) {
  19661. res.set_chunked_content_provider(
  19662. "text/event-stream", [](size_t offset, DataSink &sink) {
  19663. if (offset == 0) {
  19664. std::string event = "event: update\ndata: updated\n\n"
  19665. "event: delete\ndata: deleted\n\n";
  19666. sink.write(event.data(), event.size());
  19667. }
  19668. return false; // End stream after sending
  19669. });
  19670. });
  19671. }
  19672. void start_server() {
  19673. port_ = server_->bind_to_any_port(HOST);
  19674. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19675. // Wait for server to start
  19676. while (!server_->is_running()) {
  19677. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19678. }
  19679. }
  19680. int get_port() const { return port_; }
  19681. void send_event(const std::string &event) {
  19682. std::lock_guard<std::mutex> lock(event_mutex_);
  19683. events_.push_back(event);
  19684. event_cv_.notify_all();
  19685. }
  19686. std::unique_ptr<Server> server_;
  19687. std::thread server_thread_;
  19688. std::mutex event_mutex_;
  19689. std::condition_variable event_cv_;
  19690. std::vector<std::string> events_;
  19691. std::atomic<bool> stop_server_{false};
  19692. std::string last_received_event_id_;
  19693. int port_ = 0;
  19694. };
  19695. //==============================================================================
  19696. // SSE Parsing Tests
  19697. //==============================================================================
  19698. class SSEParsingTest : public SSEIntegrationTest {
  19699. protected:
  19700. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19701. // A trailing sentinel event tells when the whole stream has been parsed.
  19702. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19703. auto body = stream + "event: end\ndata: end\n\n";
  19704. server_->Get("/parse", [body](const Request &, Response &res) {
  19705. res.set_content(body, "text/event-stream");
  19706. });
  19707. return collect("/parse");
  19708. }
  19709. // Runs SSEClient against path until an "end" event arrives and returns the
  19710. // messages dispatched before it
  19711. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19712. Client client(HOST, get_port());
  19713. sse::SSEClient sse(client, path);
  19714. std::mutex mutex;
  19715. std::condition_variable cv;
  19716. std::vector<sse::SSEMessage> messages;
  19717. auto done = false;
  19718. sse.on_message([&](const sse::SSEMessage &msg) {
  19719. std::lock_guard<std::mutex> lock(mutex);
  19720. // Ignore a replay from a reconnect that races with stop()
  19721. if (!done) { messages.push_back(msg); }
  19722. });
  19723. sse.on_event("end", [&](const sse::SSEMessage &) {
  19724. std::lock_guard<std::mutex> lock(mutex);
  19725. done = true;
  19726. cv.notify_all();
  19727. });
  19728. sse.set_reconnect_interval(100);
  19729. sse.start_async();
  19730. {
  19731. std::unique_lock<std::mutex> lock(mutex);
  19732. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19733. }
  19734. sse.stop();
  19735. EXPECT_TRUE(done);
  19736. return messages;
  19737. }
  19738. };
  19739. TEST_F(SSEParsingTest, SingleLineData) {
  19740. auto msgs = parse("data: hello\n\n");
  19741. ASSERT_EQ(msgs.size(), 1u);
  19742. EXPECT_EQ(msgs[0].data, "hello");
  19743. EXPECT_EQ(msgs[0].event, "message");
  19744. }
  19745. TEST_F(SSEParsingTest, MultiLineData) {
  19746. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19747. ASSERT_EQ(msgs.size(), 1u);
  19748. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19749. }
  19750. TEST_F(SSEParsingTest, CustomEventType) {
  19751. auto msgs = parse("event: update\ndata: payload\n\n");
  19752. ASSERT_EQ(msgs.size(), 1u);
  19753. EXPECT_EQ(msgs[0].event, "update");
  19754. EXPECT_EQ(msgs[0].data, "payload");
  19755. }
  19756. TEST_F(SSEParsingTest, EventIdHandling) {
  19757. auto msgs = parse("id: 12345\ndata: test\n\n");
  19758. ASSERT_EQ(msgs.size(), 1u);
  19759. EXPECT_EQ(msgs[0].id, "12345");
  19760. }
  19761. TEST_F(SSEParsingTest, EmptyEventId) {
  19762. auto msgs = parse("id:\ndata: test\n\n");
  19763. ASSERT_EQ(msgs.size(), 1u);
  19764. EXPECT_EQ(msgs[0].id, "");
  19765. }
  19766. TEST_F(SSEParsingTest, CommentsIgnored) {
  19767. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19768. ASSERT_EQ(msgs.size(), 1u);
  19769. EXPECT_EQ(msgs[0].data, "hello");
  19770. EXPECT_EQ(msgs[0].event, "message");
  19771. }
  19772. TEST_F(SSEParsingTest, ColonInValue) {
  19773. auto msgs = parse("data: hello:world:test\n\n");
  19774. ASSERT_EQ(msgs.size(), 1u);
  19775. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19776. }
  19777. TEST_F(SSEParsingTest, FieldNameOnly) {
  19778. // A line without a colon is a field name with an empty value
  19779. auto msgs = parse("data\n\n");
  19780. ASSERT_EQ(msgs.size(), 1u);
  19781. EXPECT_EQ(msgs[0].data, "");
  19782. }
  19783. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19784. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19785. ASSERT_EQ(msgs.size(), 1u);
  19786. EXPECT_EQ(msgs[0].event, "update");
  19787. EXPECT_EQ(msgs[0].data, "hello");
  19788. }
  19789. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19790. auto msgs = parse("data\r\n\r\n");
  19791. ASSERT_EQ(msgs.size(), 1u);
  19792. EXPECT_EQ(msgs[0].data, "");
  19793. }
  19794. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19795. auto msgs = parse("event: update\rdata: hello\r\r");
  19796. ASSERT_EQ(msgs.size(), 1u);
  19797. EXPECT_EQ(msgs[0].event, "update");
  19798. EXPECT_EQ(msgs[0].data, "hello");
  19799. }
  19800. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19801. // Chunk boundaries fall inside every \r\n and right before the first one
  19802. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19803. "\n\r", "\nevent: end\ndata: end\n\n"};
  19804. server_->Get("/split", [chunks](const Request &, Response &res) {
  19805. auto i = std::make_shared<size_t>(0);
  19806. res.set_chunked_content_provider(
  19807. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19808. if (*i == chunks.size()) {
  19809. sink.done();
  19810. } else {
  19811. sink.write(chunks[*i].data(), chunks[*i].size());
  19812. (*i)++;
  19813. }
  19814. return true;
  19815. });
  19816. });
  19817. auto msgs = collect("/split");
  19818. ASSERT_EQ(msgs.size(), 1u);
  19819. EXPECT_EQ(msgs[0].event, "update");
  19820. EXPECT_EQ(msgs[0].data, "hello");
  19821. }
  19822. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19823. // Only a BOM at the start of the stream is ignored
  19824. auto msgs = parse("\xEF\xBB\xBF"
  19825. "data: first\n\n"
  19826. "\xEF\xBB\xBF"
  19827. "data: second\n\n");
  19828. ASSERT_EQ(msgs.size(), 1u);
  19829. EXPECT_EQ(msgs[0].data, "first");
  19830. }
  19831. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19832. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19833. ASSERT_EQ(msgs.size(), 1u);
  19834. EXPECT_EQ(msgs[0].data, "hello");
  19835. EXPECT_EQ(msgs[0].event, "message");
  19836. }
  19837. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19838. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19839. ASSERT_EQ(msgs.size(), 2u);
  19840. EXPECT_EQ(msgs[0].data, "hello");
  19841. EXPECT_EQ(msgs[1].data, "hello");
  19842. }
  19843. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19844. // An event without data is not dispatched, and its type must not leak
  19845. // into the next event
  19846. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19847. ASSERT_EQ(msgs.size(), 1u);
  19848. EXPECT_EQ(msgs[0].event, "message");
  19849. EXPECT_EQ(msgs[0].data, "hello");
  19850. }
  19851. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19852. // The first connection sends only an id; the second echoes back the
  19853. // Last-Event-ID it was reconnected with
  19854. std::atomic<int> connection_count{0};
  19855. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19856. if (connection_count++ == 0) {
  19857. res.set_content("id: 42\n\n", "text/event-stream");
  19858. } else {
  19859. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19860. "\n\nevent: end\ndata: end\n\n",
  19861. "text/event-stream");
  19862. }
  19863. });
  19864. auto msgs = collect("/id-only");
  19865. ASSERT_EQ(msgs.size(), 1u);
  19866. EXPECT_EQ(msgs[0].data, "42");
  19867. }
  19868. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19869. // The first connection sets an id and then clears it with an empty one; the
  19870. // second reports whether it was reconnected with a Last-Event-ID
  19871. std::atomic<int> connection_count{0};
  19872. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19873. if (connection_count++ == 0) {
  19874. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19875. "text/event-stream");
  19876. } else {
  19877. res.set_content(
  19878. std::string("data: ") +
  19879. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19880. "\n\nevent: end\ndata: end\n\n",
  19881. "text/event-stream");
  19882. }
  19883. });
  19884. auto msgs = collect("/id-clear");
  19885. ASSERT_EQ(msgs.size(), 3u);
  19886. EXPECT_EQ(msgs[0].id, "1");
  19887. EXPECT_EQ(msgs[1].id, "");
  19888. EXPECT_EQ(msgs[2].data, "not sent");
  19889. }
  19890. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19891. // The first connection sets an id and then sends ids that cannot be carried
  19892. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19893. // with
  19894. std::atomic<int> connection_count{0};
  19895. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19896. if (connection_count++ == 0) {
  19897. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19898. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19899. "text/event-stream");
  19900. } else {
  19901. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19902. "\n\nevent: end\ndata: end\n\n",
  19903. "text/event-stream");
  19904. }
  19905. });
  19906. auto msgs = collect("/id-unsendable");
  19907. ASSERT_EQ(msgs.size(), 1u);
  19908. EXPECT_EQ(msgs[0].data, "42");
  19909. }
  19910. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19911. auto msgs = parse("event: notification\nid: evt-42\n"
  19912. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19913. ASSERT_EQ(msgs.size(), 1u);
  19914. EXPECT_EQ(msgs[0].event, "notification");
  19915. EXPECT_EQ(msgs[0].id, "evt-42");
  19916. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19917. }
  19918. TEST(SSEMessageTest, Clear) {
  19919. sse::SSEMessage msg;
  19920. msg.event = "custom";
  19921. msg.data = "some data";
  19922. msg.id = "123";
  19923. msg.clear();
  19924. EXPECT_EQ(msg.event, "message");
  19925. EXPECT_EQ(msg.data, "");
  19926. EXPECT_EQ(msg.id, "");
  19927. }
  19928. //==============================================================================
  19929. // SSE Integration Tests
  19930. //==============================================================================
  19931. // Test: Successful connection and on_open callback
  19932. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19933. // Add a simple endpoint that sends one event and closes
  19934. server_->Get("/simple-event", [](const Request &, Response &res) {
  19935. res.set_chunked_content_provider(
  19936. "text/event-stream", [](size_t offset, DataSink &sink) {
  19937. if (offset == 0) {
  19938. std::string event = "data: hello\n\n";
  19939. sink.write(event.data(), event.size());
  19940. }
  19941. return false; // Close stream after sending
  19942. });
  19943. });
  19944. Client client("localhost", get_port());
  19945. sse::SSEClient sse(client, "/simple-event");
  19946. std::atomic<bool> open_called{false};
  19947. std::atomic<bool> message_received{false};
  19948. sse.on_open([&open_called]() { open_called.store(true); });
  19949. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19950. if (msg.data == "hello") { message_received.store(true); }
  19951. });
  19952. sse.set_reconnect_interval(100);
  19953. sse.set_max_reconnect_attempts(1);
  19954. // Start async
  19955. sse.start_async();
  19956. // Wait for message to be processed
  19957. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19958. sse.stop();
  19959. EXPECT_TRUE(open_called.load());
  19960. EXPECT_TRUE(message_received.load());
  19961. }
  19962. // Test: on_message callback
  19963. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19964. // Endpoint that sends multiple events then closes
  19965. server_->Get("/multi-event", [](const Request &, Response &res) {
  19966. res.set_chunked_content_provider(
  19967. "text/event-stream", [](size_t offset, DataSink &sink) {
  19968. if (offset == 0) {
  19969. std::string events = "data: message1\n\ndata: message2\n\n";
  19970. sink.write(events.data(), events.size());
  19971. }
  19972. return false;
  19973. });
  19974. });
  19975. Client client("localhost", get_port());
  19976. sse::SSEClient sse(client, "/multi-event");
  19977. std::vector<std::string> received_messages;
  19978. std::mutex messages_mutex;
  19979. sse.on_message([&](const sse::SSEMessage &msg) {
  19980. std::lock_guard<std::mutex> lock(messages_mutex);
  19981. received_messages.push_back(msg.data);
  19982. });
  19983. sse.set_reconnect_interval(100);
  19984. sse.set_max_reconnect_attempts(1);
  19985. sse.start_async();
  19986. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19987. sse.stop();
  19988. std::lock_guard<std::mutex> lock(messages_mutex);
  19989. EXPECT_GE(received_messages.size(), 2u);
  19990. if (received_messages.size() >= 2) {
  19991. EXPECT_EQ(received_messages[0], "message1");
  19992. EXPECT_EQ(received_messages[1], "message2");
  19993. }
  19994. }
  19995. // Test: on_event for specific types
  19996. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19997. Client client("localhost", get_port());
  19998. sse::SSEClient sse(client, "/custom-events");
  19999. std::atomic<bool> update_received{false};
  20000. std::atomic<bool> delete_received{false};
  20001. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20002. if (msg.data == "updated") { update_received.store(true); }
  20003. });
  20004. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20005. if (msg.data == "deleted") { delete_received.store(true); }
  20006. });
  20007. sse.set_max_reconnect_attempts(1);
  20008. sse.start_async();
  20009. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20010. sse.stop();
  20011. EXPECT_TRUE(update_received.load());
  20012. EXPECT_TRUE(delete_received.load());
  20013. }
  20014. // Test: on_error callback on connection failure
  20015. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20016. // Connect to a non-existent port
  20017. Client client("localhost", 59999);
  20018. sse::SSEClient sse(client, "/events");
  20019. std::atomic<bool> error_called{false};
  20020. Error received_error = Error::Success;
  20021. sse.on_error([&](Error err) {
  20022. error_called.store(true);
  20023. received_error = err;
  20024. });
  20025. sse.set_reconnect_interval(50);
  20026. sse.set_max_reconnect_attempts(1);
  20027. sse.start_async();
  20028. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20029. sse.stop();
  20030. EXPECT_TRUE(error_called.load());
  20031. EXPECT_NE(received_error, Error::Success);
  20032. }
  20033. // Test: Last-Event-ID header sent on reconnect
  20034. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20035. // Endpoint that sends event with ID
  20036. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20037. res.set_chunked_content_provider(
  20038. "text/event-stream", [](size_t offset, DataSink &sink) {
  20039. if (offset == 0) {
  20040. std::string event = "id: evt-123\ndata: test\n\n";
  20041. sink.write(event.data(), event.size());
  20042. }
  20043. return false;
  20044. });
  20045. });
  20046. Client client("localhost", get_port());
  20047. sse::SSEClient sse(client, "/event-with-id");
  20048. std::atomic<bool> id_received{false};
  20049. sse.on_message([&](const sse::SSEMessage &msg) {
  20050. if (!msg.id.empty()) { id_received.store(true); }
  20051. });
  20052. sse.set_reconnect_interval(100);
  20053. sse.set_max_reconnect_attempts(1);
  20054. sse.start_async();
  20055. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20056. sse.stop();
  20057. EXPECT_TRUE(id_received.load());
  20058. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20059. }
  20060. // Test: Manual stop
  20061. TEST_F(SSEIntegrationTest, ManualStop) {
  20062. // Endpoint that sends one event and stays open briefly
  20063. std::atomic<bool> handler_running{true};
  20064. server_->Get("/stay-open", [&handler_running](const Request &,
  20065. Response &res) {
  20066. res.set_chunked_content_provider(
  20067. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20068. if (offset == 0) {
  20069. std::string event = "data: connected\n\n";
  20070. sink.write(event.data(), event.size());
  20071. }
  20072. // Keep connection open while handler_running is true
  20073. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20074. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20075. }
  20076. return false;
  20077. });
  20078. });
  20079. Client client("localhost", get_port());
  20080. sse::SSEClient sse(client, "/stay-open");
  20081. std::atomic<bool> connected{false};
  20082. sse.on_open([&connected]() { connected.store(true); });
  20083. sse.set_reconnect_interval(100);
  20084. sse.set_max_reconnect_attempts(1);
  20085. sse.start_async();
  20086. // Wait for connection to establish
  20087. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20088. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20089. }
  20090. EXPECT_TRUE(connected.load());
  20091. EXPECT_TRUE(sse.is_connected());
  20092. // Signal handler to stop
  20093. handler_running.store(false);
  20094. // Stop SSE client
  20095. sse.stop();
  20096. EXPECT_FALSE(sse.is_connected());
  20097. }
  20098. // Test: SSEClient with custom headers
  20099. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20100. // Setup a server endpoint that checks for custom header
  20101. std::atomic<bool> header_received{false};
  20102. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20103. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20104. header_received.store(true);
  20105. }
  20106. res.set_chunked_content_provider("text/event-stream",
  20107. [](size_t, DataSink &) { return false; });
  20108. });
  20109. Client client("localhost", get_port());
  20110. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20111. sse::SSEClient sse(client, "/header-check", headers);
  20112. sse.set_max_reconnect_attempts(1);
  20113. sse.start_async();
  20114. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20115. sse.stop();
  20116. EXPECT_TRUE(header_received.load());
  20117. }
  20118. // Test: Reconnect interval configuration
  20119. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20120. Client client("localhost", get_port());
  20121. sse::SSEClient sse(client, "/events");
  20122. auto &result = sse.set_reconnect_interval(500);
  20123. // Builder pattern should return reference to self
  20124. EXPECT_EQ(&result, &sse);
  20125. }
  20126. // Test: Max reconnect attempts
  20127. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20128. // Connect to non-existent port to force reconnects
  20129. Client client("localhost", 59998);
  20130. sse::SSEClient sse(client, "/events");
  20131. std::atomic<int> error_count{0};
  20132. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20133. sse.set_reconnect_interval(50);
  20134. sse.set_max_reconnect_attempts(2);
  20135. auto start = std::chrono::steady_clock::now();
  20136. sse.start(); // Blocking call
  20137. auto end = std::chrono::steady_clock::now();
  20138. // Should have stopped after 2 failed attempts
  20139. EXPECT_GE(error_count.load(), 2);
  20140. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20141. auto duration =
  20142. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20143. #ifdef _WIN32
  20144. // Windows is much slower for socket connection failures
  20145. EXPECT_LT(duration.count(), 7000);
  20146. #else
  20147. EXPECT_LT(duration.count(), 1000);
  20148. #endif
  20149. }
  20150. // Test: Multi-line data in integration
  20151. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20152. // Endpoint with multi-line data
  20153. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20154. res.set_chunked_content_provider(
  20155. "text/event-stream", [](size_t offset, DataSink &sink) {
  20156. if (offset == 0) {
  20157. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20158. sink.write(event.data(), event.size());
  20159. }
  20160. return false;
  20161. });
  20162. });
  20163. Client client("localhost", get_port());
  20164. sse::SSEClient sse(client, "/multiline-data");
  20165. std::string received_data;
  20166. std::mutex data_mutex;
  20167. sse.on_message([&](const sse::SSEMessage &msg) {
  20168. std::lock_guard<std::mutex> lock(data_mutex);
  20169. received_data = msg.data;
  20170. });
  20171. sse.set_reconnect_interval(100);
  20172. sse.set_max_reconnect_attempts(1);
  20173. sse.start_async();
  20174. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20175. sse.stop();
  20176. std::lock_guard<std::mutex> lock(data_mutex);
  20177. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20178. }
  20179. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20180. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20181. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20182. DataSink &sink) {
  20183. if (offset == 0) {
  20184. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20185. sink.write(events.data(), events.size());
  20186. }
  20187. return false;
  20188. });
  20189. });
  20190. Client client("localhost", get_port());
  20191. sse::SSEClient sse(client, "/empty-data-lines");
  20192. std::mutex mutex;
  20193. std::condition_variable cv;
  20194. std::vector<std::string> received;
  20195. sse.on_message([&](const sse::SSEMessage &msg) {
  20196. std::lock_guard<std::mutex> lock(mutex);
  20197. received.push_back(msg.data);
  20198. cv.notify_all();
  20199. });
  20200. sse.set_max_reconnect_attempts(1);
  20201. sse.start_async();
  20202. {
  20203. std::unique_lock<std::mutex> lock(mutex);
  20204. cv.wait_for(lock, std::chrono::seconds(2),
  20205. [&] { return received.size() >= 3; });
  20206. }
  20207. sse.stop();
  20208. ASSERT_GE(received.size(), 3u);
  20209. EXPECT_EQ(received[0], "");
  20210. EXPECT_EQ(received[1], "\nhello");
  20211. EXPECT_EQ(received[2], "");
  20212. }
  20213. // Test: Auto-reconnect after server disconnection
  20214. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20215. std::atomic<int> connection_count{0};
  20216. std::atomic<int> message_count{0};
  20217. // Endpoint that sends one event and closes, forcing reconnect
  20218. server_->Get("/reconnect-test",
  20219. [&connection_count](const Request &, Response &res) {
  20220. connection_count.fetch_add(1);
  20221. res.set_chunked_content_provider(
  20222. "text/event-stream", [](size_t offset, DataSink &sink) {
  20223. if (offset == 0) {
  20224. std::string event = "data: hello\n\n";
  20225. sink.write(event.data(), event.size());
  20226. }
  20227. return false; // Close connection after sending
  20228. });
  20229. });
  20230. Client client("localhost", get_port());
  20231. sse::SSEClient sse(client, "/reconnect-test");
  20232. sse.on_message([&message_count](const sse::SSEMessage &) {
  20233. message_count.fetch_add(1);
  20234. });
  20235. sse.set_reconnect_interval(100);
  20236. sse.set_max_reconnect_attempts(3);
  20237. sse.start_async();
  20238. // Wait long enough for multiple reconnects
  20239. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20240. sse.stop();
  20241. // Should have connected multiple times (initial + reconnects)
  20242. EXPECT_GE(connection_count.load(), 2);
  20243. // Should have received messages from multiple connections
  20244. EXPECT_GE(message_count.load(), 2);
  20245. }
  20246. // Test: A retry field that is not all ASCII digits is ignored
  20247. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20248. std::atomic<int> connection_count{0};
  20249. server_->Get("/bad-retry",
  20250. [&connection_count](const Request &, Response &res) {
  20251. connection_count.fetch_add(1);
  20252. res.set_chunked_content_provider(
  20253. "text/event-stream", [](size_t offset, DataSink &sink) {
  20254. if (offset == 0) {
  20255. std::string event = "retry: -1\ndata: hello\n\n";
  20256. sink.write(event.data(), event.size());
  20257. }
  20258. return false;
  20259. });
  20260. });
  20261. Client client("localhost", get_port());
  20262. sse::SSEClient sse(client, "/bad-retry");
  20263. sse.set_reconnect_interval(10000);
  20264. sse.start_async();
  20265. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20266. sse.stop();
  20267. EXPECT_EQ(connection_count.load(), 1);
  20268. }
  20269. // Test: A retry field of all ASCII digits sets the reconnection time
  20270. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20271. std::mutex mutex;
  20272. std::condition_variable cv;
  20273. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20274. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20275. {
  20276. std::lock_guard<std::mutex> lock(mutex);
  20277. connected_at.push_back(std::chrono::steady_clock::now());
  20278. cv.notify_all();
  20279. }
  20280. res.set_chunked_content_provider(
  20281. "text/event-stream", [](size_t offset, DataSink &sink) {
  20282. if (offset == 0) {
  20283. std::string event = "retry: 0\ndata: hello\n\n";
  20284. sink.write(event.data(), event.size());
  20285. }
  20286. return false;
  20287. });
  20288. });
  20289. Client client("localhost", get_port());
  20290. sse::SSEClient sse(client, "/zero-retry");
  20291. sse.set_reconnect_interval(10000);
  20292. sse.start_async();
  20293. {
  20294. std::unique_lock<std::mutex> lock(mutex);
  20295. cv.wait_for(lock, std::chrono::seconds(5),
  20296. [&] { return connected_at.size() >= 2; });
  20297. }
  20298. sse.stop();
  20299. // The server-supplied interval is applied, but never below 100ms, so
  20300. // "retry: 0" does not cause a busy reconnect loop
  20301. std::lock_guard<std::mutex> lock(mutex);
  20302. ASSERT_GE(connected_at.size(), 2u);
  20303. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20304. connected_at[1] - connected_at[0])
  20305. .count();
  20306. EXPECT_GE(interval_ms, 100);
  20307. }
  20308. // Test: Last-Event-ID sent on reconnect
  20309. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20310. std::atomic<int> connection_count{0};
  20311. std::vector<std::string> received_last_event_ids;
  20312. std::mutex id_mutex;
  20313. // Endpoint that checks Last-Event-ID header and sends event with ID
  20314. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20315. int conn = connection_count.fetch_add(1);
  20316. // Capture the Last-Event-ID header from each connection
  20317. {
  20318. std::lock_guard<std::mutex> lock(id_mutex);
  20319. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20320. }
  20321. res.set_chunked_content_provider(
  20322. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20323. if (offset == 0) {
  20324. std::string event =
  20325. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20326. sink.write(event.data(), event.size());
  20327. }
  20328. return false;
  20329. });
  20330. });
  20331. Client client("localhost", get_port());
  20332. sse::SSEClient sse(client, "/reconnect-with-id");
  20333. sse.set_reconnect_interval(100);
  20334. sse.set_max_reconnect_attempts(3);
  20335. sse.start_async();
  20336. // Wait for at least 2 connections
  20337. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20338. sse.stop();
  20339. // Verify behavior
  20340. std::lock_guard<std::mutex> lock(id_mutex);
  20341. EXPECT_GE(received_last_event_ids.size(), 2u);
  20342. // First connection should have no Last-Event-ID
  20343. if (!received_last_event_ids.empty()) {
  20344. EXPECT_EQ(received_last_event_ids[0], "");
  20345. }
  20346. // Second connection should have Last-Event-ID from first connection
  20347. if (received_last_event_ids.size() >= 2) {
  20348. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20349. }
  20350. }
  20351. // Test: set_headers updates headers used on reconnect
  20352. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20353. std::vector<std::string> received_tokens;
  20354. std::mutex token_mutex;
  20355. // Endpoint that captures Authorization header
  20356. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20357. {
  20358. std::lock_guard<std::mutex> lock(token_mutex);
  20359. received_tokens.push_back(req.get_header_value("Authorization"));
  20360. }
  20361. res.set_chunked_content_provider(
  20362. "text/event-stream", [](size_t offset, DataSink &sink) {
  20363. if (offset == 0) {
  20364. std::string event = "data: hello\n\n";
  20365. sink.write(event.data(), event.size());
  20366. }
  20367. return false; // Close connection to trigger reconnect
  20368. });
  20369. });
  20370. Client client("localhost", get_port());
  20371. Headers headers = {{"Authorization", "Bearer old-token"}};
  20372. sse::SSEClient sse(client, "/auth-check", headers);
  20373. // Update headers on each successful connection
  20374. sse.on_open(
  20375. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20376. sse.set_reconnect_interval(100);
  20377. sse.set_max_reconnect_attempts(3);
  20378. sse.start_async();
  20379. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20380. sse.stop();
  20381. std::lock_guard<std::mutex> lock(token_mutex);
  20382. ASSERT_GE(received_tokens.size(), 2u);
  20383. // First connection uses original header
  20384. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20385. // Second connection uses updated header from set_headers
  20386. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20387. }
  20388. // Test: 401 allows reconnection (so on_error can refresh headers)
  20389. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20390. std::atomic<int> connection_count{0};
  20391. // Endpoint: returns 401 on first attempt, 200 on second
  20392. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20393. int conn = connection_count.fetch_add(1);
  20394. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20395. res.status = StatusCode::Unauthorized_401;
  20396. res.set_content("Unauthorized", "text/plain");
  20397. return;
  20398. }
  20399. res.set_chunked_content_provider(
  20400. "text/event-stream", [](size_t offset, DataSink &sink) {
  20401. if (offset == 0) {
  20402. std::string event = "data: authenticated\n\n";
  20403. sink.write(event.data(), event.size());
  20404. }
  20405. return false;
  20406. });
  20407. });
  20408. Client client("localhost", get_port());
  20409. Headers headers = {{"Authorization", "Bearer expired"}};
  20410. sse::SSEClient sse(client, "/auth-retry", headers);
  20411. std::atomic<bool> message_received{false};
  20412. // Refresh token on error
  20413. sse.on_error(
  20414. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20415. sse.on_message([&](const sse::SSEMessage &msg) {
  20416. if (msg.data == "authenticated") { message_received.store(true); }
  20417. });
  20418. sse.set_reconnect_interval(100);
  20419. sse.set_max_reconnect_attempts(3);
  20420. sse.start_async();
  20421. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20422. sse.stop();
  20423. // Should have reconnected after 401 and succeeded with new token
  20424. EXPECT_GE(connection_count.load(), 2);
  20425. EXPECT_TRUE(message_received.load());
  20426. }
  20427. TEST(Issue2318Test, EmptyHostString) {
  20428. {
  20429. httplib::Client cli_empty("", PORT);
  20430. auto res = cli_empty.Get("/");
  20431. ASSERT_FALSE(res);
  20432. EXPECT_EQ(httplib::Error::Connection, res.error());
  20433. }
  20434. {
  20435. httplib::Client cli(" ", PORT);
  20436. auto res = cli.Get("/");
  20437. ASSERT_FALSE(res);
  20438. EXPECT_EQ(httplib::Error::Connection, res.error());
  20439. }
  20440. }
  20441. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20442. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20443. Server svr;
  20444. // Set a small payload limit (1KB)
  20445. svr.set_payload_max_length(1024);
  20446. svr.Post("/test", [&](const Request &req, Response &res) {
  20447. res.set_content("Body size: " + std::to_string(req.body.size()),
  20448. "text/plain");
  20449. });
  20450. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20451. auto se = detail::scope_exit([&] {
  20452. svr.stop();
  20453. listen_thread.join();
  20454. });
  20455. svr.wait_until_ready();
  20456. // Create data that compresses well but exceeds limit when decompressed
  20457. // 8KB of repeated null bytes compresses to a very small size
  20458. std::string original_data(8 * 1024, '\0');
  20459. // Compress the data using gzip
  20460. std::string compressed_data;
  20461. detail::gzip_compressor compressor;
  20462. compressor.compress(original_data.data(), original_data.size(), true,
  20463. [&](const char *data, size_t size) {
  20464. compressed_data.append(data, size);
  20465. return true;
  20466. });
  20467. // Verify compression worked (compressed should be much smaller)
  20468. ASSERT_LT(compressed_data.size(), original_data.size());
  20469. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20470. // Send compressed data with Content-Encoding: gzip
  20471. Client cli(HOST, PORT);
  20472. Headers headers = {{"Content-Encoding", "gzip"}};
  20473. auto res =
  20474. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20475. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20477. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20478. }
  20479. #endif
  20480. // ============================================================================
  20481. // OpenSSL-Specific Tests
  20482. // ============================================================================
  20483. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20484. X509 *readCertificate(const std::string &strFileName) {
  20485. std::ifstream inStream(strFileName);
  20486. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20487. std::istreambuf_iterator<char>());
  20488. if (strCertPEM.empty()) return (nullptr);
  20489. BIO *pbCert = BIO_new(BIO_s_mem());
  20490. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20491. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20492. BIO_free(pbCert);
  20493. return (pCert);
  20494. }
  20495. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20496. std::ifstream inStream(strFileName);
  20497. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20498. std::istreambuf_iterator<char>());
  20499. if (strPrivateKeyPEM.empty()) return (nullptr);
  20500. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20501. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20502. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20503. BIO_free(pbPrivKey);
  20504. return (pPrivateKey);
  20505. }
  20506. TEST(BindServerTest, UpdateCerts) {
  20507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20508. int port = svr.bind_to_any_port("0.0.0.0");
  20509. ASSERT_TRUE(svr.is_valid());
  20510. ASSERT_TRUE(port > 0);
  20511. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20512. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20513. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20514. ASSERT_TRUE(cert != nullptr);
  20515. ASSERT_TRUE(ca_cert != nullptr);
  20516. ASSERT_TRUE(key != nullptr);
  20517. X509_STORE *cert_store = X509_STORE_new();
  20518. X509_STORE_add_cert(cert_store, ca_cert);
  20519. // svr.update_certs(cert, key, cert_store); // deprecated
  20520. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20521. CLIENT_CA_CERT_FILE);
  20522. ASSERT_TRUE(svr.is_valid());
  20523. svr.stop();
  20524. X509_STORE_free(cert_store);
  20525. X509_free(cert);
  20526. X509_free(ca_cert);
  20527. EVP_PKEY_free(key);
  20528. }
  20529. // Test that update_certs() updates client CA list correctly
  20530. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20531. // Start with file-based constructor
  20532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20533. ASSERT_TRUE(svr.is_valid());
  20534. // Initially no client CA list should be set
  20535. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20536. ASSERT_TRUE(ssl_ctx != nullptr);
  20537. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20538. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20539. EXPECT_EQ(0, count_before);
  20540. // Now update with client CA (PEM string)
  20541. std::string cert_pem, key_pem, ca_pem;
  20542. read_file(SERVER_CERT_FILE, cert_pem);
  20543. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20544. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20545. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20546. ASSERT_TRUE(svr.is_valid());
  20547. // Now client CA list should be set
  20548. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20549. ASSERT_TRUE(ca_list_after != nullptr);
  20550. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20551. }
  20552. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20553. // Test that the file-path SSLServer constructor properly sets the client CA
  20554. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20555. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20556. ASSERT_TRUE(svr.is_valid());
  20557. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20558. ASSERT_TRUE(ssl_ctx != nullptr);
  20559. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20560. ASSERT_TRUE(ca_list != nullptr);
  20561. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20562. }
  20563. #endif
  20564. // ============================================================================
  20565. // MbedTLS-Specific Tests
  20566. // ============================================================================
  20567. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20568. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20569. using namespace httplib::tls;
  20570. // Track if callback was invoked
  20571. bool callback_invoked = false;
  20572. // The callback receives void* ctx which is actually MbedTlsContext*
  20573. // We can access the mbedtls_ssl_config via the context
  20574. auto setup_callback = [&callback_invoked](void *ctx) {
  20575. callback_invoked = true;
  20576. // Cast to MbedTlsContext* to access the ssl config
  20577. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20578. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20579. // Use static variables to hold certificate data (simplified for test)
  20580. static mbedtls_x509_crt own_cert;
  20581. static mbedtls_pk_context own_key;
  20582. static mbedtls_x509_crt ca_chain;
  20583. static bool initialized = false;
  20584. if (!initialized) {
  20585. mbedtls_x509_crt_init(&own_cert);
  20586. mbedtls_pk_init(&own_key);
  20587. mbedtls_x509_crt_init(&ca_chain);
  20588. // Load server certificate
  20589. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20590. return false;
  20591. }
  20592. // Load server private key.
  20593. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20594. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20595. #if MBEDTLS_VERSION_MAJOR == 3
  20596. ,
  20597. mbedtls_ctr_drbg_random, nullptr
  20598. #endif
  20599. ) != 0) {
  20600. return false;
  20601. }
  20602. // Load CA chain for client verification
  20603. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20604. return false;
  20605. }
  20606. initialized = true;
  20607. }
  20608. // Configure the SSL config
  20609. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20610. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20611. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20612. // Set minimum TLS version using mbedTLS native API
  20613. #if MBEDTLS_VERSION_MAJOR >= 3
  20614. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20615. #else
  20616. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20617. MBEDTLS_SSL_MINOR_VERSION_3);
  20618. #endif
  20619. return true;
  20620. };
  20621. SSLServer svr(setup_callback);
  20622. ASSERT_TRUE(svr.is_valid());
  20623. ASSERT_TRUE(callback_invoked);
  20624. svr.Get("/test", [&](const Request &req, Response &res) {
  20625. res.set_content("test", "text/plain");
  20626. auto cert = req.peer_cert();
  20627. ASSERT_TRUE(static_cast<bool>(cert));
  20628. auto common_name = cert.subject_cn();
  20629. EXPECT_EQ("Common Name", common_name);
  20630. });
  20631. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20632. auto se = detail::scope_exit([&] {
  20633. svr.stop();
  20634. t.join();
  20635. ASSERT_FALSE(svr.is_running());
  20636. });
  20637. svr.wait_until_ready();
  20638. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20639. cli.enable_server_certificate_verification(false);
  20640. cli.set_connection_timeout(30);
  20641. auto res = cli.Get("/test");
  20642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20643. ASSERT_EQ(StatusCode::OK_200, res->status);
  20644. }
  20645. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20646. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20647. // keep-alive SSL session, which reads through that config in
  20648. // mbedtls_ssl_close_notify.
  20649. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20650. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20651. ASSERT_TRUE(svr.is_valid());
  20652. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20653. res.set_content("test", "text/plain");
  20654. });
  20655. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20656. auto se = detail::scope_exit([&] {
  20657. svr.stop();
  20658. t.join();
  20659. ASSERT_FALSE(svr.is_running());
  20660. });
  20661. svr.wait_until_ready();
  20662. {
  20663. SSLClient cli(HOST, PORT);
  20664. cli.enable_server_certificate_verification(false);
  20665. cli.set_keep_alive(true);
  20666. auto res = cli.Get("/test");
  20667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20668. ASSERT_EQ(StatusCode::OK_200, res->status);
  20669. // cli is destructed here with the keep-alive SSL session still open.
  20670. }
  20671. }
  20672. #endif
  20673. // WebSocket Tests
  20674. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20675. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20676. // defining the meaning of these bits has been negotiated.
  20677. auto make_frame = [](uint8_t first_byte) {
  20678. std::string frame;
  20679. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20680. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20681. frame += "Hello";
  20682. return frame;
  20683. };
  20684. // RSV1 set (0x40)
  20685. {
  20686. detail::BufferStream strm;
  20687. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20688. ws::Opcode opcode;
  20689. std::string payload;
  20690. bool fin;
  20691. EXPECT_EQ(
  20692. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20693. ws::impl::FrameRead::Fail);
  20694. }
  20695. // RSV2 set (0x20)
  20696. {
  20697. detail::BufferStream strm;
  20698. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20699. ws::Opcode opcode;
  20700. std::string payload;
  20701. bool fin;
  20702. EXPECT_EQ(
  20703. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20704. ws::impl::FrameRead::Fail);
  20705. }
  20706. // RSV3 set (0x10)
  20707. {
  20708. detail::BufferStream strm;
  20709. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20710. ws::Opcode opcode;
  20711. std::string payload;
  20712. bool fin;
  20713. EXPECT_EQ(
  20714. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20715. ws::impl::FrameRead::Fail);
  20716. }
  20717. // No RSV bits set - should succeed
  20718. {
  20719. detail::BufferStream strm;
  20720. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20721. ws::Opcode opcode;
  20722. std::string payload;
  20723. bool fin;
  20724. EXPECT_EQ(
  20725. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20726. ws::impl::FrameRead::Ok);
  20727. EXPECT_EQ(ws::Opcode::Text, opcode);
  20728. EXPECT_EQ("Hello", payload);
  20729. EXPECT_TRUE(fin);
  20730. }
  20731. }
  20732. TEST(WebSocketTest, ControlFrameValidation) {
  20733. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20734. // payload length <= 125.
  20735. // Ping with FIN=0 - must be rejected
  20736. {
  20737. detail::BufferStream strm;
  20738. std::string frame;
  20739. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20740. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20741. strm.write(frame.data(), frame.size());
  20742. ws::Opcode opcode;
  20743. std::string payload;
  20744. bool fin;
  20745. EXPECT_EQ(
  20746. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20747. ws::impl::FrameRead::Fail);
  20748. }
  20749. // Close with FIN=0 - must be rejected
  20750. {
  20751. detail::BufferStream strm;
  20752. std::string frame;
  20753. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20754. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20755. strm.write(frame.data(), frame.size());
  20756. ws::Opcode opcode;
  20757. std::string payload;
  20758. bool fin;
  20759. EXPECT_EQ(
  20760. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20761. ws::impl::FrameRead::Fail);
  20762. }
  20763. // Ping with payload_len=126 (extended length) - must be rejected
  20764. {
  20765. detail::BufferStream strm;
  20766. std::string frame;
  20767. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20768. frame += static_cast<char>(126); // payload_len=126 (>125)
  20769. frame += static_cast<char>(0x00); // extended length high byte
  20770. frame += static_cast<char>(126); // extended length low byte
  20771. frame += std::string(126, 'x');
  20772. strm.write(frame.data(), frame.size());
  20773. ws::Opcode opcode;
  20774. std::string payload;
  20775. bool fin;
  20776. EXPECT_EQ(
  20777. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20778. ws::impl::FrameRead::Fail);
  20779. }
  20780. // Ping with FIN=1 and payload_len=125 - should succeed
  20781. {
  20782. detail::BufferStream strm;
  20783. std::string frame;
  20784. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20785. frame += static_cast<char>(125); // payload_len=125
  20786. frame += std::string(125, 'x');
  20787. strm.write(frame.data(), frame.size());
  20788. ws::Opcode opcode;
  20789. std::string payload;
  20790. bool fin;
  20791. EXPECT_EQ(
  20792. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20793. ws::impl::FrameRead::Ok);
  20794. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20795. EXPECT_EQ(125u, payload.size());
  20796. EXPECT_TRUE(fin);
  20797. }
  20798. }
  20799. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20800. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20801. // length MUST be 0.
  20802. // MSB set - must be rejected
  20803. {
  20804. detail::BufferStream strm;
  20805. std::string frame;
  20806. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20807. frame += static_cast<char>(127); // 64-bit extended length
  20808. frame += static_cast<char>(0x80); // MSB set (invalid)
  20809. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20810. strm.write(frame.data(), frame.size());
  20811. ws::Opcode opcode;
  20812. std::string payload;
  20813. bool fin;
  20814. EXPECT_EQ(
  20815. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20816. ws::impl::FrameRead::Fail);
  20817. }
  20818. // MSB clear - should pass length parsing (will be rejected by max_len,
  20819. // but that's a different check; use a small length to verify)
  20820. {
  20821. detail::BufferStream strm;
  20822. std::string frame;
  20823. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20824. frame += static_cast<char>(127); // 64-bit extended length
  20825. frame += std::string(7, '\0'); // high bytes = 0
  20826. frame += static_cast<char>(0x03); // length = 3
  20827. frame += "abc";
  20828. strm.write(frame.data(), frame.size());
  20829. ws::Opcode opcode;
  20830. std::string payload;
  20831. bool fin;
  20832. EXPECT_EQ(
  20833. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20834. ws::impl::FrameRead::Ok);
  20835. EXPECT_EQ(ws::Opcode::Text, opcode);
  20836. EXPECT_EQ("abc", payload);
  20837. }
  20838. }
  20839. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20840. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20841. // Valid UTF-8
  20842. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20843. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20844. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20845. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20846. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20847. // Invalid UTF-8
  20848. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20849. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20850. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20851. EXPECT_FALSE(
  20852. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20853. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20854. }
  20855. TEST(WebSocketTest, ConnectAndDisconnect) {
  20856. Server svr;
  20857. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20858. std::string msg;
  20859. while (ws.read(msg)) {}
  20860. });
  20861. auto port = svr.bind_to_any_port(HOST);
  20862. std::thread t([&]() { svr.listen_after_bind(); });
  20863. svr.wait_until_ready();
  20864. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20865. auto res = client.connect();
  20866. ASSERT_TRUE(res);
  20867. EXPECT_EQ(Error::Success, res.error());
  20868. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20869. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20870. EXPECT_TRUE(client.is_open());
  20871. client.close();
  20872. EXPECT_FALSE(client.is_open());
  20873. svr.stop();
  20874. t.join();
  20875. }
  20876. TEST(WebSocketTest, ValidURL) {
  20877. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20878. EXPECT_TRUE(ws1.is_valid());
  20879. ws::WebSocketClient ws2("ws://example.com/path");
  20880. EXPECT_TRUE(ws2.is_valid());
  20881. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20882. EXPECT_TRUE(ws3.is_valid());
  20883. #ifdef CPPHTTPLIB_SSL_ENABLED
  20884. ws::WebSocketClient wss1("wss://example.com/path");
  20885. EXPECT_TRUE(wss1.is_valid());
  20886. ws::WebSocketClient wss2("wss://example.com:443/path");
  20887. EXPECT_TRUE(wss2.is_valid());
  20888. #endif
  20889. }
  20890. TEST(WebSocketTest, InvalidURL) {
  20891. // No scheme
  20892. ws::WebSocketClient ws1("localhost:8080/path");
  20893. EXPECT_FALSE(ws1.is_valid());
  20894. // No path
  20895. ws::WebSocketClient ws2("ws://localhost:8080");
  20896. EXPECT_FALSE(ws2.is_valid());
  20897. // Empty string
  20898. ws::WebSocketClient ws3("");
  20899. EXPECT_FALSE(ws3.is_valid());
  20900. // Missing host
  20901. ws::WebSocketClient ws4("ws://:8080/path");
  20902. EXPECT_FALSE(ws4.is_valid());
  20903. // Port number overflow — should not crash
  20904. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20905. EXPECT_FALSE(ws5.is_valid());
  20906. // Port out of range
  20907. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20908. EXPECT_FALSE(ws6.is_valid());
  20909. }
  20910. TEST(WebSocketTest, UnsupportedScheme) {
  20911. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20912. ws::WebSocketClient ws1("http://localhost:8080/path");
  20913. EXPECT_FALSE(ws1.is_valid());
  20914. ws::WebSocketClient ws2("https://localhost:8080/path");
  20915. EXPECT_FALSE(ws2.is_valid());
  20916. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20917. EXPECT_FALSE(ws3.is_valid());
  20918. #else
  20919. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20920. std::invalid_argument);
  20921. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20922. std::invalid_argument);
  20923. #endif
  20924. }
  20925. TEST(WebSocketTest, ConnectWhenInvalid) {
  20926. ws::WebSocketClient ws("not a valid url");
  20927. EXPECT_FALSE(ws.is_valid());
  20928. auto res = ws.connect();
  20929. EXPECT_FALSE(res);
  20930. EXPECT_EQ(Error::Connection, res.error());
  20931. EXPECT_EQ(-1, res.status());
  20932. }
  20933. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20934. // Grab a port that is free, then close it again so nothing listens there
  20935. Server svr;
  20936. auto port = svr.bind_to_any_port(HOST);
  20937. svr.stop();
  20938. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20939. auto res = client.connect();
  20940. ASSERT_FALSE(res);
  20941. EXPECT_EQ(Error::Connection, res.error());
  20942. EXPECT_EQ(-1, res.status());
  20943. }
  20944. TEST(WebSocketTest, DefaultPort) {
  20945. ws::WebSocketClient ws1("ws://example.com/path");
  20946. EXPECT_TRUE(ws1.is_valid());
  20947. // ws:// defaults to port 80 (verified by successful parse)
  20948. #ifdef CPPHTTPLIB_SSL_ENABLED
  20949. ws::WebSocketClient ws2("wss://example.com/path");
  20950. EXPECT_TRUE(ws2.is_valid());
  20951. // wss:// defaults to port 443 (verified by successful parse)
  20952. #endif
  20953. }
  20954. TEST(WebSocketTest, IPv6LiteralAddress) {
  20955. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20956. EXPECT_TRUE(ws1.is_valid());
  20957. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20958. EXPECT_TRUE(ws2.is_valid());
  20959. }
  20960. TEST(WebSocketTest, ComplexPath) {
  20961. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20962. EXPECT_TRUE(ws1.is_valid());
  20963. ws::WebSocketClient ws2("ws://localhost:8080/");
  20964. EXPECT_TRUE(ws2.is_valid());
  20965. }
  20966. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20967. Server svr;
  20968. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20969. std::string msg;
  20970. while (ws.read(msg)) {}
  20971. });
  20972. auto port = svr.bind_to_any_port(HOST);
  20973. std::thread t([&]() { svr.listen_after_bind(); });
  20974. svr.wait_until_ready();
  20975. auto another_host = "example.com";
  20976. auto wrong_ip = "192.0.2.1";
  20977. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20978. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20979. ASSERT_TRUE(client.connect());
  20980. EXPECT_TRUE(client.is_open());
  20981. client.close();
  20982. svr.stop();
  20983. t.join();
  20984. }
  20985. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20986. Server svr;
  20987. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20988. std::string msg;
  20989. while (ws.read(msg)) {}
  20990. });
  20991. auto port = svr.bind_to_any_port(HOST);
  20992. std::thread t([&]() { svr.listen_after_bind(); });
  20993. svr.wait_until_ready();
  20994. auto wrong_ip = "192.0.2.1";
  20995. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20996. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20997. client.set_connection_timeout(1);
  20998. client.set_read_timeout(1);
  20999. client.set_write_timeout(1);
  21000. EXPECT_FALSE(client.connect());
  21001. EXPECT_FALSE(client.is_open());
  21002. svr.stop();
  21003. t.join();
  21004. }
  21005. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21006. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21007. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21008. // (RFC 6761) is only a map key and the Host header value.
  21009. auto host = "target.invalid";
  21010. Server svr;
  21011. std::string received_host;
  21012. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21013. received_host = req.get_header_value("Host");
  21014. std::string msg;
  21015. while (ws.read(msg)) {}
  21016. });
  21017. auto port = svr.bind_to_any_port(HOST);
  21018. std::thread t([&]() { svr.listen_after_bind(); });
  21019. // ASSERT_* below returns from the test body, which would leave t joinable
  21020. // and make ~thread call std::terminate.
  21021. auto se = detail::scope_exit([&] {
  21022. svr.stop();
  21023. if (t.joinable()) { t.join(); }
  21024. });
  21025. svr.wait_until_ready();
  21026. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21027. std::to_string(port) + "/ws");
  21028. client.set_hostname_addr_map({{host, HOST}});
  21029. ASSERT_TRUE(client.connect());
  21030. EXPECT_TRUE(client.is_open());
  21031. client.close();
  21032. svr.stop();
  21033. t.join();
  21034. // The mapping only redirects the connection; the identity stays host_.
  21035. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21036. }
  21037. class WebSocketIntegrationTest : public ::testing::Test {
  21038. protected:
  21039. void SetUp() override {
  21040. server_ = httplib::detail::make_unique<Server>();
  21041. setup_server();
  21042. start_server();
  21043. }
  21044. void TearDown() override {
  21045. server_->stop();
  21046. if (server_thread_.joinable()) { server_thread_.join(); }
  21047. }
  21048. void setup_server() {
  21049. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21050. std::string msg;
  21051. ws::ReadResult ret;
  21052. while ((ret = ws.read(msg))) {
  21053. if (ret == ws::Binary) {
  21054. ws.send(msg.data(), msg.size());
  21055. } else {
  21056. ws.send(msg);
  21057. }
  21058. }
  21059. });
  21060. server_->WebSocket("/ws-echo-string",
  21061. [](const Request &, ws::WebSocket &ws) {
  21062. std::string msg;
  21063. while (ws.read(msg)) {
  21064. ws.send("echo: " + msg);
  21065. }
  21066. });
  21067. server_->WebSocket(
  21068. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21069. // Echo back request metadata
  21070. ws.send("path:" + req.path);
  21071. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21072. std::string msg;
  21073. while (ws.read(msg)) {}
  21074. });
  21075. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21076. std::string msg;
  21077. ws.read(msg); // wait for a message
  21078. ws.close();
  21079. });
  21080. server_->WebSocket("/ws-close-status",
  21081. [](const Request &, ws::WebSocket &ws) {
  21082. std::string msg;
  21083. ws.read(msg); // wait for a message
  21084. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21085. });
  21086. server_->WebSocket(
  21087. "/ws-subprotocol",
  21088. [](const Request &, ws::WebSocket &ws) {
  21089. std::string msg;
  21090. while (ws.read(msg)) {
  21091. ws.send(msg);
  21092. }
  21093. },
  21094. [](const std::vector<std::string> &protocols) -> std::string {
  21095. for (const auto &p : protocols) {
  21096. if (p == "graphql-ws") { return p; }
  21097. }
  21098. return "";
  21099. });
  21100. server_->WebSocket(
  21101. "/ws-subprotocol-unoffered",
  21102. [](const Request &, ws::WebSocket &ws) {
  21103. std::string msg;
  21104. while (ws.read(msg)) {
  21105. ws.send(msg);
  21106. }
  21107. },
  21108. [](const std::vector<std::string> &) -> std::string {
  21109. return "admin";
  21110. });
  21111. }
  21112. void start_server() {
  21113. port_ = server_->bind_to_any_port(HOST);
  21114. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21115. server_->wait_until_ready();
  21116. }
  21117. std::unique_ptr<Server> server_;
  21118. std::thread server_thread_;
  21119. int port_ = 0;
  21120. };
  21121. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21122. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21123. "/ws-echo");
  21124. ASSERT_TRUE(client.connect());
  21125. ASSERT_TRUE(client.is_open());
  21126. ASSERT_TRUE(client.send("Hello WebSocket"));
  21127. std::string msg;
  21128. EXPECT_EQ(ws::Text, client.read(msg));
  21129. EXPECT_EQ("Hello WebSocket", msg);
  21130. client.close();
  21131. }
  21132. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21133. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21134. "/ws-echo");
  21135. ASSERT_TRUE(client.connect());
  21136. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21137. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21138. std::string msg;
  21139. EXPECT_EQ(ws::Binary, client.read(msg));
  21140. EXPECT_EQ(binary_data, msg);
  21141. client.close();
  21142. }
  21143. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21144. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21145. "/ws-echo");
  21146. ASSERT_TRUE(client.connect());
  21147. for (int i = 0; i < 10; i++) {
  21148. auto text = "message " + std::to_string(i);
  21149. ASSERT_TRUE(client.send(text));
  21150. std::string msg;
  21151. ASSERT_TRUE(client.read(msg));
  21152. EXPECT_EQ(text, msg);
  21153. }
  21154. client.close();
  21155. }
  21156. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21157. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21158. "/ws-close");
  21159. ASSERT_TRUE(client.connect());
  21160. // Send a message to trigger the server to close
  21161. ASSERT_TRUE(client.send("trigger close"));
  21162. // The server will close, so read should return false
  21163. std::string msg;
  21164. EXPECT_FALSE(client.read(msg));
  21165. EXPECT_FALSE(client.is_open());
  21166. }
  21167. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21168. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21169. "/ws-echo");
  21170. ASSERT_TRUE(client.connect());
  21171. // 128KB message
  21172. std::string large_data(128 * 1024, 'X');
  21173. ASSERT_TRUE(client.send(large_data));
  21174. std::string msg;
  21175. ASSERT_TRUE(client.read(msg));
  21176. EXPECT_EQ(large_data, msg);
  21177. client.close();
  21178. }
  21179. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21180. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21181. "/ws-echo");
  21182. ASSERT_TRUE(client.connect());
  21183. const int num_threads = 4;
  21184. std::vector<std::thread> threads;
  21185. std::atomic<int> send_count{0};
  21186. for (int t = 0; t < num_threads; t++) {
  21187. threads.emplace_back([&client, &send_count, t]() {
  21188. for (int i = 0; i < 5; i++) {
  21189. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21190. if (client.send(text)) { send_count++; }
  21191. }
  21192. });
  21193. }
  21194. for (auto &th : threads) {
  21195. th.join();
  21196. }
  21197. int received = 0;
  21198. std::string msg;
  21199. while (received < send_count.load()) {
  21200. if (!client.read(msg)) { break; }
  21201. received++;
  21202. }
  21203. EXPECT_EQ(send_count.load(), received);
  21204. client.close();
  21205. }
  21206. TEST_F(WebSocketIntegrationTest, ReadString) {
  21207. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21208. "/ws-echo-string");
  21209. ASSERT_TRUE(client.connect());
  21210. ASSERT_TRUE(client.send("hello"));
  21211. std::string msg;
  21212. ASSERT_TRUE(client.read(msg));
  21213. EXPECT_EQ("echo: hello", msg);
  21214. ASSERT_TRUE(client.send("world"));
  21215. ASSERT_TRUE(client.read(msg));
  21216. EXPECT_EQ("echo: world", msg);
  21217. client.close();
  21218. }
  21219. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21220. Headers headers = {{"X-Test-Header", "test-value"}};
  21221. ws::WebSocketClient client(
  21222. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21223. ASSERT_TRUE(client.connect());
  21224. std::string msg;
  21225. ASSERT_TRUE(client.read(msg));
  21226. EXPECT_EQ("path:/ws-request-info", msg);
  21227. ASSERT_TRUE(client.read(msg));
  21228. EXPECT_EQ("header:test-value", msg);
  21229. client.close();
  21230. }
  21231. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21232. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21233. "/ws-echo");
  21234. client.set_read_timeout(1, 0); // 1 second
  21235. ASSERT_TRUE(client.connect());
  21236. // Don't send anything — server echo handler waits for a message, so read()
  21237. // should time out. The connection survives it: nothing was consumed.
  21238. std::string msg;
  21239. EXPECT_EQ(client.read(msg), ws::Timeout);
  21240. EXPECT_TRUE(client.is_open());
  21241. // And it is still usable afterwards.
  21242. EXPECT_TRUE(client.send("after timeout"));
  21243. EXPECT_EQ(client.read(msg), ws::Text);
  21244. EXPECT_EQ(msg, "after timeout");
  21245. }
  21246. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21247. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21248. "/ws-echo");
  21249. client.set_read_timeout(1, 0);
  21250. ASSERT_TRUE(client.connect());
  21251. ASSERT_TRUE(client.send("first"));
  21252. std::string msg;
  21253. ASSERT_EQ(client.read(msg), ws::Text);
  21254. ASSERT_EQ(msg, "first");
  21255. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21256. // not be used with a read timeout: it would reprocess the previous message.
  21257. EXPECT_EQ(client.read(msg), ws::Timeout);
  21258. EXPECT_EQ(msg, "first");
  21259. }
  21260. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21261. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21262. "/ws-echo");
  21263. ASSERT_TRUE(client.connect());
  21264. // Setting it once the connection is open reaches the live stream, not just
  21265. // the seed for the next connect().
  21266. client.set_read_timeout(1, 0);
  21267. std::string msg;
  21268. EXPECT_EQ(client.read(msg), ws::Timeout);
  21269. EXPECT_TRUE(client.is_open());
  21270. }
  21271. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21272. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21273. "/ws-echo");
  21274. client.set_read_timeout(5, 0);
  21275. ASSERT_TRUE(client.connect());
  21276. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21277. // The server should reject it and close the connection.
  21278. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21279. client.send(oversized);
  21280. // The server's read() should have failed due to payload limit,
  21281. // so our read() should return false (connection closed).
  21282. std::string msg;
  21283. EXPECT_FALSE(client.read(msg));
  21284. }
  21285. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21286. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21287. "/ws-echo");
  21288. client.set_read_timeout(10, 0);
  21289. ASSERT_TRUE(client.connect());
  21290. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21291. // This should succeed.
  21292. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21293. ASSERT_TRUE(client.send(at_limit));
  21294. std::string msg;
  21295. ASSERT_TRUE(client.read(msg));
  21296. EXPECT_EQ(at_limit.size(), msg.size());
  21297. client.close();
  21298. }
  21299. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21300. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21301. "/nonexistent");
  21302. auto res = client.connect();
  21303. EXPECT_FALSE(res);
  21304. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21305. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21306. EXPECT_FALSE(client.is_open());
  21307. }
  21308. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21309. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21310. "/ws-echo");
  21311. ASSERT_TRUE(client.connect());
  21312. ASSERT_TRUE(client.send(""));
  21313. std::string msg;
  21314. EXPECT_EQ(ws::Text, client.read(msg));
  21315. EXPECT_EQ("", msg);
  21316. client.close();
  21317. }
  21318. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21319. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21320. "/ws-echo");
  21321. // First connection
  21322. ASSERT_TRUE(client.connect());
  21323. ASSERT_TRUE(client.send("first"));
  21324. std::string msg;
  21325. ASSERT_TRUE(client.read(msg));
  21326. EXPECT_EQ("first", msg);
  21327. client.close();
  21328. EXPECT_FALSE(client.is_open());
  21329. // Reconnect using the same client object
  21330. ASSERT_TRUE(client.connect());
  21331. ASSERT_TRUE(client.is_open());
  21332. ASSERT_TRUE(client.send("second"));
  21333. ASSERT_TRUE(client.read(msg));
  21334. EXPECT_EQ("second", msg);
  21335. client.close();
  21336. }
  21337. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21338. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21339. "/ws-close-status");
  21340. ASSERT_TRUE(client.connect());
  21341. // Trigger the server to close with GoingAway status
  21342. ASSERT_TRUE(client.send("trigger"));
  21343. // read() should return false after receiving the close frame
  21344. std::string msg;
  21345. EXPECT_FALSE(client.read(msg));
  21346. EXPECT_FALSE(client.is_open());
  21347. }
  21348. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21349. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21350. "/ws-echo");
  21351. ASSERT_TRUE(client.connect());
  21352. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21353. EXPECT_FALSE(client.is_open());
  21354. }
  21355. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21356. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21357. ws::WebSocketClient client(
  21358. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21359. ASSERT_TRUE(client.connect());
  21360. // Server should have selected graphql-ws
  21361. EXPECT_EQ("graphql-ws", client.subprotocol());
  21362. client.close();
  21363. }
  21364. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21365. Headers headers;
  21366. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21367. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21368. ws::WebSocketClient client(
  21369. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21370. ASSERT_TRUE(client.connect());
  21371. // The offer on the second field line counts too, so graphql-ws is selected
  21372. EXPECT_EQ("graphql-ws", client.subprotocol());
  21373. client.close();
  21374. }
  21375. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21376. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21377. ws::WebSocketClient client(
  21378. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21379. ASSERT_TRUE(client.connect());
  21380. // Server should not have selected any subprotocol
  21381. EXPECT_TRUE(client.subprotocol().empty());
  21382. client.close();
  21383. }
  21384. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21385. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21386. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21387. "/ws-subprotocol-unoffered",
  21388. headers);
  21389. ASSERT_TRUE(client.connect());
  21390. EXPECT_TRUE(client.subprotocol().empty());
  21391. client.close();
  21392. }
  21393. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21394. // Connect without requesting any subprotocol
  21395. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21396. "/ws-subprotocol");
  21397. ASSERT_TRUE(client.connect());
  21398. EXPECT_TRUE(client.subprotocol().empty());
  21399. client.close();
  21400. }
  21401. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21402. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21403. "/ws-echo");
  21404. client.set_tcp_nodelay(true);
  21405. client.set_connection_timeout(3, 0);
  21406. bool socket_options_called = false;
  21407. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21408. ASSERT_TRUE(client.connect());
  21409. ASSERT_TRUE(client.is_open());
  21410. EXPECT_TRUE(socket_options_called);
  21411. ASSERT_TRUE(client.send("hello"));
  21412. std::string msg;
  21413. auto result = client.read(msg);
  21414. EXPECT_EQ(result, ws::ReadResult::Text);
  21415. EXPECT_EQ(msg, "hello");
  21416. client.close();
  21417. }
  21418. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21419. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21420. "/ws-echo");
  21421. client.set_connection_timeout(std::chrono::seconds(3));
  21422. client.set_write_timeout(std::chrono::seconds(3));
  21423. // A sub-second remainder exercises the seconds/microseconds split.
  21424. client.set_read_timeout(std::chrono::milliseconds(1500));
  21425. ASSERT_TRUE(client.connect());
  21426. auto start = std::chrono::steady_clock::now();
  21427. std::string msg;
  21428. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21429. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21430. std::chrono::steady_clock::now() - start)
  21431. .count();
  21432. // Above 1s so that dropping the microseconds half of the split fails here.
  21433. // Ignoring the setter altogether would not reach this line at all: a client
  21434. // waits forever by default.
  21435. EXPECT_GE(elapsed, 1400);
  21436. EXPECT_LT(elapsed, 30000);
  21437. }
  21438. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21439. Server svr;
  21440. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21441. if (!req.has_header("Authorization")) {
  21442. res.status = StatusCode::Unauthorized_401;
  21443. res.set_content("Unauthorized", "text/plain");
  21444. return Server::HandlerResponse::Handled;
  21445. }
  21446. return Server::HandlerResponse::Unhandled;
  21447. });
  21448. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21449. std::string msg;
  21450. while (ws.read(msg)) {
  21451. ws.send(msg);
  21452. }
  21453. });
  21454. auto port = svr.bind_to_any_port("localhost");
  21455. std::thread t([&]() { svr.listen_after_bind(); });
  21456. svr.wait_until_ready();
  21457. // Without Authorization header - should be rejected before upgrade
  21458. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21459. EXPECT_FALSE(client1.connect());
  21460. // The rejection is framed like any other HTTP response
  21461. {
  21462. Client cli("localhost", port);
  21463. Headers headers = {{"Upgrade", "websocket"},
  21464. {"Connection", "Upgrade"},
  21465. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21466. {"Sec-WebSocket-Version", "13"}};
  21467. auto res = cli.Get("/ws", headers);
  21468. ASSERT_TRUE(res);
  21469. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21470. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21471. EXPECT_EQ("Unauthorized", res->body);
  21472. }
  21473. // With Authorization header - should succeed
  21474. Headers headers = {{"Authorization", "Bearer token123"}};
  21475. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21476. headers);
  21477. ASSERT_TRUE(client2.connect());
  21478. ASSERT_TRUE(client2.send("hello"));
  21479. std::string msg;
  21480. ASSERT_TRUE(client2.read(msg));
  21481. EXPECT_EQ("hello", msg);
  21482. client2.close();
  21483. svr.stop();
  21484. t.join();
  21485. }
  21486. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21487. Server svr;
  21488. std::atomic<int> pre_request_calls{0};
  21489. std::atomic<bool> route_matched{false};
  21490. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21491. pre_request_calls++;
  21492. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21493. if (req.get_header_value("Authorization") != "Bearer token123") {
  21494. res.status = StatusCode::Unauthorized_401;
  21495. res.set_content("Unauthorized", "text/plain");
  21496. return Server::HandlerResponse::Handled;
  21497. }
  21498. return Server::HandlerResponse::Unhandled;
  21499. });
  21500. std::atomic<bool> handler_called{false};
  21501. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21502. handler_called = true;
  21503. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21504. });
  21505. auto port = svr.bind_to_any_port("localhost");
  21506. std::thread t([&]() { svr.listen_after_bind(); });
  21507. svr.wait_until_ready();
  21508. // Without Authorization header - should be rejected before upgrade
  21509. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21510. "/ws/1");
  21511. EXPECT_FALSE(client1.connect());
  21512. EXPECT_FALSE(handler_called);
  21513. EXPECT_EQ(1, pre_request_calls);
  21514. EXPECT_TRUE(route_matched);
  21515. // The rejection is an ordinary HTTP response, not a protocol switch
  21516. {
  21517. Client cli("localhost", port);
  21518. Headers headers = {{"Upgrade", "websocket"},
  21519. {"Connection", "Upgrade"},
  21520. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21521. {"Sec-WebSocket-Version", "13"}};
  21522. auto res = cli.Get("/ws/1", headers);
  21523. ASSERT_TRUE(res);
  21524. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21525. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21526. EXPECT_EQ("Unauthorized", res->body);
  21527. }
  21528. EXPECT_FALSE(handler_called);
  21529. // With Authorization header - should succeed
  21530. Headers headers = {{"Authorization", "Bearer token123"}};
  21531. ws::WebSocketClient client2(
  21532. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21533. ASSERT_TRUE(client2.connect());
  21534. std::string msg;
  21535. ASSERT_TRUE(client2.read(msg));
  21536. EXPECT_EQ("/ws/:id 2", msg);
  21537. EXPECT_TRUE(handler_called);
  21538. client2.close();
  21539. svr.stop();
  21540. t.join();
  21541. }
  21542. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21543. Server svr;
  21544. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21545. // A read timeout is how a handler gets control back. Without it, a handler
  21546. // parked in read() can never write on the connection it is reading.
  21547. ws.set_read_timeout(std::chrono::milliseconds(100));
  21548. std::string msg;
  21549. while (ws.is_open()) {
  21550. auto r = ws.read(msg);
  21551. if (r == httplib::ws::Timeout) {
  21552. ws.send("tick");
  21553. continue;
  21554. }
  21555. if (r == httplib::ws::Fail) { break; }
  21556. ws.send(msg);
  21557. }
  21558. });
  21559. auto port = svr.bind_to_any_port("localhost");
  21560. std::thread t([&]() { svr.listen_after_bind(); });
  21561. svr.wait_until_ready();
  21562. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21563. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21564. ASSERT_TRUE(client.connect());
  21565. // The client sends nothing, so anything it receives came out of the
  21566. // handler's timeout path.
  21567. std::string msg;
  21568. ASSERT_EQ(client.read(msg), ws::Text);
  21569. EXPECT_EQ("tick", msg);
  21570. client.close();
  21571. svr.stop();
  21572. t.join();
  21573. }
  21574. // Stream::read may return fewer bytes than asked for. This is that contract at
  21575. // its worst -- one byte per call -- which is what a frame header straddling a
  21576. // read buffer's boundary looks like to the frame parser.
  21577. class WsByteAtATimeStream : public Stream {
  21578. public:
  21579. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21580. bool is_readable() const override { return true; }
  21581. bool wait_readable() const override { return true; }
  21582. bool wait_writable() const override { return true; }
  21583. ssize_t read(char *ptr, size_t size) override {
  21584. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21585. *ptr = data_[pos_++];
  21586. return 1;
  21587. }
  21588. ssize_t write(const char *, size_t size) override {
  21589. return static_cast<ssize_t>(size);
  21590. }
  21591. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21592. ip = "127.0.0.1";
  21593. port = 0;
  21594. }
  21595. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21596. ip = "127.0.0.1";
  21597. port = 0;
  21598. }
  21599. socket_t socket() const override { return INVALID_SOCKET; }
  21600. time_t duration() const override { return 0; }
  21601. private:
  21602. std::string data_;
  21603. size_t pos_ = 0;
  21604. };
  21605. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21606. // The payload uses the 16-bit extended length, so the header, the length
  21607. // and the mask key are all multi-byte fields here. Each used to be read
  21608. // with a single read() call, which fails as soon as one is split. The
  21609. // payload is also a little over one read chunk, so it is read in two.
  21610. std::string body;
  21611. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21612. body += static_cast<char>(i % 251);
  21613. }
  21614. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21615. std::string frame;
  21616. frame += static_cast<char>(0x81); // FIN + Text
  21617. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21618. frame += static_cast<char>(body.size() >> 8);
  21619. frame += static_cast<char>(body.size() & 0xff);
  21620. for (size_t i = 0; i < 4; i++) {
  21621. frame += static_cast<char>(mask[i]);
  21622. }
  21623. for (size_t i = 0; i < body.size(); i++) {
  21624. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21625. }
  21626. WsByteAtATimeStream strm(frame);
  21627. ws::Opcode opcode;
  21628. std::string payload;
  21629. bool fin = false;
  21630. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21631. /*expect_masked=*/true, body.size()),
  21632. ws::impl::FrameRead::Ok);
  21633. EXPECT_TRUE(fin);
  21634. EXPECT_EQ(opcode, ws::Opcode::Text);
  21635. EXPECT_EQ(payload, body);
  21636. }
  21637. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  21638. std::string body(2000, 'x');
  21639. std::string frame;
  21640. frame += static_cast<char>(0x82); // FIN + Binary
  21641. frame += static_cast<char>(126); // 16-bit length follows
  21642. frame += static_cast<char>(body.size() >> 8);
  21643. frame += static_cast<char>(body.size() & 0xff);
  21644. frame += body;
  21645. detail::BufferStream strm;
  21646. strm.write(frame.data(), frame.size());
  21647. ws::Opcode opcode;
  21648. std::string payload;
  21649. bool fin;
  21650. EXPECT_EQ(
  21651. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  21652. ws::impl::FrameRead::Ok);
  21653. EXPECT_EQ(body, payload);
  21654. }
  21655. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21656. // The header announces the largest payload allowed, and only 3 bytes of it
  21657. // ever arrive.
  21658. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21659. std::string frame;
  21660. frame += static_cast<char>(0x82); // FIN + Binary
  21661. frame += static_cast<char>(127); // 64-bit length follows
  21662. for (int shift = 56; shift >= 0; shift -= 8) {
  21663. frame += static_cast<char>((len >> shift) & 0xff);
  21664. }
  21665. frame += "abc";
  21666. detail::BufferStream strm;
  21667. strm.write(frame.data(), frame.size());
  21668. ws::Opcode opcode;
  21669. std::string payload;
  21670. bool fin;
  21671. EXPECT_EQ(
  21672. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21673. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21674. ws::impl::FrameRead::Fail);
  21675. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21676. }
  21677. TEST(WebSocketTest, QueryStringInHandshake) {
  21678. Server svr;
  21679. std::mutex mtx;
  21680. std::string received_target;
  21681. std::string received_token;
  21682. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21683. {
  21684. std::lock_guard<std::mutex> lock(mtx);
  21685. received_target = req.target;
  21686. if (req.has_param("token")) {
  21687. received_token = req.get_param_value("token");
  21688. }
  21689. }
  21690. std::string msg;
  21691. while (ws.read(msg)) {
  21692. ws.send(msg);
  21693. }
  21694. });
  21695. auto port = svr.bind_to_any_port("localhost");
  21696. std::thread t([&]() { svr.listen_after_bind(); });
  21697. svr.wait_until_ready();
  21698. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21699. "/ws?token=ABC&session=123");
  21700. ASSERT_TRUE(client.connect());
  21701. // Round-trip ensures the handler has run and captured the request.
  21702. ASSERT_TRUE(client.send("hello"));
  21703. std::string msg;
  21704. ASSERT_TRUE(client.read(msg));
  21705. EXPECT_EQ("hello", msg);
  21706. client.close();
  21707. {
  21708. std::lock_guard<std::mutex> lock(mtx);
  21709. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21710. EXPECT_EQ("ABC", received_token);
  21711. }
  21712. svr.stop();
  21713. t.join();
  21714. }
  21715. // Run a handshake against a throwaway server and hand the request the server
  21716. // received back to the caller, so tests can assert on the headers the client
  21717. // actually put on the wire.
  21718. static void capture_websocket_handshake_request(
  21719. const Headers &client_headers,
  21720. std::function<void(const Request &, int port)> verify) {
  21721. Server svr;
  21722. std::mutex mtx;
  21723. Request received;
  21724. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21725. {
  21726. std::lock_guard<std::mutex> lock(mtx);
  21727. received = req;
  21728. }
  21729. std::string msg;
  21730. while (ws.read(msg)) {
  21731. ws.send(msg);
  21732. }
  21733. });
  21734. auto port = svr.bind_to_any_port("localhost");
  21735. std::thread t([&]() { svr.listen_after_bind(); });
  21736. auto se = detail::scope_exit([&] {
  21737. svr.stop();
  21738. t.join();
  21739. });
  21740. svr.wait_until_ready();
  21741. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21742. client_headers);
  21743. ASSERT_TRUE(client.connect());
  21744. ASSERT_TRUE(client.send("hello"));
  21745. std::string msg;
  21746. ASSERT_TRUE(client.read(msg));
  21747. client.close();
  21748. {
  21749. std::lock_guard<std::mutex> lock(mtx);
  21750. verify(received, port);
  21751. }
  21752. }
  21753. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21754. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21755. // Non-default port must be present in the Host header. Default ports
  21756. // (80/443) are omitted; that logic is covered by
  21757. // MakeHostAndPortStringTest.
  21758. EXPECT_EQ("localhost:" + std::to_string(port),
  21759. req.get_header_value("Host"));
  21760. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21761. req.get_header_value("User-Agent"));
  21762. EXPECT_FALSE(req.has_header("Accept"));
  21763. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21764. EXPECT_FALSE(req.has_header("Content-Length"));
  21765. });
  21766. }
  21767. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21768. capture_websocket_handshake_request(
  21769. {{"Host", "example.com"},
  21770. {"User-Agent", "custom-agent"},
  21771. {"X-Custom", "value"}},
  21772. [](const Request &req, int) {
  21773. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21774. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21775. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21776. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21777. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21778. });
  21779. }
  21780. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21781. capture_websocket_handshake_request(
  21782. {{"Upgrade", "bogus"},
  21783. {"Connection", "close"},
  21784. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21785. {"Sec-WebSocket-Version", "8"}},
  21786. [](const Request &req, int) {
  21787. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21788. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21789. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21790. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21791. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21792. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21793. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21794. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21795. req.get_header_value("Sec-WebSocket-Key"));
  21796. });
  21797. }
  21798. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21799. // A header the client refuses to send must abort the handshake before any
  21800. // part of it reaches the wire; a lone request line would otherwise sit in
  21801. // the peer's buffer as a truncated request.
  21802. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21803. ASSERT_NE(INVALID_SOCKET, srv);
  21804. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21805. sockaddr_in addr{};
  21806. addr.sin_family = AF_INET;
  21807. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21808. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21809. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21810. ASSERT_EQ(0, ::listen(srv, 1));
  21811. sockaddr_in bound{};
  21812. socklen_t bound_len = sizeof(bound);
  21813. ASSERT_EQ(
  21814. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21815. auto port = ntohs(bound.sin_port);
  21816. ssize_t received = -1;
  21817. std::thread t([&] {
  21818. // Bound every blocking call so a regression fails the test with a bad
  21819. // value instead of hanging the suite.
  21820. fd_set rfds;
  21821. FD_ZERO(&rfds);
  21822. FD_SET(srv, &rfds);
  21823. timeval tv{5, 0};
  21824. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21825. 0) {
  21826. return;
  21827. }
  21828. sockaddr_in cli_addr{};
  21829. socklen_t cli_len = sizeof(cli_addr);
  21830. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21831. if (cli == INVALID_SOCKET) { return; }
  21832. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21833. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21834. char buf[4096];
  21835. received = ::recv(cli, buf, sizeof(buf), 0);
  21836. });
  21837. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21838. // connect() has already shut the socket down by the time it returns false,
  21839. // so the peer sees EOF without waiting for the client to be destroyed.
  21840. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21841. {{"X-Bad", "a\r\nInjected: 1"}});
  21842. EXPECT_FALSE(client.connect());
  21843. t.join();
  21844. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21845. EXPECT_EQ(0, received);
  21846. }
  21847. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21848. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21849. // contains "upgrade" as a substring is a different token and must not
  21850. // start a WebSocket handshake.
  21851. auto make_request = [](const std::vector<std::string> &connection_values) {
  21852. Request req;
  21853. req.method = "GET";
  21854. req.headers.emplace("Upgrade", "websocket");
  21855. for (const auto &value : connection_values) {
  21856. req.headers.emplace("Connection", value);
  21857. }
  21858. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21859. req.headers.emplace("Sec-WebSocket-Version", "13");
  21860. return req;
  21861. };
  21862. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21863. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21864. EXPECT_TRUE(
  21865. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21866. EXPECT_TRUE(
  21867. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21868. EXPECT_TRUE(
  21869. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21870. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21871. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21872. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21873. EXPECT_FALSE(
  21874. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21875. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21876. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21877. }
  21878. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21879. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21880. // asks recipients to match each protocol-name case-insensitively, and RFC
  21881. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21882. // client naming websocket alongside another protocol, or on a second field
  21883. // line, is offering websocket; a value that merely contains "websocket" as a
  21884. // substring is a different protocol name and is not.
  21885. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21886. Request req;
  21887. req.method = "GET";
  21888. for (const auto &value : upgrade_values) {
  21889. req.headers.emplace("Upgrade", value);
  21890. }
  21891. req.headers.emplace("Connection", "Upgrade");
  21892. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21893. req.headers.emplace("Sec-WebSocket-Version", "13");
  21894. return req;
  21895. };
  21896. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21897. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21898. EXPECT_TRUE(
  21899. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21900. EXPECT_TRUE(
  21901. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21902. EXPECT_TRUE(
  21903. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21904. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21905. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21906. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21907. EXPECT_FALSE(
  21908. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21909. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21910. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21911. }
  21912. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21913. Server svr;
  21914. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21915. auto port = svr.bind_to_any_port("localhost");
  21916. std::thread t([&]() { svr.listen_after_bind(); });
  21917. auto se = detail::scope_exit([&] {
  21918. svr.stop();
  21919. t.join();
  21920. });
  21921. svr.wait_until_ready();
  21922. Headers headers = {{"Upgrade", "websocket"},
  21923. {"Connection", "notupgrade"},
  21924. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21925. {"Sec-WebSocket-Version", "13"}};
  21926. Client cli("localhost", port);
  21927. auto res = cli.Get("/ws", headers);
  21928. // The route exists only as a WebSocket route, so a request that fails the
  21929. // handshake check falls through to ordinary routing.
  21930. ASSERT_TRUE(res);
  21931. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21932. }
  21933. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21934. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21935. // Connection value is the only thing left for the client to reject.
  21936. Server svr;
  21937. svr.Get("/ws", [](const Request &req, Response &res) {
  21938. res.status = StatusCode::SwitchingProtocol_101;
  21939. res.set_header("Upgrade", "websocket");
  21940. res.set_header("Connection", "notupgrade");
  21941. res.set_header("Sec-WebSocket-Accept",
  21942. detail::websocket_accept_key(
  21943. req.get_header_value("Sec-WebSocket-Key")));
  21944. });
  21945. auto port = svr.bind_to_any_port("localhost");
  21946. std::thread t([&]() { svr.listen_after_bind(); });
  21947. auto se = detail::scope_exit([&] {
  21948. svr.stop();
  21949. t.join();
  21950. });
  21951. svr.wait_until_ready();
  21952. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21953. auto res = client.connect();
  21954. EXPECT_FALSE(res);
  21955. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21956. EXPECT_FALSE(client.is_open());
  21957. }
  21958. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21959. Server svr;
  21960. svr.Get("/ws", [](const Request &req, Response &res) {
  21961. res.status = StatusCode::SwitchingProtocol_101;
  21962. res.set_header("Upgrade", "websocket");
  21963. res.set_header("Connection", "Upgrade");
  21964. res.set_header("Sec-WebSocket-Accept",
  21965. detail::websocket_accept_key(
  21966. req.get_header_value("Sec-WebSocket-Key")));
  21967. res.set_header("Sec-WebSocket-Protocol", "admin");
  21968. });
  21969. auto port = svr.bind_to_any_port("localhost");
  21970. std::thread t([&]() { svr.listen_after_bind(); });
  21971. auto se = detail::scope_exit([&] {
  21972. svr.stop();
  21973. t.join();
  21974. });
  21975. svr.wait_until_ready();
  21976. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21977. // Server selects a subprotocol the client never offered
  21978. {
  21979. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21980. ws::WebSocketClient client(url, headers);
  21981. auto res = client.connect();
  21982. EXPECT_FALSE(res);
  21983. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21984. EXPECT_FALSE(client.is_open());
  21985. EXPECT_TRUE(client.subprotocol().empty());
  21986. }
  21987. // Client offered none but the server named one anyway
  21988. {
  21989. ws::WebSocketClient client(url);
  21990. auto res = client.connect();
  21991. EXPECT_FALSE(res);
  21992. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21993. EXPECT_FALSE(client.is_open());
  21994. EXPECT_TRUE(client.subprotocol().empty());
  21995. }
  21996. }
  21997. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21998. // The socket path doubles as the URL host, so it must not contain '/'.
  21999. const char *shard = getenv("GTEST_SHARD_INDEX");
  22000. const std::string sock_path =
  22001. shard ? std::string("httplib-ws-") + shard + ".sock"
  22002. : std::string("httplib-ws.sock");
  22003. std::remove(sock_path.c_str());
  22004. Server svr;
  22005. std::mutex mtx;
  22006. std::string received_host;
  22007. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22008. {
  22009. std::lock_guard<std::mutex> lock(mtx);
  22010. received_host = req.get_header_value("Host");
  22011. }
  22012. std::string msg;
  22013. while (ws.read(msg)) {
  22014. ws.send(msg);
  22015. }
  22016. });
  22017. svr.set_address_family(AF_UNIX);
  22018. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22019. auto se = detail::scope_exit([&] {
  22020. svr.stop();
  22021. t.join();
  22022. std::remove(sock_path.c_str());
  22023. });
  22024. svr.wait_until_ready();
  22025. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22026. client.set_address_family(AF_UNIX);
  22027. ASSERT_TRUE(client.connect());
  22028. ASSERT_TRUE(client.send("hello"));
  22029. std::string msg;
  22030. ASSERT_TRUE(client.read(msg));
  22031. client.close();
  22032. {
  22033. std::lock_guard<std::mutex> lock(mtx);
  22034. // There is no host:port for a Unix socket, so the same "localhost"
  22035. // placeholder the HTTP client uses is expected.
  22036. EXPECT_EQ("localhost", received_host);
  22037. }
  22038. }
  22039. // Two threads must never parse WebSocket frames from the same stream.
  22040. // close() used to read the peer's Close reply with its own frame read, so it
  22041. // raced a reader thread that was in the middle of a payload: the payload loop
  22042. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22043. // so bytes taken by close() were replaced with bytes from further along the
  22044. // stream. The message kept its length and silently changed content.
  22045. //
  22046. // The raw peer below sends a frame header plus part of the payload, waits for
  22047. // the handler to call close(), and only then sends the rest. Whichever thread
  22048. // would win the race for those bytes, the message must arrive intact, because
  22049. // close() must not touch the stream while read() owns it.
  22050. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22051. #ifndef _WIN32
  22052. signal(SIGPIPE, SIG_IGN);
  22053. #endif
  22054. const size_t payload_len = 120; // fits the 7-bit length field
  22055. const size_t prefix_len = 8;
  22056. const int attempts = 8;
  22057. std::string expected(payload_len, '\0');
  22058. for (size_t i = 0; i < payload_len; i++) {
  22059. expected[i] = static_cast<char>('a' + i % 26);
  22060. }
  22061. std::atomic<bool> peer_stalled{false};
  22062. std::atomic<bool> handler_done{false};
  22063. std::mutex received_mutex;
  22064. std::vector<std::string> received;
  22065. // Bound every wait, so a regression fails the test instead of hanging the
  22066. // suite.
  22067. auto wait_for = [](const std::atomic<bool> &flag) {
  22068. for (int i = 0; i < 500 && !flag; i++) {
  22069. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22070. }
  22071. };
  22072. Server svr;
  22073. svr.set_websocket_ping_interval(0);
  22074. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22075. std::thread reader([&]() {
  22076. std::string msg;
  22077. while (ws.read(msg)) {
  22078. std::lock_guard<std::mutex> guard(received_mutex);
  22079. received.push_back(msg);
  22080. }
  22081. });
  22082. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22083. // inside read_websocket_frame() when close() runs.
  22084. wait_for(peer_stalled);
  22085. ws.close();
  22086. reader.join();
  22087. handler_done = true;
  22088. });
  22089. auto port = svr.bind_to_any_port("127.0.0.1");
  22090. std::thread t([&]() { svr.listen_after_bind(); });
  22091. auto se = detail::scope_exit([&] {
  22092. svr.stop();
  22093. t.join();
  22094. });
  22095. svr.wait_until_ready();
  22096. auto send_bytes = [](socket_t s, const std::string &data) {
  22097. #ifdef _WIN32
  22098. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22099. #else
  22100. auto n = ::send(s, data.data(), data.size(), 0);
  22101. #endif
  22102. return n == static_cast<decltype(n)>(data.size());
  22103. };
  22104. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22105. // Every length used here fits the 7-bit length field.
  22106. auto masked_header = [](uint8_t first_byte, size_t len) {
  22107. std::string h;
  22108. h += static_cast<char>(first_byte);
  22109. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22110. h.append(4, '\0'); // mask key
  22111. return h;
  22112. };
  22113. for (int attempt = 0; attempt < attempts; attempt++) {
  22114. peer_stalled = false;
  22115. handler_done = false;
  22116. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22117. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22118. auto se_sock = detail::scope_exit([&] {
  22119. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22120. });
  22121. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22122. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22123. sockaddr_in addr{};
  22124. addr.sin_family = AF_INET;
  22125. addr.sin_port = htons(static_cast<uint16_t>(port));
  22126. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22127. ASSERT_EQ(
  22128. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22129. << "attempt " << attempt;
  22130. ASSERT_TRUE(send_bytes(sock,
  22131. "GET /ws HTTP/1.1\r\n"
  22132. "Host: 127.0.0.1\r\n"
  22133. "Upgrade: websocket\r\n"
  22134. "Connection: Upgrade\r\n"
  22135. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22136. "Sec-WebSocket-Version: 13\r\n"
  22137. "\r\n"))
  22138. << "attempt " << attempt;
  22139. std::string response;
  22140. while (response.find("\r\n\r\n") == std::string::npos) {
  22141. char buf[512];
  22142. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22143. if (n <= 0) { break; }
  22144. response.append(buf, static_cast<size_t>(n));
  22145. }
  22146. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22147. << "attempt " << attempt;
  22148. // Send the header of a Binary message but only the first prefix_len bytes
  22149. // of its payload, leaving the reader thread stalled inside the payload.
  22150. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22151. expected.substr(0, prefix_len)))
  22152. << "attempt " << attempt;
  22153. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22154. peer_stalled = true;
  22155. // Let close() send its Close frame and park in its own read before the
  22156. // rest of the payload arrives, so both threads are waiting for it.
  22157. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22158. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22159. close_frame += static_cast<char>(0x03); // status 1000
  22160. close_frame += static_cast<char>(0xE8);
  22161. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22162. << "attempt " << attempt;
  22163. // Closing the peer releases the reader thread even on the buggy path,
  22164. // where it waits for bytes another thread already consumed.
  22165. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22166. detail::close_socket(sock);
  22167. sock = INVALID_SOCKET;
  22168. wait_for(handler_done);
  22169. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22170. }
  22171. std::lock_guard<std::mutex> guard(received_mutex);
  22172. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22173. << "a message in flight when close() ran was dropped";
  22174. for (size_t i = 0; i < received.size(); i++) {
  22175. EXPECT_EQ(expected, received[i]) << "message " << i;
  22176. }
  22177. }
  22178. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22179. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22180. protected:
  22181. void SetUp() override {
  22182. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22183. SERVER_PRIVATE_KEY_FILE);
  22184. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22185. std::string msg;
  22186. ws::ReadResult ret;
  22187. while ((ret = ws.read(msg))) {
  22188. if (ret == ws::Binary) {
  22189. ws.send(msg.data(), msg.size());
  22190. } else {
  22191. ws.send(msg);
  22192. }
  22193. }
  22194. });
  22195. port_ = server_->bind_to_any_port(HOST);
  22196. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22197. server_->wait_until_ready();
  22198. }
  22199. void TearDown() override {
  22200. server_->stop();
  22201. if (server_thread_.joinable()) { server_thread_.join(); }
  22202. }
  22203. std::unique_ptr<SSLServer> server_;
  22204. std::thread server_thread_;
  22205. int port_ = 0;
  22206. };
  22207. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22208. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22209. "/ws-echo");
  22210. client.enable_server_certificate_verification(false);
  22211. ASSERT_TRUE(client.connect());
  22212. ASSERT_TRUE(client.is_open());
  22213. ASSERT_TRUE(client.send("Hello WSS"));
  22214. std::string msg;
  22215. EXPECT_EQ(ws::Text, client.read(msg));
  22216. EXPECT_EQ("Hello WSS", msg);
  22217. client.close();
  22218. }
  22219. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22220. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22221. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22222. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22223. // client (without calling close() first) is the only path that runs
  22224. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22225. // bug exactly.
  22226. //
  22227. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22228. // when linked against an instrumented libssl; run under Valgrind to catch it
  22229. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22230. // suite (the freed session otherwise stalls on the close handshake) — this test
  22231. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22232. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22233. {
  22234. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22235. "/ws-echo");
  22236. client.enable_server_certificate_verification(false);
  22237. client.set_read_timeout(2, 0);
  22238. client.set_write_timeout(2, 0);
  22239. ASSERT_TRUE(client.connect());
  22240. ASSERT_TRUE(client.is_open());
  22241. ASSERT_TRUE(client.send("still open"));
  22242. // Intentionally do NOT call client.close(): leaving scope runs
  22243. // shutdown_and_close() with the WebSocket still open, which must send the
  22244. // close frame while the TLS session is still alive.
  22245. }
  22246. }
  22247. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22248. // shutdown_and_close() at the start of connect(), reproducing the same
  22249. // use-after-free within the test body rather than at scope exit. The second
  22250. // connect must succeed and echo, proving the close handshake ran over a live
  22251. // session. See the note above about memory-tool requirements.
  22252. TEST_F(WebSocketSSLIntegrationTest,
  22253. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22254. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22255. "/ws-echo");
  22256. client.enable_server_certificate_verification(false);
  22257. client.set_read_timeout(2, 0);
  22258. client.set_write_timeout(2, 0);
  22259. ASSERT_TRUE(client.connect());
  22260. ASSERT_TRUE(client.is_open());
  22261. ASSERT_TRUE(client.send("still open"));
  22262. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22263. // the still-open connection, which must not touch a freed TLS session.
  22264. ASSERT_TRUE(client.connect());
  22265. ASSERT_TRUE(client.is_open());
  22266. ASSERT_TRUE(client.send("after reconnect"));
  22267. std::string msg;
  22268. EXPECT_EQ(ws::Text, client.read(msg));
  22269. EXPECT_EQ("after reconnect", msg);
  22270. client.close();
  22271. }
  22272. #endif
  22273. #ifdef CPPHTTPLIB_SSL_ENABLED
  22274. class WebSocketSSLCATest : public ::testing::Test {
  22275. protected:
  22276. void SetUp() override {
  22277. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22278. SERVER_PRIVATE_KEY_FILE);
  22279. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22280. std::string msg;
  22281. while (ws.read(msg)) {
  22282. ws.send(msg);
  22283. }
  22284. });
  22285. port_ = server_->bind_to_any_port("127.0.0.1");
  22286. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22287. server_->wait_until_ready();
  22288. }
  22289. void TearDown() override {
  22290. server_->stop();
  22291. if (server_thread_.joinable()) { server_thread_.join(); }
  22292. }
  22293. std::string url() const {
  22294. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22295. }
  22296. std::unique_ptr<SSLServer> server_;
  22297. std::thread server_thread_;
  22298. int port_ = 0;
  22299. };
  22300. // A custom CA loaded as PEM verifies the server with full certificate
  22301. // verification enabled
  22302. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22303. ws::WebSocketClient client(url());
  22304. std::string cert;
  22305. read_file(SERVER_CERT2_FILE, cert);
  22306. client.load_ca_cert_store(cert.c_str(), cert.size());
  22307. ASSERT_TRUE(client.connect());
  22308. ASSERT_TRUE(client.send("hello"));
  22309. std::string msg;
  22310. EXPECT_EQ(ws::Text, client.read(msg));
  22311. EXPECT_EQ("hello", msg);
  22312. client.close();
  22313. }
  22314. // A custom CA that does not cover the server must fail verification (the
  22315. // custom CA is exclusive; system certs are not loaded alongside it)
  22316. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22317. ws::WebSocketClient client(url());
  22318. std::string cert;
  22319. read_file(CLIENT_CA_CERT_FILE, cert);
  22320. client.load_ca_cert_store(cert.c_str(), cert.size());
  22321. auto res = client.connect();
  22322. ASSERT_FALSE(res);
  22323. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22324. EXPECT_EQ(-1, res.status());
  22325. EXPECT_NE(0u, res.ssl_backend_error());
  22326. }
  22327. // The same CA as a file path rather than PEM in memory
  22328. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22329. ws::WebSocketClient client(url());
  22330. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22331. ASSERT_TRUE(client.connect());
  22332. ASSERT_TRUE(client.send("hello"));
  22333. std::string msg;
  22334. EXPECT_EQ(ws::Text, client.read(msg));
  22335. EXPECT_EQ("hello", msg);
  22336. client.close();
  22337. }
  22338. // ...and a CA file that does not cover the server still fails, so it is the
  22339. // path above that decides the outcome
  22340. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22341. ws::WebSocketClient client(url());
  22342. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22343. ASSERT_FALSE(client.connect());
  22344. }
  22345. // Regression test: reconnecting with a native custom CA store used to reuse
  22346. // a store handle the previous TLS context had already freed (use-after-free
  22347. // under the OpenSSL backend). The context now lives as long as the client.
  22348. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22349. ws::WebSocketClient client(url());
  22350. std::string cert;
  22351. read_file(SERVER_CERT2_FILE, cert);
  22352. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22353. ASSERT_TRUE(client.connect());
  22354. client.close();
  22355. ASSERT_TRUE(client.connect());
  22356. ASSERT_TRUE(client.send("again"));
  22357. std::string msg;
  22358. EXPECT_EQ(ws::Text, client.read(msg));
  22359. EXPECT_EQ("again", msg);
  22360. client.close();
  22361. }
  22362. // Regression test: a certificate with a trusted chain but no identity match
  22363. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22364. // verification entirely for IP hosts, so this connection succeeded there.
  22365. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22366. // chain verification while the identity check must still fail.
  22367. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22368. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22369. ASSERT_TRUE(svr.is_valid());
  22370. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22371. std::string msg;
  22372. while (ws.read(msg)) {
  22373. ws.send(msg);
  22374. }
  22375. });
  22376. auto port = svr.bind_to_any_port("127.0.0.1");
  22377. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22378. auto se = detail::scope_exit([&] {
  22379. svr.stop();
  22380. t.join();
  22381. });
  22382. svr.wait_until_ready();
  22383. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22384. "/echo");
  22385. std::string cert;
  22386. read_file(SERVER_CERT_FILE, cert);
  22387. client.load_ca_cert_store(cert.c_str(), cert.size());
  22388. ASSERT_FALSE(client.connect());
  22389. }
  22390. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22391. // SNI, so nothing binds the host name to the TLS session. These bind the
  22392. // server to "localhost" instead, the only shape that exercises the SNI and
  22393. // hostname-verification path with certificate verification left enabled.
  22394. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22395. protected:
  22396. void Start(const char *cert_file) {
  22397. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22398. SERVER_PRIVATE_KEY_FILE);
  22399. ASSERT_TRUE(server_->is_valid());
  22400. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22401. std::string msg;
  22402. while (ws.read(msg)) {
  22403. ws.send(msg);
  22404. }
  22405. });
  22406. port_ = server_->bind_to_any_port("localhost");
  22407. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22408. server_->wait_until_ready();
  22409. }
  22410. void TearDown() override {
  22411. if (server_) { server_->stop(); }
  22412. if (server_thread_.joinable()) { server_thread_.join(); }
  22413. }
  22414. std::string url() const {
  22415. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22416. }
  22417. std::unique_ptr<SSLServer> server_;
  22418. std::thread server_thread_;
  22419. int port_ = 0;
  22420. };
  22421. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22422. // out and the connection is usable
  22423. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22424. Start(SERVER_CERT2_FILE);
  22425. ws::WebSocketClient client(url());
  22426. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22427. ASSERT_TRUE(client.connect());
  22428. ASSERT_TRUE(client.send("hello"));
  22429. std::string msg;
  22430. EXPECT_EQ(ws::Text, client.read(msg));
  22431. EXPECT_EQ("hello", msg);
  22432. client.close();
  22433. }
  22434. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22435. // while the identity check must still reject "localhost"
  22436. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22437. Start(SERVER_CERT_FILE);
  22438. ws::WebSocketClient client(url());
  22439. client.set_ca_cert_path(SERVER_CERT_FILE);
  22440. auto res = client.connect();
  22441. ASSERT_FALSE(res);
  22442. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22443. EXPECT_EQ(-1, res.status());
  22444. }
  22445. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22446. // disabled: the chain is still checked, only the identity check is skipped
  22447. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22448. Start(SERVER_CERT_FILE);
  22449. ws::WebSocketClient client(url());
  22450. client.set_ca_cert_path(SERVER_CERT_FILE);
  22451. client.enable_server_hostname_verification(false);
  22452. ASSERT_TRUE(client.connect());
  22453. ASSERT_TRUE(client.send("hello"));
  22454. std::string msg;
  22455. EXPECT_EQ(ws::Text, client.read(msg));
  22456. EXPECT_EQ("hello", msg);
  22457. client.close();
  22458. }
  22459. // A CA that did not sign the server certificate fails the chain, even though
  22460. // the name would match
  22461. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22462. Start(SERVER_CERT2_FILE);
  22463. ws::WebSocketClient client(url());
  22464. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22465. ASSERT_FALSE(client.connect());
  22466. }
  22467. // With verification disabled, neither the chain nor the name is checked
  22468. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22469. Start(SERVER_CERT_FILE);
  22470. ws::WebSocketClient client(url());
  22471. client.enable_server_certificate_verification(false);
  22472. ASSERT_TRUE(client.connect());
  22473. ASSERT_TRUE(client.send("hello"));
  22474. std::string msg;
  22475. EXPECT_EQ(ws::Text, client.read(msg));
  22476. EXPECT_EQ("hello", msg);
  22477. client.close();
  22478. }
  22479. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22480. protected:
  22481. void SetUp() override {
  22482. server_ = httplib::detail::make_unique<SSLServer>(
  22483. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22484. ASSERT_TRUE(server_->is_valid());
  22485. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22486. std::string msg;
  22487. while (ws.read(msg)) {
  22488. ws.send(msg);
  22489. }
  22490. });
  22491. port_ = server_->bind_to_any_port("localhost");
  22492. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22493. server_->wait_until_ready();
  22494. }
  22495. void TearDown() override {
  22496. server_->stop();
  22497. if (server_thread_.joinable()) { server_thread_.join(); }
  22498. }
  22499. std::string url() const {
  22500. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22501. }
  22502. void ConnectWithClientCert(const std::string &client_cert_file,
  22503. const std::string &client_private_key_file,
  22504. const char *private_key_password) {
  22505. std::string cert_pem, key_pem;
  22506. read_file(client_cert_file, cert_pem);
  22507. read_file(client_private_key_file, key_pem);
  22508. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22509. key_pem.c_str(), key_pem.size(),
  22510. private_key_password};
  22511. ws::WebSocketClient client(url(), pem);
  22512. ASSERT_TRUE(client.is_valid());
  22513. client.enable_server_certificate_verification(false);
  22514. ASSERT_TRUE(client.connect());
  22515. ASSERT_TRUE(client.send("hello"));
  22516. std::string msg;
  22517. EXPECT_EQ(ws::Text, client.read(msg));
  22518. EXPECT_EQ("hello", msg);
  22519. client.close();
  22520. }
  22521. std::unique_ptr<SSLServer> server_;
  22522. std::thread server_thread_;
  22523. int port_ = 0;
  22524. };
  22525. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22526. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22527. }
  22528. // Control for the tests above: the fixture's server really does require a
  22529. // client certificate, so it is the PEM the constructor installed that decides
  22530. // the outcome.
  22531. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22532. ws::WebSocketClient client(url());
  22533. ASSERT_TRUE(client.is_valid());
  22534. client.enable_server_certificate_verification(false);
  22535. EXPECT_FALSE(client.connect());
  22536. }
  22537. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22538. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22539. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22540. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22541. }
  22542. #endif
  22543. #if !defined(_WIN32)
  22544. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22545. auto secret_dir = std::string("./symlink_test_secret");
  22546. auto served_dir = std::string("./symlink_test_served");
  22547. auto secret_file = secret_dir + "/secret.txt";
  22548. auto symlink_path = served_dir + "/escape";
  22549. // Setup: create directories and files
  22550. mkdir(secret_dir.c_str(), 0755);
  22551. mkdir(served_dir.c_str(), 0755);
  22552. {
  22553. std::ofstream ofs(secret_file);
  22554. ofs << "SECRET_DATA";
  22555. }
  22556. // Create symlink using absolute path so it resolves correctly
  22557. #ifdef PATH_MAX
  22558. char abs_secret[PATH_MAX];
  22559. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22560. #else
  22561. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22562. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22563. ASSERT_NE(nullptr, abs_secret);
  22564. #endif
  22565. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22566. auto se = detail::scope_exit([&] {
  22567. unlink(symlink_path.c_str());
  22568. unlink(secret_file.c_str());
  22569. rmdir(served_dir.c_str());
  22570. rmdir(secret_dir.c_str());
  22571. });
  22572. Server svr;
  22573. svr.set_mount_point("/", served_dir);
  22574. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22575. auto se2 = detail::scope_exit([&] {
  22576. svr.stop();
  22577. listen_thread.join();
  22578. });
  22579. svr.wait_until_ready();
  22580. Client cli("localhost", PORT);
  22581. // Symlink pointing outside base dir should be blocked
  22582. auto res = cli.Get("/escape/secret.txt");
  22583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22584. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22585. }
  22586. #endif
  22587. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22588. // "GET /smuggled" request), reads the first response, and only then sends the
  22589. // embedded request as the body. Returns how many times /smuggled ran.
  22590. //
  22591. // The body is sent AFTER receiving the first response (as in the original
  22592. // PoC) so that the stream_line_reader cannot buffer it together with the
  22593. // headers of the first request.
  22594. static int count_smuggled_requests(const std::string &outer_head,
  22595. std::string &first_response) {
  22596. Server svr;
  22597. svr.set_mount_point("/", "./www");
  22598. std::atomic<int> smuggled_count(0);
  22599. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22600. smuggled_count++;
  22601. res.set_content("oops", "text/plain");
  22602. });
  22603. svr.Post("/post", [&](const Request &req, Response &res) {
  22604. res.set_content(req.body, "text/plain");
  22605. });
  22606. auto port = svr.bind_to_any_port("localhost");
  22607. thread t = thread([&] { svr.listen_after_bind(); });
  22608. auto se = detail::scope_exit([&] {
  22609. svr.stop();
  22610. t.join();
  22611. });
  22612. svr.wait_until_ready();
  22613. auto error = Error::Success;
  22614. auto sock = detail::create_client_socket(
  22615. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22616. /*connection_timeout_sec=*/2, 0,
  22617. /*read_timeout_sec=*/2, 0,
  22618. /*write_timeout_sec=*/2, 0, std::string(), error);
  22619. EXPECT_NE(INVALID_SOCKET, sock);
  22620. if (sock == INVALID_SOCKET) { return -1; }
  22621. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22622. // The "smuggled" request will be sent as the body of the outer request
  22623. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22624. "Host: localhost\r\n"
  22625. "Connection: close\r\n"
  22626. "\r\n";
  22627. auto head = outer_head;
  22628. auto len = std::to_string(smuggled.size());
  22629. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22630. pos = head.find("{len}", pos + len.size())) {
  22631. head.replace(pos, 5, len);
  22632. }
  22633. // Step 1: Send only the outer request headers (no body yet)
  22634. auto sent = send(sock, head.data(), head.size(), 0);
  22635. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22636. // Step 2: Read the first response
  22637. char buf[4096];
  22638. for (;;) {
  22639. auto n = recv(sock, buf, sizeof(buf), 0);
  22640. if (n <= 0) break;
  22641. first_response.append(buf, static_cast<size_t>(n));
  22642. // Stop once we have a complete response (headers + body)
  22643. auto hdr_end = first_response.find("\r\n\r\n");
  22644. if (hdr_end != std::string::npos) {
  22645. // Check for Content-Length to know when the body is complete
  22646. auto cl_pos = first_response.find("Content-Length:");
  22647. if (cl_pos != std::string::npos) {
  22648. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22649. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22650. auto cl = std::stoul(
  22651. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22652. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22653. } else {
  22654. break; // No Content-Length, assume headers-only response
  22655. }
  22656. }
  22657. }
  22658. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22659. // vulnerable server the keep-alive loop reads this as a second request. The
  22660. // server may already have closed the connection, so the result is ignored.
  22661. send(sock, smuggled.data(), smuggled.size(), 0);
  22662. // Half-close so that a server which drained the body sees EOF and closes,
  22663. // instead of the read below waiting for the read timeout.
  22664. #ifdef _WIN32
  22665. ::shutdown(sock, SD_SEND);
  22666. #else
  22667. ::shutdown(sock, SHUT_WR);
  22668. #endif
  22669. // Step 4: Read until the server closes the connection
  22670. for (;;) {
  22671. auto n = recv(sock, buf, sizeof(buf), 0);
  22672. if (n <= 0) break;
  22673. }
  22674. return smuggled_count.load();
  22675. }
  22676. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22677. // A GET request with Content-Length to a static file handler must have its
  22678. // body drained before the keep-alive connection is reused. Otherwise the
  22679. // unread body bytes are interpreted as the next HTTP request.
  22680. std::string first_response;
  22681. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22682. "Host: localhost\r\n"
  22683. "Content-Length: {len}\r\n"
  22684. "\r\n",
  22685. first_response));
  22686. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22687. }
  22688. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22689. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22690. // be answered with 400 and the connection closed. Treating it as "no body"
  22691. // leaves the body to be parsed as the next request.
  22692. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22693. const char *targets[] = {
  22694. "GET /file", // handler that never reads the body
  22695. "GET /not-found", // no handler matches (404)
  22696. "POST /post", // handler that reads the body
  22697. };
  22698. for (auto target : targets) {
  22699. for (auto value : values) {
  22700. std::string first_response;
  22701. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22702. " HTTP/1.1\r\n"
  22703. "Host: localhost\r\n"
  22704. "Content-Length: " +
  22705. value + "\r\n\r\n",
  22706. first_response))
  22707. << target << " with Content-Length: " << value;
  22708. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22709. << target << " with Content-Length: " << value;
  22710. }
  22711. }
  22712. }
  22713. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22714. // A 400 for an unparseable request line leaves the rest of the message
  22715. // unread, so the connection must be closed rather than reused.
  22716. std::string first_response;
  22717. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22718. "Host: localhost\r\n"
  22719. "Content-Length: {len}\r\n"
  22720. "\r\n",
  22721. first_response));
  22722. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22723. }
  22724. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22725. // Same as above for a header block that fails to parse.
  22726. std::string first_response;
  22727. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22728. "Host: localhost\r\n"
  22729. "Bad Header\r\n"
  22730. "Content-Length: {len}\r\n"
  22731. "\r\n",
  22732. first_response));
  22733. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22734. }
  22735. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22736. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22737. // server must not read another request on that connection, even when the
  22738. // request had no body to drain.
  22739. std::string first_response;
  22740. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22741. "Host: localhost\r\n"
  22742. "\r\n",
  22743. first_response));
  22744. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22745. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22746. }
  22747. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22748. // A content reader that stops early leaves the stream inside the body.
  22749. // Draining the whole Content-Length from there, or reading the body again,
  22750. // reads into the next request, and whatever follows is parsed as a request
  22751. // of its own.
  22752. Server svr;
  22753. std::atomic<int> smuggled_count(0);
  22754. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22755. svr.Post("/upload", [](const Request &req, Response &res,
  22756. const ContentReader &content_reader) {
  22757. // Stop at the last chunk, so the whole body has been read however it
  22758. // arrives.
  22759. auto length = req.get_header_value_u64("Content-Length");
  22760. size_t total = 0;
  22761. auto consumed = content_reader([&](const char *, size_t n) {
  22762. total += n;
  22763. return total < length;
  22764. });
  22765. EXPECT_FALSE(consumed);
  22766. if (req.has_param("retry")) {
  22767. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22768. }
  22769. // Replace the 400 the aborted read set, which would close the connection.
  22770. res.set_redirect("/done");
  22771. });
  22772. auto port = svr.bind_to_any_port(HOST);
  22773. thread t = thread([&] { svr.listen_after_bind(); });
  22774. auto se = detail::scope_exit([&] {
  22775. svr.stop();
  22776. t.join();
  22777. });
  22778. svr.wait_until_ready();
  22779. // A front end sees the second request as a POST whose body is the GET. The
  22780. // first body is as long as the POST's headers, so draining it again reads
  22781. // exactly those and leaves the GET to be parsed next.
  22782. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22783. "Host: localhost\r\n"
  22784. "\r\n";
  22785. std::string second_head = "POST /post HTTP/1.1\r\n"
  22786. "Host: localhost\r\n"
  22787. "Content-Length: " +
  22788. std::to_string(inner.size()) +
  22789. "\r\n"
  22790. "\r\n";
  22791. for (auto target : {"/upload", "/upload?retry"}) {
  22792. smuggled_count = 0;
  22793. std::string request = "POST " + std::string(target) +
  22794. " HTTP/1.1\r\n"
  22795. "Host: localhost\r\n"
  22796. "Content-Length: " +
  22797. std::to_string(second_head.size()) +
  22798. "\r\n"
  22799. "\r\n" +
  22800. std::string(second_head.size(), 'A') + second_head +
  22801. inner;
  22802. std::string response;
  22803. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22804. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22805. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22806. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22807. EXPECT_EQ(0, smuggled_count.load()) << target;
  22808. }
  22809. }
  22810. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22811. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22812. // must be rejected with 400 Bad Request.
  22813. Server svr;
  22814. svr.Post("/test", [&](const Request &, Response &res) {
  22815. res.set_content("ok", "text/plain");
  22816. });
  22817. thread t = thread([&] { svr.listen(HOST, PORT); });
  22818. auto se = detail::scope_exit([&] {
  22819. svr.stop();
  22820. t.join();
  22821. ASSERT_FALSE(svr.is_running());
  22822. });
  22823. svr.wait_until_ready();
  22824. // Exact "chunked"
  22825. {
  22826. auto req = "POST /test HTTP/1.1\r\n"
  22827. "Host: localhost\r\n"
  22828. "Content-Length: 5\r\n"
  22829. "Transfer-Encoding: chunked\r\n"
  22830. "Connection: close\r\n"
  22831. "\r\n"
  22832. "hello";
  22833. std::string response;
  22834. ASSERT_TRUE(send_request(1, req, &response));
  22835. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22836. response.substr(0, response.find("\r\n")));
  22837. }
  22838. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22839. {
  22840. auto req = "POST /test HTTP/1.1\r\n"
  22841. "Host: localhost\r\n"
  22842. "Content-Length: 5\r\n"
  22843. "Transfer-Encoding: gzip, chunked\r\n"
  22844. "Connection: close\r\n"
  22845. "\r\n"
  22846. "hello";
  22847. std::string response;
  22848. ASSERT_TRUE(send_request(1, req, &response));
  22849. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22850. response.substr(0, response.find("\r\n")));
  22851. }
  22852. }
  22853. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22854. Server svr;
  22855. svr.Post("/test", [&](const Request &, Response &res) {
  22856. res.set_content("ok", "text/plain");
  22857. });
  22858. thread t = thread([&] { svr.listen(HOST, PORT); });
  22859. auto se = detail::scope_exit([&] {
  22860. svr.stop();
  22861. t.join();
  22862. ASSERT_FALSE(svr.is_running());
  22863. });
  22864. svr.wait_until_ready();
  22865. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22866. // length cannot be determined, so the server must answer 400 and close
  22867. // rather than treat the request as bodyless and leave the body in the
  22868. // socket for the next request to pick up.
  22869. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22870. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22871. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22872. std::string response;
  22873. ASSERT_TRUE(send_request(1, req, &response));
  22874. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22875. response.substr(0, response.find("\r\n")))
  22876. << transfer_encoding;
  22877. }
  22878. // RFC 9110 5.3: the codings may also be split across several
  22879. // Transfer-Encoding lines, which combine in the order they were received.
  22880. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22881. // just like the single-line "chunked, gzip" above.
  22882. {
  22883. auto req = "POST /test HTTP/1.1\r\n"
  22884. "Host: localhost\r\n"
  22885. "Transfer-Encoding: chunked\r\n"
  22886. "Transfer-Encoding: gzip\r\n"
  22887. "\r\n"
  22888. "0\r\n\r\n";
  22889. std::string response;
  22890. ASSERT_TRUE(send_request(1, req, &response));
  22891. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22892. response.substr(0, response.find("\r\n")));
  22893. }
  22894. // A sequence ending in chunked stays valid.
  22895. auto req = "POST /test HTTP/1.1\r\n"
  22896. "Host: localhost\r\n"
  22897. "Transfer-Encoding: gzip, chunked\r\n"
  22898. "Connection: close\r\n"
  22899. "\r\n"
  22900. "0\r\n\r\n";
  22901. std::string response;
  22902. ASSERT_TRUE(send_request(1, req, &response));
  22903. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22904. // ...including when it is spread over several lines.
  22905. auto split_req = "POST /test HTTP/1.1\r\n"
  22906. "Host: localhost\r\n"
  22907. "Transfer-Encoding: gzip\r\n"
  22908. "Transfer-Encoding: chunked\r\n"
  22909. "Connection: close\r\n"
  22910. "\r\n"
  22911. "0\r\n\r\n";
  22912. std::string split_response;
  22913. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22914. EXPECT_EQ("HTTP/1.1 200 OK",
  22915. split_response.substr(0, split_response.find("\r\n")));
  22916. }
  22917. // Regression for issue #2450: a DELETE without Content-Length on a
  22918. // keep-alive connection must not let the post-response drain consume the
  22919. // next request's bytes.
  22920. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22921. Server svr;
  22922. std::atomic<int> delete_count(0);
  22923. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22924. delete_count++;
  22925. res.status = StatusCode::NoContent_204;
  22926. });
  22927. auto port = svr.bind_to_any_port(HOST);
  22928. thread t = thread([&] { svr.listen_after_bind(); });
  22929. auto se = detail::scope_exit([&] {
  22930. svr.stop();
  22931. t.join();
  22932. });
  22933. svr.wait_until_ready();
  22934. auto error = Error::Success;
  22935. auto sock = detail::create_client_socket(
  22936. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22937. /*connection_timeout_sec=*/2, 0,
  22938. /*read_timeout_sec=*/2, 0,
  22939. /*write_timeout_sec=*/2, 0, std::string(), error);
  22940. ASSERT_NE(INVALID_SOCKET, sock);
  22941. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22942. auto send_request_and_read_response = [&](const std::string &req,
  22943. std::string &out) -> bool {
  22944. auto sent = send(sock, req.data(), req.size(), 0);
  22945. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22946. char buf[4096];
  22947. for (;;) {
  22948. auto n = recv(sock, buf, sizeof(buf), 0);
  22949. if (n <= 0) { return !out.empty(); }
  22950. out.append(buf, static_cast<size_t>(n));
  22951. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22952. }
  22953. };
  22954. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22955. "Host: localhost\r\n"
  22956. "\r\n";
  22957. std::string resp1;
  22958. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22959. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22960. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22961. "Host: localhost\r\n"
  22962. "Connection: close\r\n"
  22963. "\r\n";
  22964. std::string resp2;
  22965. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22966. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22967. EXPECT_EQ(2, delete_count.load());
  22968. }
  22969. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22970. Server svr;
  22971. svr.Post("/ingest", [&](const Request &, Response &res,
  22972. const ContentReader &content_reader) {
  22973. auto consumed = content_reader([](const char *, size_t) { return false; });
  22974. EXPECT_FALSE(consumed);
  22975. res.status = StatusCode::Conflict_409;
  22976. res.set_header("Connection", "close");
  22977. });
  22978. auto port = svr.bind_to_any_port(HOST);
  22979. thread t = thread([&] { svr.listen_after_bind(); });
  22980. auto se = detail::scope_exit([&] {
  22981. svr.stop();
  22982. t.join();
  22983. });
  22984. svr.wait_until_ready();
  22985. auto error = Error::Success;
  22986. auto sock = detail::create_client_socket(
  22987. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22988. /*connection_timeout_sec=*/2, 0,
  22989. /*read_timeout_sec=*/1, 0,
  22990. /*write_timeout_sec=*/2, 0, std::string(), error);
  22991. ASSERT_NE(INVALID_SOCKET, sock);
  22992. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22993. std::string request = "POST /ingest HTTP/1.1\r\n"
  22994. "Host: localhost\r\n"
  22995. "Transfer-Encoding: chunked\r\n"
  22996. "\r\n"
  22997. "4\r\n"
  22998. "data\r\n";
  22999. auto sent = send(sock, request.data(), request.size(), 0);
  23000. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23001. std::string response;
  23002. ssize_t received = 0;
  23003. do {
  23004. char buf[4096];
  23005. received = recv(sock, buf, sizeof(buf), 0);
  23006. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23007. } while (received > 0);
  23008. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23009. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23010. EXPECT_EQ(0, received);
  23011. }
  23012. namespace no_proxy_test {
  23013. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23014. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23015. // calling listen().
  23016. class ScopedServer {
  23017. public:
  23018. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23019. ~ScopedServer() {
  23020. svr_.stop();
  23021. if (th_.joinable()) { th_.join(); }
  23022. }
  23023. Server &svr() { return svr_; }
  23024. int port() const { return port_; }
  23025. void listen() {
  23026. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23027. svr_.wait_until_ready();
  23028. }
  23029. private:
  23030. Server svr_;
  23031. std::thread th_;
  23032. int port_ = 0;
  23033. };
  23034. class ProxyAndTargetServers {
  23035. public:
  23036. ProxyAndTargetServers() {
  23037. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23038. proxy_hits_++;
  23039. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23040. res.set_content("via-proxy", "text/plain");
  23041. });
  23042. target_.Get(".*", [this](const Request &req, Response &res) {
  23043. target_hits_++;
  23044. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23045. res.set_content("direct", "text/plain");
  23046. });
  23047. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23048. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23049. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23050. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23051. proxy_mock_.wait_until_ready();
  23052. target_.wait_until_ready();
  23053. }
  23054. ~ProxyAndTargetServers() {
  23055. proxy_mock_.stop();
  23056. target_.stop();
  23057. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23058. if (target_thread_.joinable()) { target_thread_.join(); }
  23059. }
  23060. Server &proxy_mock() { return proxy_mock_; }
  23061. Server &target() { return target_; }
  23062. int proxy_port() const { return proxy_port_; }
  23063. int target_port() const { return target_port_; }
  23064. int proxy_hits() const { return proxy_hits_.load(); }
  23065. int target_hits() const { return target_hits_.load(); }
  23066. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23067. void reset_counters() {
  23068. proxy_hits_ = 0;
  23069. target_hits_ = 0;
  23070. last_had_proxy_authz_ = false;
  23071. }
  23072. private:
  23073. Server proxy_mock_;
  23074. Server target_;
  23075. std::thread proxy_thread_;
  23076. std::thread target_thread_;
  23077. int proxy_port_ = 0;
  23078. int target_port_ = 0;
  23079. std::atomic<int> proxy_hits_{0};
  23080. std::atomic<int> target_hits_{0};
  23081. std::atomic<bool> last_had_proxy_authz_{false};
  23082. };
  23083. inline std::unique_ptr<Client> make_client(const std::string &host,
  23084. ProxyAndTargetServers &s) {
  23085. auto cli = detail::make_unique<Client>(host, s.target_port());
  23086. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23087. cli->set_proxy("127.0.0.1", s.proxy_port());
  23088. return cli;
  23089. }
  23090. } // namespace no_proxy_test
  23091. using no_proxy_test::make_client;
  23092. using no_proxy_test::ProxyAndTargetServers;
  23093. TEST(NoProxyTest, ExactHostnameBypasses) {
  23094. ProxyAndTargetServers s;
  23095. auto cli = make_client("example.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_EQ(0, s.proxy_hits());
  23100. EXPECT_EQ(1, s.target_hits());
  23101. }
  23102. TEST(NoProxyTest, SubdomainBypasses) {
  23103. ProxyAndTargetServers s;
  23104. auto cli = make_client("foo.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, EvilExampleDoesNotMatchExample) {
  23112. // Regression guard: "evilexample.com" must not be considered a subdomain
  23113. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23114. // check would let traffic bypass the proxy and leak credentials direct
  23115. // to the attacker host.
  23116. ProxyAndTargetServers s;
  23117. auto cli = make_client("evilexample.com", s);
  23118. cli->set_no_proxy({"example.com"});
  23119. auto res = cli->Get("/");
  23120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23121. EXPECT_GE(s.proxy_hits(), 1);
  23122. EXPECT_EQ(0, s.target_hits());
  23123. }
  23124. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23125. ProxyAndTargetServers s;
  23126. auto cli = make_client("example.com.evil.com", s);
  23127. cli->set_no_proxy({"example.com"});
  23128. auto res = cli->Get("/");
  23129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23130. EXPECT_GE(s.proxy_hits(), 1);
  23131. EXPECT_EQ(0, s.target_hits());
  23132. }
  23133. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  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, CaseInsensitiveHostname) {
  23143. ProxyAndTargetServers s;
  23144. auto cli = make_client("Example.COM", s);
  23145. cli->set_no_proxy({"EXAMPLE.com"});
  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, TrailingDotIsNormalized) {
  23152. ProxyAndTargetServers s;
  23153. auto cli = make_client("example.com.", s);
  23154. cli->set_no_proxy({"example.com"});
  23155. auto res = cli->Get("/");
  23156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23157. EXPECT_EQ(0, s.proxy_hits());
  23158. EXPECT_EQ(1, s.target_hits());
  23159. }
  23160. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23161. // Trailing dots must be normalized on BOTH sides — host and entry.
  23162. // An implementation that only strips the host-side trailing dot would
  23163. // fail to match host "example.com" against entry "example.com." because
  23164. // a literal substring search would compare 11 chars against 12.
  23165. ProxyAndTargetServers s;
  23166. auto cli = make_client("example.com", s);
  23167. cli->set_no_proxy({"example.com."});
  23168. auto res = cli->Get("/");
  23169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23170. EXPECT_EQ(0, s.proxy_hits());
  23171. EXPECT_EQ(1, s.target_hits());
  23172. }
  23173. TEST(NoProxyTest, WildcardBypassesEverything) {
  23174. ProxyAndTargetServers s;
  23175. auto cli = make_client("anything.invalid.test", s);
  23176. cli->set_no_proxy({"*"});
  23177. auto res = cli->Get("/");
  23178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23179. EXPECT_EQ(0, s.proxy_hits());
  23180. EXPECT_EQ(1, s.target_hits());
  23181. }
  23182. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23183. ProxyAndTargetServers s;
  23184. Client cli("127.0.0.1", s.target_port());
  23185. cli.set_proxy("127.0.0.1", s.proxy_port());
  23186. cli.set_no_proxy({"127.0.0.1"});
  23187. auto res = cli.Get("/");
  23188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23189. EXPECT_EQ(0, s.proxy_hits());
  23190. EXPECT_EQ(1, s.target_hits());
  23191. }
  23192. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23193. ProxyAndTargetServers s;
  23194. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23195. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23196. cli.set_proxy("127.0.0.1", s.proxy_port());
  23197. cli.set_no_proxy({"::1"});
  23198. auto res = cli.Get("/");
  23199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23200. EXPECT_EQ(0, s.proxy_hits());
  23201. EXPECT_EQ(1, s.target_hits());
  23202. }
  23203. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23204. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23205. // must still be recognized as IPv6 for CIDR matching. Implementations
  23206. // that detect IPv6 only when the host begins with '[' would parse the
  23207. // host as a hostname and miss the match.
  23208. ProxyAndTargetServers s;
  23209. Client cli("fe80::1", s.target_port());
  23210. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23211. cli.set_proxy("127.0.0.1", s.proxy_port());
  23212. cli.set_no_proxy({"fe80::/10"});
  23213. auto res = cli.Get("/");
  23214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23215. EXPECT_EQ(0, s.proxy_hits());
  23216. EXPECT_EQ(1, s.target_hits());
  23217. }
  23218. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23219. ProxyAndTargetServers s;
  23220. Client cli("::1", s.target_port());
  23221. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23222. cli.set_proxy("127.0.0.1", s.proxy_port());
  23223. cli.set_no_proxy({"[::1]"});
  23224. auto res = cli.Get("/");
  23225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23226. EXPECT_EQ(0, s.proxy_hits());
  23227. EXPECT_EQ(1, s.target_hits());
  23228. }
  23229. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23230. ProxyAndTargetServers s;
  23231. Client cli("fe80::1", s.target_port());
  23232. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23233. cli.set_proxy("127.0.0.1", s.proxy_port());
  23234. cli.set_no_proxy({"[fe80::]/10"});
  23235. auto res = cli.Get("/");
  23236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23237. EXPECT_EQ(0, s.proxy_hits());
  23238. EXPECT_EQ(1, s.target_hits());
  23239. }
  23240. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23241. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23242. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23243. // tricks via address-family conversion.
  23244. ProxyAndTargetServers s;
  23245. Client cli("::ffff:127.0.0.1", s.target_port());
  23246. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23247. cli.set_proxy("127.0.0.1", s.proxy_port());
  23248. cli.set_no_proxy({"127.0.0.1"});
  23249. auto res = cli.Get("/");
  23250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23251. EXPECT_GE(s.proxy_hits(), 1);
  23252. EXPECT_EQ(0, s.target_hits());
  23253. }
  23254. TEST(NoProxyTest, IPv4CidrMatch) {
  23255. ProxyAndTargetServers s;
  23256. Client cli("127.0.0.1", s.target_port());
  23257. cli.set_proxy("127.0.0.1", s.proxy_port());
  23258. cli.set_no_proxy({"127.0.0.0/8"});
  23259. auto res = cli.Get("/");
  23260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23261. EXPECT_EQ(0, s.proxy_hits());
  23262. EXPECT_EQ(1, s.target_hits());
  23263. }
  23264. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23265. ProxyAndTargetServers s;
  23266. Client cli("127.0.0.1", s.target_port());
  23267. cli.set_proxy("127.0.0.1", s.proxy_port());
  23268. cli.set_no_proxy({"10.0.0.0/8"});
  23269. auto res = cli.Get("/");
  23270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23271. EXPECT_GE(s.proxy_hits(), 1);
  23272. EXPECT_EQ(0, s.target_hits());
  23273. }
  23274. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23275. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23276. // IPv4 target matches.
  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({"0.0.0.0/0"});
  23281. auto res = cli.Get("/");
  23282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23283. EXPECT_EQ(0, s.proxy_hits());
  23284. EXPECT_EQ(1, s.target_hits());
  23285. }
  23286. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23287. ProxyAndTargetServers s;
  23288. Client cli("127.0.0.1", s.target_port());
  23289. cli.set_proxy("127.0.0.1", s.proxy_port());
  23290. cli.set_no_proxy({"127.0.0.1"});
  23291. auto res = cli.Get("/");
  23292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23293. EXPECT_EQ(0, s.proxy_hits());
  23294. EXPECT_EQ(1, s.target_hits());
  23295. }
  23296. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23297. ProxyAndTargetServers s;
  23298. Client cli("127.0.0.1", s.target_port());
  23299. cli.set_proxy("127.0.0.1", s.proxy_port());
  23300. cli.set_no_proxy({"127.0.0.0/33"});
  23301. auto res = cli.Get("/");
  23302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23303. EXPECT_GE(s.proxy_hits(), 1);
  23304. EXPECT_EQ(0, s.target_hits());
  23305. }
  23306. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23307. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23308. ProxyAndTargetServers s;
  23309. Client cli("127.0.0.1", s.target_port());
  23310. cli.set_proxy("127.0.0.1", s.proxy_port());
  23311. cli.set_no_proxy({"127.0.0.1/"});
  23312. auto res = cli.Get("/");
  23313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23314. EXPECT_GE(s.proxy_hits(), 1);
  23315. EXPECT_EQ(0, s.target_hits());
  23316. }
  23317. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23318. ProxyAndTargetServers s;
  23319. auto cli = make_client("internal.corp", s);
  23320. cli->set_proxy_basic_auth("u", "p");
  23321. cli->set_no_proxy({"internal.corp"});
  23322. auto res = cli->Get("/");
  23323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23324. EXPECT_EQ(1, s.target_hits());
  23325. EXPECT_EQ(0, s.proxy_hits());
  23326. EXPECT_FALSE(s.last_had_proxy_authz())
  23327. << "Proxy-Authorization must not be sent direct to the target";
  23328. }
  23329. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23330. ProxyAndTargetServers s;
  23331. auto cli = make_client("public.example", s);
  23332. cli->set_proxy_basic_auth("u", "p");
  23333. cli->set_no_proxy({"internal.corp"}); // does not match
  23334. auto res = cli->Get("/");
  23335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23336. EXPECT_GE(s.proxy_hits(), 1);
  23337. EXPECT_TRUE(s.last_had_proxy_authz());
  23338. }
  23339. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23340. std::atomic<int> hits{0};
  23341. std::atomic<int> hits_with_authz{0};
  23342. no_proxy_test::ScopedServer proxy_mock;
  23343. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23344. hits++;
  23345. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23346. if (req.target.find("/redir") != std::string::npos) {
  23347. res.set_redirect("http://other.example/landed");
  23348. } else {
  23349. res.set_content("via-proxy", "text/plain");
  23350. }
  23351. });
  23352. proxy_mock.listen();
  23353. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23354. hits = 0;
  23355. hits_with_authz = 0;
  23356. Client cli("public.example", 80);
  23357. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23358. cli.set_proxy_basic_auth(c.first, c.second);
  23359. cli.set_follow_location(true);
  23360. // The redirect to another host goes through the proxy as well
  23361. auto res = cli.Get("/redir");
  23362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23363. EXPECT_EQ(2, hits.load());
  23364. EXPECT_EQ(2, hits_with_authz.load());
  23365. }
  23366. }
  23367. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23368. ProxyAndTargetServers s;
  23369. auto cli = make_client("anything.test", s);
  23370. auto res = cli->Get("/");
  23371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23372. EXPECT_GE(s.proxy_hits(), 1);
  23373. EXPECT_EQ(0, s.target_hits());
  23374. }
  23375. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23376. ProxyAndTargetServers s;
  23377. auto cli = make_client("example.com", s);
  23378. cli->set_no_proxy({"example.com:8080"});
  23379. auto res = cli->Get("/");
  23380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23381. EXPECT_GE(s.proxy_hits(), 1);
  23382. EXPECT_EQ(0, s.target_hits());
  23383. }
  23384. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23385. ProxyAndTargetServers s;
  23386. auto cli = make_client("anything.test", s);
  23387. cli->set_no_proxy({"", " ", "\t"});
  23388. auto res = cli->Get("/");
  23389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23390. EXPECT_GE(s.proxy_hits(), 1);
  23391. EXPECT_EQ(0, s.target_hits());
  23392. }
  23393. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23394. // An entry with leading/trailing whitespace must still match — env-style
  23395. // values are commonly pasted with stray spaces and an implementation
  23396. // that feeds the raw token directly to inet_pton would fail to match
  23397. // valid CIDRs because of the spaces.
  23398. ProxyAndTargetServers s;
  23399. Client cli("127.0.0.1", s.target_port());
  23400. cli.set_proxy("127.0.0.1", s.proxy_port());
  23401. cli.set_no_proxy({" 127.0.0.0/8 "});
  23402. auto res = cli.Get("/");
  23403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23404. EXPECT_EQ(0, s.proxy_hits());
  23405. EXPECT_EQ(1, s.target_hits());
  23406. }
  23407. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23408. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23409. // go direct and must NOT carry Proxy-Authorization.
  23410. std::atomic<int> proxy_hits{0};
  23411. std::atomic<int> target_hits{0};
  23412. std::atomic<bool> target_saw_authz{false};
  23413. no_proxy_test::ScopedServer proxy_mock, target;
  23414. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23415. proxy_hits++;
  23416. res.status = 302;
  23417. res.set_header("Location", "http://127.0.0.1:" +
  23418. std::to_string(target.port()) + "/landed");
  23419. });
  23420. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23421. target_hits++;
  23422. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23423. res.set_content("direct", "text/plain");
  23424. });
  23425. proxy_mock.listen();
  23426. target.listen();
  23427. Client cli("public.example", target.port());
  23428. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23429. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23430. cli.set_proxy_basic_auth("u", "p");
  23431. cli.set_no_proxy({"127.0.0.1"});
  23432. cli.set_follow_location(true);
  23433. auto res = cli.Get("/redir");
  23434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23435. EXPECT_GE(proxy_hits.load(), 1);
  23436. EXPECT_GE(target_hits.load(), 1);
  23437. EXPECT_FALSE(target_saw_authz.load());
  23438. }
  23439. #ifdef CPPHTTPLIB_SSL_ENABLED
  23440. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23441. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23442. // proxy creds would be sent to the (possibly hostile) origin.
  23443. std::atomic<int> target_hits{0};
  23444. std::atomic<bool> target_saw_proxy_authz{false};
  23445. no_proxy_test::ScopedServer target;
  23446. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23447. target_hits++;
  23448. if (req.has_header("Proxy-Authorization")) {
  23449. target_saw_proxy_authz = true;
  23450. }
  23451. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23452. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23453. "nonce=\"abc\", algorithm=MD5");
  23454. });
  23455. target.listen();
  23456. // The proxy address is set to the target's port: the bypass MUST kick in;
  23457. // if it doesn't, the test still routes "via proxy" to the same server and
  23458. // the Proxy-Authorization assertion below catches the leak.
  23459. Client cli("evil.example", target.port());
  23460. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23461. cli.set_proxy("127.0.0.1", target.port());
  23462. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23463. cli.set_no_proxy({"evil.example"});
  23464. auto res = cli.Get("/x");
  23465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23466. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23467. EXPECT_EQ(1, target_hits.load());
  23468. EXPECT_FALSE(target_saw_proxy_authz.load());
  23469. }
  23470. #endif
  23471. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23472. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23473. std::atomic<int> proxy_hits{0};
  23474. std::atomic<int> bypass_hits{0};
  23475. std::atomic<bool> proxy_saw_c_url{false};
  23476. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23477. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23478. proxy_hits++;
  23479. if (req.path.find("/start") != std::string::npos) {
  23480. res.status = 302;
  23481. res.set_header("Location", "http://127.0.0.1:" +
  23482. std::to_string(bypass_server.port()) +
  23483. "/middle");
  23484. return;
  23485. }
  23486. if (req.path.find("/end") != std::string::npos) {
  23487. proxy_saw_c_url = true;
  23488. res.set_content("c-via-proxy", "text/plain");
  23489. return;
  23490. }
  23491. res.set_content("unexpected", "text/plain");
  23492. });
  23493. // public.example's "advertised" port is arbitrary (the request never lands
  23494. // there — it goes through the proxy), but use a dynamic value to stay
  23495. // friendly with sharded parallel runs.
  23496. int public_port = bypass_server.port();
  23497. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23498. bypass_hits++;
  23499. res.status = 302;
  23500. res.set_header("Location", "http://public.example:" +
  23501. std::to_string(public_port) + "/end");
  23502. });
  23503. proxy_mock.listen();
  23504. bypass_server.listen();
  23505. Client cli("public.example", public_port);
  23506. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23507. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23508. cli.set_no_proxy({"127.0.0.1"});
  23509. cli.set_follow_location(true);
  23510. auto res = cli.Get("/start");
  23511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23512. EXPECT_EQ(StatusCode::OK_200, res->status);
  23513. EXPECT_EQ("c-via-proxy", res->body);
  23514. EXPECT_GE(proxy_hits.load(), 2);
  23515. EXPECT_GE(bypass_hits.load(), 1);
  23516. EXPECT_TRUE(proxy_saw_c_url.load());
  23517. }
  23518. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23519. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23520. // request reconnects to the correct endpoint.
  23521. std::atomic<int> proxy_hits{0};
  23522. std::atomic<int> target_hits{0};
  23523. no_proxy_test::ScopedServer proxy_mock, target;
  23524. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23525. proxy_hits++;
  23526. res.set_content("via-proxy", "text/plain");
  23527. });
  23528. target.svr().Get(".*", [&](const Request &, Response &res) {
  23529. target_hits++;
  23530. res.set_content("direct", "text/plain");
  23531. });
  23532. proxy_mock.listen();
  23533. target.listen();
  23534. Client cli("public.example", target.port());
  23535. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23536. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23537. cli.set_keep_alive(true);
  23538. auto res1 = cli.Get("/a");
  23539. ASSERT_TRUE(res1);
  23540. EXPECT_EQ("via-proxy", res1->body);
  23541. EXPECT_EQ(1, proxy_hits.load());
  23542. EXPECT_EQ(0, target_hits.load());
  23543. cli.set_no_proxy({"public.example"});
  23544. auto res2 = cli.Get("/b");
  23545. ASSERT_TRUE(res2);
  23546. EXPECT_EQ("direct", res2->body);
  23547. EXPECT_EQ(1, proxy_hits.load());
  23548. EXPECT_EQ(1, target_hits.load());
  23549. }
  23550. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23551. namespace proxy_tunnel_test {
  23552. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23553. class ScopedSSLServer {
  23554. public:
  23555. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23556. port_ = svr_.bind_to_any_port("127.0.0.1");
  23557. }
  23558. ~ScopedSSLServer() {
  23559. svr_.stop();
  23560. if (th_.joinable()) { th_.join(); }
  23561. }
  23562. SSLServer &svr() { return svr_; }
  23563. int port() const { return port_; }
  23564. void listen() {
  23565. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23566. svr_.wait_until_ready();
  23567. }
  23568. private:
  23569. SSLServer svr_;
  23570. std::thread th_;
  23571. int port_ = 0;
  23572. };
  23573. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23574. class ScopedConnectProxy {
  23575. public:
  23576. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23577. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23578. if (listen_fd_ < 0) { return; }
  23579. int yes = 1;
  23580. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23581. sockaddr_in a{};
  23582. a.sin_family = AF_INET;
  23583. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23584. a.sin_port = 0;
  23585. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23586. return;
  23587. }
  23588. socklen_t alen = sizeof(a);
  23589. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23590. 0) {
  23591. return;
  23592. }
  23593. port_ = ntohs(a.sin_port);
  23594. if (::listen(listen_fd_, 1) != 0) { return; }
  23595. th_ = std::thread([this] { run(); });
  23596. }
  23597. ~ScopedConnectProxy() {
  23598. stop_ = true;
  23599. if (listen_fd_ >= 0) {
  23600. ::shutdown(listen_fd_, SHUT_RDWR);
  23601. ::close(listen_fd_);
  23602. }
  23603. if (th_.joinable()) { th_.join(); }
  23604. }
  23605. int port() const { return port_; }
  23606. int connect_hits() const { return connect_hits_.load(); }
  23607. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23608. std::string connect_request() const {
  23609. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23610. return connect_request_;
  23611. }
  23612. private:
  23613. void run() {
  23614. while (!stop_.load()) {
  23615. fd_set rfds;
  23616. FD_ZERO(&rfds);
  23617. FD_SET(listen_fd_, &rfds);
  23618. timeval tv{0, 100 * 1000};
  23619. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23620. if (sel <= 0) { continue; }
  23621. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23622. if (client_fd < 0) { continue; }
  23623. std::string req;
  23624. char buf[2048];
  23625. while (req.find("\r\n\r\n") == std::string::npos) {
  23626. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23627. if (n <= 0) { break; }
  23628. req.append(buf, static_cast<size_t>(n));
  23629. }
  23630. if (req.compare(0, 7, "CONNECT") != 0) {
  23631. ::close(client_fd);
  23632. continue;
  23633. }
  23634. connect_hits_++;
  23635. {
  23636. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23637. connect_request_ = req;
  23638. }
  23639. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23640. ::send(client_fd, ok, std::strlen(ok), 0);
  23641. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23642. sockaddr_in o{};
  23643. o.sin_family = AF_INET;
  23644. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23645. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23646. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23647. 0) {
  23648. ::close(client_fd);
  23649. ::close(origin_fd);
  23650. continue;
  23651. }
  23652. auto forward = [](int from, int to) {
  23653. char b[8192];
  23654. for (;;) {
  23655. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23656. if (n <= 0) { break; }
  23657. ssize_t off = 0;
  23658. while (off < n) {
  23659. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23660. if (s <= 0) {
  23661. off = n;
  23662. break;
  23663. }
  23664. off += s;
  23665. }
  23666. }
  23667. ::shutdown(to, SHUT_WR);
  23668. };
  23669. std::thread t1([&] { forward(client_fd, origin_fd); });
  23670. std::thread t2([&] { forward(origin_fd, client_fd); });
  23671. t1.join();
  23672. t2.join();
  23673. ::close(client_fd);
  23674. ::close(origin_fd);
  23675. }
  23676. }
  23677. int forward_port_ = -1;
  23678. int listen_fd_ = -1;
  23679. int port_ = 0;
  23680. std::thread th_;
  23681. std::atomic<bool> stop_{false};
  23682. std::atomic<int> connect_hits_{0};
  23683. mutable std::mutex connect_request_mutex_;
  23684. std::string connect_request_;
  23685. };
  23686. // Sends one request through the CONNECT proxy to the TLS origin with a
  23687. // credential configured for each hop, and checks that each credential reaches
  23688. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23689. // origin's (every header in origin_headers) on the tunnelled request.
  23690. void CredentialsStayWithTheirHop(
  23691. const std::function<void(SSLClient &)> &set_credentials,
  23692. const std::string &scheme,
  23693. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23694. std::atomic<int> origin_hits{0};
  23695. std::atomic<bool> origin_saw_proxy_authz{false};
  23696. std::atomic<bool> origin_saw_headers{false};
  23697. ScopedSSLServer origin;
  23698. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23699. origin_hits++;
  23700. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23701. origin_saw_headers =
  23702. std::all_of(origin_headers.begin(), origin_headers.end(),
  23703. [&](const std::string &h) { return req.has_header(h); });
  23704. res.set_content("ok", "text/plain");
  23705. });
  23706. origin.listen();
  23707. ScopedConnectProxy proxy(origin.port());
  23708. ASSERT_NE(0, proxy.port());
  23709. // Pinned to 127.0.0.1 for the same reason as the test below.
  23710. SSLClient cli("127.0.0.1", origin.port());
  23711. cli.enable_server_certificate_verification(false);
  23712. cli.set_proxy("127.0.0.1", proxy.port());
  23713. set_credentials(cli);
  23714. auto res = cli.Get("/x");
  23715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23716. EXPECT_EQ(StatusCode::OK_200, res->status);
  23717. EXPECT_EQ(1, origin_hits.load());
  23718. EXPECT_EQ(1, proxy.connect_hits());
  23719. EXPECT_TRUE(origin_saw_headers.load());
  23720. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23721. << "Proxy-Authorization must not be sent inside the tunnel";
  23722. auto connect_req = proxy.connect_request();
  23723. EXPECT_NE(std::string::npos,
  23724. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23725. for (const auto &h : origin_headers) {
  23726. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23727. << h << " must not be sent to the proxy on CONNECT";
  23728. }
  23729. }
  23730. } // namespace proxy_tunnel_test
  23731. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23732. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23733. [](SSLClient &cli) {
  23734. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23735. cli.set_basic_auth("origin-user", "origin-pass");
  23736. },
  23737. "Basic");
  23738. }
  23739. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23740. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23741. [](SSLClient &cli) {
  23742. cli.set_proxy_bearer_token_auth("proxy-token");
  23743. cli.set_bearer_token_auth("origin-token");
  23744. },
  23745. "Bearer");
  23746. }
  23747. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23748. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23749. [](SSLClient &cli) {
  23750. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23751. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23752. {"Cookie", "sid=origin-session"},
  23753. {"X-Api-Key", "origin-key"}});
  23754. },
  23755. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23756. }
  23757. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23758. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23759. // retry; otherwise proxy creds would be sent to the origin.
  23760. std::atomic<int> origin_hits{0};
  23761. std::atomic<bool> origin_saw_proxy_authz{false};
  23762. proxy_tunnel_test::ScopedSSLServer origin;
  23763. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23764. origin_hits++;
  23765. if (req.has_header("Proxy-Authorization")) {
  23766. origin_saw_proxy_authz = true;
  23767. }
  23768. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23769. res.set_header("Proxy-Authenticate",
  23770. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23771. "algorithm=MD5");
  23772. });
  23773. origin.listen();
  23774. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23775. ASSERT_NE(0, proxy.port());
  23776. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23777. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23778. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23779. // and answer with its own status, making this test flaky.
  23780. SSLClient cli("127.0.0.1", origin.port());
  23781. cli.enable_server_certificate_verification(false);
  23782. cli.set_proxy("127.0.0.1", proxy.port());
  23783. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23784. auto res = cli.Get("/x");
  23785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23786. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23787. EXPECT_EQ(1, origin_hits.load());
  23788. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23789. EXPECT_EQ(1, proxy.connect_hits());
  23790. }
  23791. #endif