test.cc 879 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154
  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_PRIVATE_KEY_FILE "./key.pem"
  43. #define CA_CERT_FILE "./ca-bundle.crt"
  44. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  45. #define CLIENT_CA_CERT_DIR "."
  46. #define CLIENT_CERT_FILE "./client.cert.pem"
  47. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  48. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  49. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  50. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  51. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  52. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  53. #else
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  55. #endif
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  57. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  60. #ifdef CPPHTTPLIB_SSL_ENABLED
  61. namespace httplib {
  62. namespace tls {
  63. // Declared here for the split build, where the TLS abstraction declarations
  64. // live below the split border; the definition is linked from httplib.cc.
  65. ca_store_t create_ca_store(const char *pem, size_t len);
  66. } // namespace tls
  67. } // namespace httplib
  68. #endif
  69. using namespace std;
  70. using namespace httplib;
  71. const char *HOST = "localhost";
  72. static int get_base_port() {
  73. const char *shard = getenv("GTEST_SHARD_INDEX");
  74. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  75. }
  76. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  77. // New standalone tests MUST use svr.bind_to_any_port() instead.
  78. const int PORT = get_base_port();
  79. const string LONG_QUERY_VALUE = string(25000, '@');
  80. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  81. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  82. const string TOO_LONG_QUERY_URL =
  83. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  84. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  85. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  86. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  87. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  88. return file.name == key;
  89. });
  90. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  91. return *it;
  92. #else
  93. if (it != items.end()) { return *it; }
  94. throw std::runtime_error("invalid multipart form data name error");
  95. #endif
  96. }
  97. static void read_file(const std::string &path, std::string &out) {
  98. std::ifstream fs(path, std::ios_base::binary);
  99. if (!fs) {
  100. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  101. return;
  102. #else
  103. throw std::runtime_error("File not found: " + path);
  104. #endif
  105. }
  106. fs.seekg(0, std::ios_base::end);
  107. auto size = fs.tellg();
  108. fs.seekg(0);
  109. out.resize(static_cast<size_t>(size));
  110. fs.read(&out[0], static_cast<std::streamsize>(size));
  111. }
  112. class UnixSocketTest : public ::testing::Test {
  113. protected:
  114. void TearDown() override { std::remove(pathname_.c_str()); }
  115. void client_GET(const std::string &addr) {
  116. httplib::Client cli{addr};
  117. cli.set_address_family(AF_UNIX);
  118. ASSERT_TRUE(cli.is_valid());
  119. const auto &result = cli.Get(pattern_);
  120. ASSERT_TRUE(result) << "error: " << result.error();
  121. const auto &resp = result.value();
  122. EXPECT_EQ(resp.status, StatusCode::OK_200);
  123. EXPECT_EQ(resp.body, content_);
  124. }
  125. static std::string make_sock_path() {
  126. const char *shard = getenv("GTEST_SHARD_INDEX");
  127. return shard ? std::string("./httplib-server-") + shard + ".sock"
  128. : "./httplib-server.sock";
  129. }
  130. const std::string pathname_{make_sock_path()};
  131. const std::string pattern_{"/hi"};
  132. const std::string content_{"Hello World!"};
  133. };
  134. TEST_F(UnixSocketTest, pathname) {
  135. httplib::Server svr;
  136. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. });
  139. std::thread t{[&] {
  140. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  141. }};
  142. auto se = detail::scope_exit([&] {
  143. svr.stop();
  144. t.join();
  145. ASSERT_FALSE(svr.is_running());
  146. });
  147. svr.wait_until_ready();
  148. ASSERT_TRUE(svr.is_running());
  149. client_GET(pathname_);
  150. }
  151. #if defined(__linux__) || \
  152. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  153. TEST_F(UnixSocketTest, PeerPid) {
  154. httplib::Server svr;
  155. std::string remote_port_val;
  156. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  157. res.set_content(content_, "text/plain");
  158. remote_port_val = std::to_string(req.remote_port);
  159. });
  160. std::thread t{[&] {
  161. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  162. }};
  163. auto se = detail::scope_exit([&] {
  164. svr.stop();
  165. t.join();
  166. ASSERT_FALSE(svr.is_running());
  167. });
  168. svr.wait_until_ready();
  169. ASSERT_TRUE(svr.is_running());
  170. client_GET(pathname_);
  171. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  172. }
  173. #endif
  174. #ifdef __linux__
  175. TEST_F(UnixSocketTest, abstract) {
  176. constexpr char svr_path[]{"\x00httplib-server.sock"};
  177. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  178. httplib::Server svr;
  179. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  180. res.set_content(content_, "text/plain");
  181. });
  182. std::thread t{[&] {
  183. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  184. }};
  185. auto se = detail::scope_exit([&] {
  186. svr.stop();
  187. t.join();
  188. ASSERT_FALSE(svr.is_running());
  189. });
  190. svr.wait_until_ready();
  191. ASSERT_TRUE(svr.is_running());
  192. client_GET(abstract_addr);
  193. }
  194. #endif
  195. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  196. httplib::Server svr;
  197. std::string received_host_header;
  198. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  199. // Capture the Host header sent by the client
  200. auto host_iter = req.headers.find("Host");
  201. if (host_iter != req.headers.end()) {
  202. received_host_header = host_iter->second;
  203. }
  204. res.set_content(content_, "text/plain");
  205. });
  206. std::thread t{[&] {
  207. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  208. }};
  209. auto se = detail::scope_exit([&] {
  210. svr.stop();
  211. t.join();
  212. ASSERT_FALSE(svr.is_running());
  213. });
  214. svr.wait_until_ready();
  215. ASSERT_TRUE(svr.is_running());
  216. // Test that Host header is automatically set to "localhost" for Unix socket
  217. // connections
  218. httplib::Client cli{pathname_};
  219. cli.set_address_family(AF_UNIX);
  220. ASSERT_TRUE(cli.is_valid());
  221. const auto &result = cli.Get(pattern_);
  222. ASSERT_TRUE(result) << "error: " << result.error();
  223. const auto &resp = result.value();
  224. EXPECT_EQ(resp.status, StatusCode::OK_200);
  225. EXPECT_EQ(resp.body, content_);
  226. // Verify that Host header was automatically set to "localhost"
  227. EXPECT_EQ(received_host_header, "localhost");
  228. }
  229. #ifndef _WIN32
  230. TEST(SocketStream, wait_writable_UNIX) {
  231. int fds[2];
  232. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  233. const auto asSocketStream = [&](socket_t fd,
  234. std::function<bool(Stream &)> func) {
  235. return detail::process_client_socket(
  236. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  237. };
  238. asSocketStream(fds[0], [&](Stream &s0) {
  239. EXPECT_EQ(s0.socket(), fds[0]);
  240. EXPECT_TRUE(s0.wait_writable());
  241. EXPECT_TRUE(s0.is_peer_alive());
  242. EXPECT_EQ(0, close(fds[1]));
  243. EXPECT_FALSE(s0.is_peer_alive());
  244. return true;
  245. });
  246. EXPECT_EQ(0, close(fds[0]));
  247. }
  248. TEST(SocketStream, wait_writable_INET) {
  249. sockaddr_in addr;
  250. memset(&addr, 0, sizeof(addr));
  251. addr.sin_family = AF_INET;
  252. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  253. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  254. int disconnected_svr_sock = -1;
  255. std::thread svr{[&] {
  256. const int s = socket(AF_INET, SOCK_STREAM, 0);
  257. ASSERT_LE(0, s);
  258. // PORT + 1 is shared with the SSL redirect tests and with
  259. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  260. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  261. // because that happens on a worker thread the ASSERT does not stop the
  262. // test: it runs on and fails at the disconnected_svr_sock check instead.
  263. default_socket_options(s);
  264. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  265. ASSERT_EQ(0, listen(s, 1));
  266. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  267. ASSERT_EQ(0, close(s));
  268. }};
  269. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  270. std::thread cli{[&] {
  271. const int s = socket(AF_INET, SOCK_STREAM, 0);
  272. ASSERT_LE(0, s);
  273. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  274. ASSERT_EQ(0, close(s));
  275. }};
  276. cli.join();
  277. svr.join();
  278. ASSERT_NE(disconnected_svr_sock, -1);
  279. const auto asSocketStream = [&](socket_t fd,
  280. std::function<bool(Stream &)> func) {
  281. return detail::process_client_socket(
  282. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  283. };
  284. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  285. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  286. // wait_writable() returns true because select_write() only checks if the
  287. // send buffer has space. Peer disconnection is detected later by send().
  288. EXPECT_TRUE(ss.wait_writable());
  289. return true;
  290. });
  291. ASSERT_EQ(0, close(disconnected_svr_sock));
  292. }
  293. #endif // #ifndef _WIN32
  294. TEST(SetSocketOptTest, TcpNoDelay) {
  295. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  296. ASSERT_NE(sock, INVALID_SOCKET);
  297. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  298. int val = 0;
  299. socklen_t len = sizeof(val);
  300. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  301. reinterpret_cast<char *>(&val), &len));
  302. EXPECT_NE(val, 0);
  303. detail::close_socket(sock);
  304. }
  305. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  306. // accept() reports failures through WSAGetLastError() on Windows and through
  307. // errno everywhere else. Asking the wrong one is what made the accept loop
  308. // treat every recoverable failure as fatal on Windows.
  309. struct Classification {
  310. bool resource;
  311. bool transient;
  312. };
  313. auto classify = [](int err) {
  314. #ifdef _WIN32
  315. WSASetLastError(err);
  316. #else
  317. errno = err;
  318. #endif
  319. // Read both before asserting: an assertion may clobber the error slot.
  320. Classification c;
  321. c.resource = detail::is_accept_resource_error();
  322. c.transient = detail::is_accept_transient_error();
  323. return c;
  324. };
  325. #ifdef _WIN32
  326. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  327. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  328. WSAECONNRESET, WSAECONNABORTED};
  329. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  330. #else
  331. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  332. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  333. ECONNABORTED};
  334. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  335. #endif
  336. for (auto err : resource_errors) {
  337. const auto c = classify(err);
  338. EXPECT_TRUE(c.resource) << "error " << err;
  339. EXPECT_FALSE(c.transient) << "error " << err;
  340. }
  341. for (auto err : transient_errors) {
  342. const auto c = classify(err);
  343. EXPECT_TRUE(c.transient) << "error " << err;
  344. EXPECT_FALSE(c.resource) << "error " << err;
  345. }
  346. for (auto err : fatal_errors) {
  347. const auto c = classify(err);
  348. EXPECT_FALSE(c.resource) << "error " << err;
  349. EXPECT_FALSE(c.transient) << "error " << err;
  350. }
  351. #ifdef _WIN32
  352. WSASetLastError(0);
  353. #else
  354. errno = 0;
  355. #endif
  356. }
  357. TEST(ClientTest, MoveConstructible) {
  358. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  359. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  360. }
  361. TEST(ClientTest, MoveAssignable) {
  362. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  363. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  364. }
  365. #ifdef _WIN32
  366. TEST(StartupTest, WSAStartup) {
  367. WSADATA wsaData;
  368. int ret = WSAStartup(0x0002, &wsaData);
  369. ASSERT_EQ(0, ret);
  370. }
  371. #endif
  372. TEST(DecodePathTest, PercentCharacter) {
  373. EXPECT_EQ(
  374. decode_path_component(
  375. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  376. U8("descrip=Gastos áéíóúñÑ 6"));
  377. }
  378. TEST(DecodePathTest, PercentCharacterNUL) {
  379. string expected;
  380. expected.push_back('x');
  381. expected.push_back('\0');
  382. expected.push_back('x');
  383. EXPECT_EQ(decode_path_component("x%00x"), expected);
  384. }
  385. TEST(DecodePathTest, UnicodeEncoding) {
  386. // %u0041 = 'A' (1-byte UTF-8)
  387. EXPECT_EQ("A", decode_path_component("%u0041"));
  388. // %u00E9 = 'é' (2-byte UTF-8)
  389. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  390. // %u3042 = 'あ' (3-byte UTF-8)
  391. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  392. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  393. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  394. // %uD800 = surrogate (invalid, silently dropped)
  395. EXPECT_EQ("", decode_path_component("%uD800"));
  396. }
  397. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  398. // A sign or whitespace inside the two-character escape window must not be
  399. // accepted as a valid percent-encoding; the sequence is passed through
  400. // literally, matching decode_uri_component / decode_path_component.
  401. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  402. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  403. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  404. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  405. // Well-formed escapes still decode.
  406. EXPECT_EQ("-", decode_query_component("%2D", false));
  407. EXPECT_EQ("A", decode_query_component("%41", false));
  408. }
  409. TEST(SanitizeFilenameTest, VariousPatterns) {
  410. // Path traversal
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  413. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  414. // Normal and edge cases
  415. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  416. EXPECT_EQ("filename.txt",
  417. httplib::sanitize_filename("/path/to/filename.txt"));
  418. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  419. EXPECT_EQ("", httplib::sanitize_filename(".."));
  420. EXPECT_EQ("", httplib::sanitize_filename(""));
  421. // Null bytes stripped
  422. EXPECT_EQ("safe.txt",
  423. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  424. // Whitespace-only rejected
  425. EXPECT_EQ("", httplib::sanitize_filename(" "));
  426. }
  427. // Forward declaration (see the base64_encode note below): split builds move the
  428. // definition into httplib.cc, so re-declaring it here lets the test link.
  429. namespace httplib {
  430. namespace detail {
  431. bool is_chunked_transfer_encoding(const Headers &headers);
  432. } // namespace detail
  433. } // namespace httplib
  434. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  435. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  436. auto make = [](std::initializer_list<const char *> lines) {
  437. Headers h;
  438. for (auto te : lines) {
  439. if (te) { h.emplace("Transfer-Encoding", te); }
  440. }
  441. return h;
  442. };
  443. // Sole coding, matched case-insensitively.
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  447. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  451. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  456. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  457. // were received, into one list. Headers preserves that order, so the answer
  458. // is decided by the last coding of the last line and the order the lines
  459. // arrived in is significant.
  460. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  463. // The split can fall anywhere in the list.
  464. EXPECT_TRUE(
  465. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  466. EXPECT_FALSE(
  467. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  468. // A trailing line naming no coding leaves the list ending in nothing, so it
  469. // must not inherit the chunked from the line before it.
  470. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  471. }
  472. // Forward declaration: in split builds split.py strips `inline` and moves the
  473. // definition into httplib.cc, so detail::base64_encode is not visible from the
  474. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  475. // in both header-only and split builds.
  476. namespace httplib {
  477. namespace detail {
  478. std::string base64_encode(const std::string &in);
  479. } // namespace detail
  480. } // namespace httplib
  481. TEST(Base64EncodeTest, KnownAnswers) {
  482. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  483. // where the accumulator's top bit is already set before the next shift.
  484. EXPECT_EQ("", detail::base64_encode(""));
  485. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  486. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  487. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  488. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  489. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  490. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  491. // High bytes keep the top bit set across several rounds.
  492. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  493. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  494. }
  495. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  496. string unescapedCharacters = "-_.!~*'()";
  497. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  498. }
  499. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  500. string reservedCharacters = ";,/?:@&=+$";
  501. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  502. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  503. }
  504. TEST(ClientQueryOrder, PreserveOrder) {
  505. // This test reproduces Issue #2259: client may reorder query parameters
  506. // when sending a GET request. The expected behavior is that the client
  507. // preserves the original query string order when the caller supplied it
  508. // as part of the path.
  509. Server svr;
  510. svr.Get("/", [&](const Request &req, Response &res) {
  511. // Echo back the raw target so the test can assert ordering
  512. res.set_content(req.target, "text/plain");
  513. });
  514. std::thread t{[&] { svr.listen(HOST, PORT); }};
  515. auto se = detail::scope_exit([&] {
  516. svr.stop();
  517. t.join();
  518. ASSERT_FALSE(svr.is_running());
  519. });
  520. svr.wait_until_ready();
  521. Client cli(HOST, PORT);
  522. ASSERT_TRUE(cli.is_valid());
  523. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  524. auto res = cli.Get(original);
  525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  526. // Expect the echoed target to exactly match the original path (order
  527. // preserved)
  528. EXPECT_EQ(res->body, original);
  529. }
  530. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  531. string chineseCharacters = U8("中国語");
  532. string russianCharacters = U8("дом");
  533. string brazilianCharacters = U8("óculos");
  534. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  535. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  536. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  537. "%D0%B4%D0%BE%D0%BC");
  538. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  539. }
  540. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  541. string unescapedCharacters = "-_.!~*'()";
  542. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  543. }
  544. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  545. string reservedCharacters = ";,/?:@&=+$";
  546. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  547. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  548. }
  549. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  550. string chineseCharacters = U8("中国語");
  551. string russianCharacters = U8("дом");
  552. string brazilianCharacters = U8("óculos");
  553. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  554. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  555. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  556. "%D0%B4%D0%BE%D0%BC");
  557. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  558. }
  559. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  560. // Issue #2082 use case: encoding path component with ampersand
  561. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  562. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  563. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  564. }
  565. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  566. string unescapedCharacters = "-_.!~*'()";
  567. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  568. }
  569. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  570. string reservedCharacters = ";,/?:@&=+$#";
  571. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  572. }
  573. TEST(EncodeUriTest, TestUTF8Characters) {
  574. string chineseCharacters = U8("中国語");
  575. string russianCharacters = U8("дом");
  576. string brazilianCharacters = U8("óculos");
  577. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  578. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  579. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  580. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  581. }
  582. TEST(EncodeUriTest, TestCompleteUri) {
  583. string uri =
  584. "https://example.com/path/to/resource?query=value&param=test#fragment";
  585. EXPECT_EQ(
  586. httplib::encode_uri(uri),
  587. "https://example.com/path/to/resource?query=value&param=test#fragment");
  588. }
  589. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  590. string uri =
  591. "https://example.com/path with spaces/file name.html?q=hello world";
  592. EXPECT_EQ(httplib::encode_uri(uri),
  593. "https://example.com/path%20with%20spaces/"
  594. "file%20name.html?q=hello%20world");
  595. }
  596. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  597. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  598. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  599. }
  600. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  601. string unescapedCharacters = "-_.!~*'()";
  602. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  603. }
  604. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  605. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  606. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  607. string encodedBrazilian = "%C3%B3culos";
  608. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  610. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  611. }
  612. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  613. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  614. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  615. "Piri Tommy Villiers - on & on");
  616. }
  617. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  618. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  619. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  620. }
  621. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  622. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  623. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  624. }
  625. TEST(DecodeUriTest, TestUTF8Characters) {
  626. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  627. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  628. string encodedBrazilian = "%C3%B3culos";
  629. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  630. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  631. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  632. }
  633. TEST(DecodeUriTest, TestCompleteUri) {
  634. string encodedUri = "https://example.com/path%20with%20spaces/"
  635. "file%20name.html?q=hello%20world";
  636. EXPECT_EQ(
  637. httplib::decode_uri(encodedUri),
  638. "https://example.com/path with spaces/file name.html?q=hello world");
  639. }
  640. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  641. string original =
  642. "https://example.com/path with spaces/file name.html?q=hello world";
  643. string encoded = httplib::encode_uri(original);
  644. string decoded = httplib::decode_uri(encoded);
  645. EXPECT_EQ(decoded, original);
  646. }
  647. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  648. // decode_uri is the inverse of encode_uri: an escaped reserved character
  649. // stays encoded so it is not promoted into a real delimiter, while
  650. // non-reserved escapes still decode (like JS decodeURI).
  651. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  652. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  653. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  654. "%3F%3A%40%26%3D%2B%24%2C%3B");
  655. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  656. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  657. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  658. "http://example.com/a%2Fb");
  659. // decode_uri_component still decodes the reserved character.
  660. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  661. }
  662. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  663. string original = "Piri Tommy Villiers - on & on";
  664. string encoded = httplib::encode_uri_component(original);
  665. string decoded = httplib::decode_uri_component(encoded);
  666. EXPECT_EQ(decoded, original);
  667. }
  668. TEST(TrimTests, TrimStringTests) {
  669. EXPECT_EQ("abc", detail::trim_copy("abc"));
  670. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  671. EXPECT_TRUE(detail::trim_copy("").empty());
  672. }
  673. TEST(AsciiTest, LocaleIndependentClassification) {
  674. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  675. // which consult the global C locale: std::isalnum(0xC5) can return true
  676. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  677. // helpers must classify every byte by the ASCII grammar alone.
  678. for (int i = 0; i < 256; i++) {
  679. auto c = static_cast<char>(i);
  680. auto is_digit = i >= '0' && i <= '9';
  681. auto is_upper = i >= 'A' && i <= 'Z';
  682. auto is_lower = i >= 'a' && i <= 'z';
  683. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  684. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  685. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  686. << "byte " << i;
  687. }
  688. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  689. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  690. // Non-ASCII bytes must be percent-encoded, never passed through as
  691. // alphanumeric.
  692. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  693. }
  694. TEST(FromCharsTest, Double) {
  695. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  696. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  697. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  698. auto parse = [](const std::string &s, double &v) {
  699. return detail::from_chars(s.data(), s.data() + s.size(), v);
  700. };
  701. double v = -1.0;
  702. // Representative quality values.
  703. EXPECT_EQ(parse("0", v).ec, std::errc{});
  704. EXPECT_DOUBLE_EQ(v, 0.0);
  705. EXPECT_EQ(parse("1", v).ec, std::errc{});
  706. EXPECT_DOUBLE_EQ(v, 1.0);
  707. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  708. EXPECT_DOUBLE_EQ(v, 0.8);
  709. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  710. EXPECT_DOUBLE_EQ(v, 0.001);
  711. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  712. EXPECT_DOUBLE_EQ(v, 1.0);
  713. // A missing integer or fractional part is tolerated.
  714. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  715. EXPECT_DOUBLE_EQ(v, 0.5);
  716. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  717. EXPECT_DOUBLE_EQ(v, 5.0);
  718. // Values outside [0, 1] still parse; the caller range-checks them.
  719. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  720. EXPECT_DOUBLE_EQ(v, 123.456);
  721. // Stops at the first byte that is not part of the number and reports where.
  722. std::string trailing = "0.9, text/html";
  723. auto r = parse(trailing, v);
  724. EXPECT_EQ(r.ec, std::errc{});
  725. EXPECT_DOUBLE_EQ(v, 0.9);
  726. EXPECT_EQ(*r.ptr, ',');
  727. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  728. // outright, and an 'e'/'E' simply ends the number.
  729. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  730. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  731. std::string exp_input = "1.5e3";
  732. r = parse(exp_input, v);
  733. EXPECT_EQ(r.ec, std::errc{});
  734. EXPECT_DOUBLE_EQ(v, 1.5);
  735. EXPECT_EQ(*r.ptr, 'e');
  736. // Invalid inputs.
  737. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  741. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  742. // Pathological but well-formed inputs must stay bounded (no overflow, no
  743. // out-of-bounds table access) and stay within [0, 1] for the caller.
  744. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  745. std::errc{});
  746. EXPECT_DOUBLE_EQ(v, 0.0);
  747. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  748. std::errc{});
  749. EXPECT_GE(v, 0.0);
  750. EXPECT_LE(v, 1.0);
  751. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  752. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  753. }
  754. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  755. // Simple case without quality values
  756. std::vector<std::string> result1;
  757. EXPECT_TRUE(detail::parse_accept_header(
  758. "text/html,application/json,text/plain", result1));
  759. EXPECT_EQ(result1.size(), 3U);
  760. EXPECT_EQ(result1[0], "text/html");
  761. EXPECT_EQ(result1[1], "application/json");
  762. EXPECT_EQ(result1[2], "text/plain");
  763. // With quality values
  764. std::vector<std::string> result2;
  765. EXPECT_TRUE(detail::parse_accept_header(
  766. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  767. EXPECT_EQ(result2.size(), 3U);
  768. EXPECT_EQ(result2[0], "application/json"); // highest q value
  769. EXPECT_EQ(result2[1], "text/html");
  770. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  771. }
  772. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  773. // Mixed with and without quality values
  774. std::vector<std::string> result;
  775. EXPECT_TRUE(detail::parse_accept_header(
  776. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  777. EXPECT_EQ(result.size(), 3U);
  778. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  779. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  780. EXPECT_EQ(result[2], "application/json"); // q=0.5
  781. }
  782. TEST(ParseAcceptHeaderTest, EdgeCases) {
  783. // Empty header
  784. std::vector<std::string> empty_result;
  785. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  786. EXPECT_TRUE(empty_result.empty());
  787. // Single type
  788. std::vector<std::string> single_result;
  789. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  790. EXPECT_EQ(single_result.size(), 1U);
  791. EXPECT_EQ(single_result[0], "application/json");
  792. // Wildcard types
  793. std::vector<std::string> wildcard_result;
  794. EXPECT_TRUE(detail::parse_accept_header(
  795. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  796. EXPECT_EQ(wildcard_result.size(), 3U);
  797. EXPECT_EQ(wildcard_result[0], "application/json");
  798. EXPECT_EQ(wildcard_result[1], "text/*");
  799. EXPECT_EQ(wildcard_result[2], "*/*");
  800. }
  801. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  802. // Common browser Accept header
  803. std::vector<std::string> browser_result;
  804. EXPECT_TRUE(
  805. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  806. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  807. browser_result));
  808. EXPECT_EQ(browser_result.size(), 6U);
  809. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  813. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  814. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  815. // API client header
  816. std::vector<std::string> api_result;
  817. EXPECT_TRUE(detail::parse_accept_header(
  818. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  819. api_result));
  820. EXPECT_EQ(api_result.size(), 3U);
  821. EXPECT_EQ(api_result[0], "application/json");
  822. EXPECT_EQ(api_result[1], "application/xml");
  823. EXPECT_EQ(api_result[2], "text/plain");
  824. }
  825. TEST(ParseAcceptHeaderTest, SpecialCases) {
  826. // Quality value with 3 decimal places
  827. std::vector<std::string> decimal_result;
  828. EXPECT_TRUE(detail::parse_accept_header(
  829. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  830. EXPECT_EQ(decimal_result.size(), 2U);
  831. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  832. EXPECT_EQ(decimal_result[1], "text/html");
  833. // Zero quality (should still be included but with lowest priority)
  834. std::vector<std::string> zero_q_result;
  835. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  836. zero_q_result));
  837. EXPECT_EQ(zero_q_result.size(), 2U);
  838. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  839. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  840. // No spaces around commas
  841. std::vector<std::string> no_space_result;
  842. EXPECT_TRUE(detail::parse_accept_header(
  843. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  844. no_space_result));
  845. EXPECT_EQ(no_space_result.size(), 3U);
  846. EXPECT_EQ(no_space_result[0], "text/html");
  847. EXPECT_EQ(no_space_result[1], "application/json");
  848. EXPECT_EQ(no_space_result[2], "text/plain");
  849. }
  850. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  851. // Quality values always use '.' as the decimal separator, so parsing must
  852. // not depend on the process locale. An embedding application may have
  853. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  854. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  855. std::string saved = cur ? cur : "C";
  856. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  857. "fr_FR.UTF-8"};
  858. bool switched = false;
  859. for (const auto loc : comma_locales) {
  860. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  861. std::localeconv()->decimal_point[0] == ',') {
  862. switched = true;
  863. break;
  864. }
  865. }
  866. if (!switched) {
  867. std::setlocale(LC_NUMERIC, saved.c_str());
  868. GTEST_SKIP() << "no comma-decimal locale available on this host";
  869. }
  870. // The higher-weighted type appears later in the list, so a correct parse
  871. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  872. // sensitive parse reads both weights as 0 and leaves the original order.
  873. std::vector<std::string> result;
  874. EXPECT_TRUE(detail::parse_accept_header(
  875. "application/json;q=0.1,text/html;q=0.9", result));
  876. ASSERT_EQ(result.size(), 2U);
  877. EXPECT_EQ(result[0], "text/html");
  878. EXPECT_EQ(result[1], "application/json");
  879. std::setlocale(LC_NUMERIC, saved.c_str());
  880. }
  881. TEST(ParseAcceptHeaderTest, InvalidCases) {
  882. std::vector<std::string> result;
  883. // Invalid quality value (> 1.0)
  884. EXPECT_FALSE(
  885. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  886. // Invalid quality value (< 0.0)
  887. EXPECT_FALSE(
  888. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  889. // Invalid quality value (not a number)
  890. EXPECT_FALSE(detail::parse_accept_header(
  891. "text/html;q=invalid,application/json", result));
  892. // A valid numeric prefix does not make the entire quality value valid.
  893. EXPECT_FALSE(detail::parse_accept_header(
  894. "text/html;q=0.5junk,application/json", result));
  895. // Empty quality value
  896. EXPECT_FALSE(
  897. detail::parse_accept_header("text/html;q=,application/json", result));
  898. // Invalid media type format (no slash and not wildcard)
  899. EXPECT_FALSE(
  900. detail::parse_accept_header("invalidtype,application/json", result));
  901. // Valid cases should still work
  902. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  903. EXPECT_EQ(result.size(), 1U);
  904. EXPECT_EQ(result[0], "*/*");
  905. EXPECT_TRUE(detail::parse_accept_header("*", result));
  906. EXPECT_EQ(result.size(), 1U);
  907. EXPECT_EQ(result[0], "*");
  908. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  909. EXPECT_EQ(result.size(), 1U);
  910. EXPECT_EQ(result[0], "text/*");
  911. }
  912. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  913. // elements, so a leading, trailing or doubled comma is a legal Accept value
  914. // and must not be answered with 400 Bad Request.
  915. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  916. struct {
  917. const char *value;
  918. std::vector<std::string> expected;
  919. } cases[] = {
  920. {",application/json", {"application/json"}},
  921. {"text/html,", {"text/html"}},
  922. {"text/html,,*/*", {"text/html", "*/*"}},
  923. // An empty element may be spelled with whitespace in it
  924. {"text/html, , application/json", {"text/html", "application/json"}},
  925. // Nothing but empty elements is an empty list, which means the same
  926. // thing as no Accept header at all
  927. {",,,", {}},
  928. // Quality values still apply across ignored empty elements
  929. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  930. };
  931. for (const auto &c : cases) {
  932. std::vector<std::string> result;
  933. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  934. << "value: " << c.value;
  935. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  936. }
  937. // An invalid entry is still rejected when empty elements surround it
  938. std::vector<std::string> result;
  939. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  940. }
  941. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  942. Server svr;
  943. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  944. EXPECT_EQ(req.accept_content_types.size(), 3U);
  945. EXPECT_EQ(req.accept_content_types[0], "application/json");
  946. EXPECT_EQ(req.accept_content_types[1], "text/html");
  947. EXPECT_EQ(req.accept_content_types[2], "*/*");
  948. res.set_content("ok", "text/plain");
  949. });
  950. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  951. EXPECT_TRUE(false);
  952. res.set_content("bad request", "text/plain");
  953. });
  954. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  955. auto se = detail::scope_exit([&] {
  956. svr.stop();
  957. listen_thread.join();
  958. ASSERT_FALSE(svr.is_running());
  959. });
  960. svr.wait_until_ready();
  961. Client cli("localhost", PORT);
  962. {
  963. auto res = cli.Get(
  964. "/accept_ok",
  965. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  967. EXPECT_EQ(StatusCode::OK_200, res->status);
  968. }
  969. {
  970. auto res = cli.Get("/accept_bad_request",
  971. Headers{{"Accept", "text/html;q=abc,application/json"}});
  972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  973. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  974. }
  975. }
  976. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  977. Server svr;
  978. svr.Get("/", [](const Request & /*req*/, Response &res) {
  979. res.set_content("ok", "text/plain");
  980. });
  981. std::atomic<int> start_count{0};
  982. std::atomic<bool> running_when_called{false};
  983. svr.set_start_handler([&]() {
  984. running_when_called = svr.is_running();
  985. start_count++;
  986. });
  987. auto port = svr.bind_to_any_port(HOST);
  988. std::thread t([&]() { svr.listen_after_bind(); });
  989. auto se = detail::scope_exit([&] {
  990. svr.stop();
  991. t.join();
  992. ASSERT_FALSE(svr.is_running());
  993. });
  994. svr.wait_until_ready();
  995. // A successful request proves the accept loop is running, which the start
  996. // handler precedes; so by now the handler must have run exactly once.
  997. Client cli(HOST, port);
  998. cli.set_connection_timeout(std::chrono::seconds(5));
  999. auto res = cli.Get("/");
  1000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1001. EXPECT_EQ(StatusCode::OK_200, res->status);
  1002. EXPECT_EQ(1, start_count.load());
  1003. EXPECT_TRUE(running_when_called.load());
  1004. }
  1005. TEST(DivideTest, DivideStringTests) {
  1006. auto divide = [](const std::string &str, char d) {
  1007. std::string lhs;
  1008. std::string rhs;
  1009. detail::divide(str, d,
  1010. [&](const char *lhs_data, std::size_t lhs_size,
  1011. const char *rhs_data, std::size_t rhs_size) {
  1012. lhs.assign(lhs_data, lhs_size);
  1013. rhs.assign(rhs_data, rhs_size);
  1014. });
  1015. return std::make_pair(std::move(lhs), std::move(rhs));
  1016. };
  1017. {
  1018. const auto res = divide("", '=');
  1019. EXPECT_EQ(res.first, "");
  1020. EXPECT_EQ(res.second, "");
  1021. }
  1022. {
  1023. const auto res = divide("=", '=');
  1024. EXPECT_EQ(res.first, "");
  1025. EXPECT_EQ(res.second, "");
  1026. }
  1027. {
  1028. const auto res = divide(" ", '=');
  1029. EXPECT_EQ(res.first, " ");
  1030. EXPECT_EQ(res.second, "");
  1031. }
  1032. {
  1033. const auto res = divide("a", '=');
  1034. EXPECT_EQ(res.first, "a");
  1035. EXPECT_EQ(res.second, "");
  1036. }
  1037. {
  1038. const auto res = divide("a=", '=');
  1039. EXPECT_EQ(res.first, "a");
  1040. EXPECT_EQ(res.second, "");
  1041. }
  1042. {
  1043. const auto res = divide("=b", '=');
  1044. EXPECT_EQ(res.first, "");
  1045. EXPECT_EQ(res.second, "b");
  1046. }
  1047. {
  1048. const auto res = divide("a=b", '=');
  1049. EXPECT_EQ(res.first, "a");
  1050. EXPECT_EQ(res.second, "b");
  1051. }
  1052. {
  1053. const auto res = divide("a=b=", '=');
  1054. EXPECT_EQ(res.first, "a");
  1055. EXPECT_EQ(res.second, "b=");
  1056. }
  1057. {
  1058. const auto res = divide("a=b=c", '=');
  1059. EXPECT_EQ(res.first, "a");
  1060. EXPECT_EQ(res.second, "b=c");
  1061. }
  1062. }
  1063. TEST(SplitTest, ParseQueryString) {
  1064. string s = "key1=val1&key2=val2&key3=val3";
  1065. Params dic;
  1066. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1067. [&](const char *b, const char *e) {
  1068. string key, val;
  1069. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1070. if (key.empty()) {
  1071. key.assign(b2, e2);
  1072. } else {
  1073. val.assign(b2, e2);
  1074. }
  1075. });
  1076. dic.emplace(key, val);
  1077. });
  1078. EXPECT_EQ("val1", dic.find("key1")->second);
  1079. EXPECT_EQ("val2", dic.find("key2")->second);
  1080. EXPECT_EQ("val3", dic.find("key3")->second);
  1081. }
  1082. TEST(SplitTest, ParseInvalidQueryTests) {
  1083. {
  1084. string s = " ";
  1085. Params dict;
  1086. detail::parse_query_text(s, dict);
  1087. EXPECT_TRUE(dict.empty());
  1088. }
  1089. {
  1090. string s = " = =";
  1091. Params dict;
  1092. detail::parse_query_text(s, dict);
  1093. EXPECT_TRUE(dict.empty());
  1094. }
  1095. }
  1096. TEST(ParseQueryTest, ParseQueryString) {
  1097. {
  1098. std::string s = "key1=val1&key2=val2&key3=val3";
  1099. Params dic;
  1100. detail::parse_query_text(s, dic);
  1101. EXPECT_EQ("val1", dic.find("key1")->second);
  1102. EXPECT_EQ("val2", dic.find("key2")->second);
  1103. EXPECT_EQ("val3", dic.find("key3")->second);
  1104. }
  1105. {
  1106. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1107. Params dic;
  1108. detail::parse_query_text(s, dic);
  1109. EXPECT_EQ("", dic.find("key1")->second);
  1110. EXPECT_EQ("val1", dic.find("key2")->second);
  1111. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1112. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1113. }
  1114. }
  1115. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1116. Params dic;
  1117. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1118. dic.emplace("key1", "val1");
  1119. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1120. dic.emplace("key2", "val2");
  1121. dic.emplace("key3", "val3");
  1122. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1123. }
  1124. // Joins every entry of a Headers or Params into "key=value " so a whole
  1125. // traversal can be compared in one assertion. Both are instantiations of the
  1126. // same insertion-ordered container, so one helper serves both.
  1127. template <typename Map> static std::string entries_to_string(const Map &m) {
  1128. std::string s;
  1129. for (const auto &entry : m) {
  1130. s += entry.first + "=" + entry.second + " ";
  1131. }
  1132. return s;
  1133. }
  1134. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1135. // Params used to be a std::multimap, which sorted by name and handed the
  1136. // caller's query back alphabetised. A client signing its query string could
  1137. // not reproduce the order it asked for.
  1138. Params dic;
  1139. dic.emplace("zulu", "1");
  1140. dic.emplace("alpha", "2");
  1141. dic.emplace("mike", "3");
  1142. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1143. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1144. }
  1145. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1146. Params dic;
  1147. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1148. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1149. }
  1150. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1151. Request req;
  1152. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1153. req.params);
  1154. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1155. EXPECT_EQ("first", req.get_param_value("tag"));
  1156. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1157. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1158. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1159. EXPECT_EQ("", req.get_param_value("tag", 3));
  1160. }
  1161. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1162. // Params shares its container with Headers, which matches field names
  1163. // case-insensitively. Parameter names must not pick that up.
  1164. Params dic;
  1165. dic.emplace("Key", "upper");
  1166. dic.emplace("key", "lower");
  1167. EXPECT_EQ(2U, dic.size());
  1168. EXPECT_EQ(1U, dic.count("Key"));
  1169. EXPECT_EQ(1U, dic.count("key"));
  1170. EXPECT_EQ("upper", dic.find("Key")->second);
  1171. EXPECT_EQ("lower", dic.find("key")->second);
  1172. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1173. }
  1174. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1175. Server svr;
  1176. std::string order;
  1177. svr.Get("/order", [&](const Request &req, Response &res) {
  1178. order = entries_to_string(req.params);
  1179. res.set_content("ok", "text/plain");
  1180. });
  1181. auto port = svr.bind_to_any_port(HOST);
  1182. thread t = thread([&] { svr.listen_after_bind(); });
  1183. auto se = detail::scope_exit([&] {
  1184. svr.stop();
  1185. t.join();
  1186. ASSERT_FALSE(svr.is_running());
  1187. });
  1188. svr.wait_until_ready();
  1189. Client cli(HOST, port);
  1190. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1191. ASSERT_TRUE(res);
  1192. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1193. }
  1194. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1195. Server svr;
  1196. std::string field_order, file_order;
  1197. svr.Post("/order", [&](const Request &req, Response &res) {
  1198. for (const auto &field : req.form.fields) {
  1199. field_order += field.first + "=" + field.second.content + " ";
  1200. }
  1201. for (const auto &file : req.form.files) {
  1202. file_order += file.first + "=" + file.second.filename + " ";
  1203. }
  1204. res.set_content("ok", "text/plain");
  1205. });
  1206. auto port = svr.bind_to_any_port(HOST);
  1207. thread t = thread([&] { svr.listen_after_bind(); });
  1208. auto se = detail::scope_exit([&] {
  1209. svr.stop();
  1210. t.join();
  1211. ASSERT_FALSE(svr.is_running());
  1212. });
  1213. svr.wait_until_ready();
  1214. UploadFormDataItems items = {
  1215. {"zulu", "1", "", ""},
  1216. {"alpha", "2", "", ""},
  1217. {"mike", "3", "", ""},
  1218. {"zebra", "z", "z.txt", "text/plain"},
  1219. {"apple", "a", "a.txt", "text/plain"},
  1220. };
  1221. Client cli(HOST, port);
  1222. auto res = cli.Post("/order", items);
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1225. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1226. }
  1227. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1228. Server svr;
  1229. std::vector<std::string> values;
  1230. std::string first, second, out_of_range, order;
  1231. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1232. values = req.form.get_fields("tag");
  1233. first = req.form.get_field("tag", 0);
  1234. second = req.form.get_field("tag", 1);
  1235. out_of_range = req.form.get_field("tag", 2);
  1236. for (const auto &field : req.form.fields) {
  1237. order += field.first + "=" + field.second.content + " ";
  1238. }
  1239. res.set_content("ok", "text/plain");
  1240. });
  1241. auto port = svr.bind_to_any_port(HOST);
  1242. thread t = thread([&] { svr.listen_after_bind(); });
  1243. auto se = detail::scope_exit([&] {
  1244. svr.stop();
  1245. t.join();
  1246. ASSERT_FALSE(svr.is_running());
  1247. });
  1248. svr.wait_until_ready();
  1249. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1250. // not adjacent in the container.
  1251. UploadFormDataItems items = {
  1252. {"tag", "first", "", ""},
  1253. {"other", "x", "", ""},
  1254. {"tag", "second", "", ""},
  1255. };
  1256. Client cli(HOST, port);
  1257. auto res = cli.Post("/repeated", items);
  1258. ASSERT_TRUE(res);
  1259. ASSERT_EQ(2U, values.size());
  1260. EXPECT_EQ("first", values[0]);
  1261. EXPECT_EQ("second", values[1]);
  1262. EXPECT_EQ("first", first);
  1263. EXPECT_EQ("second", second);
  1264. // std::multimap already kept entries sharing a name in insertion order, so
  1265. // everything above passes without this change too. The whole traversal is
  1266. // what tells the two apart: sorting by name would hoist "other" to the front
  1267. // and the two "tag" parts would end up adjacent.
  1268. EXPECT_EQ("tag=first other=x tag=second ", order);
  1269. // Advancing past the last entry of a name used to run off the container;
  1270. // the container's saturating increment makes it return the default instead.
  1271. EXPECT_EQ("", out_of_range);
  1272. }
  1273. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1274. // Server::read_content() keeps a FormFields::iterator alive across the
  1275. // content callbacks that fill the part it points at. The container is
  1276. // vector-backed, so a later emplace can reallocate and invalidate an older
  1277. // iterator; 64 parts grow the vector through seven reallocations, which
  1278. // checks that every part's content still lands in its own entry.
  1279. const size_t part_count = 64;
  1280. // One formula for both the parts sent and the values expected back, so the
  1281. // two cannot drift apart.
  1282. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1283. auto content_of = [](size_t i) {
  1284. return std::string(64, static_cast<char>('a' + (i % 26)));
  1285. };
  1286. Server svr;
  1287. std::vector<std::pair<std::string, std::string>> received;
  1288. svr.Post("/many", [&](const Request &req, Response &res) {
  1289. for (const auto &field : req.form.fields) {
  1290. received.emplace_back(field.first, field.second.content);
  1291. }
  1292. res.set_content("ok", "text/plain");
  1293. });
  1294. auto port = svr.bind_to_any_port(HOST);
  1295. thread t = thread([&] { svr.listen_after_bind(); });
  1296. auto se = detail::scope_exit([&] {
  1297. svr.stop();
  1298. t.join();
  1299. ASSERT_FALSE(svr.is_running());
  1300. });
  1301. svr.wait_until_ready();
  1302. UploadFormDataItems items;
  1303. for (size_t i = 0; i < part_count; i++) {
  1304. items.push_back({name_of(i), content_of(i), "", ""});
  1305. }
  1306. Client cli(HOST, port);
  1307. auto res = cli.Post("/many", items);
  1308. ASSERT_TRUE(res);
  1309. ASSERT_EQ(part_count, received.size());
  1310. for (size_t i = 0; i < part_count; i++) {
  1311. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1312. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1313. }
  1314. }
  1315. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1316. string content_type = "multipart/form-data; boundary=something";
  1317. string boundary;
  1318. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1319. EXPECT_TRUE(ret);
  1320. EXPECT_EQ(boundary, "something");
  1321. }
  1322. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1323. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1324. string boundary;
  1325. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1326. EXPECT_TRUE(ret);
  1327. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1328. }
  1329. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1330. string content_type =
  1331. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1332. string boundary;
  1333. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1334. EXPECT_TRUE(ret);
  1335. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1336. }
  1337. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1338. string content_type =
  1339. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1340. string boundary;
  1341. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1342. EXPECT_TRUE(ret);
  1343. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1344. }
  1345. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1346. const string boundary(70, 'a');
  1347. string content_type = "multipart/form-data; boundary=" + boundary;
  1348. string parsed;
  1349. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1350. EXPECT_TRUE(ret);
  1351. EXPECT_EQ(parsed, boundary);
  1352. }
  1353. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1354. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1355. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1356. string parsed;
  1357. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1358. EXPECT_FALSE(ret);
  1359. }
  1360. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1361. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1362. // is 72 characters on the wire and still valid.
  1363. const string boundary(70, 'a');
  1364. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1365. string parsed;
  1366. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1367. EXPECT_EQ(parsed, boundary);
  1368. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1369. parsed.clear();
  1370. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1371. }
  1372. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1373. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1374. // The parameter parser must not treat that '=' as the key/value separator.
  1375. string content_type =
  1376. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1377. "charset=UTF-8";
  1378. string parsed;
  1379. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1380. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1381. }
  1382. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1383. // A ';' inside the quoted-string is part of the value, not a parameter
  1384. // separator, so it must not truncate the boundary.
  1385. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1386. string parsed;
  1387. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1388. EXPECT_EQ(parsed, "a;b");
  1389. }
  1390. TEST(ParseDispositionParamsTest, QuotedValues) {
  1391. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1392. // ';' and '=' are ordinary characters inside one.
  1393. struct {
  1394. const char *value;
  1395. std::vector<std::pair<const char *, const char *>> expected;
  1396. } cases[] = {
  1397. {"name=\"file1\"; filename=\"a.txt\"",
  1398. {{"name", "file1"}, {"filename", "a.txt"}}},
  1399. // Whitespace around '=' and ';' is still trimmed
  1400. {"name=\"file2\" ;filename = \"a.html\"",
  1401. {{"name", "file2"}, {"filename", "a.html"}}},
  1402. // '=' inside the value used to leave only the text after the last one
  1403. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1404. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1405. {"name=\"x=y\"", {{"name", "x=y"}}},
  1406. // ';' inside the value used to truncate the pair and leave a bogus one
  1407. {"name=\"file3\"; filename=\"a;b.txt\"",
  1408. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1409. // An unquoted value keeps working, and so does filename*
  1410. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1411. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1412. // A parameter with no key is dropped rather than turned into one whose
  1413. // key is the value
  1414. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1415. };
  1416. for (const auto &c : cases) {
  1417. Params params;
  1418. detail::parse_disposition_params(c.value, params);
  1419. for (const auto &kv : c.expected) {
  1420. auto it = params.find(kv.first);
  1421. ASSERT_NE(it, params.end())
  1422. << "value: " << c.value << ", key: " << kv.first;
  1423. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1424. }
  1425. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1426. }
  1427. }
  1428. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1429. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1430. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1431. Server svr;
  1432. std::string field_value, file_name, file_filename;
  1433. bool has_field = false, has_file = false;
  1434. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1435. has_field = req.form.has_field("x=y");
  1436. field_value = req.form.get_field("x=y");
  1437. has_file = req.form.has_file("file1");
  1438. const auto &file = req.form.get_file("file1");
  1439. file_name = file.name;
  1440. file_filename = file.filename;
  1441. res.set_content("ok", "text/plain");
  1442. });
  1443. auto port = svr.bind_to_any_port(HOST);
  1444. thread t = thread([&] { svr.listen_after_bind(); });
  1445. auto se = detail::scope_exit([&] {
  1446. svr.stop();
  1447. t.join();
  1448. ASSERT_FALSE(svr.is_running());
  1449. });
  1450. svr.wait_until_ready();
  1451. UploadFormDataItems items = {
  1452. {"x=y", "field-value", "", ""},
  1453. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1454. };
  1455. Client cli(HOST, port);
  1456. auto res = cli.Post("/quoted", items);
  1457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1458. ASSERT_EQ(StatusCode::OK_200, res->status);
  1459. EXPECT_TRUE(has_field);
  1460. EXPECT_EQ("field-value", field_value);
  1461. EXPECT_TRUE(has_file);
  1462. EXPECT_EQ("file1", file_name);
  1463. EXPECT_EQ("a;b=report.pdf", file_filename);
  1464. }
  1465. TEST(GetHeaderValueTest, DefaultValue) {
  1466. Headers headers = {{"Dummy", "Dummy"}};
  1467. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1468. EXPECT_STREQ("text/plain", val);
  1469. }
  1470. TEST(GetHeaderValueTest, DefaultValueInt) {
  1471. Headers headers = {{"Dummy", "Dummy"}};
  1472. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1473. EXPECT_EQ(100ull, val);
  1474. }
  1475. TEST(GetHeaderValueTest, RegularValue) {
  1476. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1477. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1478. EXPECT_STREQ("text/html", val);
  1479. }
  1480. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1481. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1482. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1483. EXPECT_STREQ("text/html", val);
  1484. }
  1485. TEST(GetHeaderValueTest, SetContent) {
  1486. Response res;
  1487. res.set_content("html", "text/html");
  1488. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1489. res.set_content("text", "text/plain");
  1490. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1491. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1492. }
  1493. TEST(GetHeaderValueTest, RegularValueInt) {
  1494. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1495. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1496. EXPECT_EQ(100ull, val);
  1497. }
  1498. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1499. Headers headers = {{"Content-Length", "x"}};
  1500. auto is_invalid_value = false;
  1501. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1502. is_invalid_value);
  1503. EXPECT_EQ(0ull, val);
  1504. EXPECT_TRUE(is_invalid_value);
  1505. }
  1506. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1507. // An all-digit value that overflows size_t must be reported as invalid, not
  1508. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1509. // a large length to a small one on 32-bit builds, leaving the framing length
  1510. // wrong while is_invalid_value stayed false.
  1511. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1512. auto is_invalid_value = false;
  1513. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1514. is_invalid_value);
  1515. EXPECT_TRUE(is_invalid_value);
  1516. // A well-formed length is unaffected.
  1517. Headers ok = {{"Content-Length", "1234"}};
  1518. is_invalid_value = false;
  1519. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1520. is_invalid_value);
  1521. EXPECT_EQ(1234ull, val);
  1522. EXPECT_FALSE(is_invalid_value);
  1523. }
  1524. TEST(GetHeaderValueTest, Range) {
  1525. {
  1526. Headers headers = {make_range_header({{1, -1}})};
  1527. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1528. EXPECT_STREQ("bytes=1-", val);
  1529. }
  1530. {
  1531. Headers headers = {make_range_header({{-1, 1}})};
  1532. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1533. EXPECT_STREQ("bytes=-1", val);
  1534. }
  1535. {
  1536. Headers headers = {make_range_header({{1, 10}})};
  1537. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1538. EXPECT_STREQ("bytes=1-10", val);
  1539. }
  1540. {
  1541. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1542. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1543. EXPECT_STREQ("bytes=1-10, 100-", val);
  1544. }
  1545. {
  1546. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1547. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1548. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1549. }
  1550. {
  1551. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1552. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1553. EXPECT_STREQ("bytes=0-0, -1", val);
  1554. }
  1555. }
  1556. TEST(BearerTokenAuthTest, SchemeValidation) {
  1557. // A value shorter than "Bearer " must not throw from the fixed-length
  1558. // substr, and a non-Bearer scheme must not be reported as a token.
  1559. struct {
  1560. const char *value;
  1561. const char *expected;
  1562. } cases[] = {
  1563. {"x", ""},
  1564. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1565. {"Bearer abc123", "abc123"},
  1566. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1567. };
  1568. for (const auto &c : cases) {
  1569. Request req;
  1570. req.set_header("Authorization", c.value);
  1571. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1572. }
  1573. }
  1574. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1575. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1576. // to depend on the standard library (libstdc++ handed back duplicates in
  1577. // reverse insertion order, libc++ in insertion order).
  1578. Request req;
  1579. req.set_header("Accept-Encoding", "gzip");
  1580. req.set_header("Accept-Encoding", "deflate");
  1581. req.set_header("Accept-Encoding", "br");
  1582. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1583. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1584. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1585. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1586. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1587. }
  1588. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1589. Request req;
  1590. req.set_header("X-Test", "only");
  1591. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1592. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1593. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1594. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1595. }
  1596. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1597. Headers headers;
  1598. headers.emplace("Host", "example.com");
  1599. headers.emplace("Accept-Encoding", "gzip");
  1600. headers.emplace("User-Agent", "test");
  1601. headers.emplace("Accept-Encoding", "deflate");
  1602. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1603. "Accept-Encoding=deflate ",
  1604. entries_to_string(headers));
  1605. }
  1606. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1607. Headers headers = {{"Content-Type", "text/html"},
  1608. {"CONTENT-TYPE", "text/xml"}};
  1609. EXPECT_EQ(2U, headers.count("content-type"));
  1610. auto it = headers.find("content-type");
  1611. ASSERT_TRUE(it != headers.end());
  1612. EXPECT_EQ("text/html", it->second);
  1613. }
  1614. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1615. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1616. // drop only those fields and leave everything positioned between them.
  1617. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1618. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1619. auto rng = headers.equal_range("a");
  1620. headers.erase(rng.first, rng.second);
  1621. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1622. }
  1623. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1624. Headers headers = {
  1625. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1626. EXPECT_EQ(3U, headers.erase("A"));
  1627. EXPECT_EQ(0U, headers.count("A"));
  1628. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1629. }
  1630. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1631. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1632. headers.emplace_front("Host", "example.com");
  1633. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1634. entries_to_string(headers));
  1635. }
  1636. TEST(ParseHeaderValueTest, Range) {
  1637. {
  1638. Ranges ranges;
  1639. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1640. EXPECT_TRUE(ret);
  1641. EXPECT_EQ(1u, ranges.size());
  1642. EXPECT_EQ(1u, ranges[0].first);
  1643. EXPECT_EQ(-1, ranges[0].second);
  1644. }
  1645. {
  1646. Ranges ranges;
  1647. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1648. EXPECT_TRUE(ret);
  1649. EXPECT_EQ(1u, ranges.size());
  1650. EXPECT_EQ(-1, ranges[0].first);
  1651. EXPECT_EQ(1u, ranges[0].second);
  1652. }
  1653. {
  1654. Ranges ranges;
  1655. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1656. EXPECT_TRUE(ret);
  1657. EXPECT_EQ(1u, ranges.size());
  1658. EXPECT_EQ(1u, ranges[0].first);
  1659. EXPECT_EQ(10u, ranges[0].second);
  1660. }
  1661. {
  1662. Ranges ranges;
  1663. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1664. EXPECT_FALSE(ret);
  1665. }
  1666. {
  1667. Ranges ranges;
  1668. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1669. EXPECT_TRUE(ret);
  1670. EXPECT_EQ(2u, ranges.size());
  1671. EXPECT_EQ(1u, ranges[0].first);
  1672. EXPECT_EQ(10u, ranges[0].second);
  1673. EXPECT_EQ(100u, ranges[1].first);
  1674. EXPECT_EQ(-1, ranges[1].second);
  1675. }
  1676. {
  1677. Ranges ranges;
  1678. auto ret =
  1679. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1680. EXPECT_TRUE(ret);
  1681. EXPECT_EQ(3u, ranges.size());
  1682. EXPECT_EQ(1u, ranges[0].first);
  1683. EXPECT_EQ(10u, ranges[0].second);
  1684. EXPECT_EQ(100u, ranges[1].first);
  1685. EXPECT_EQ(200u, ranges[1].second);
  1686. EXPECT_EQ(300u, ranges[2].first);
  1687. EXPECT_EQ(400u, ranges[2].second);
  1688. }
  1689. {
  1690. Ranges ranges;
  1691. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1700. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1701. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1702. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1703. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1704. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1705. EXPECT_FALSE(
  1706. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1707. EXPECT_TRUE(ranges.empty());
  1708. }
  1709. {
  1710. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1711. // remainder of the representation, so it stays accepted.
  1712. Ranges ranges;
  1713. auto ret =
  1714. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1715. EXPECT_TRUE(ret);
  1716. ASSERT_EQ(1u, ranges.size());
  1717. EXPECT_EQ(0, ranges[0].first);
  1718. EXPECT_EQ(-1, ranges[0].second);
  1719. }
  1720. }
  1721. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1722. Request req;
  1723. req.set_header("Accept-Encoding", "gzip");
  1724. Response res;
  1725. res.set_header("Content-Type", "text/plain");
  1726. auto ret = detail::encoding_type(req, res);
  1727. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1728. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1729. #else
  1730. EXPECT_TRUE(ret == detail::EncodingType::None);
  1731. #endif
  1732. }
  1733. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1734. Request req;
  1735. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1736. Response res;
  1737. res.set_header("Content-Type", "text/plain");
  1738. auto ret = detail::encoding_type(req, res);
  1739. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1740. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1741. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1742. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1743. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1744. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1745. #else
  1746. EXPECT_TRUE(ret == detail::EncodingType::None);
  1747. #endif
  1748. }
  1749. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1750. Request req;
  1751. req.set_header("Accept-Encoding",
  1752. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1753. Response res;
  1754. res.set_header("Content-Type", "text/plain");
  1755. auto ret = detail::encoding_type(req, res);
  1756. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1757. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1758. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1759. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1760. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1761. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1762. #else
  1763. EXPECT_TRUE(ret == detail::EncodingType::None);
  1764. #endif
  1765. }
  1766. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1767. // All supported encodings rejected with q=0 should return None
  1768. Request req;
  1769. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1770. Response res;
  1771. res.set_header("Content-Type", "text/plain");
  1772. auto ret = detail::encoding_type(req, res);
  1773. EXPECT_TRUE(ret == detail::EncodingType::None);
  1774. }
  1775. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1776. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1777. Request req;
  1778. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1779. Response res;
  1780. res.set_header("Content-Type", "text/plain");
  1781. auto ret = detail::encoding_type(req, res);
  1782. EXPECT_TRUE(ret == detail::EncodingType::None);
  1783. }
  1784. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1785. Request req;
  1786. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1787. Response res;
  1788. res.set_header("Content-Type", "text/plain");
  1789. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1790. }
  1791. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1792. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1793. Request req;
  1794. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1795. Response res;
  1796. res.set_header("Content-Type", "text/plain");
  1797. auto ret = detail::encoding_type(req, res);
  1798. EXPECT_TRUE(ret == detail::EncodingType::None);
  1799. }
  1800. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1801. // RFC 7231: Accept-Encoding values are case-insensitive
  1802. Request req;
  1803. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1804. Response res;
  1805. res.set_header("Content-Type", "text/plain");
  1806. auto ret = detail::encoding_type(req, res);
  1807. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1808. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1809. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1810. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1811. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1812. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1813. #else
  1814. EXPECT_TRUE(ret == detail::EncodingType::None);
  1815. #endif
  1816. }
  1817. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1818. // q value should determine priority, not hardcoded order
  1819. Request req;
  1820. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1821. Response res;
  1822. res.set_header("Content-Type", "text/plain");
  1823. auto ret = detail::encoding_type(req, res);
  1824. // gzip has highest q=1.0, so it should be selected even though
  1825. // br and zstd are also supported
  1826. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1827. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1828. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1829. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1830. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1831. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1832. #else
  1833. EXPECT_TRUE(ret == detail::EncodingType::None);
  1834. #endif
  1835. }
  1836. TEST(BufferStreamTest, read) {
  1837. detail::BufferStream strm1;
  1838. Stream &strm = strm1;
  1839. EXPECT_EQ(5, strm.write("hello"));
  1840. char buf[512];
  1841. EXPECT_EQ(2, strm.read(buf, 2));
  1842. EXPECT_EQ('h', buf[0]);
  1843. EXPECT_EQ('e', buf[1]);
  1844. EXPECT_EQ(2, strm.read(buf, 2));
  1845. EXPECT_EQ('l', buf[0]);
  1846. EXPECT_EQ('l', buf[1]);
  1847. EXPECT_EQ(1, strm.read(buf, 1));
  1848. EXPECT_EQ('o', buf[0]);
  1849. EXPECT_EQ(0, strm.read(buf, 1));
  1850. }
  1851. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1852. auto host = "www.httpwatch.com";
  1853. auto ip = hosted_at(host);
  1854. EXPECT_EQ("23.96.13.243", ip);
  1855. std::vector<std::string> addrs;
  1856. hosted_at(host, addrs);
  1857. EXPECT_EQ(1u, addrs.size());
  1858. }
  1859. #if 0 // It depends on each test environment...
  1860. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1861. auto host = "www.youtube.com";
  1862. std::vector<std::string> addrs;
  1863. hosted_at(host, addrs);
  1864. EXPECT_EQ(20u, addrs.size());
  1865. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1866. EXPECT_TRUE(it != addrs.end());
  1867. }
  1868. #endif
  1869. class ChunkedEncodingTest : public ::testing::Test {
  1870. protected:
  1871. ChunkedEncodingTest()
  1872. : cli_(HOST, PORT)
  1873. #ifdef CPPHTTPLIB_SSL_ENABLED
  1874. ,
  1875. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1876. #endif
  1877. {
  1878. cli_.set_connection_timeout(2);
  1879. #ifdef CPPHTTPLIB_SSL_ENABLED
  1880. cli_.enable_server_certificate_verification(false);
  1881. #endif
  1882. }
  1883. virtual void SetUp() {
  1884. read_file("./image.jpg", image_data_);
  1885. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1886. res.set_content("Hello World!", "text/plain");
  1887. });
  1888. svr_.Get(
  1889. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1890. res.set_chunked_content_provider(
  1891. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1892. size_t remaining = image_data_.size() - offset;
  1893. if (remaining == 0) {
  1894. sink.done();
  1895. } else {
  1896. constexpr size_t CHUNK_SIZE = 1024;
  1897. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1898. sink.write(&image_data_[offset], send_size);
  1899. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1900. }
  1901. return true;
  1902. });
  1903. });
  1904. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1905. svr_.wait_until_ready();
  1906. }
  1907. virtual void TearDown() {
  1908. svr_.stop();
  1909. if (!request_threads_.empty()) {
  1910. std::this_thread::sleep_for(std::chrono::seconds(1));
  1911. for (auto &t : request_threads_) {
  1912. t.join();
  1913. }
  1914. }
  1915. t_.join();
  1916. }
  1917. #ifdef CPPHTTPLIB_SSL_ENABLED
  1918. SSLClient cli_;
  1919. SSLServer svr_;
  1920. #else
  1921. Client cli_;
  1922. Server svr_;
  1923. #endif
  1924. thread t_;
  1925. std::vector<thread> request_threads_;
  1926. std::string image_data_;
  1927. };
  1928. TEST_F(ChunkedEncodingTest, NormalGet) {
  1929. auto res = cli_.Get("/chunked");
  1930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1931. std::string out;
  1932. read_file("./image.jpg", out);
  1933. EXPECT_EQ(StatusCode::OK_200, res->status);
  1934. EXPECT_EQ(out, res->body);
  1935. }
  1936. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1937. std::string body;
  1938. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1939. body.append(data, data_length);
  1940. return true;
  1941. });
  1942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1943. std::string out;
  1944. read_file("./image.jpg", out);
  1945. EXPECT_EQ(StatusCode::OK_200, res->status);
  1946. EXPECT_EQ(out, body);
  1947. }
  1948. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1949. std::string body;
  1950. auto res = cli_.Get(
  1951. "/chunked",
  1952. [&](const Response &response) {
  1953. EXPECT_EQ(StatusCode::OK_200, response.status);
  1954. return true;
  1955. },
  1956. [&](const char *data, size_t data_length) {
  1957. body.append(data, data_length);
  1958. return true;
  1959. });
  1960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1961. std::string out;
  1962. read_file("./image.jpg", out);
  1963. EXPECT_EQ(StatusCode::OK_200, res->status);
  1964. EXPECT_EQ(out, body);
  1965. }
  1966. TEST(RangeTest, FromHTTPBin_Online) {
  1967. auto host = "httpbingo.org";
  1968. auto path = std::string{"/range/32"};
  1969. #ifdef CPPHTTPLIB_SSL_ENABLED
  1970. auto port = 443;
  1971. SSLClient cli(host, port);
  1972. #else
  1973. auto port = 80;
  1974. Client cli(host, port);
  1975. #endif
  1976. cli.set_connection_timeout(5);
  1977. {
  1978. auto res = cli.Get(path);
  1979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1980. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1981. EXPECT_EQ(StatusCode::OK_200, res->status);
  1982. }
  1983. {
  1984. Headers headers = {make_range_header({{1, -1}})};
  1985. auto res = cli.Get(path, headers);
  1986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1987. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1988. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1989. }
  1990. {
  1991. Headers headers = {make_range_header({{1, 10}})};
  1992. auto res = cli.Get(path, headers);
  1993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1994. EXPECT_EQ("bcdefghijk", res->body);
  1995. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1996. }
  1997. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1998. // entire resource, while the original httpbin returned 200. Both are
  1999. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2000. {
  2001. Headers headers = {make_range_header({{0, 31}})};
  2002. auto res = cli.Get(path, headers);
  2003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2004. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2005. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2006. res->status == StatusCode::PartialContent_206);
  2007. }
  2008. {
  2009. Headers headers = {make_range_header({{0, -1}})};
  2010. auto res = cli.Get(path, headers);
  2011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2012. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2013. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2014. res->status == StatusCode::PartialContent_206);
  2015. }
  2016. // go-httpbin returns 206 with clamped range for over-range requests,
  2017. // while the original httpbin returned 416. Both behaviors are observed
  2018. // in real servers, so we only verify the request succeeds.
  2019. {
  2020. Headers headers = {make_range_header({{0, 32}})};
  2021. auto res = cli.Get(path, headers);
  2022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2023. }
  2024. }
  2025. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2026. auto host = "unresolvableaddress.local";
  2027. auto path = std::string{"/"};
  2028. #ifdef CPPHTTPLIB_SSL_ENABLED
  2029. auto port = 443;
  2030. SSLClient cli(host, port);
  2031. #else
  2032. auto port = 80;
  2033. Client cli(host, port);
  2034. #endif
  2035. cli.set_connection_timeout(1);
  2036. {
  2037. auto res = cli.Get(path);
  2038. ASSERT_FALSE(res);
  2039. }
  2040. std::this_thread::sleep_for(std::chrono::seconds(8));
  2041. }
  2042. #if defined(__linux__) && defined(__GLIBC__) && \
  2043. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2044. // Forward declaration: in split builds split.py strips `inline` and moves the
  2045. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2046. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2047. // against the symbol in both header-only and split builds.
  2048. namespace httplib {
  2049. namespace detail {
  2050. int getaddrinfo_with_timeout(const char *node, const char *service,
  2051. const struct addrinfo *hints,
  2052. struct addrinfo **res, time_t timeout_sec);
  2053. } // namespace detail
  2054. } // namespace httplib
  2055. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2056. //
  2057. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2058. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2059. // gai_suspend() call hits the connection timeout the function calls
  2060. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2061. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2062. // still alive and still references the now-destroyed stack frame.
  2063. //
  2064. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2065. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2066. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2067. // and runs them in a container.
  2068. namespace {
  2069. bool should_run_issue_2431_tests() {
  2070. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2071. return v && *v && std::string(v) != "0";
  2072. }
  2073. std::string unique_unresolvable_host(int n) {
  2074. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2075. // glibc still asks the configured nameserver — which is exactly the path
  2076. // we want to exercise. A unique label per call avoids the resolver cache.
  2077. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2078. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2079. std::to_string(n) + ".invalid";
  2080. }
  2081. } // namespace
  2082. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2083. if (!should_run_issue_2431_tests()) {
  2084. GTEST_SKIP()
  2085. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2086. }
  2087. for (int i = 0; i < 8; ++i) {
  2088. struct addrinfo hints;
  2089. memset(&hints, 0, sizeof(hints));
  2090. hints.ai_family = AF_UNSPEC;
  2091. hints.ai_socktype = SOCK_STREAM;
  2092. auto host = unique_unresolvable_host(i);
  2093. struct addrinfo *result = nullptr;
  2094. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2095. &result, /*timeout_sec=*/1);
  2096. if (rc == 0 && result) { freeaddrinfo(result); }
  2097. }
  2098. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2099. // stack region they still believe holds their gaicb.
  2100. std::this_thread::sleep_for(std::chrono::seconds(3));
  2101. }
  2102. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2103. if (!should_run_issue_2431_tests()) {
  2104. GTEST_SKIP()
  2105. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2106. }
  2107. std::atomic<bool> stop{false};
  2108. std::vector<std::thread> threads;
  2109. for (int t = 0; t < 8; ++t) {
  2110. threads.emplace_back([t, &stop] {
  2111. int i = 0;
  2112. while (!stop.load(std::memory_order_relaxed)) {
  2113. struct addrinfo hints;
  2114. memset(&hints, 0, sizeof(hints));
  2115. hints.ai_family = AF_UNSPEC;
  2116. hints.ai_socktype = SOCK_STREAM;
  2117. auto host = unique_unresolvable_host(t * 100000 + i++);
  2118. struct addrinfo *result = nullptr;
  2119. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2120. &result, /*timeout_sec=*/1);
  2121. if (rc == 0 && result) { freeaddrinfo(result); }
  2122. }
  2123. });
  2124. }
  2125. std::this_thread::sleep_for(std::chrono::seconds(8));
  2126. stop.store(true, std::memory_order_relaxed);
  2127. for (auto &th : threads) {
  2128. th.join();
  2129. }
  2130. std::this_thread::sleep_for(std::chrono::seconds(3));
  2131. }
  2132. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2133. if (!should_run_issue_2431_tests()) {
  2134. GTEST_SKIP()
  2135. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2136. }
  2137. std::atomic<bool> stop{false};
  2138. std::vector<std::thread> threads;
  2139. for (int t = 0; t < 8; ++t) {
  2140. threads.emplace_back([t, &stop] {
  2141. int i = 0;
  2142. while (!stop.load(std::memory_order_relaxed)) {
  2143. auto host = unique_unresolvable_host(t * 100000 + i++);
  2144. Client cli(host, 80);
  2145. cli.set_connection_timeout(1, 0);
  2146. cli.set_read_timeout(1, 0);
  2147. cli.set_write_timeout(1, 0);
  2148. (void)cli.Get("/");
  2149. }
  2150. });
  2151. }
  2152. std::this_thread::sleep_for(std::chrono::seconds(8));
  2153. stop.store(true, std::memory_order_relaxed);
  2154. for (auto &th : threads) {
  2155. th.join();
  2156. }
  2157. std::this_thread::sleep_for(std::chrono::seconds(3));
  2158. }
  2159. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2160. TEST(ConnectionErrorTest, InvalidHost) {
  2161. auto host = "-abcde.com";
  2162. #ifdef CPPHTTPLIB_SSL_ENABLED
  2163. auto port = 443;
  2164. SSLClient cli(host, port);
  2165. #else
  2166. auto port = 80;
  2167. Client cli(host, port);
  2168. #endif
  2169. cli.set_connection_timeout(std::chrono::seconds(2));
  2170. auto res = cli.Get("/");
  2171. ASSERT_TRUE(!res);
  2172. EXPECT_EQ(Error::Connection, res.error());
  2173. }
  2174. TEST(ConnectionErrorTest, InvalidHost2) {
  2175. auto host = "httpcan.org/";
  2176. #ifdef CPPHTTPLIB_SSL_ENABLED
  2177. SSLClient cli(host);
  2178. #else
  2179. Client cli(host);
  2180. #endif
  2181. cli.set_connection_timeout(std::chrono::seconds(2));
  2182. auto res = cli.Get("/");
  2183. ASSERT_TRUE(!res);
  2184. EXPECT_EQ(Error::Connection, res.error());
  2185. }
  2186. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2187. auto host = "httpcan.org/";
  2188. #ifdef CPPHTTPLIB_SSL_ENABLED
  2189. SSLClient cli(host);
  2190. #else
  2191. Client cli(host);
  2192. #endif
  2193. cli.set_connection_timeout(std::chrono::seconds(2));
  2194. auto res = cli.Get("/");
  2195. ASSERT_TRUE(!res);
  2196. stringstream s;
  2197. s << "error code: " << res.error();
  2198. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2199. }
  2200. TEST(ConnectionErrorTest, InvalidPort) {
  2201. auto host = "localhost";
  2202. auto port = 44380;
  2203. #ifdef CPPHTTPLIB_SSL_ENABLED
  2204. SSLClient cli(host, port);
  2205. #else
  2206. Client cli(host, port);
  2207. #endif
  2208. cli.set_connection_timeout(std::chrono::seconds(2));
  2209. auto res = cli.Get("/");
  2210. ASSERT_TRUE(!res);
  2211. EXPECT_TRUE(Error::Connection == res.error() ||
  2212. Error::ConnectionTimeout == res.error());
  2213. }
  2214. TEST(ConnectionErrorTest, Timeout_Online) {
  2215. auto host = "google.com";
  2216. #ifdef CPPHTTPLIB_SSL_ENABLED
  2217. auto port = 44380;
  2218. SSLClient cli(host, port);
  2219. #else
  2220. auto port = 8080;
  2221. Client cli(host, port);
  2222. #endif
  2223. cli.set_connection_timeout(std::chrono::seconds(2));
  2224. // only probe one address type so that the error reason
  2225. // correlates to the timed-out IPv4, not the unsupported
  2226. // IPv6 connection attempt
  2227. cli.set_address_family(AF_INET);
  2228. auto res = cli.Get("/");
  2229. ASSERT_TRUE(!res);
  2230. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2231. }
  2232. TEST(CancelTest, NoCancel_Online) {
  2233. auto host = "httpbingo.org";
  2234. auto path = std::string{"/range/32"};
  2235. #ifdef CPPHTTPLIB_SSL_ENABLED
  2236. auto port = 443;
  2237. SSLClient cli(host, port);
  2238. #else
  2239. auto port = 80;
  2240. Client cli(host, port);
  2241. #endif
  2242. cli.set_connection_timeout(std::chrono::seconds(5));
  2243. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2245. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2246. EXPECT_EQ(StatusCode::OK_200, res->status);
  2247. }
  2248. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2249. // Use /bytes with a large payload so that the DownloadProgress callback
  2250. // (which only fires for Content-Length responses) is invoked before the
  2251. // entire body is received, giving cancellation a chance to fire.
  2252. auto host = "httpbingo.org";
  2253. auto path = std::string{"/bytes/524288"};
  2254. #ifdef CPPHTTPLIB_SSL_ENABLED
  2255. auto port = 443;
  2256. SSLClient cli(host, port);
  2257. #else
  2258. auto port = 80;
  2259. Client cli(host, port);
  2260. #endif
  2261. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2262. cli.set_connection_timeout(std::chrono::seconds(5));
  2263. ASSERT_TRUE(!res);
  2264. EXPECT_EQ(Error::Canceled, res.error());
  2265. }
  2266. TEST(CancelTest, WithCancelLargePayload_Online) {
  2267. auto host = "httpbingo.org";
  2268. auto path = std::string{"/bytes/524288"};
  2269. #ifdef CPPHTTPLIB_SSL_ENABLED
  2270. auto port = 443;
  2271. SSLClient cli(host, port);
  2272. #else
  2273. auto port = 80;
  2274. Client cli(host, port);
  2275. #endif
  2276. cli.set_connection_timeout(std::chrono::seconds(5));
  2277. uint32_t count = 0;
  2278. auto res =
  2279. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2280. ASSERT_TRUE(!res);
  2281. EXPECT_EQ(Error::Canceled, res.error());
  2282. }
  2283. TEST(CancelTest, NoCancelPost) {
  2284. Server svr;
  2285. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2286. res.set_content("Hello World!", "text/plain");
  2287. });
  2288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2289. auto se = detail::scope_exit([&] {
  2290. svr.stop();
  2291. thread.join();
  2292. ASSERT_FALSE(svr.is_running());
  2293. });
  2294. svr.wait_until_ready();
  2295. Client cli(HOST, PORT);
  2296. cli.set_connection_timeout(std::chrono::seconds(5));
  2297. auto res =
  2298. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2299. "application/json", [](uint64_t, uint64_t) { return true; });
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. EXPECT_EQ("Hello World!", res->body);
  2302. EXPECT_EQ(StatusCode::OK_200, res->status);
  2303. }
  2304. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2305. Server svr;
  2306. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2307. res.set_content("Hello World!", "text/plain");
  2308. });
  2309. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2310. auto se = detail::scope_exit([&] {
  2311. svr.stop();
  2312. thread.join();
  2313. ASSERT_FALSE(svr.is_running());
  2314. });
  2315. svr.wait_until_ready();
  2316. Client cli(HOST, PORT);
  2317. cli.set_connection_timeout(std::chrono::seconds(5));
  2318. auto res =
  2319. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2320. "application/json", [](uint64_t, uint64_t) { return false; });
  2321. ASSERT_TRUE(!res);
  2322. EXPECT_EQ(Error::Canceled, res.error());
  2323. }
  2324. TEST(CancelTest, WithCancelLargePayloadPost) {
  2325. Server svr;
  2326. svr.set_payload_max_length(200 * 1024 * 1024);
  2327. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2328. res.set_content(LARGE_DATA, "text/plain");
  2329. });
  2330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2331. auto se = detail::scope_exit([&] {
  2332. svr.stop();
  2333. thread.join();
  2334. ASSERT_FALSE(svr.is_running());
  2335. });
  2336. svr.wait_until_ready();
  2337. Client cli(HOST, PORT);
  2338. cli.set_payload_max_length(200 * 1024 * 1024);
  2339. cli.set_connection_timeout(std::chrono::seconds(5));
  2340. auto res =
  2341. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2342. "application/json", [](uint64_t, uint64_t) { return false; });
  2343. ASSERT_TRUE(!res);
  2344. EXPECT_EQ(Error::Canceled, res.error());
  2345. }
  2346. TEST(CancelTest, NoCancelPut) {
  2347. Server svr;
  2348. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2349. res.set_content("Hello World!", "text/plain");
  2350. });
  2351. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2352. auto se = detail::scope_exit([&] {
  2353. svr.stop();
  2354. thread.join();
  2355. ASSERT_FALSE(svr.is_running());
  2356. });
  2357. svr.wait_until_ready();
  2358. Client cli(HOST, PORT);
  2359. cli.set_connection_timeout(std::chrono::seconds(5));
  2360. auto res =
  2361. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2362. "application/json", [](uint64_t, uint64_t) { return true; });
  2363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2364. EXPECT_EQ("Hello World!", res->body);
  2365. EXPECT_EQ(StatusCode::OK_200, res->status);
  2366. }
  2367. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2368. Server svr;
  2369. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2370. res.set_content("Hello World!", "text/plain");
  2371. });
  2372. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2373. auto se = detail::scope_exit([&] {
  2374. svr.stop();
  2375. thread.join();
  2376. ASSERT_FALSE(svr.is_running());
  2377. });
  2378. svr.wait_until_ready();
  2379. Client cli(HOST, PORT);
  2380. cli.set_connection_timeout(std::chrono::seconds(5));
  2381. auto res =
  2382. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2383. "application/json", [](uint64_t, uint64_t) { return false; });
  2384. ASSERT_TRUE(!res);
  2385. EXPECT_EQ(Error::Canceled, res.error());
  2386. }
  2387. TEST(CancelTest, WithCancelLargePayloadPut) {
  2388. Server svr;
  2389. svr.set_payload_max_length(200 * 1024 * 1024);
  2390. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2391. res.set_content(LARGE_DATA, "text/plain");
  2392. });
  2393. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2394. auto se = detail::scope_exit([&] {
  2395. svr.stop();
  2396. thread.join();
  2397. ASSERT_FALSE(svr.is_running());
  2398. });
  2399. svr.wait_until_ready();
  2400. Client cli(HOST, PORT);
  2401. cli.set_payload_max_length(200 * 1024 * 1024);
  2402. cli.set_connection_timeout(std::chrono::seconds(5));
  2403. auto res =
  2404. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2405. "application/json", [](uint64_t, uint64_t) { return false; });
  2406. ASSERT_TRUE(!res);
  2407. EXPECT_EQ(Error::Canceled, res.error());
  2408. }
  2409. TEST(CancelTest, NoCancelPatch) {
  2410. Server svr;
  2411. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2412. res.set_content("Hello World!", "text/plain");
  2413. });
  2414. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2415. auto se = detail::scope_exit([&] {
  2416. svr.stop();
  2417. thread.join();
  2418. ASSERT_FALSE(svr.is_running());
  2419. });
  2420. svr.wait_until_ready();
  2421. Client cli(HOST, PORT);
  2422. cli.set_connection_timeout(std::chrono::seconds(5));
  2423. auto res =
  2424. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2425. "application/json", [](uint64_t, uint64_t) { return true; });
  2426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2427. EXPECT_EQ("Hello World!", res->body);
  2428. EXPECT_EQ(StatusCode::OK_200, res->status);
  2429. }
  2430. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2431. Server svr;
  2432. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2433. res.set_content("Hello World!", "text/plain");
  2434. });
  2435. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2436. auto se = detail::scope_exit([&] {
  2437. svr.stop();
  2438. thread.join();
  2439. ASSERT_FALSE(svr.is_running());
  2440. });
  2441. svr.wait_until_ready();
  2442. Client cli(HOST, PORT);
  2443. cli.set_connection_timeout(std::chrono::seconds(5));
  2444. auto res =
  2445. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2446. "application/json", [](uint64_t, uint64_t) { return false; });
  2447. ASSERT_TRUE(!res);
  2448. EXPECT_EQ(Error::Canceled, res.error());
  2449. }
  2450. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2451. Server svr;
  2452. svr.set_payload_max_length(200 * 1024 * 1024);
  2453. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2454. res.set_content(LARGE_DATA, "text/plain");
  2455. });
  2456. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2457. auto se = detail::scope_exit([&] {
  2458. svr.stop();
  2459. thread.join();
  2460. ASSERT_FALSE(svr.is_running());
  2461. });
  2462. svr.wait_until_ready();
  2463. Client cli(HOST, PORT);
  2464. cli.set_payload_max_length(200 * 1024 * 1024);
  2465. cli.set_connection_timeout(std::chrono::seconds(5));
  2466. auto res =
  2467. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2468. "application/json", [](uint64_t, uint64_t) { return false; });
  2469. ASSERT_TRUE(!res);
  2470. EXPECT_EQ(Error::Canceled, res.error());
  2471. }
  2472. TEST(CancelTest, NoCancelDelete) {
  2473. Server svr;
  2474. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2475. res.set_content("Hello World!", "text/plain");
  2476. });
  2477. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2478. auto se = detail::scope_exit([&] {
  2479. svr.stop();
  2480. thread.join();
  2481. ASSERT_FALSE(svr.is_running());
  2482. });
  2483. svr.wait_until_ready();
  2484. Client cli(HOST, PORT);
  2485. cli.set_connection_timeout(std::chrono::seconds(5));
  2486. auto res =
  2487. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2488. "application/json", [](uint64_t, uint64_t) { return true; });
  2489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2490. EXPECT_EQ("Hello World!", res->body);
  2491. EXPECT_EQ(StatusCode::OK_200, res->status);
  2492. }
  2493. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2494. Server svr;
  2495. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2496. res.set_content("Hello World!", "text/plain");
  2497. });
  2498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2499. auto se = detail::scope_exit([&] {
  2500. svr.stop();
  2501. thread.join();
  2502. ASSERT_FALSE(svr.is_running());
  2503. });
  2504. svr.wait_until_ready();
  2505. Client cli(HOST, PORT);
  2506. cli.set_connection_timeout(std::chrono::seconds(5));
  2507. auto res =
  2508. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2509. "application/json", [](uint64_t, uint64_t) { return false; });
  2510. ASSERT_TRUE(!res);
  2511. EXPECT_EQ(Error::Canceled, res.error());
  2512. }
  2513. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2514. Server svr;
  2515. svr.set_payload_max_length(200 * 1024 * 1024);
  2516. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2517. res.set_content(LARGE_DATA, "text/plain");
  2518. });
  2519. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2520. auto se = detail::scope_exit([&] {
  2521. svr.stop();
  2522. thread.join();
  2523. ASSERT_FALSE(svr.is_running());
  2524. });
  2525. svr.wait_until_ready();
  2526. Client cli(HOST, PORT);
  2527. cli.set_payload_max_length(200 * 1024 * 1024);
  2528. cli.set_connection_timeout(std::chrono::seconds(5));
  2529. auto res =
  2530. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2531. "application/json", [](uint64_t, uint64_t) { return false; });
  2532. ASSERT_TRUE(!res);
  2533. EXPECT_EQ(Error::Canceled, res.error());
  2534. }
  2535. static std::string remove_whitespace(const std::string &input) {
  2536. std::string output;
  2537. output.reserve(input.size());
  2538. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2539. [](unsigned char c) { return !std::isspace(c); });
  2540. return output;
  2541. }
  2542. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2543. auto host = "httpbingo.org";
  2544. auto path = std::string{"/basic-auth/hello/world"};
  2545. #ifdef CPPHTTPLIB_SSL_ENABLED
  2546. auto port = 443;
  2547. SSLClient cli(host, port);
  2548. #else
  2549. auto port = 80;
  2550. Client cli(host, port);
  2551. #endif
  2552. {
  2553. auto res = cli.Get(path);
  2554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2555. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2556. }
  2557. {
  2558. auto res = cli.Get(
  2559. path, Headers{make_basic_authentication_header("hello", "world")});
  2560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2561. auto body = remove_whitespace(res->body);
  2562. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2563. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2564. EXPECT_EQ(StatusCode::OK_200, res->status);
  2565. }
  2566. {
  2567. cli.set_basic_auth("hello", "world");
  2568. auto res = cli.Get(path);
  2569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2570. auto body = remove_whitespace(res->body);
  2571. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2572. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2573. EXPECT_EQ(StatusCode::OK_200, res->status);
  2574. }
  2575. {
  2576. cli.set_basic_auth("hello", "bad");
  2577. auto res = cli.Get(path);
  2578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2579. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2580. }
  2581. {
  2582. cli.set_basic_auth("bad", "world");
  2583. auto res = cli.Get(path);
  2584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2585. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2586. }
  2587. }
  2588. #ifdef CPPHTTPLIB_SSL_ENABLED
  2589. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2590. auto host = "httpbingo.org";
  2591. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2592. auto paths = std::vector<std::string>{
  2593. "/digest-auth/auth/hello/world/MD5",
  2594. "/digest-auth/auth/hello/world/SHA-256",
  2595. };
  2596. auto port = 443;
  2597. SSLClient cli(host, port);
  2598. {
  2599. auto res = cli.Get(unauth_path);
  2600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2601. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2602. }
  2603. {
  2604. cli.set_digest_auth("hello", "world");
  2605. for (const auto &path : paths) {
  2606. auto res = cli.Get(path.c_str());
  2607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2608. auto body = remove_whitespace(res->body);
  2609. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2610. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2611. EXPECT_EQ(StatusCode::OK_200, res->status);
  2612. }
  2613. cli.set_digest_auth("hello", "bad");
  2614. for (const auto &path : paths) {
  2615. auto res = cli.Get(path.c_str());
  2616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2617. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2618. }
  2619. }
  2620. }
  2621. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2622. // comma-separated list of challenges, and each challenge may itself carry a
  2623. // comma-separated auth-param list, so a server can legally offer Basic
  2624. // before Digest, either as two field lines or packed into one. Runs one 401
  2625. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2626. // value() joins them in receipt order) and checks that the retry carries a
  2627. // well-formed Digest Authorization header naming expected_realm.
  2628. static void
  2629. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2630. const std::string &expected_realm) {
  2631. std::atomic<int> hits{0};
  2632. Server svr;
  2633. svr.Get("/x", [&](const Request &req, Response &res) {
  2634. if (++hits == 1) {
  2635. res.status = StatusCode::Unauthorized_401;
  2636. for (const auto &challenge : challenges) {
  2637. res.set_header("WWW-Authenticate", challenge);
  2638. }
  2639. } else {
  2640. auto authorization = req.get_header_value("Authorization");
  2641. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2642. EXPECT_NE(std::string::npos,
  2643. authorization.find("realm=\"" + expected_realm + "\""));
  2644. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2645. res.set_content("ok", "text/plain");
  2646. }
  2647. });
  2648. auto port = svr.bind_to_any_port(HOST);
  2649. std::thread t([&]() { svr.listen_after_bind(); });
  2650. auto se = detail::scope_exit([&] {
  2651. svr.stop();
  2652. t.join();
  2653. });
  2654. svr.wait_until_ready();
  2655. Client cli(HOST, port);
  2656. cli.set_digest_auth("hello", "world");
  2657. auto res = cli.Get("/x");
  2658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2659. EXPECT_EQ(2, hits.load());
  2660. }
  2661. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2662. static const char *kDigestChallenge =
  2663. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2664. "algorithm=MD5";
  2665. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2666. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2667. "testrealm");
  2668. }
  2669. // Same challenge list with the schemes in the opposite order, to make sure
  2670. // the fix above didn't just special-case "Basic first".
  2671. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2672. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2673. "testrealm");
  2674. }
  2675. // A comma inside a quoted auth-param value must not be mistaken for the
  2676. // separator between two challenges (or two auth-params).
  2677. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2678. run_digest_challenge_list_test(
  2679. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2680. "algorithm=MD5"},
  2681. "test,realm");
  2682. }
  2683. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2684. // make_digest_authentication_header() dereferences both unconditionally, so
  2685. // a server sending a challenge missing either one must not be treated as
  2686. // usable -- doing so used to crash the client with std::out_of_range.
  2687. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2688. Server svr;
  2689. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2690. res.status = StatusCode::Unauthorized_401;
  2691. res.set_header("WWW-Authenticate", challenge);
  2692. });
  2693. auto port = svr.bind_to_any_port(HOST);
  2694. std::thread t([&]() { svr.listen_after_bind(); });
  2695. auto se = detail::scope_exit([&] {
  2696. svr.stop();
  2697. t.join();
  2698. });
  2699. svr.wait_until_ready();
  2700. Client cli(HOST, port);
  2701. cli.set_digest_auth("hello", "world");
  2702. auto res = cli.Get("/x");
  2703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2704. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2705. }
  2706. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2707. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2708. }
  2709. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2710. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2711. }
  2712. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2713. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2714. }
  2715. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2716. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2717. // when storing the values, so the header builder has to re-escape them (and
  2718. // keep algorithm a bare token); otherwise the value breaks out of its
  2719. // quoted-string and injects extra auth-params into the client's Authorization.
  2720. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2721. std::atomic<int> hits{0};
  2722. std::string authorization;
  2723. Server svr;
  2724. svr.Get("/x", [&](const Request &req, Response &res) {
  2725. if (++hits == 1) {
  2726. res.status = StatusCode::Unauthorized_401;
  2727. // On the wire the quotes embedded in the values are backslash-escaped.
  2728. res.set_header("WWW-Authenticate",
  2729. "Digest realm=\"testrealm\", "
  2730. "nonce=\"n\\\"; injected=\\\"x\", "
  2731. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2732. } else {
  2733. authorization = req.get_header_value("Authorization");
  2734. res.set_content("ok", "text/plain");
  2735. }
  2736. });
  2737. auto port = svr.bind_to_any_port(HOST);
  2738. std::thread t([&]() { svr.listen_after_bind(); });
  2739. auto se = detail::scope_exit([&] {
  2740. svr.stop();
  2741. t.join();
  2742. });
  2743. svr.wait_until_ready();
  2744. Client cli(HOST, port);
  2745. cli.set_digest_auth("hello", "world");
  2746. auto res = cli.Get("/x");
  2747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2748. EXPECT_EQ(2, hits.load());
  2749. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2750. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2751. // inside its quoted-string rather than starting an "injected" auth-param.
  2752. EXPECT_NE(std::string::npos,
  2753. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2754. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2755. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2756. }
  2757. #endif
  2758. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2759. auto host = "google.com";
  2760. auto another_host = "example.com";
  2761. auto wrong_ip = "0.0.0.0";
  2762. #ifdef CPPHTTPLIB_SSL_ENABLED
  2763. SSLClient cli(host);
  2764. #else
  2765. Client cli(host);
  2766. #endif
  2767. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2768. auto res = cli.Get("/");
  2769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2770. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2771. }
  2772. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2773. auto host = "google.com";
  2774. auto wrong_ip = "0.0.0.0";
  2775. #ifdef CPPHTTPLIB_SSL_ENABLED
  2776. SSLClient cli(host);
  2777. #else
  2778. Client cli(host);
  2779. #endif
  2780. cli.set_hostname_addr_map({{host, wrong_ip}});
  2781. auto res = cli.Get("/");
  2782. ASSERT_TRUE(!res);
  2783. EXPECT_EQ(Error::Connection, res.error());
  2784. }
  2785. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2786. // A mapped value that is not an IP literal must be resolved. "localhost"
  2787. // resolves from the hosts file, so this test needs no external DNS.
  2788. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2789. auto host = "target.invalid";
  2790. Server svr;
  2791. std::string received_host;
  2792. svr.Get("/hi", [&](const Request &req, Response &res) {
  2793. received_host = req.get_header_value("Host");
  2794. res.set_content("Hello World!", "text/plain");
  2795. });
  2796. auto port = svr.bind_to_any_port(HOST);
  2797. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2798. auto se = detail::scope_exit([&] {
  2799. svr.stop();
  2800. thread.join();
  2801. ASSERT_FALSE(svr.is_running());
  2802. });
  2803. svr.wait_until_ready();
  2804. Client cli(host, port);
  2805. cli.set_hostname_addr_map({{host, HOST}});
  2806. auto res = cli.Get("/hi");
  2807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2808. EXPECT_EQ(StatusCode::OK_200, res->status);
  2809. // The mapping only redirects the connection; the identity stays host_.
  2810. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2811. }
  2812. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2813. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2814. auto host = "target.invalid";
  2815. Server svr;
  2816. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2817. res.set_content("Hello World!", "text/plain");
  2818. });
  2819. auto port = svr.bind_to_any_port("127.0.0.1");
  2820. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2821. auto se = detail::scope_exit([&] {
  2822. svr.stop();
  2823. thread.join();
  2824. ASSERT_FALSE(svr.is_running());
  2825. });
  2826. svr.wait_until_ready();
  2827. Client cli(host, port);
  2828. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2829. auto res = cli.Get("/hi");
  2830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2831. EXPECT_EQ(StatusCode::OK_200, res->status);
  2832. }
  2833. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2834. // An empty mapped value must leave host_ as the connection target. Without
  2835. // that guard the empty value would become the host argument, getaddrinfo
  2836. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2837. // loopback - silently connecting somewhere the caller never asked for.
  2838. // The server listens on loopback, so such a fallback would succeed and is
  2839. // therefore observable as a failure of this test.
  2840. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2841. Server svr;
  2842. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2843. res.set_content("Hello World!", "text/plain");
  2844. });
  2845. auto port = svr.bind_to_any_port(HOST);
  2846. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2847. auto se = detail::scope_exit([&] {
  2848. svr.stop();
  2849. thread.join();
  2850. ASSERT_FALSE(svr.is_running());
  2851. });
  2852. svr.wait_until_ready();
  2853. Client cli(blackhole, port);
  2854. cli.set_hostname_addr_map({{blackhole, ""}});
  2855. cli.set_connection_timeout(1);
  2856. auto res = cli.Get("/hi");
  2857. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2858. }
  2859. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2860. auto host = "httpbingo.org";
  2861. auto path = std::string{"/absolute-redirect/3"};
  2862. #ifdef CPPHTTPLIB_SSL_ENABLED
  2863. SSLClient cli(host);
  2864. #else
  2865. Client cli(host);
  2866. #endif
  2867. cli.set_follow_location(true);
  2868. auto res = cli.Get(path);
  2869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2870. EXPECT_EQ(StatusCode::OK_200, res->status);
  2871. }
  2872. TEST(RedirectTest, Redirect_Online) {
  2873. auto host = "httpbingo.org";
  2874. auto path = std::string{"/redirect/3"};
  2875. #ifdef CPPHTTPLIB_SSL_ENABLED
  2876. SSLClient cli(host);
  2877. #else
  2878. Client cli(host);
  2879. #endif
  2880. cli.set_follow_location(true);
  2881. auto res = cli.Get(path);
  2882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2883. EXPECT_EQ(StatusCode::OK_200, res->status);
  2884. }
  2885. TEST(RelativeRedirectTest, Redirect_Online) {
  2886. auto host = "httpbingo.org";
  2887. auto path = std::string{"/relative-redirect/3"};
  2888. #ifdef CPPHTTPLIB_SSL_ENABLED
  2889. SSLClient cli(host);
  2890. #else
  2891. Client cli(host);
  2892. #endif
  2893. cli.set_follow_location(true);
  2894. auto res = cli.Get(path);
  2895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2896. EXPECT_EQ(StatusCode::OK_200, res->status);
  2897. }
  2898. TEST(TooManyRedirectTest, Redirect_Online) {
  2899. auto host = "httpbingo.org";
  2900. auto path = std::string{"/redirect/21"};
  2901. #ifdef CPPHTTPLIB_SSL_ENABLED
  2902. SSLClient cli(host);
  2903. #else
  2904. Client cli(host);
  2905. #endif
  2906. cli.set_follow_location(true);
  2907. auto res = cli.Get(path);
  2908. ASSERT_TRUE(!res);
  2909. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2910. }
  2911. #ifdef CPPHTTPLIB_SSL_ENABLED
  2912. TEST(YahooRedirectTest, Redirect_Online) {
  2913. Client cli("yahoo.com");
  2914. auto res = cli.Get("/");
  2915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2916. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2917. cli.set_follow_location(true);
  2918. res = cli.Get("/");
  2919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2920. EXPECT_EQ(StatusCode::OK_200, res->status);
  2921. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2922. }
  2923. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2924. #define REDIR_HOST "httpbingo.org"
  2925. #define REDIR_PATH "/redirect-to"
  2926. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2927. SSLClient cli(REDIR_HOST);
  2928. cli.set_follow_location(true);
  2929. auto res =
  2930. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2932. EXPECT_EQ(StatusCode::OK_200, res->status);
  2933. }
  2934. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2935. SSLClient cli(REDIR_HOST);
  2936. cli.set_follow_location(true);
  2937. Params params;
  2938. params.emplace("url", "http://example.com");
  2939. params.emplace("status_code", "302");
  2940. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2942. EXPECT_EQ(StatusCode::OK_200, res->status);
  2943. }
  2944. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2945. SSLClient cli(REDIR_HOST);
  2946. cli.set_follow_location(true);
  2947. Params params;
  2948. params.emplace("url", "http://example.com");
  2949. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2951. EXPECT_EQ(StatusCode::OK_200, res->status);
  2952. }
  2953. TEST(UrlWithSpace, Redirect_Online) {
  2954. SSLClient cli("edge.forgecdn.net");
  2955. cli.set_follow_location(true);
  2956. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2958. EXPECT_EQ(StatusCode::OK_200, res->status);
  2959. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2960. }
  2961. #endif
  2962. #if !defined(_WIN32) && !defined(_WIN64)
  2963. TEST(ReceiveSignals, Signal) {
  2964. auto setupSignalHandlers = []() {
  2965. struct sigaction act;
  2966. sigemptyset(&act.sa_mask);
  2967. act.sa_flags = SA_SIGINFO;
  2968. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2969. switch (sig) {
  2970. case SIGINT:
  2971. default: break;
  2972. }
  2973. };
  2974. ::sigaction(SIGINT, &act, nullptr);
  2975. };
  2976. Server svr;
  2977. int port = 0;
  2978. auto thread = std::thread([&]() {
  2979. setupSignalHandlers();
  2980. port = svr.bind_to_any_port(HOST);
  2981. svr.listen_after_bind();
  2982. });
  2983. auto se = detail::scope_exit([&] {
  2984. svr.stop();
  2985. thread.join();
  2986. ASSERT_FALSE(svr.is_running());
  2987. });
  2988. svr.wait_until_ready();
  2989. ASSERT_TRUE(svr.is_running());
  2990. pthread_kill(thread.native_handle(), SIGINT);
  2991. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2992. ASSERT_TRUE(svr.is_running());
  2993. }
  2994. #endif
  2995. TEST(RedirectToDifferentPort, Redirect) {
  2996. Server svr1;
  2997. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2998. res.set_content("Hello World!", "text/plain");
  2999. });
  3000. int svr1_port = 0;
  3001. auto thread1 = std::thread([&]() {
  3002. svr1_port = svr1.bind_to_any_port(HOST);
  3003. svr1.listen_after_bind();
  3004. });
  3005. Server svr2;
  3006. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3007. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3008. });
  3009. int svr2_port = 0;
  3010. auto thread2 = std::thread([&]() {
  3011. svr2_port = svr2.bind_to_any_port(HOST);
  3012. svr2.listen_after_bind();
  3013. });
  3014. auto se = detail::scope_exit([&] {
  3015. svr2.stop();
  3016. thread2.join();
  3017. svr1.stop();
  3018. thread1.join();
  3019. ASSERT_FALSE(svr2.is_running());
  3020. ASSERT_FALSE(svr1.is_running());
  3021. });
  3022. svr1.wait_until_ready();
  3023. svr2.wait_until_ready();
  3024. Client cli("localhost", svr2_port);
  3025. cli.set_follow_location(true);
  3026. auto res = cli.Get("/2");
  3027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3028. EXPECT_EQ(StatusCode::OK_200, res->status);
  3029. EXPECT_EQ("Hello World!", res->body);
  3030. }
  3031. static void
  3032. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3033. Server svr1;
  3034. std::string captured_authorization;
  3035. svr1.Get("/target", [&](const Request &req, Response &res) {
  3036. captured_authorization = req.get_header_value("Authorization");
  3037. res.set_content("OK", "text/plain");
  3038. });
  3039. int svr1_port = 0;
  3040. auto thread1 = std::thread([&]() {
  3041. svr1_port = svr1.bind_to_any_port(HOST);
  3042. svr1.listen_after_bind();
  3043. });
  3044. Server svr2;
  3045. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3046. res.set_redirect(
  3047. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3048. });
  3049. int svr2_port = 0;
  3050. auto thread2 = std::thread([&]() {
  3051. svr2_port = svr2.bind_to_any_port(HOST);
  3052. svr2.listen_after_bind();
  3053. });
  3054. auto se = detail::scope_exit([&] {
  3055. svr2.stop();
  3056. thread2.join();
  3057. svr1.stop();
  3058. thread1.join();
  3059. ASSERT_FALSE(svr2.is_running());
  3060. ASSERT_FALSE(svr1.is_running());
  3061. });
  3062. svr1.wait_until_ready();
  3063. svr2.wait_until_ready();
  3064. Client cli("localhost", svr2_port);
  3065. cli.set_follow_location(true);
  3066. set_auth(cli);
  3067. auto res = cli.Get("/redir");
  3068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3069. EXPECT_EQ(StatusCode::OK_200, res->status);
  3070. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3071. EXPECT_TRUE(captured_authorization.empty());
  3072. }
  3073. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3074. TestDoNotForwardCredentialsOnRedirect(
  3075. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3076. }
  3077. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3078. TestDoNotForwardCredentialsOnRedirect(
  3079. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3080. }
  3081. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3082. Server svr1;
  3083. std::string captured_cookie;
  3084. bool target_hit = false;
  3085. svr1.Get("/target", [&](const Request &req, Response &res) {
  3086. captured_cookie = req.get_header_value("Cookie");
  3087. target_hit = true;
  3088. res.set_content("OK", "text/plain");
  3089. });
  3090. int svr1_port = 0;
  3091. auto thread1 = std::thread([&]() {
  3092. svr1_port = svr1.bind_to_any_port(HOST);
  3093. svr1.listen_after_bind();
  3094. });
  3095. Server svr2;
  3096. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3097. res.set_redirect(
  3098. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3099. });
  3100. int svr2_port = 0;
  3101. auto thread2 = std::thread([&]() {
  3102. svr2_port = svr2.bind_to_any_port(HOST);
  3103. svr2.listen_after_bind();
  3104. });
  3105. auto se = detail::scope_exit([&] {
  3106. svr2.stop();
  3107. thread2.join();
  3108. svr1.stop();
  3109. thread1.join();
  3110. ASSERT_FALSE(svr2.is_running());
  3111. ASSERT_FALSE(svr1.is_running());
  3112. });
  3113. svr1.wait_until_ready();
  3114. svr2.wait_until_ready();
  3115. Client cli("localhost", svr2_port);
  3116. cli.set_follow_location(true);
  3117. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3118. auto res = cli.Get("/redir", headers);
  3119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3120. EXPECT_EQ(StatusCode::OK_200, res->status);
  3121. EXPECT_TRUE(target_hit);
  3122. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3123. EXPECT_TRUE(captured_cookie.empty());
  3124. }
  3125. TEST(RedirectToSamePort, ForwardCookie) {
  3126. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3127. // header so that ordinary session flows keep working.
  3128. Server svr;
  3129. std::string captured_cookie;
  3130. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3131. res.set_redirect("/target", 302);
  3132. });
  3133. svr.Get("/target", [&](const Request &req, Response &res) {
  3134. captured_cookie = req.get_header_value("Cookie");
  3135. res.set_content("OK", "text/plain");
  3136. });
  3137. auto port = svr.bind_to_any_port(HOST);
  3138. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3139. auto se = detail::scope_exit([&] {
  3140. svr.stop();
  3141. thread.join();
  3142. ASSERT_FALSE(svr.is_running());
  3143. });
  3144. svr.wait_until_ready();
  3145. Client cli(HOST, port);
  3146. cli.set_follow_location(true);
  3147. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3148. auto res = cli.Get("/redir", headers);
  3149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3150. EXPECT_EQ(StatusCode::OK_200, res->status);
  3151. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3152. }
  3153. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3154. Server svr;
  3155. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3156. // Port number that overflows int — should not crash
  3157. res.set_redirect("http://localhost:99999999999999999999/target");
  3158. });
  3159. auto port = svr.bind_to_any_port(HOST);
  3160. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3161. auto se = detail::scope_exit([&] {
  3162. svr.stop();
  3163. thread.join();
  3164. ASSERT_FALSE(svr.is_running());
  3165. });
  3166. svr.wait_until_ready();
  3167. Client cli(HOST, port);
  3168. cli.set_follow_location(true);
  3169. auto res = cli.Get("/redir");
  3170. // Should fail gracefully, not crash (no valid response due to bad port)
  3171. EXPECT_FALSE(res);
  3172. }
  3173. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3174. Server svr;
  3175. auto port = svr.bind_to_any_port(HOST);
  3176. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3177. // The server's own port followed by junk must not be followed
  3178. res.set_redirect("http://" + std::string(HOST) + ":" +
  3179. std::to_string(port) + "junk/target");
  3180. });
  3181. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3182. res.set_content("target", "text/plain");
  3183. });
  3184. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3185. auto se = detail::scope_exit([&] {
  3186. svr.stop();
  3187. thread.join();
  3188. ASSERT_FALSE(svr.is_running());
  3189. });
  3190. svr.wait_until_ready();
  3191. Client cli(HOST, port);
  3192. cli.set_follow_location(true);
  3193. auto res = cli.Get("/redir");
  3194. EXPECT_FALSE(res);
  3195. }
  3196. TEST(RedirectFromPageWithContent, Redirect) {
  3197. Server svr;
  3198. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3199. res.set_content("___", "text/plain");
  3200. res.set_redirect("/2");
  3201. });
  3202. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3203. res.set_content("Hello World!", "text/plain");
  3204. });
  3205. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3206. auto se = detail::scope_exit([&] {
  3207. svr.stop();
  3208. th.join();
  3209. ASSERT_FALSE(svr.is_running());
  3210. });
  3211. svr.wait_until_ready();
  3212. {
  3213. Client cli("localhost", PORT);
  3214. cli.set_follow_location(true);
  3215. std::string body;
  3216. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3217. body.append(data, data_length);
  3218. return true;
  3219. });
  3220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. EXPECT_EQ("Hello World!", body);
  3223. }
  3224. {
  3225. Client cli("localhost", PORT);
  3226. std::string body;
  3227. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3228. body.append(data, data_length);
  3229. return true;
  3230. });
  3231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3232. EXPECT_EQ(StatusCode::Found_302, res->status);
  3233. EXPECT_EQ("___", body);
  3234. }
  3235. }
  3236. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3237. Server svr;
  3238. auto port_str = std::to_string(PORT);
  3239. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3240. auto expected_host = "[::1]:" + port_str;
  3241. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3242. res.set_content("___", "text/plain");
  3243. // res.set_redirect("/2");
  3244. res.set_redirect(redirect_url);
  3245. });
  3246. svr.Get("/2", [&](const Request &req, Response &res) {
  3247. auto host_header = req.headers.find("Host");
  3248. ASSERT_TRUE(host_header != req.headers.end());
  3249. EXPECT_EQ(expected_host, host_header->second);
  3250. res.set_content("Hello World!", "text/plain");
  3251. });
  3252. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3253. auto se = detail::scope_exit([&] {
  3254. svr.stop();
  3255. th.join();
  3256. ASSERT_FALSE(svr.is_running());
  3257. });
  3258. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3259. // actually starts anything, so the condition !svr.is_running() will
  3260. // always remain true, and the loop never stops.
  3261. // This basically counts how many milliseconds have passed since the
  3262. // call to svr.listen(), and if after 5 seconds nothing started yet
  3263. // aborts the test.
  3264. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3265. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3266. ASSERT_LT(milliseconds, 5000U);
  3267. }
  3268. {
  3269. Client cli("::1", PORT);
  3270. cli.set_follow_location(true);
  3271. std::string body;
  3272. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3273. body.append(data, data_length);
  3274. return true;
  3275. });
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. EXPECT_EQ("Hello World!", body);
  3279. }
  3280. {
  3281. Client cli("::1", PORT);
  3282. std::string body;
  3283. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3284. body.append(data, data_length);
  3285. return true;
  3286. });
  3287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3288. EXPECT_EQ(StatusCode::Found_302, res->status);
  3289. EXPECT_EQ("___", body);
  3290. }
  3291. }
  3292. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3293. Server svr;
  3294. svr.Get("/foo", [](const Request &req, Response &res) {
  3295. auto a = req.params.find("a");
  3296. if (a != req.params.end()) {
  3297. res.set_content((*a).second, "text/plain");
  3298. res.status = StatusCode::OK_200;
  3299. } else {
  3300. res.status = StatusCode::BadRequest_400;
  3301. }
  3302. });
  3303. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3304. auto se = detail::scope_exit([&] {
  3305. svr.stop();
  3306. thread.join();
  3307. ASSERT_FALSE(svr.is_running());
  3308. });
  3309. svr.wait_until_ready();
  3310. {
  3311. Client cli(HOST, PORT);
  3312. cli.set_path_encode(false);
  3313. auto res = cli.Get("/foo?a=explicitly+encoded");
  3314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3315. EXPECT_EQ(StatusCode::OK_200, res->status);
  3316. // This expects it back with a space, as the `+` won't have been
  3317. // url-encoded, and server-side the params get decoded turning `+`
  3318. // into spaces.
  3319. EXPECT_EQ("explicitly encoded", res->body);
  3320. }
  3321. }
  3322. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3323. // When path encoding is disabled the client must transmit the supplied
  3324. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3325. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3326. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3327. // than a space (0x20). Assert on the raw wire target to catch this.
  3328. Server svr;
  3329. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3330. svr.Get("/foo", [&](const Request &req, Response &res) {
  3331. EXPECT_EQ(expected_target, req.target);
  3332. res.status = StatusCode::OK_200;
  3333. });
  3334. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3335. auto se = detail::scope_exit([&] {
  3336. svr.stop();
  3337. thread.join();
  3338. ASSERT_FALSE(svr.is_running());
  3339. });
  3340. svr.wait_until_ready();
  3341. {
  3342. Client cli(HOST, PORT);
  3343. cli.set_path_encode(false);
  3344. auto res = cli.Get(expected_target.c_str());
  3345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3346. EXPECT_EQ(StatusCode::OK_200, res->status);
  3347. }
  3348. }
  3349. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3350. // `open_stream()` used to skip the path encoding that the buffered send
  3351. // path applies, so the same `path` produced different bytes in the request
  3352. // line depending on which API was used. Assert the two agree.
  3353. Server svr;
  3354. std::string target;
  3355. svr.Get(".*", [&](const Request &req, Response &res) {
  3356. target = req.target;
  3357. res.status = StatusCode::OK_200;
  3358. });
  3359. auto port = svr.bind_to_any_port(HOST);
  3360. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3361. auto se = detail::scope_exit([&] {
  3362. svr.stop();
  3363. thread.join();
  3364. ASSERT_FALSE(svr.is_running());
  3365. });
  3366. svr.wait_until_ready();
  3367. struct {
  3368. const char *path;
  3369. const char *expected;
  3370. } cases[] = {
  3371. {"/a b?x=1", "/a%20b?x=1"},
  3372. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3373. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3374. };
  3375. for (const auto &c : cases) {
  3376. Client cli(HOST, port);
  3377. target.clear();
  3378. auto res = cli.Get(c.path);
  3379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3380. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3381. auto buffered_target = target;
  3382. target.clear();
  3383. auto handle = cli.open_stream("GET", c.path);
  3384. EXPECT_TRUE(handle.is_valid())
  3385. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3386. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3387. }
  3388. }
  3389. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3390. // The `set_path_encode(false)` contract — transmit the supplied target
  3391. // verbatim — must hold for the streaming API too.
  3392. Server svr;
  3393. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3394. std::string target;
  3395. svr.Get("/foo", [&](const Request &req, Response &res) {
  3396. target = req.target;
  3397. res.status = StatusCode::OK_200;
  3398. });
  3399. auto port = svr.bind_to_any_port(HOST);
  3400. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3401. auto se = detail::scope_exit([&] {
  3402. svr.stop();
  3403. thread.join();
  3404. ASSERT_FALSE(svr.is_running());
  3405. });
  3406. svr.wait_until_ready();
  3407. {
  3408. Client cli(HOST, port);
  3409. cli.set_path_encode(false);
  3410. auto handle = cli.open_stream("GET", expected_target);
  3411. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3412. EXPECT_EQ(expected_target, target);
  3413. }
  3414. }
  3415. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3416. // With path encoding enabled a CR/LF in the target is percent-encoded
  3417. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3418. // write_request_line still backstops `set_path_encode(false)`, which is
  3419. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3420. Server svr;
  3421. // Captured before routing: the decoded path contains a newline, which a
  3422. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3423. std::string target;
  3424. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3425. target = req.target;
  3426. res.status = StatusCode::OK_200;
  3427. return Server::HandlerResponse::Handled;
  3428. });
  3429. auto port = svr.bind_to_any_port(HOST);
  3430. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3431. auto se = detail::scope_exit([&] {
  3432. svr.stop();
  3433. thread.join();
  3434. ASSERT_FALSE(svr.is_running());
  3435. });
  3436. svr.wait_until_ready();
  3437. {
  3438. Client cli(HOST, port);
  3439. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3440. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3441. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3442. }
  3443. }
  3444. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3445. // Every control character is percent-encoded, not just CR/LF, so the target
  3446. // passes the request-target check in write_request_line.
  3447. Server svr;
  3448. std::string target;
  3449. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3450. target = req.target;
  3451. res.status = StatusCode::OK_200;
  3452. return Server::HandlerResponse::Handled;
  3453. });
  3454. auto port = svr.bind_to_any_port(HOST);
  3455. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3456. auto se = detail::scope_exit([&] {
  3457. svr.stop();
  3458. thread.join();
  3459. ASSERT_FALSE(svr.is_running());
  3460. });
  3461. svr.wait_until_ready();
  3462. {
  3463. Client cli(HOST, port);
  3464. auto res = cli.Get("/a\tb\x1b\x7f");
  3465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3466. EXPECT_EQ("/a%09b%1B%7F", target);
  3467. }
  3468. }
  3469. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3470. // Nothing may reach the wire: a raw CR/LF target would split the request
  3471. // line and inject headers.
  3472. Server svr;
  3473. // Pre-routing so that "not called" means nothing reached the server at all,
  3474. // rather than merely failing to match a handler pattern.
  3475. auto handler_called = false;
  3476. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3477. handler_called = true;
  3478. res.status = StatusCode::OK_200;
  3479. return Server::HandlerResponse::Handled;
  3480. });
  3481. auto port = svr.bind_to_any_port(HOST);
  3482. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3483. auto se = detail::scope_exit([&] {
  3484. svr.stop();
  3485. thread.join();
  3486. ASSERT_FALSE(svr.is_running());
  3487. });
  3488. svr.wait_until_ready();
  3489. {
  3490. Client cli(HOST, port);
  3491. cli.set_path_encode(false);
  3492. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3493. EXPECT_FALSE(handle.is_valid());
  3494. EXPECT_EQ(Error::Write, handle.error);
  3495. EXPECT_FALSE(handler_called);
  3496. }
  3497. }
  3498. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3499. // Which of the two branches runs is decided by whether the query component
  3500. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3501. // an empty query and must still fall back to building one from
  3502. // `req.params`, while a non-empty query must win over `req.params`.
  3503. Server svr;
  3504. std::string target;
  3505. svr.Get("/foo", [&](const Request &req, Response &res) {
  3506. target = req.target;
  3507. res.status = StatusCode::OK_200;
  3508. });
  3509. auto port = svr.bind_to_any_port(HOST);
  3510. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3511. auto se = detail::scope_exit([&] {
  3512. svr.stop();
  3513. thread.join();
  3514. ASSERT_FALSE(svr.is_running());
  3515. });
  3516. svr.wait_until_ready();
  3517. {
  3518. // Trailing `?` -> empty query component -> `req.params` is used.
  3519. Client cli(HOST, port);
  3520. Request req;
  3521. req.method = "GET";
  3522. req.path = "/foo?";
  3523. req.params.emplace("a", "1");
  3524. target.clear();
  3525. auto res = cli.send(req);
  3526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3527. EXPECT_EQ("/foo?a=1", target);
  3528. }
  3529. {
  3530. // Non-empty query in `req.path` -> `req.params` is not appended.
  3531. Client cli(HOST, port);
  3532. Request req;
  3533. req.method = "GET";
  3534. req.path = "/foo?b=2";
  3535. req.params.emplace("a", "1");
  3536. target.clear();
  3537. auto res = cli.send(req);
  3538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3539. EXPECT_EQ("/foo?b=2", target);
  3540. }
  3541. }
  3542. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3543. Server svr;
  3544. svr.Get("/", [](const Request &req, Response &) {
  3545. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3546. });
  3547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3548. auto se = detail::scope_exit([&] {
  3549. svr.stop();
  3550. thread.join();
  3551. ASSERT_FALSE(svr.is_running());
  3552. });
  3553. svr.wait_until_ready();
  3554. {
  3555. Client cli(HOST, PORT);
  3556. cli.set_path_encode(false);
  3557. auto res = cli.Get("/?something=%0A");
  3558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3559. EXPECT_EQ(StatusCode::OK_200, res->status);
  3560. }
  3561. }
  3562. TEST(BindServerTest, BindDualStack) {
  3563. Server svr;
  3564. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3565. res.set_content("Hello World!", "text/plain");
  3566. });
  3567. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3568. auto se = detail::scope_exit([&] {
  3569. svr.stop();
  3570. thread.join();
  3571. ASSERT_FALSE(svr.is_running());
  3572. });
  3573. svr.wait_until_ready();
  3574. {
  3575. Client cli("127.0.0.1", PORT);
  3576. auto res = cli.Get("/1");
  3577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3578. EXPECT_EQ(StatusCode::OK_200, res->status);
  3579. EXPECT_EQ("Hello World!", res->body);
  3580. }
  3581. {
  3582. Client cli("::1", PORT);
  3583. auto res = cli.Get("/1");
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ(StatusCode::OK_200, res->status);
  3586. EXPECT_EQ("Hello World!", res->body);
  3587. }
  3588. }
  3589. TEST(BindServerTest, BindAndListenSeparately) {
  3590. Server svr;
  3591. int port = svr.bind_to_any_port("0.0.0.0");
  3592. ASSERT_TRUE(svr.is_valid());
  3593. ASSERT_TRUE(port > 0);
  3594. svr.stop();
  3595. }
  3596. // Reports whether anything is still listening on a loopback port. A plain
  3597. // connect() is used instead of a Client request because a socket left bound by
  3598. // mistake accepts the connection into its backlog and never answers, which
  3599. // would hang the test instead of failing it.
  3600. static bool is_loopback_port_accepting(int port) {
  3601. sockaddr_in addr{};
  3602. addr.sin_family = AF_INET;
  3603. addr.sin_port = htons(static_cast<uint16_t>(port));
  3604. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3605. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3606. EXPECT_NE(sock, INVALID_SOCKET);
  3607. if (sock == INVALID_SOCKET) { return false; }
  3608. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3609. static_cast<socklen_t>(sizeof(addr)));
  3610. detail::close_socket(sock);
  3611. return ret == 0;
  3612. }
  3613. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3614. Server svr;
  3615. auto port = svr.bind_to_any_port("127.0.0.1");
  3616. ASSERT_TRUE(port > 0);
  3617. svr.stop();
  3618. // bind_to_any_port() already called listen(2), so until stop() closed the
  3619. // descriptor the port kept accepting connections into the backlog. ASSERT
  3620. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3621. // below blocks forever in the accept loop.
  3622. ASSERT_FALSE(is_loopback_port_accepting(port));
  3623. // Nothing is left to accept on, so listen_after_bind() must report failure
  3624. // instead of returning success without ever serving.
  3625. EXPECT_FALSE(svr.listen_after_bind());
  3626. // The failed listen marks the server decommissioned, so a waiter returns
  3627. // instead of spinning forever.
  3628. svr.wait_until_ready();
  3629. }
  3630. #ifdef CPPHTTPLIB_SSL_ENABLED
  3631. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3632. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3633. CLIENT_CA_CERT_DIR);
  3634. int port = svr.bind_to_any_port("0.0.0.0");
  3635. ASSERT_TRUE(svr.is_valid());
  3636. ASSERT_TRUE(port > 0);
  3637. svr.stop();
  3638. }
  3639. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3640. // or a rejected CustomRoute() registration would not stop the server binding.
  3641. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3642. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3643. CLIENT_CA_CERT_DIR);
  3644. ASSERT_TRUE(svr.is_valid());
  3645. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3646. EXPECT_FALSE(svr.is_valid());
  3647. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3648. }
  3649. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3650. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3651. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3652. int port = svr.bind_to_any_port("0.0.0.0");
  3653. ASSERT_TRUE(svr.is_valid());
  3654. ASSERT_TRUE(port > 0);
  3655. svr.stop();
  3656. }
  3657. TEST(BindServerTest, UpdateCertsPem) {
  3658. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3659. int port = svr.bind_to_any_port("0.0.0.0");
  3660. ASSERT_TRUE(svr.is_valid());
  3661. ASSERT_TRUE(port > 0);
  3662. // Read PEM files
  3663. std::string cert_pem, key_pem, ca_pem;
  3664. read_file(SERVER_CERT_FILE, cert_pem);
  3665. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3666. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3667. // Update server certificates using PEM API
  3668. ASSERT_TRUE(
  3669. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3670. ASSERT_TRUE(svr.is_valid());
  3671. svr.stop();
  3672. }
  3673. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3674. // Start server with client CA (enables client auth)
  3675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3676. ASSERT_TRUE(svr.is_valid());
  3677. bool handler_called = false;
  3678. svr.Get("/test", [&](const Request &req, Response &res) {
  3679. handler_called = true;
  3680. // Verify client certificate is present
  3681. auto cert = req.peer_cert();
  3682. EXPECT_TRUE(static_cast<bool>(cert));
  3683. res.set_content("ok", "text/plain");
  3684. });
  3685. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3686. auto se = detail::scope_exit([&] {
  3687. svr.stop();
  3688. t.join();
  3689. ASSERT_FALSE(svr.is_running());
  3690. });
  3691. svr.wait_until_ready();
  3692. // Read PEM files
  3693. std::string cert_pem, key_pem, ca_pem;
  3694. read_file(SERVER_CERT_FILE, cert_pem);
  3695. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3696. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3697. // Update server certificates and client CA using PEM API while server running
  3698. ASSERT_TRUE(
  3699. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3700. // Connect with client certificate
  3701. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3702. cli.enable_server_certificate_verification(false);
  3703. cli.set_connection_timeout(30);
  3704. auto res = cli.Get("/test");
  3705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3706. ASSERT_EQ(StatusCode::OK_200, res->status);
  3707. ASSERT_TRUE(handler_called);
  3708. EXPECT_EQ("ok", res->body);
  3709. }
  3710. #endif
  3711. TEST(ErrorHandlerTest, ContentLength) {
  3712. Server svr;
  3713. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3714. res.status = StatusCode::OK_200;
  3715. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3716. "text/html"); // <= Content-Length still 13
  3717. });
  3718. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3719. res.set_content("Hello World!\n", "text/plain");
  3720. res.status = 524;
  3721. });
  3722. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3723. auto se = detail::scope_exit([&] {
  3724. svr.stop();
  3725. thread.join();
  3726. ASSERT_FALSE(svr.is_running());
  3727. });
  3728. svr.wait_until_ready();
  3729. {
  3730. Client cli(HOST, PORT);
  3731. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ(StatusCode::OK_200, res->status);
  3734. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3735. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3736. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3737. }
  3738. }
  3739. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3740. TEST(ExceptionTest, WithoutExceptionHandler) {
  3741. Server svr;
  3742. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3743. throw std::runtime_error("exception...");
  3744. });
  3745. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3746. throw std::runtime_error("exception\r\n...");
  3747. });
  3748. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3749. auto se = detail::scope_exit([&] {
  3750. svr.stop();
  3751. listen_thread.join();
  3752. ASSERT_FALSE(svr.is_running());
  3753. });
  3754. svr.wait_until_ready();
  3755. Client cli("localhost", PORT);
  3756. {
  3757. auto res = cli.Get("/exception");
  3758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3759. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3760. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3761. }
  3762. {
  3763. auto res = cli.Get("/unknown");
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3766. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3767. }
  3768. }
  3769. TEST(ExceptionTest, WithExceptionHandler) {
  3770. Server svr;
  3771. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3772. std::exception_ptr ep) {
  3773. EXPECT_FALSE(ep == nullptr);
  3774. try {
  3775. std::rethrow_exception(ep);
  3776. } catch (std::exception &e) {
  3777. EXPECT_EQ("abc", std::string(e.what()));
  3778. } catch (...) {}
  3779. res.status = StatusCode::InternalServerError_500;
  3780. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3781. "text/html"); // <= Content-Length still 13 at this point
  3782. });
  3783. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3784. res.set_content("Hello World!\n", "text/plain");
  3785. throw std::runtime_error("abc");
  3786. });
  3787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3788. auto se = detail::scope_exit([&] {
  3789. svr.stop();
  3790. thread.join();
  3791. ASSERT_FALSE(svr.is_running());
  3792. });
  3793. svr.wait_until_ready();
  3794. for (size_t i = 0; i < 10; i++) {
  3795. Client cli(HOST, PORT);
  3796. for (size_t j = 0; j < 100; j++) {
  3797. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3799. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3800. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3801. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3802. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3803. }
  3804. cli.set_keep_alive(true);
  3805. for (size_t j = 0; j < 100; j++) {
  3806. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3808. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3809. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3810. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3811. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3812. }
  3813. }
  3814. }
  3815. TEST(ExceptionTest, AndErrorHandler) {
  3816. Server svr;
  3817. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3818. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3819. });
  3820. svr.set_exception_handler(
  3821. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3822. EXPECT_FALSE(ep == nullptr);
  3823. try {
  3824. std::rethrow_exception(ep);
  3825. } catch (std::exception &e) {
  3826. res.set_content(e.what(), "text/html");
  3827. } catch (...) {}
  3828. res.status = StatusCode::InternalServerError_500;
  3829. });
  3830. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3831. throw std::runtime_error("EXCEPTION");
  3832. });
  3833. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3834. res.set_content("ERROR", "text/html");
  3835. res.status = StatusCode::InternalServerError_500;
  3836. });
  3837. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3838. auto se = detail::scope_exit([&] {
  3839. svr.stop();
  3840. thread.join();
  3841. ASSERT_FALSE(svr.is_running());
  3842. });
  3843. svr.wait_until_ready();
  3844. Client cli(HOST, PORT);
  3845. {
  3846. auto res = cli.Get("/exception");
  3847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3848. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3849. EXPECT_EQ("EXCEPTION", res->body);
  3850. }
  3851. {
  3852. auto res = cli.Get("/error");
  3853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3854. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3855. EXPECT_EQ("ERROR", res->body);
  3856. }
  3857. {
  3858. auto res = cli.Get("/invalid");
  3859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3860. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3861. EXPECT_EQ("NOT_FOUND", res->body);
  3862. }
  3863. }
  3864. #endif
  3865. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3866. // process_request() wraps only routing() in a try/catch, so an exception from
  3867. // any other user callback used to unwind into the task queue - which does not
  3868. // catch - and terminate the process. Each test below runs the server on a
  3869. // single worker thread: a guard that catches the exception but still loses the
  3870. // thread would otherwise be hidden by a spare worker serving the follow-up
  3871. // request. Note that a regression here aborts the whole test binary rather
  3872. // than failing one test.
  3873. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3874. Server svr;
  3875. svr.new_task_queue = [] { return new ThreadPool(1); };
  3876. std::atomic<int> reported{0};
  3877. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3878. if (err == Error::UserCallbackException) { reported++; }
  3879. });
  3880. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3881. res.set_content_provider(
  3882. 1024, "text/plain",
  3883. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3884. sink.write("hello", 5);
  3885. throw std::runtime_error("from the content provider");
  3886. });
  3887. });
  3888. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3889. res.set_content("ok", "text/plain");
  3890. });
  3891. auto port = svr.bind_to_any_port(HOST);
  3892. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3893. auto se = detail::scope_exit([&] {
  3894. svr.stop();
  3895. listen_thread.join();
  3896. ASSERT_FALSE(svr.is_running());
  3897. });
  3898. svr.wait_until_ready();
  3899. {
  3900. Client cli(HOST, port);
  3901. cli.set_read_timeout(5, 0);
  3902. EXPECT_FALSE(cli.Get("/throw"));
  3903. }
  3904. EXPECT_TRUE(svr.is_running());
  3905. EXPECT_EQ(1, reported.load());
  3906. // A request on a fresh connection is still served.
  3907. {
  3908. Client cli(HOST, port);
  3909. auto res = cli.Get("/ok");
  3910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3911. EXPECT_EQ(StatusCode::OK_200, res->status);
  3912. EXPECT_EQ("ok", res->body);
  3913. }
  3914. }
  3915. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3916. Server svr;
  3917. svr.new_task_queue = [] { return new ThreadPool(1); };
  3918. std::atomic<bool> should_throw{true};
  3919. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3920. res.set_content("hi", "text/plain");
  3921. });
  3922. svr.set_post_routing_handler(
  3923. [&](const Request & /*req*/, Response & /*res*/) {
  3924. if (should_throw) {
  3925. throw std::runtime_error("from the post-routing handler");
  3926. }
  3927. });
  3928. auto port = svr.bind_to_any_port(HOST);
  3929. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3930. auto se = detail::scope_exit([&] {
  3931. svr.stop();
  3932. listen_thread.join();
  3933. ASSERT_FALSE(svr.is_running());
  3934. });
  3935. svr.wait_until_ready();
  3936. {
  3937. Client cli(HOST, port);
  3938. cli.set_read_timeout(5, 0);
  3939. EXPECT_FALSE(cli.Get("/hi"));
  3940. }
  3941. EXPECT_TRUE(svr.is_running());
  3942. should_throw = false;
  3943. {
  3944. Client cli(HOST, port);
  3945. auto res = cli.Get("/hi");
  3946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3947. EXPECT_EQ(StatusCode::OK_200, res->status);
  3948. EXPECT_EQ("hi", res->body);
  3949. }
  3950. }
  3951. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3952. // The guard reports the caught exception through the error logger, which is
  3953. // a user callback too. A logger that throws has to be contained as well, or
  3954. // the process would terminate from inside the catch.
  3955. Server svr;
  3956. svr.new_task_queue = [] { return new ThreadPool(1); };
  3957. std::atomic<int> reported{0};
  3958. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3959. if (err == Error::UserCallbackException) {
  3960. reported++;
  3961. throw std::runtime_error("from the error logger");
  3962. }
  3963. });
  3964. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3965. res.set_content_provider(
  3966. 1024, "text/plain",
  3967. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3968. sink.write("hello", 5);
  3969. throw std::runtime_error("from the content provider");
  3970. });
  3971. });
  3972. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3973. res.set_content("ok", "text/plain");
  3974. });
  3975. auto port = svr.bind_to_any_port(HOST);
  3976. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3977. auto se = detail::scope_exit([&] {
  3978. svr.stop();
  3979. listen_thread.join();
  3980. ASSERT_FALSE(svr.is_running());
  3981. });
  3982. svr.wait_until_ready();
  3983. {
  3984. Client cli(HOST, port);
  3985. cli.set_read_timeout(5, 0);
  3986. EXPECT_FALSE(cli.Get("/throw"));
  3987. }
  3988. EXPECT_TRUE(svr.is_running());
  3989. EXPECT_EQ(1, reported.load());
  3990. {
  3991. Client cli(HOST, port);
  3992. auto res = cli.Get("/ok");
  3993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3994. EXPECT_EQ(StatusCode::OK_200, res->status);
  3995. EXPECT_EQ("ok", res->body);
  3996. }
  3997. }
  3998. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3999. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4000. // so the exception unwinds through the ws::WebSocket object on its way to
  4001. // the guard. None of the HTTP cases above cross that.
  4002. Server svr;
  4003. svr.new_task_queue = [] { return new ThreadPool(1); };
  4004. std::atomic<int> reported{0};
  4005. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4006. if (err == Error::UserCallbackException) { reported++; }
  4007. });
  4008. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4009. throw std::runtime_error("from the WebSocket handler");
  4010. });
  4011. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4012. res.set_content("ok", "text/plain");
  4013. });
  4014. auto port = svr.bind_to_any_port(HOST);
  4015. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4016. auto se = detail::scope_exit([&] {
  4017. svr.stop();
  4018. listen_thread.join();
  4019. ASSERT_FALSE(svr.is_running());
  4020. });
  4021. svr.wait_until_ready();
  4022. {
  4023. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4024. "/ws");
  4025. auto res = client.connect();
  4026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4027. // The server dropped the connection instead of dying.
  4028. std::string msg;
  4029. EXPECT_FALSE(client.read(msg));
  4030. client.close();
  4031. }
  4032. EXPECT_TRUE(svr.is_running());
  4033. EXPECT_EQ(1, reported.load());
  4034. {
  4035. Client cli(HOST, port);
  4036. auto res = cli.Get("/ok");
  4037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4038. EXPECT_EQ(StatusCode::OK_200, res->status);
  4039. EXPECT_EQ("ok", res->body);
  4040. }
  4041. }
  4042. #ifdef CPPHTTPLIB_SSL_ENABLED
  4043. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4044. // SSLServer::process_and_close_socket() is a separate overload with its own
  4045. // guard, so it is exercised on its own.
  4046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4047. ASSERT_TRUE(svr.is_valid());
  4048. svr.new_task_queue = [] { return new ThreadPool(1); };
  4049. std::atomic<int> reported{0};
  4050. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4051. if (err == Error::UserCallbackException) { reported++; }
  4052. });
  4053. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4054. res.set_content_provider(
  4055. 1024, "text/plain",
  4056. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4057. sink.write("hello", 5);
  4058. throw std::runtime_error("from the content provider");
  4059. });
  4060. });
  4061. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4062. res.set_content("ok", "text/plain");
  4063. });
  4064. auto port = svr.bind_to_any_port(HOST);
  4065. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4066. auto se = detail::scope_exit([&] {
  4067. svr.stop();
  4068. listen_thread.join();
  4069. ASSERT_FALSE(svr.is_running());
  4070. });
  4071. svr.wait_until_ready();
  4072. {
  4073. SSLClient cli(HOST, port);
  4074. cli.enable_server_certificate_verification(false);
  4075. cli.set_read_timeout(5, 0);
  4076. EXPECT_FALSE(cli.Get("/throw"));
  4077. }
  4078. EXPECT_TRUE(svr.is_running());
  4079. EXPECT_EQ(1, reported.load());
  4080. {
  4081. SSLClient cli(HOST, port);
  4082. cli.enable_server_certificate_verification(false);
  4083. auto res = cli.Get("/ok");
  4084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4085. EXPECT_EQ(StatusCode::OK_200, res->status);
  4086. EXPECT_EQ("ok", res->body);
  4087. }
  4088. }
  4089. #endif
  4090. #endif
  4091. TEST(NoContentTest, ContentLength) {
  4092. Server svr;
  4093. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4094. res.status = StatusCode::NoContent_204;
  4095. });
  4096. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4097. auto se = detail::scope_exit([&] {
  4098. svr.stop();
  4099. thread.join();
  4100. ASSERT_FALSE(svr.is_running());
  4101. });
  4102. svr.wait_until_ready();
  4103. {
  4104. Client cli(HOST, PORT);
  4105. auto res = cli.Get("/hi");
  4106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4107. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4108. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4109. }
  4110. }
  4111. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4112. #ifdef CPPHTTPLIB_SSL_ENABLED
  4113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4114. ASSERT_TRUE(svr.is_valid());
  4115. #else
  4116. Server svr;
  4117. #endif
  4118. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4119. if (req.path == "/routing_handler") {
  4120. res.set_header("PRE_ROUTING", "on");
  4121. res.set_content("Routing Handler", "text/plain");
  4122. return httplib::Server::HandlerResponse::Handled;
  4123. }
  4124. return httplib::Server::HandlerResponse::Unhandled;
  4125. });
  4126. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4127. res.set_content("Error", "text/html");
  4128. });
  4129. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4130. if (req.path == "/routing_handler") {
  4131. res.set_header("POST_ROUTING", "on");
  4132. }
  4133. });
  4134. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4135. res.set_content("Hello World!\n", "text/plain");
  4136. });
  4137. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4138. auto se = detail::scope_exit([&] {
  4139. svr.stop();
  4140. thread.join();
  4141. ASSERT_FALSE(svr.is_running());
  4142. });
  4143. svr.wait_until_ready();
  4144. {
  4145. #ifdef CPPHTTPLIB_SSL_ENABLED
  4146. SSLClient cli(HOST, PORT);
  4147. cli.enable_server_certificate_verification(false);
  4148. #else
  4149. Client cli(HOST, PORT);
  4150. #endif
  4151. auto res = cli.Get("/routing_handler");
  4152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4153. EXPECT_EQ(StatusCode::OK_200, res->status);
  4154. EXPECT_EQ("Routing Handler", res->body);
  4155. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4156. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4157. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4158. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4159. }
  4160. {
  4161. #ifdef CPPHTTPLIB_SSL_ENABLED
  4162. SSLClient cli(HOST, PORT);
  4163. cli.enable_server_certificate_verification(false);
  4164. #else
  4165. Client cli(HOST, PORT);
  4166. #endif
  4167. auto res = cli.Get("/hi");
  4168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4169. EXPECT_EQ(StatusCode::OK_200, res->status);
  4170. EXPECT_EQ("Hello World!\n", res->body);
  4171. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4172. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4173. }
  4174. {
  4175. #ifdef CPPHTTPLIB_SSL_ENABLED
  4176. SSLClient cli(HOST, PORT);
  4177. cli.enable_server_certificate_verification(false);
  4178. #else
  4179. Client cli(HOST, PORT);
  4180. #endif
  4181. auto res = cli.Get("/aaa");
  4182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4183. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4184. EXPECT_EQ("Error", res->body);
  4185. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4186. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4187. }
  4188. }
  4189. TEST(RequestHandlerTest, PreRequestHandler) {
  4190. auto route_path = "/user/:user";
  4191. Server svr;
  4192. svr.Get("/hi", [](const Request &, Response &res) {
  4193. res.set_content("hi", "text/plain");
  4194. });
  4195. svr.Get(route_path, [](const Request &req, Response &res) {
  4196. res.set_content(req.path_params.at("user"), "text/plain");
  4197. });
  4198. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4199. if (req.matched_route == route_path) {
  4200. auto user = req.path_params.at("user");
  4201. if (user != "john") {
  4202. res.status = StatusCode::Forbidden_403;
  4203. res.set_content("error", "text/html");
  4204. return Server::HandlerResponse::Handled;
  4205. }
  4206. }
  4207. return Server::HandlerResponse::Unhandled;
  4208. });
  4209. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4210. auto se = detail::scope_exit([&] {
  4211. svr.stop();
  4212. thread.join();
  4213. ASSERT_FALSE(svr.is_running());
  4214. });
  4215. svr.wait_until_ready();
  4216. Client cli(HOST, PORT);
  4217. {
  4218. auto res = cli.Get("/hi");
  4219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4220. EXPECT_EQ(StatusCode::OK_200, res->status);
  4221. EXPECT_EQ("hi", res->body);
  4222. }
  4223. {
  4224. auto res = cli.Get("/user/john");
  4225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4226. EXPECT_EQ(StatusCode::OK_200, res->status);
  4227. EXPECT_EQ("john", res->body);
  4228. }
  4229. {
  4230. auto res = cli.Get("/user/invalid-user");
  4231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4232. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4233. EXPECT_EQ("error", res->body);
  4234. }
  4235. }
  4236. // The pre-request handler must run before the request body is read, so a
  4237. // rejected request never forces the server to buffer a (potentially large)
  4238. // body. Here the posted body is larger than the payload limit: if the body
  4239. // were read first the server would answer 413, but because the pre-request
  4240. // handler runs first it answers 403 and the body is never read.
  4241. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4242. Server svr;
  4243. svr.set_payload_max_length(8);
  4244. auto handler_ran = false;
  4245. svr.Post("/reject", [&](const Request &req, Response &res) {
  4246. handler_ran = true;
  4247. res.set_content(req.body, "text/plain");
  4248. });
  4249. svr.Post("/accept", [](const Request &req, Response &res) {
  4250. res.set_content(req.body, "text/plain");
  4251. });
  4252. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4253. if (req.matched_route == "/reject") {
  4254. res.status = StatusCode::Forbidden_403;
  4255. res.set_content("denied", "text/plain");
  4256. return Server::HandlerResponse::Handled;
  4257. }
  4258. return Server::HandlerResponse::Unhandled;
  4259. });
  4260. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4261. auto se = detail::scope_exit([&] {
  4262. svr.stop();
  4263. thread.join();
  4264. ASSERT_FALSE(svr.is_running());
  4265. });
  4266. svr.wait_until_ready();
  4267. Client cli(HOST, PORT);
  4268. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4269. // rejects with 403 before the body is read, so 413 is never reached.
  4270. {
  4271. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4273. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4274. EXPECT_EQ("denied", res->body);
  4275. EXPECT_FALSE(handler_ran);
  4276. }
  4277. // An approved route still reads the body and enforces the payload limit.
  4278. {
  4279. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4281. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4282. }
  4283. }
  4284. TEST(UserDataTest, BasicOperations) {
  4285. httplib::UserData ud;
  4286. // Initially empty
  4287. EXPECT_FALSE(ud.has("key"));
  4288. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4289. // set and get
  4290. ud.set("key", 42);
  4291. EXPECT_TRUE(ud.has("key"));
  4292. auto *p = ud.get<int>("key");
  4293. ASSERT_NE(nullptr, p);
  4294. EXPECT_EQ(42, *p);
  4295. // Type mismatch → nullptr
  4296. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4297. // Overwrite with different type
  4298. ud.set("key", std::string("hello"));
  4299. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4300. auto *s = ud.get<std::string>("key");
  4301. ASSERT_NE(nullptr, s);
  4302. EXPECT_EQ("hello", *s);
  4303. // erase
  4304. ud.erase("key");
  4305. EXPECT_FALSE(ud.has("key"));
  4306. // clear
  4307. ud.set("a", 1);
  4308. ud.set("b", 2);
  4309. ud.clear();
  4310. EXPECT_FALSE(ud.has("a"));
  4311. EXPECT_FALSE(ud.has("b"));
  4312. }
  4313. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4314. struct AuthCtx {
  4315. std::string user_id;
  4316. };
  4317. Server svr;
  4318. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4319. res.user_data.set("auth", AuthCtx{"alice"});
  4320. return Server::HandlerResponse::Unhandled;
  4321. });
  4322. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4323. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4324. ASSERT_NE(nullptr, ctx);
  4325. res.set_content("Hello " + ctx->user_id, "text/plain");
  4326. });
  4327. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4328. auto se = detail::scope_exit([&] {
  4329. svr.stop();
  4330. thread.join();
  4331. ASSERT_FALSE(svr.is_running());
  4332. });
  4333. svr.wait_until_ready();
  4334. Client cli(HOST, PORT);
  4335. auto res = cli.Get("/me");
  4336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4337. EXPECT_EQ(StatusCode::OK_200, res->status);
  4338. EXPECT_EQ("Hello alice", res->body);
  4339. }
  4340. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4341. struct RoleCtx {
  4342. std::string role;
  4343. };
  4344. Server svr;
  4345. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4346. res.user_data.set("role", RoleCtx{"admin"});
  4347. return Server::HandlerResponse::Unhandled;
  4348. });
  4349. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4350. auto *ctx = res.user_data.get<RoleCtx>("role");
  4351. ASSERT_NE(nullptr, ctx);
  4352. res.set_content(ctx->role, "text/plain");
  4353. });
  4354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4355. auto se = detail::scope_exit([&] {
  4356. svr.stop();
  4357. thread.join();
  4358. ASSERT_FALSE(svr.is_running());
  4359. });
  4360. svr.wait_until_ready();
  4361. Client cli(HOST, PORT);
  4362. auto res = cli.Get("/role");
  4363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4364. EXPECT_EQ(StatusCode::OK_200, res->status);
  4365. EXPECT_EQ("admin", res->body);
  4366. }
  4367. TEST(InvalidFormatTest, StatusCode) {
  4368. Server svr;
  4369. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4370. res.set_content("Hello World!\n", "text/plain");
  4371. res.status = 9999; // Status should be a three-digit code...
  4372. });
  4373. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4374. auto se = detail::scope_exit([&] {
  4375. svr.stop();
  4376. thread.join();
  4377. ASSERT_FALSE(svr.is_running());
  4378. });
  4379. svr.wait_until_ready();
  4380. {
  4381. Client cli(HOST, PORT);
  4382. auto res = cli.Get("/hi");
  4383. ASSERT_FALSE(res);
  4384. }
  4385. }
  4386. TEST(URLFragmentTest, WithFragment) {
  4387. Server svr;
  4388. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4389. EXPECT_TRUE(req.target == "/hi");
  4390. });
  4391. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4392. auto se = detail::scope_exit([&] {
  4393. svr.stop();
  4394. thread.join();
  4395. ASSERT_FALSE(svr.is_running());
  4396. });
  4397. svr.wait_until_ready();
  4398. {
  4399. Client cli(HOST, PORT);
  4400. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4401. EXPECT_TRUE(res);
  4402. EXPECT_EQ(StatusCode::OK_200, res->status);
  4403. res = cli.Get("/hi%23key1=val1=key2=val2");
  4404. EXPECT_TRUE(res);
  4405. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4406. }
  4407. }
  4408. TEST(HeaderWriter, SetHeaderWriter) {
  4409. Server svr;
  4410. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4411. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4412. return detail::write_headers(strm, hdrs);
  4413. });
  4414. svr.Get("/hi", [](const Request &req, Response &res) {
  4415. auto it = req.headers.find("CustomClientHeader");
  4416. EXPECT_TRUE(it != req.headers.end());
  4417. EXPECT_EQ(it->second, "CustomClientValue");
  4418. res.set_content("Hello World!\n", "text/plain");
  4419. });
  4420. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4421. auto se = detail::scope_exit([&] {
  4422. svr.stop();
  4423. thread.join();
  4424. ASSERT_FALSE(svr.is_running());
  4425. });
  4426. svr.wait_until_ready();
  4427. {
  4428. Client cli(HOST, PORT);
  4429. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4430. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4431. return detail::write_headers(strm, hdrs);
  4432. });
  4433. auto res = cli.Get("/hi");
  4434. EXPECT_TRUE(res);
  4435. EXPECT_EQ(StatusCode::OK_200, res->status);
  4436. auto it = res->headers.find("CustomServerHeader");
  4437. EXPECT_TRUE(it != res->headers.end());
  4438. EXPECT_EQ(it->second, "CustomServerValue");
  4439. }
  4440. }
  4441. class ServerTest : public ::testing::Test {
  4442. protected:
  4443. ServerTest()
  4444. : cli_(HOST, PORT)
  4445. #ifdef CPPHTTPLIB_SSL_ENABLED
  4446. ,
  4447. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4448. #endif
  4449. {
  4450. #ifdef CPPHTTPLIB_SSL_ENABLED
  4451. cli_.enable_server_certificate_verification(false);
  4452. #endif
  4453. // Allow LARGE_DATA (100MB) responses
  4454. cli_.set_payload_max_length(200 * 1024 * 1024);
  4455. }
  4456. virtual void SetUp() {
  4457. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4458. svr_.set_payload_max_length(200 * 1024 * 1024);
  4459. svr_.set_mount_point("/", "./www");
  4460. svr_.set_mount_point("/mount", "./www2");
  4461. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4462. svr_.Get("/hi",
  4463. [&](const Request & /*req*/, Response &res) {
  4464. res.set_content("Hello World!", "text/plain");
  4465. })
  4466. .Get("/file_content",
  4467. [&](const Request & /*req*/, Response &res) {
  4468. res.set_file_content("./www/dir/test.html");
  4469. })
  4470. .Get("/file_content_with_content_type",
  4471. [&](const Request & /*req*/, Response &res) {
  4472. res.set_file_content("./www/file", "text/plain");
  4473. })
  4474. .Get("/invalid_file_content",
  4475. [&](const Request & /*req*/, Response &res) {
  4476. res.set_file_content("./www/dir/invalid_file_path");
  4477. })
  4478. .Get("/http_response_splitting",
  4479. [&](const Request & /*req*/, Response &res) {
  4480. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4481. EXPECT_EQ(0U, res.headers.size());
  4482. EXPECT_FALSE(res.has_header("a"));
  4483. res.set_header("a", "1\nSet-Cookie: a=1");
  4484. EXPECT_EQ(0U, res.headers.size());
  4485. EXPECT_FALSE(res.has_header("a"));
  4486. res.set_header("a", "1\rSet-Cookie: a=1");
  4487. EXPECT_EQ(0U, res.headers.size());
  4488. EXPECT_FALSE(res.has_header("a"));
  4489. res.set_header("a\r\nb", "0");
  4490. EXPECT_EQ(0U, res.headers.size());
  4491. EXPECT_FALSE(res.has_header("a"));
  4492. res.set_header("a\rb", "0");
  4493. EXPECT_EQ(0U, res.headers.size());
  4494. EXPECT_FALSE(res.has_header("a"));
  4495. res.set_header("a\nb", "0");
  4496. EXPECT_EQ(0U, res.headers.size());
  4497. EXPECT_FALSE(res.has_header("a"));
  4498. res.set_redirect("1\r\nSet-Cookie: a=1");
  4499. EXPECT_EQ(0U, res.headers.size());
  4500. EXPECT_FALSE(res.has_header("Location"));
  4501. })
  4502. .Get("/slow",
  4503. [&](const Request & /*req*/, Response &res) {
  4504. std::this_thread::sleep_for(std::chrono::seconds(4));
  4505. res.set_content("slow", "text/plain");
  4506. })
  4507. #if 0
  4508. .Post("/slowpost",
  4509. [&](const Request & /*req*/, Response &res) {
  4510. std::this_thread::sleep_for(std::chrono::seconds(2));
  4511. res.set_content("slow", "text/plain");
  4512. })
  4513. #endif
  4514. .Get("/remote_addr",
  4515. [&](const Request &req, Response &res) {
  4516. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4517. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4518. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4519. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4520. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4521. #endif
  4522. res.set_content(req.remote_addr, "text/plain");
  4523. })
  4524. .Get("/local_addr",
  4525. [&](const Request &req, Response &res) {
  4526. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4527. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4528. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4529. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4530. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4531. #endif
  4532. auto local_addr = req.local_addr;
  4533. auto local_port = std::to_string(req.local_port);
  4534. res.set_content(local_addr.append(":").append(local_port),
  4535. "text/plain");
  4536. })
  4537. .Get("/endwith%",
  4538. [&](const Request & /*req*/, Response &res) {
  4539. res.set_content("Hello World!", "text/plain");
  4540. })
  4541. .Get("/a\\+\\+b",
  4542. [&](const Request &req, Response &res) {
  4543. ASSERT_TRUE(req.has_param("a +b"));
  4544. auto val = req.get_param_value("a +b");
  4545. res.set_content(val, "text/plain");
  4546. })
  4547. .Get("/", [&](const Request & /*req*/,
  4548. Response &res) { res.set_redirect("/hi"); })
  4549. .Post("/1",
  4550. [](const Request & /*req*/, Response &res) {
  4551. res.set_redirect("/2", StatusCode::SeeOther_303);
  4552. })
  4553. .Get("/2",
  4554. [](const Request & /*req*/, Response &res) {
  4555. res.set_content("redirected.", "text/plain");
  4556. res.status = StatusCode::OK_200;
  4557. })
  4558. .Post("/person",
  4559. [&](const Request &req, Response &res) {
  4560. if (req.has_param("name") && req.has_param("note")) {
  4561. persons_[req.get_param_value("name")] =
  4562. req.get_param_value("note");
  4563. } else {
  4564. res.status = StatusCode::BadRequest_400;
  4565. }
  4566. })
  4567. .Put("/person",
  4568. [&](const Request &req, Response &res) {
  4569. if (req.has_param("name") && req.has_param("note")) {
  4570. persons_[req.get_param_value("name")] =
  4571. req.get_param_value("note");
  4572. } else {
  4573. res.status = StatusCode::BadRequest_400;
  4574. }
  4575. })
  4576. .Get("/person/(.*)",
  4577. [&](const Request &req, Response &res) {
  4578. string name = req.matches[1];
  4579. if (persons_.find(name) != persons_.end()) {
  4580. auto note = persons_[name];
  4581. res.set_content(note, "text/plain");
  4582. } else {
  4583. res.status = StatusCode::NotFound_404;
  4584. }
  4585. })
  4586. .Delete("/person",
  4587. [&](const Request &req, Response &res) {
  4588. if (req.has_param("name")) {
  4589. string name = req.get_param_value("name");
  4590. if (persons_.find(name) != persons_.end()) {
  4591. persons_.erase(name);
  4592. res.set_content("DELETED", "text/plain");
  4593. } else {
  4594. res.status = StatusCode::NotFound_404;
  4595. }
  4596. } else {
  4597. res.status = StatusCode::BadRequest_400;
  4598. }
  4599. })
  4600. .Post("/x-www-form-urlencoded-json",
  4601. [&](const Request &req, Response &res) {
  4602. auto json = req.get_param_value("json");
  4603. ASSERT_EQ(JSON_DATA, json);
  4604. res.set_content(json, "appliation/json");
  4605. res.status = StatusCode::OK_200;
  4606. })
  4607. .Get("/streamed-chunked",
  4608. [&](const Request & /*req*/, Response &res) {
  4609. res.set_chunked_content_provider(
  4610. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4611. sink.os << "123";
  4612. sink.os << "456";
  4613. sink.os << "789";
  4614. sink.done();
  4615. return true;
  4616. });
  4617. })
  4618. .Get("/streamed-chunked-with-prohibited-trailer",
  4619. [&](const Request & /*req*/, Response &res) {
  4620. auto i = new int(0);
  4621. // Declare both a prohibited trailer (Content-Length) and an
  4622. // allowed one
  4623. res.set_header("Trailer", "Content-Length, X-Allowed");
  4624. res.set_chunked_content_provider(
  4625. "text/plain",
  4626. [i](size_t /*offset*/, DataSink &sink) {
  4627. switch (*i) {
  4628. case 0: sink.os << "123"; break;
  4629. case 1: sink.os << "456"; break;
  4630. case 2: sink.os << "789"; break;
  4631. case 3: {
  4632. sink.done_with_trailer(
  4633. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4634. } break;
  4635. }
  4636. (*i)++;
  4637. return true;
  4638. },
  4639. [i](bool success) {
  4640. EXPECT_TRUE(success);
  4641. delete i;
  4642. });
  4643. })
  4644. .Get("/streamed-chunked2",
  4645. [&](const Request & /*req*/, Response &res) {
  4646. auto i = new int(0);
  4647. res.set_chunked_content_provider(
  4648. "text/plain",
  4649. [i](size_t /*offset*/, DataSink &sink) {
  4650. switch (*i) {
  4651. case 0: sink.os << "123"; break;
  4652. case 1: sink.os << "456"; break;
  4653. case 2: sink.os << "789"; break;
  4654. case 3: sink.done(); break;
  4655. }
  4656. (*i)++;
  4657. return true;
  4658. },
  4659. [i](bool success) {
  4660. EXPECT_TRUE(success);
  4661. delete i;
  4662. });
  4663. })
  4664. .Get("/streamed-chunked-with-trailer",
  4665. [&](const Request & /*req*/, Response &res) {
  4666. auto i = new int(0);
  4667. res.set_header("Trailer", "Dummy1, Dummy2");
  4668. res.set_chunked_content_provider(
  4669. "text/plain",
  4670. [i](size_t /*offset*/, DataSink &sink) {
  4671. switch (*i) {
  4672. case 0: sink.os << "123"; break;
  4673. case 1: sink.os << "456"; break;
  4674. case 2: sink.os << "789"; break;
  4675. case 3: {
  4676. sink.done_with_trailer(
  4677. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4678. } break;
  4679. }
  4680. (*i)++;
  4681. return true;
  4682. },
  4683. [i](bool success) {
  4684. EXPECT_TRUE(success);
  4685. delete i;
  4686. });
  4687. })
  4688. .Get("/streamed",
  4689. [&](const Request & /*req*/, Response &res) {
  4690. res.set_content_provider(
  4691. 6, "text/plain",
  4692. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4693. sink.os << (offset < 3 ? "a" : "b");
  4694. return true;
  4695. });
  4696. })
  4697. .Get("/streamed-without-length",
  4698. [&](const Request & /*req*/, Response &res) {
  4699. auto data = new std::string("abcdefg");
  4700. res.set_content_provider(
  4701. "text/plain",
  4702. [data](size_t offset, DataSink &sink) {
  4703. if (offset < data->size()) {
  4704. sink.os << data->substr(offset);
  4705. }
  4706. sink.done();
  4707. return true;
  4708. },
  4709. [data](bool success) {
  4710. EXPECT_TRUE(success);
  4711. delete data;
  4712. });
  4713. })
  4714. .Get("/streamed-with-range",
  4715. [&](const Request &req, Response &res) {
  4716. auto data = new std::string("abcdefg");
  4717. // An explicit status keeps the server from picking the 206 it
  4718. // would otherwise choose for a ranged request, so the response
  4719. // is not a partial representation.
  4720. auto status = req.get_param_value("status");
  4721. if (status == "200") {
  4722. res.status = StatusCode::OK_200;
  4723. } else if (status == "403") {
  4724. res.status = StatusCode::Forbidden_403;
  4725. }
  4726. res.set_content_provider(
  4727. data->size(), "text/plain",
  4728. [data](size_t offset, size_t length, DataSink &sink) {
  4729. size_t DATA_CHUNK_SIZE = 4;
  4730. const auto &d = *data;
  4731. auto out_len =
  4732. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4733. auto ret =
  4734. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4735. EXPECT_TRUE(ret);
  4736. return true;
  4737. },
  4738. [data, &req](bool success) {
  4739. EXPECT_EQ(success, !req.has_param("error"));
  4740. delete data;
  4741. });
  4742. })
  4743. .Get("/streamed-cancel",
  4744. [&](const Request & /*req*/, Response &res) {
  4745. res.set_content_provider(
  4746. size_t(-1), "text/plain",
  4747. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4748. sink.os << "data_chunk";
  4749. return true;
  4750. });
  4751. })
  4752. .Get("/regex-with-delimiter",
  4753. [&](const Request &req, Response & /*res*/) {
  4754. ASSERT_TRUE(req.has_param("key"));
  4755. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4756. })
  4757. .Get("/with-range",
  4758. [&](const Request & /*req*/, Response &res) {
  4759. res.set_content("abcdefg", "text/plain");
  4760. })
  4761. .Get("/test-start-time",
  4762. [&](const Request &req, Response & /*res*/) {
  4763. EXPECT_NE(req.start_time_,
  4764. std::chrono::steady_clock::time_point::min());
  4765. })
  4766. .Get("/with-range-customized-response",
  4767. [&](const Request & /*req*/, Response &res) {
  4768. res.status = StatusCode::BadRequest_400;
  4769. res.set_content(JSON_DATA, "application/json");
  4770. })
  4771. .Post("/chunked",
  4772. [&](const Request &req, Response & /*res*/) {
  4773. EXPECT_EQ(req.body, "dechunked post body");
  4774. })
  4775. .Post("/large-chunked",
  4776. [&](const Request &req, Response & /*res*/) {
  4777. std::string expected(6 * 30 * 1024u, 'a');
  4778. EXPECT_EQ(req.body, expected);
  4779. })
  4780. .Post("/multipart",
  4781. [&](const Request &req, Response & /*res*/) {
  4782. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4783. req.form.get_field_count("text2") +
  4784. req.form.get_field_count("file3") +
  4785. req.form.get_field_count("file4"));
  4786. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4787. req.form.get_file_count("file2"));
  4788. ASSERT_TRUE(!req.form.has_file("???"));
  4789. ASSERT_TRUE(!req.form.has_field("???"));
  4790. ASSERT_TRUE(req.body.empty());
  4791. {
  4792. const auto &text = req.form.get_field("text1");
  4793. EXPECT_EQ("text default", text);
  4794. }
  4795. {
  4796. const auto &text = req.form.get_field("text2");
  4797. EXPECT_EQ("aωb", text);
  4798. }
  4799. {
  4800. const auto &file = req.form.get_file("file1");
  4801. EXPECT_EQ("hello.txt", file.filename);
  4802. EXPECT_EQ("text/plain", file.content_type);
  4803. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4804. }
  4805. {
  4806. const auto &file = req.form.get_file("file2");
  4807. EXPECT_EQ("world.json", file.filename);
  4808. EXPECT_EQ("application/json", file.content_type);
  4809. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4810. }
  4811. {
  4812. const auto &text = req.form.get_field("file3");
  4813. EXPECT_EQ(0u, text.size());
  4814. }
  4815. {
  4816. const auto &text = req.form.get_field("file4");
  4817. EXPECT_EQ(0u, text.size());
  4818. }
  4819. })
  4820. .Post("/multipart/multi_file_values",
  4821. [&](const Request &req, Response & /*res*/) {
  4822. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4823. req.form.get_field_count("multi_text1"));
  4824. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4825. ASSERT_TRUE(!req.form.has_file("???"));
  4826. ASSERT_TRUE(!req.form.has_field("???"));
  4827. ASSERT_TRUE(req.body.empty());
  4828. {
  4829. const auto &text = req.form.get_field("text");
  4830. EXPECT_EQ("default text", text);
  4831. }
  4832. {
  4833. const auto &text1_values = req.form.get_fields("multi_text1");
  4834. EXPECT_EQ(2u, text1_values.size());
  4835. EXPECT_EQ("aaaaa", text1_values[0]);
  4836. EXPECT_EQ("bbbbb", text1_values[1]);
  4837. }
  4838. {
  4839. const auto &file1_values = req.form.get_files("multi_file1");
  4840. EXPECT_EQ(2u, file1_values.size());
  4841. auto file1 = file1_values[0];
  4842. EXPECT_EQ(file1.filename, "hello.txt");
  4843. EXPECT_EQ(file1.content_type, "text/plain");
  4844. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4845. auto file2 = file1_values[1];
  4846. EXPECT_EQ(file2.filename, "world.json");
  4847. EXPECT_EQ(file2.content_type, "application/json");
  4848. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4849. }
  4850. })
  4851. .Post("/empty",
  4852. [&](const Request &req, Response &res) {
  4853. EXPECT_EQ(req.body, "");
  4854. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4855. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4856. res.set_content("empty", "text/plain");
  4857. })
  4858. .Post("/empty-no-content-type",
  4859. [&](const Request &req, Response &res) {
  4860. EXPECT_EQ(req.body, "");
  4861. EXPECT_FALSE(req.has_header("Content-Type"));
  4862. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4863. res.set_content("empty-no-content-type", "text/plain");
  4864. })
  4865. .Post("/path-only",
  4866. [&](const Request &req, Response &res) {
  4867. EXPECT_EQ(req.body, "");
  4868. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4869. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4870. res.set_content("path-only", "text/plain");
  4871. })
  4872. .Post("/path-headers-only",
  4873. [&](const Request &req, Response &res) {
  4874. EXPECT_EQ(req.body, "");
  4875. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4876. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4877. EXPECT_EQ("world", req.get_header_value("hello"));
  4878. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4879. res.set_content("path-headers-only", "text/plain");
  4880. })
  4881. .Post("/post-large",
  4882. [&](const Request &req, Response &res) {
  4883. EXPECT_EQ(req.body, LARGE_DATA);
  4884. res.set_content(req.body, "text/plain");
  4885. })
  4886. .Post("/post-loopback",
  4887. [&](const Request &, Response &res,
  4888. ContentReader const &content_reader) {
  4889. std::string body;
  4890. content_reader([&](const char *data, size_t data_length) {
  4891. body.append(data, data_length);
  4892. return true;
  4893. });
  4894. res.set_content(body, "text/plain");
  4895. })
  4896. .Put("/put-loopback",
  4897. [&](const Request &, Response &res,
  4898. ContentReader const &content_reader) {
  4899. std::string body;
  4900. content_reader([&](const char *data, size_t data_length) {
  4901. body.append(data, data_length);
  4902. return true;
  4903. });
  4904. res.set_content(body, "text/plain");
  4905. })
  4906. .Patch("/patch-loopback",
  4907. [&](const Request &, Response &res,
  4908. ContentReader const &content_reader) {
  4909. std::string body;
  4910. content_reader([&](const char *data, size_t data_length) {
  4911. body.append(data, data_length);
  4912. return true;
  4913. });
  4914. res.set_content(body, "text/plain");
  4915. })
  4916. .Put("/empty-no-content-type",
  4917. [&](const Request &req, Response &res) {
  4918. EXPECT_EQ(req.body, "");
  4919. EXPECT_FALSE(req.has_header("Content-Type"));
  4920. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4921. res.set_content("empty-no-content-type", "text/plain");
  4922. })
  4923. .Put("/put",
  4924. [&](const Request &req, Response &res) {
  4925. EXPECT_EQ(req.body, "PUT");
  4926. res.set_content(req.body, "text/plain");
  4927. })
  4928. .Put("/put-large",
  4929. [&](const Request &req, Response &res) {
  4930. EXPECT_EQ(req.body, LARGE_DATA);
  4931. res.set_content(req.body, "text/plain");
  4932. })
  4933. .Patch("/patch",
  4934. [&](const Request &req, Response &res) {
  4935. EXPECT_EQ(req.body, "PATCH");
  4936. res.set_content(req.body, "text/plain");
  4937. })
  4938. .Delete("/delete",
  4939. [&](const Request & /*req*/, Response &res) {
  4940. res.set_content("DELETE", "text/plain");
  4941. })
  4942. .Delete("/delete-body",
  4943. [&](const Request &req, Response &res) {
  4944. EXPECT_EQ(req.body, "content");
  4945. res.set_content(req.body, "text/plain");
  4946. })
  4947. .Options(R"(\*)",
  4948. [&](const Request & /*req*/, Response &res) {
  4949. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4950. })
  4951. .CustomRoute("PROPFIND", "/dav/:id",
  4952. [&](const Request &req, Response &res) {
  4953. res.set_header("x-body-size",
  4954. std::to_string(req.body.size()));
  4955. res.set_header("x-matched-route", req.matched_route);
  4956. res.set_header("x-dav-id", req.path_params.at("id"));
  4957. res.status = StatusCode::MultiStatus_207;
  4958. res.set_content(req.body, "application/xml");
  4959. })
  4960. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4961. [&](const Request &req, Response &res) {
  4962. res.set_header("x-dav-match", req.matches[1]);
  4963. res.status = StatusCode::MultiStatus_207;
  4964. })
  4965. .CustomRoute("MKCOL", "/dav-mkcol",
  4966. [&](const Request &req, Response &res) {
  4967. EXPECT_TRUE(req.body.empty());
  4968. res.status = StatusCode::Created_201;
  4969. })
  4970. .CustomRoute(
  4971. "REPORT", "/dav-report",
  4972. [&](const Request & /*req*/, Response &res,
  4973. const ContentReader &content_reader) {
  4974. std::string body;
  4975. content_reader([&](const char *data, size_t data_length) {
  4976. body.append(data, data_length);
  4977. return true;
  4978. });
  4979. res.set_header("x-body-size", std::to_string(body.size()));
  4980. res.status = StatusCode::MultiStatus_207;
  4981. res.set_content(body, "application/xml");
  4982. })
  4983. .Get("/request-target",
  4984. [&](const Request &req, Response & /*res*/) {
  4985. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4986. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4987. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4988. })
  4989. .Get("/long-query-value",
  4990. [&](const Request &req, Response & /*res*/) {
  4991. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4992. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4993. })
  4994. .Get("/too-long-query-value",
  4995. [&](const Request &req, Response & /*res*/) {
  4996. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4997. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4998. })
  4999. .Get("/array-param",
  5000. [&](const Request &req, Response & /*res*/) {
  5001. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5002. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5003. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5004. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5005. })
  5006. .Get("/array-param-values",
  5007. [&](const Request &req, Response & /*res*/) {
  5008. auto values = req.get_param_values("array");
  5009. EXPECT_EQ(3u, values.size());
  5010. EXPECT_EQ("value1", values[0]);
  5011. EXPECT_EQ("value2", values[1]);
  5012. EXPECT_EQ("value3", values[2]);
  5013. auto empty = req.get_param_values("nonexistent");
  5014. EXPECT_TRUE(empty.empty());
  5015. })
  5016. .Post("/validate-no-multiple-headers",
  5017. [&](const Request &req, Response & /*res*/) {
  5018. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5019. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5020. })
  5021. .Post("/content_receiver",
  5022. [&](const Request &req, Response &res,
  5023. const ContentReader &content_reader) {
  5024. if (req.is_multipart_form_data()) {
  5025. std::vector<FormData> items;
  5026. content_reader(
  5027. [&](const FormData &file) {
  5028. items.push_back(file);
  5029. return true;
  5030. },
  5031. [&](const char *data, size_t data_length) {
  5032. items.back().content.append(data, data_length);
  5033. return true;
  5034. });
  5035. EXPECT_EQ(5u, items.size());
  5036. {
  5037. const auto &file = get_file_value(items, "text1");
  5038. EXPECT_TRUE(file.filename.empty());
  5039. EXPECT_EQ("text default", file.content);
  5040. }
  5041. {
  5042. const auto &file = get_file_value(items, "text2");
  5043. EXPECT_TRUE(file.filename.empty());
  5044. EXPECT_EQ("aωb", file.content);
  5045. }
  5046. {
  5047. const auto &file = get_file_value(items, "file1");
  5048. EXPECT_EQ("hello.txt", file.filename);
  5049. EXPECT_EQ("text/plain", file.content_type);
  5050. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5051. }
  5052. {
  5053. const auto &file = get_file_value(items, "file2");
  5054. EXPECT_EQ("world.json", file.filename);
  5055. EXPECT_EQ("application/json", file.content_type);
  5056. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5057. }
  5058. {
  5059. const auto &file = get_file_value(items, "file3");
  5060. EXPECT_TRUE(file.filename.empty());
  5061. EXPECT_EQ("application/octet-stream", file.content_type);
  5062. EXPECT_EQ(0u, file.content.size());
  5063. }
  5064. } else {
  5065. std::string body;
  5066. content_reader([&](const char *data, size_t data_length) {
  5067. EXPECT_EQ(7U, data_length);
  5068. body.append(data, data_length);
  5069. return true;
  5070. });
  5071. EXPECT_EQ(body, "content");
  5072. res.set_content(body, "text/plain");
  5073. }
  5074. })
  5075. .Put("/content_receiver",
  5076. [&](const Request & /*req*/, Response &res,
  5077. const ContentReader &content_reader) {
  5078. std::string body;
  5079. content_reader([&](const char *data, size_t data_length) {
  5080. body.append(data, data_length);
  5081. return true;
  5082. });
  5083. EXPECT_EQ(body, "content");
  5084. res.set_content(body, "text/plain");
  5085. })
  5086. .Patch("/content_receiver",
  5087. [&](const Request & /*req*/, Response &res,
  5088. const ContentReader &content_reader) {
  5089. std::string body;
  5090. content_reader([&](const char *data, size_t data_length) {
  5091. body.append(data, data_length);
  5092. return true;
  5093. });
  5094. EXPECT_EQ(body, "content");
  5095. res.set_content(body, "text/plain");
  5096. })
  5097. .Post("/query-string-and-body",
  5098. [&](const Request &req, Response & /*res*/) {
  5099. ASSERT_TRUE(req.has_param("key"));
  5100. EXPECT_EQ(req.get_param_value("key"), "value");
  5101. EXPECT_EQ(req.body, "content");
  5102. })
  5103. .Get("/last-request",
  5104. [&](const Request &req, Response & /*res*/) {
  5105. EXPECT_EQ("close", req.get_header_value("Connection"));
  5106. })
  5107. .Get(R"(/redirect/(\d+))",
  5108. [&](const Request &req, Response &res) {
  5109. auto num = std::stoi(req.matches[1]) + 1;
  5110. std::string url = "/redirect/" + std::to_string(num);
  5111. res.set_redirect(url);
  5112. })
  5113. .Post("/binary",
  5114. [&](const Request &req, Response &res) {
  5115. EXPECT_EQ(4U, req.body.size());
  5116. EXPECT_EQ("application/octet-stream",
  5117. req.get_header_value("Content-Type"));
  5118. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5119. res.set_content(req.body, "application/octet-stream");
  5120. })
  5121. .Put("/binary",
  5122. [&](const Request &req, Response &res) {
  5123. EXPECT_EQ(4U, req.body.size());
  5124. EXPECT_EQ("application/octet-stream",
  5125. req.get_header_value("Content-Type"));
  5126. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5127. res.set_content(req.body, "application/octet-stream");
  5128. })
  5129. .Patch("/binary",
  5130. [&](const Request &req, Response &res) {
  5131. EXPECT_EQ(4U, req.body.size());
  5132. EXPECT_EQ("application/octet-stream",
  5133. req.get_header_value("Content-Type"));
  5134. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5135. res.set_content(req.body, "application/octet-stream");
  5136. })
  5137. .Delete("/binary",
  5138. [&](const Request &req, Response &res) {
  5139. EXPECT_EQ(4U, req.body.size());
  5140. EXPECT_EQ("application/octet-stream",
  5141. req.get_header_value("Content-Type"));
  5142. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5143. res.set_content(req.body, "application/octet-stream");
  5144. })
  5145. .Get("/issue1772",
  5146. [&](const Request & /*req*/, Response &res) {
  5147. res.status = 401;
  5148. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5149. })
  5150. .Delete("/issue609",
  5151. [](const httplib::Request &, httplib::Response &res,
  5152. const httplib::ContentReader &) {
  5153. res.set_content("ok", "text/plain");
  5154. })
  5155. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5156. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5157. .Get("/compress",
  5158. [&](const Request & /*req*/, Response &res) {
  5159. res.set_content(
  5160. "12345678901234567890123456789012345678901234567890123456789"
  5161. "01234567890123456789012345678901234567890",
  5162. "text/plain");
  5163. })
  5164. .Get("/compress-with-charset",
  5165. [&](const Request & /*req*/, Response &res) {
  5166. res.set_content(
  5167. "12345678901234567890123456789012345678901234567890123456789"
  5168. "01234567890123456789012345678901234567890",
  5169. "application/json; charset=utf-8");
  5170. })
  5171. .Get("/nocompress",
  5172. [&](const Request & /*req*/, Response &res) {
  5173. res.set_content(
  5174. "12345678901234567890123456789012345678901234567890123456789"
  5175. "01234567890123456789012345678901234567890",
  5176. "application/octet-stream");
  5177. })
  5178. .Post("/compress-multipart",
  5179. [&](const Request &req, Response & /*res*/) {
  5180. EXPECT_EQ(2u, req.form.fields.size());
  5181. ASSERT_TRUE(!req.form.has_field("???"));
  5182. {
  5183. const auto &text = req.form.get_field("key1");
  5184. EXPECT_EQ("test", text);
  5185. }
  5186. {
  5187. const auto &text = req.form.get_field("key2");
  5188. EXPECT_EQ("--abcdefg123", text);
  5189. }
  5190. })
  5191. #endif
  5192. ;
  5193. persons_["john"] = "programmer";
  5194. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5195. svr_.wait_until_ready();
  5196. }
  5197. virtual void TearDown() {
  5198. svr_.stop();
  5199. if (!request_threads_.empty()) {
  5200. std::this_thread::sleep_for(std::chrono::seconds(1));
  5201. for (auto &t : request_threads_) {
  5202. t.join();
  5203. }
  5204. }
  5205. t_.join();
  5206. }
  5207. map<string, string> persons_;
  5208. #ifdef CPPHTTPLIB_SSL_ENABLED
  5209. SSLClient cli_;
  5210. SSLServer svr_;
  5211. #else
  5212. Client cli_;
  5213. Server svr_;
  5214. #endif
  5215. thread t_;
  5216. std::vector<thread> request_threads_;
  5217. };
  5218. TEST_F(ServerTest, GetMethod200) {
  5219. auto res = cli_.Get("/hi");
  5220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5221. EXPECT_EQ("HTTP/1.1", res->version);
  5222. EXPECT_EQ(StatusCode::OK_200, res->status);
  5223. EXPECT_EQ("OK", res->reason);
  5224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5225. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5226. EXPECT_EQ("Hello World!", res->body);
  5227. }
  5228. TEST_F(ServerTest, GetEmptyFile) {
  5229. auto res = cli_.Get("/empty_file");
  5230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5231. EXPECT_EQ(StatusCode::OK_200, res->status);
  5232. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5233. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5234. EXPECT_EQ("", res->body);
  5235. }
  5236. TEST_F(ServerTest, GetFileContent) {
  5237. auto res = cli_.Get("/file_content");
  5238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5239. EXPECT_EQ(StatusCode::OK_200, res->status);
  5240. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5241. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5242. EXPECT_EQ("test.html", res->body);
  5243. }
  5244. TEST_F(ServerTest, GetFileContentWithRange) {
  5245. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5247. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5248. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5249. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5250. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5251. EXPECT_EQ("est", res->body);
  5252. }
  5253. TEST_F(ServerTest, GetFileContentWithContentType) {
  5254. auto res = cli_.Get("/file_content_with_content_type");
  5255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5256. EXPECT_EQ(StatusCode::OK_200, res->status);
  5257. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5258. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5259. EXPECT_EQ("file\n", res->body);
  5260. }
  5261. TEST_F(ServerTest, GetInvalidFileContent) {
  5262. auto res = cli_.Get("/invalid_file_content");
  5263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5265. }
  5266. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5267. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5269. EXPECT_EQ("HTTP/1.1", res->version);
  5270. EXPECT_EQ(StatusCode::OK_200, res->status);
  5271. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5272. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5273. EXPECT_EQ("Hello World!", res->body);
  5274. }
  5275. TEST_F(ServerTest, GetMethod302) {
  5276. auto res = cli_.Get("/");
  5277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5278. EXPECT_EQ(StatusCode::Found_302, res->status);
  5279. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5280. }
  5281. TEST_F(ServerTest, GetMethod302Redirect) {
  5282. cli_.set_follow_location(true);
  5283. auto res = cli_.Get("/");
  5284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5285. EXPECT_EQ(StatusCode::OK_200, res->status);
  5286. EXPECT_EQ("Hello World!", res->body);
  5287. EXPECT_EQ("/hi", res->location);
  5288. }
  5289. TEST_F(ServerTest, GetMethod404) {
  5290. auto res = cli_.Get("/invalid");
  5291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5292. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5293. }
  5294. TEST_F(ServerTest, HeadMethod200) {
  5295. auto res = cli_.Head("/hi");
  5296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5297. EXPECT_EQ(StatusCode::OK_200, res->status);
  5298. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5299. EXPECT_TRUE(res->body.empty());
  5300. }
  5301. TEST_F(ServerTest, HeadMethod200Static) {
  5302. auto res = cli_.Head("/mount/dir/index.html");
  5303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5304. EXPECT_EQ(StatusCode::OK_200, res->status);
  5305. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5306. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5307. EXPECT_TRUE(res->body.empty());
  5308. }
  5309. TEST_F(ServerTest, HeadMethod404) {
  5310. auto res = cli_.Head("/invalid");
  5311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5312. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5313. EXPECT_TRUE(res->body.empty());
  5314. }
  5315. TEST_F(ServerTest, GetMethodPersonJohn) {
  5316. auto res = cli_.Get("/person/john");
  5317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5318. EXPECT_EQ(StatusCode::OK_200, res->status);
  5319. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5320. EXPECT_EQ("programmer", res->body);
  5321. }
  5322. TEST_F(ServerTest, PostMethod1) {
  5323. auto res = cli_.Get("/person/john1");
  5324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5325. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5326. res = cli_.Post("/person", "name=john1&note=coder",
  5327. "application/x-www-form-urlencoded");
  5328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5329. ASSERT_EQ(StatusCode::OK_200, res->status);
  5330. res = cli_.Get("/person/john1");
  5331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5332. ASSERT_EQ(StatusCode::OK_200, res->status);
  5333. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5334. ASSERT_EQ("coder", res->body);
  5335. }
  5336. TEST_F(ServerTest, PostMethod2) {
  5337. auto res = cli_.Get("/person/john2");
  5338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5339. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5340. Params params;
  5341. params.emplace("name", "john2");
  5342. params.emplace("note", "coder");
  5343. res = cli_.Post("/person", params);
  5344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5345. ASSERT_EQ(StatusCode::OK_200, res->status);
  5346. res = cli_.Get("/person/john2");
  5347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5348. ASSERT_EQ(StatusCode::OK_200, res->status);
  5349. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5350. ASSERT_EQ("coder", res->body);
  5351. }
  5352. TEST_F(ServerTest, PutMethod3) {
  5353. auto res = cli_.Get("/person/john3");
  5354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5355. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5356. Params params;
  5357. params.emplace("name", "john3");
  5358. params.emplace("note", "coder");
  5359. res = cli_.Put("/person", params);
  5360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5361. ASSERT_EQ(StatusCode::OK_200, res->status);
  5362. res = cli_.Get("/person/john3");
  5363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5364. ASSERT_EQ(StatusCode::OK_200, res->status);
  5365. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5366. ASSERT_EQ("coder", res->body);
  5367. }
  5368. TEST_F(ServerTest, DeleteMethod1) {
  5369. auto res = cli_.Get("/person/john4");
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5372. Params params;
  5373. params.emplace("name", "john4");
  5374. params.emplace("note", "coder");
  5375. res = cli_.Post("/person", params);
  5376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5377. ASSERT_EQ(StatusCode::OK_200, res->status);
  5378. res = cli_.Get("/person/john4");
  5379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5380. ASSERT_EQ(StatusCode::OK_200, res->status);
  5381. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5382. ASSERT_EQ("coder", res->body);
  5383. Params delete_params;
  5384. delete_params.emplace("name", "john4");
  5385. res = cli_.Delete("/person", delete_params);
  5386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5387. ASSERT_EQ(StatusCode::OK_200, res->status);
  5388. ASSERT_EQ("DELETED", res->body);
  5389. res = cli_.Get("/person/john4");
  5390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5391. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5392. }
  5393. TEST_F(ServerTest, DeleteMethod2) {
  5394. auto res = cli_.Get("/person/john5");
  5395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5396. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5397. Params params;
  5398. params.emplace("name", "john5");
  5399. params.emplace("note", "developer");
  5400. res = cli_.Post("/person", params);
  5401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5402. ASSERT_EQ(StatusCode::OK_200, res->status);
  5403. res = cli_.Get("/person/john5");
  5404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5405. ASSERT_EQ(StatusCode::OK_200, res->status);
  5406. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5407. ASSERT_EQ("developer", res->body);
  5408. Params delete_params;
  5409. delete_params.emplace("name", "john5");
  5410. Headers headers;
  5411. headers.emplace("Custom-Header", "test-value");
  5412. res = cli_.Delete("/person", headers, delete_params);
  5413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5414. ASSERT_EQ(StatusCode::OK_200, res->status);
  5415. ASSERT_EQ("DELETED", res->body);
  5416. res = cli_.Get("/person/john5");
  5417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5418. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5419. }
  5420. TEST_F(ServerTest, DeleteMethod3) {
  5421. auto res = cli_.Get("/person/john6");
  5422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5423. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5424. Params params;
  5425. params.emplace("name", "john6");
  5426. params.emplace("note", "tester");
  5427. res = cli_.Post("/person", params);
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. ASSERT_EQ(StatusCode::OK_200, res->status);
  5430. res = cli_.Get("/person/john6");
  5431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5432. ASSERT_EQ(StatusCode::OK_200, res->status);
  5433. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5434. ASSERT_EQ("tester", res->body);
  5435. Params delete_params;
  5436. delete_params.emplace("name", "john6");
  5437. Headers headers;
  5438. headers.emplace("Custom-Header", "test-value");
  5439. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5441. ASSERT_EQ(StatusCode::OK_200, res->status);
  5442. ASSERT_EQ("DELETED", res->body);
  5443. res = cli_.Get("/person/john6");
  5444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5445. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5446. }
  5447. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5448. Params params;
  5449. params.emplace("json", JSON_DATA);
  5450. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5452. ASSERT_EQ(StatusCode::OK_200, res->status);
  5453. ASSERT_EQ(JSON_DATA, res->body);
  5454. }
  5455. TEST_F(ServerTest, PostEmptyContent) {
  5456. auto res = cli_.Post("/empty", "", "text/plain");
  5457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5458. ASSERT_EQ(StatusCode::OK_200, res->status);
  5459. ASSERT_EQ("empty", res->body);
  5460. }
  5461. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5462. auto res = cli_.Post("/empty-no-content-type");
  5463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5464. ASSERT_EQ(StatusCode::OK_200, res->status);
  5465. ASSERT_EQ("empty-no-content-type", res->body);
  5466. }
  5467. TEST_F(ServerTest, PostPathOnly) {
  5468. auto res = cli_.Post("/path-only");
  5469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5470. ASSERT_EQ(StatusCode::OK_200, res->status);
  5471. ASSERT_EQ("path-only", res->body);
  5472. }
  5473. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5474. auto res = cli_.Post("/path-headers-only",
  5475. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5477. ASSERT_EQ(StatusCode::OK_200, res->status);
  5478. ASSERT_EQ("path-headers-only", res->body);
  5479. }
  5480. TEST_F(ServerTest, PostLarge) {
  5481. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5483. ASSERT_EQ(StatusCode::OK_200, res->status);
  5484. EXPECT_EQ(LARGE_DATA, res->body);
  5485. }
  5486. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5487. auto res = cli_.Put("/empty-no-content-type");
  5488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5489. ASSERT_EQ(StatusCode::OK_200, res->status);
  5490. ASSERT_EQ("empty-no-content-type", res->body);
  5491. }
  5492. TEST_F(ServerTest, GetMethodDir) {
  5493. auto res = cli_.Get("/dir/");
  5494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5495. EXPECT_EQ(StatusCode::OK_200, res->status);
  5496. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5497. auto body = R"(<html>
  5498. <head>
  5499. </head>
  5500. <body>
  5501. <a href="/dir/test.html">Test</a>
  5502. <a href="/hi">hi</a>
  5503. </body>
  5504. </html>
  5505. )";
  5506. EXPECT_EQ(body, res->body);
  5507. }
  5508. TEST_F(ServerTest, GetMethodDirTest) {
  5509. auto res = cli_.Get("/dir/test.html");
  5510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5511. EXPECT_EQ(StatusCode::OK_200, res->status);
  5512. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5513. EXPECT_EQ("test.html", res->body);
  5514. }
  5515. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5516. auto res = cli_.Get("/dir/../dir/test.html");
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. EXPECT_EQ(StatusCode::OK_200, res->status);
  5519. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5520. EXPECT_EQ("test.html", res->body);
  5521. }
  5522. TEST_F(ServerTest, GetMethodInvalidPath) {
  5523. auto res = cli_.Get("/dir/../test.html");
  5524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5526. }
  5527. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5528. auto res = cli_.Get("/../www/dir/test.html");
  5529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5530. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5531. }
  5532. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5533. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5536. }
  5537. TEST_F(ServerTest, GetMethodDirMountTest) {
  5538. auto res = cli_.Get("/mount/dir/test.html");
  5539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5540. EXPECT_EQ(StatusCode::OK_200, res->status);
  5541. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5542. EXPECT_EQ("test.html", res->body);
  5543. }
  5544. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5545. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5549. EXPECT_EQ("test.html", res->body);
  5550. }
  5551. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5552. auto res = cli_.Get("/mount/dir/../test.html");
  5553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5554. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5555. }
  5556. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5557. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5560. }
  5561. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5562. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5564. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5565. }
  5566. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5567. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5570. }
  5571. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5572. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5574. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5575. }
  5576. TEST_F(ServerTest, PostMethod303) {
  5577. auto res = cli_.Post("/1", "body", "text/plain");
  5578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5579. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5580. EXPECT_EQ("/2", res->get_header_value("Location"));
  5581. }
  5582. TEST_F(ServerTest, PostMethod303Redirect) {
  5583. cli_.set_follow_location(true);
  5584. auto res = cli_.Post("/1", "body", "text/plain");
  5585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5586. EXPECT_EQ(StatusCode::OK_200, res->status);
  5587. EXPECT_EQ("redirected.", res->body);
  5588. EXPECT_EQ("/2", res->location);
  5589. }
  5590. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5591. auto res = cli_.Get("/dir/test.abcde");
  5592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5593. EXPECT_EQ(StatusCode::OK_200, res->status);
  5594. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5595. EXPECT_EQ("abcde", res->body);
  5596. }
  5597. TEST_F(ServerTest, StaticFileRange) {
  5598. auto res =
  5599. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5601. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5602. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5603. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5604. EXPECT_EQ(true, res->has_header("Content-Range"));
  5605. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5606. EXPECT_EQ(std::string("cd"), res->body);
  5607. }
  5608. TEST_F(ServerTest, StaticFileRanges) {
  5609. auto res = cli_.Get("/dir/test.abcde",
  5610. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5612. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5613. EXPECT_TRUE(
  5614. res->get_header_value("Content-Type")
  5615. .find(
  5616. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5617. 0);
  5618. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5619. }
  5620. TEST_F(ServerTest, StaticFileRangeHead) {
  5621. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5623. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5624. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5625. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5626. EXPECT_EQ(true, res->has_header("Content-Range"));
  5627. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5628. }
  5629. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5630. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5633. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5634. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5635. EXPECT_EQ(true, res->has_header("Content-Range"));
  5636. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5637. res->get_header_value("Content-Range"));
  5638. EXPECT_EQ("LAST\n", res->body);
  5639. }
  5640. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5641. auto res =
  5642. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5644. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5645. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5646. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5647. EXPECT_EQ(true, res->has_header("Content-Range"));
  5648. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5649. }
  5650. TEST_F(ServerTest, StaticFileBigFile) {
  5651. auto res = cli_.Get("/dir/1MB.txt");
  5652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5653. EXPECT_EQ(StatusCode::OK_200, res->status);
  5654. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5655. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5656. }
  5657. TEST_F(ServerTest, InvalidBaseDirMount) {
  5658. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5659. }
  5660. TEST_F(ServerTest, Binary) {
  5661. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5662. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5663. "application/octet-stream");
  5664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5665. ASSERT_EQ(StatusCode::OK_200, res->status);
  5666. ASSERT_EQ(4U, res->body.size());
  5667. res = cli_.Put("/binary", binary.data(), binary.size(),
  5668. "application/octet-stream");
  5669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5670. ASSERT_EQ(StatusCode::OK_200, res->status);
  5671. ASSERT_EQ(4U, res->body.size());
  5672. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5673. "application/octet-stream");
  5674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5675. ASSERT_EQ(StatusCode::OK_200, res->status);
  5676. ASSERT_EQ(4U, res->body.size());
  5677. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5678. "application/octet-stream");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. ASSERT_EQ(StatusCode::OK_200, res->status);
  5681. ASSERT_EQ(4U, res->body.size());
  5682. }
  5683. TEST_F(ServerTest, BinaryString) {
  5684. auto binary = std::string("\x00\x01\x02\x03", 4);
  5685. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5687. ASSERT_EQ(StatusCode::OK_200, res->status);
  5688. ASSERT_EQ(4U, res->body.size());
  5689. res = cli_.Put("/binary", binary, "application/octet-stream");
  5690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5691. ASSERT_EQ(StatusCode::OK_200, res->status);
  5692. ASSERT_EQ(4U, res->body.size());
  5693. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5695. ASSERT_EQ(StatusCode::OK_200, res->status);
  5696. ASSERT_EQ(4U, res->body.size());
  5697. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5699. ASSERT_EQ(StatusCode::OK_200, res->status);
  5700. ASSERT_EQ(4U, res->body.size());
  5701. }
  5702. TEST_F(ServerTest, EmptyRequest) {
  5703. auto res = cli_.Get("");
  5704. ASSERT_TRUE(!res);
  5705. EXPECT_EQ(Error::Connection, res.error());
  5706. }
  5707. TEST_F(ServerTest, LongRequest) {
  5708. std::string request;
  5709. for (size_t i = 0; i < 545; i++) {
  5710. request += "/TooLongRequest";
  5711. }
  5712. request += "OK";
  5713. auto res = cli_.Get(request.c_str());
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5716. }
  5717. TEST_F(ServerTest, TooLongRequest) {
  5718. std::string request;
  5719. for (size_t i = 0; i < 546; i++) {
  5720. request += "/TooLongRequest";
  5721. }
  5722. request += "_NG";
  5723. auto start = std::chrono::high_resolution_clock::now();
  5724. cli_.set_keep_alive(true);
  5725. auto res = cli_.Get(request.c_str());
  5726. auto end = std::chrono::high_resolution_clock::now();
  5727. auto elapsed =
  5728. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5729. .count();
  5730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5731. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5732. EXPECT_LE(elapsed, 1000);
  5733. EXPECT_EQ("close", res->get_header_value("Connection"));
  5734. EXPECT_FALSE(cli_.is_socket_open());
  5735. }
  5736. TEST_F(ServerTest, AlmostTooLongRequest) {
  5737. // test for #2046 - URI length check shouldn't include other content on req
  5738. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5739. // leading /, space, HTTP/1.1)
  5740. std::string request =
  5741. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5742. auto res = cli_.Get(request.c_str());
  5743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5744. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5745. }
  5746. TEST_F(ServerTest, LongHeader) {
  5747. Request req;
  5748. req.method = "GET";
  5749. req.path = "/hi";
  5750. std::string host_and_port;
  5751. host_and_port += HOST;
  5752. host_and_port += ":";
  5753. host_and_port += std::to_string(PORT);
  5754. req.headers.emplace("Host", host_and_port.c_str());
  5755. req.headers.emplace("Accept", "*/*");
  5756. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5757. req.headers.emplace(
  5758. "Header-Name",
  5759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5787. "@@@@@@@@@@@@@@@@");
  5788. auto res = std::make_shared<Response>();
  5789. auto error = Error::Success;
  5790. auto ret = cli_.send(req, *res, error);
  5791. ASSERT_TRUE(ret);
  5792. EXPECT_EQ(StatusCode::OK_200, res->status);
  5793. }
  5794. TEST_F(ServerTest, LongQueryValue) {
  5795. auto start = std::chrono::high_resolution_clock::now();
  5796. cli_.set_keep_alive(true);
  5797. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5798. auto end = std::chrono::high_resolution_clock::now();
  5799. auto elapsed =
  5800. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5801. .count();
  5802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5803. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5804. EXPECT_LE(elapsed, 1000);
  5805. EXPECT_EQ("close", res->get_header_value("Connection"));
  5806. EXPECT_FALSE(cli_.is_socket_open());
  5807. }
  5808. TEST_F(ServerTest, TooLongQueryValue) {
  5809. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5810. ASSERT_FALSE(res);
  5811. EXPECT_EQ(Error::Read, res.error());
  5812. }
  5813. TEST_F(ServerTest, TooLongHeader) {
  5814. Request req;
  5815. req.method = "GET";
  5816. req.path = "/hi";
  5817. std::string host_and_port;
  5818. host_and_port += HOST;
  5819. host_and_port += ":";
  5820. host_and_port += std::to_string(PORT);
  5821. req.headers.emplace("Host", host_and_port.c_str());
  5822. req.headers.emplace("Accept", "*/*");
  5823. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5824. req.headers.emplace(
  5825. "Header-Name",
  5826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5854. "@@@@@@@@@@@@@@@@@");
  5855. auto res = std::make_shared<Response>();
  5856. auto error = Error::Success;
  5857. auto ret = cli_.send(req, *res, error);
  5858. ASSERT_TRUE(ret);
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. }
  5861. TEST_F(ServerTest, HeaderCountAtLimit) {
  5862. // Test with headers just under the 100 limit
  5863. httplib::Headers headers;
  5864. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5865. // This should keep us just under the 100 header limit
  5866. for (int i = 0; i < 95; i++) {
  5867. std::string name = "X-Test-Header-" + std::to_string(i);
  5868. std::string value = "value" + std::to_string(i);
  5869. headers.emplace(name, value);
  5870. }
  5871. // This should work fine as we're under the limit
  5872. auto res = cli_.Get("/hi", headers);
  5873. EXPECT_TRUE(res);
  5874. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5875. }
  5876. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5877. // Test with many headers to exceed the 100 limit
  5878. httplib::Headers headers;
  5879. // Add 150 headers to definitely exceed the 100 limit
  5880. for (int i = 0; i < 150; i++) {
  5881. std::string name = "X-Test-Header-" + std::to_string(i);
  5882. std::string value = "value" + std::to_string(i);
  5883. headers.emplace(name, value);
  5884. }
  5885. // This should fail due to exceeding header count limit
  5886. cli_.set_keep_alive(true);
  5887. auto res = cli_.Get("/hi", headers);
  5888. // The server should respond with 400 Bad Request
  5889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5890. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5891. EXPECT_EQ("close", res->get_header_value("Connection"));
  5892. EXPECT_FALSE(cli_.is_socket_open());
  5893. }
  5894. TEST_F(ServerTest, PercentEncoding) {
  5895. auto res = cli_.Get("/e%6edwith%");
  5896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5897. EXPECT_EQ(StatusCode::OK_200, res->status);
  5898. }
  5899. TEST_F(ServerTest, PercentEncodingUnicode) {
  5900. auto res = cli_.Get("/e%u006edwith%");
  5901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5902. EXPECT_EQ(StatusCode::OK_200, res->status);
  5903. }
  5904. TEST_F(ServerTest, InvalidPercentEncoding) {
  5905. auto res = cli_.Get("/%endwith%");
  5906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5907. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5908. }
  5909. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5910. auto res = cli_.Get("/%uendwith%");
  5911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5912. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5913. }
  5914. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5915. auto res = cli_.Get("/hello?aaa=bbb%");
  5916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5917. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5918. }
  5919. TEST_F(ServerTest, PlusSignEncoding) {
  5920. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5922. EXPECT_EQ(StatusCode::OK_200, res->status);
  5923. EXPECT_EQ("a +b", res->body);
  5924. }
  5925. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5926. // This test simulates a potential DoS attack using many headers
  5927. // to verify our security fix prevents memory exhaustion
  5928. httplib::Headers attack_headers;
  5929. // Attempt to add many headers like an attacker would (200 headers to far
  5930. // exceed limit)
  5931. for (int i = 0; i < 200; i++) {
  5932. std::string name = "X-Attack-Header-" + std::to_string(i);
  5933. std::string value = "attack_payload_" + std::to_string(i);
  5934. attack_headers.emplace(name, value);
  5935. }
  5936. // Try to POST with excessive headers
  5937. cli_.set_keep_alive(true);
  5938. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5939. // Should either fail or return 400 Bad Request due to security limit
  5940. if (res) {
  5941. // If we get a response, it should be 400 Bad Request
  5942. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5943. EXPECT_EQ("close", res->get_header_value("Connection"));
  5944. }
  5945. EXPECT_FALSE(cli_.is_socket_open());
  5946. }
  5947. TEST_F(ServerTest, MultipartFormData) {
  5948. UploadFormDataItems items = {
  5949. {"text1", "text default", "", ""},
  5950. {"text2", "aωb", "", ""},
  5951. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5952. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5953. {"file3", "", "", "application/octet-stream"},
  5954. {"file4", "", "", " application/json tmp-string "}};
  5955. auto res = cli_.Post("/multipart", items);
  5956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5957. EXPECT_EQ(StatusCode::OK_200, res->status);
  5958. }
  5959. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5960. UploadFormDataItems items = {
  5961. {"text", "default text", "", ""},
  5962. {"multi_text1", "aaaaa", "", ""},
  5963. {"multi_text1", "bbbbb", "", ""},
  5964. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5965. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5966. "application/json"},
  5967. };
  5968. auto res = cli_.Post("/multipart/multi_file_values", items);
  5969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5970. EXPECT_EQ(StatusCode::OK_200, res->status);
  5971. }
  5972. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5973. auto res = cli_.Get("/hi");
  5974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5975. EXPECT_EQ(StatusCode::OK_200, res->status);
  5976. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5977. EXPECT_EQ("Hello World!", res->body);
  5978. }
  5979. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5980. Request req;
  5981. req.method = "POST";
  5982. req.path = "/chunked";
  5983. std::string host_and_port;
  5984. host_and_port += HOST;
  5985. host_and_port += ":";
  5986. host_and_port += std::to_string(PORT);
  5987. req.headers.emplace("Host", host_and_port.c_str());
  5988. req.headers.emplace("Accept", "*/*");
  5989. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5990. req.headers.emplace("Content-Type", "text/plain");
  5991. req.headers.emplace("Content-Length", "0");
  5992. req.headers.emplace(
  5993. "Transfer-Encoding",
  5994. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5995. // Client does not chunk, so make a chunked body manually.
  5996. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5997. auto res = std::make_shared<Response>();
  5998. auto error = Error::Success;
  5999. auto ret = cli_.send(req, *res, error);
  6000. ASSERT_TRUE(ret);
  6001. EXPECT_EQ(StatusCode::OK_200, res->status);
  6002. }
  6003. template <typename ClientT>
  6004. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6005. int expected_status) {
  6006. Request req;
  6007. req.method = "POST";
  6008. req.path = "/chunked";
  6009. std::string host_and_port;
  6010. host_and_port += HOST;
  6011. host_and_port += ":";
  6012. host_and_port += std::to_string(PORT);
  6013. req.headers.emplace("Host", host_and_port.c_str());
  6014. req.headers.emplace("Content-Length", "0");
  6015. req.headers.emplace("Transfer-Encoding", "chunked");
  6016. req.body = body;
  6017. auto res = std::make_shared<Response>();
  6018. auto error = Error::Success;
  6019. ASSERT_TRUE(cli.send(req, *res, error));
  6020. EXPECT_EQ(expected_status, res->status);
  6021. }
  6022. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6023. // rather than treat them as valid lengths.
  6024. template <typename ClientT>
  6025. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6026. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6027. }
  6028. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6029. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6030. }
  6031. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6032. expect_chunked_body_rejected(
  6033. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6034. }
  6035. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6036. // chunk-size line carries no CR, LF or other control character ahead of its
  6037. // terminator. Such a line must be refused rather than read as extension text.
  6038. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6039. expect_chunked_body_rejected(
  6040. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6041. }
  6042. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6043. expect_chunked_body_rejected(
  6044. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6045. }
  6046. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6047. expect_chunked_body_rejected(
  6048. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6049. }
  6050. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6051. // The literal stays split: a hex escape consumes every hex digit that
  6052. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6053. expect_chunked_body_rejected(
  6054. cli_, "4;a\x01"
  6055. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6056. }
  6057. TEST_F(ServerTest, AcceptsChunkExtension) {
  6058. expect_chunked_body_status(cli_,
  6059. "4;name=value\r\ndech\r\n"
  6060. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6061. "0;last\r\n\r\n",
  6062. StatusCode::OK_200);
  6063. }
  6064. TEST_F(ServerTest, GetStreamed2) {
  6065. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6067. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6068. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6069. EXPECT_EQ(true, res->has_header("Content-Range"));
  6070. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6071. EXPECT_EQ(std::string("ab"), res->body);
  6072. }
  6073. TEST_F(ServerTest, GetStreamed) {
  6074. auto res = cli_.Get("/streamed");
  6075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6076. EXPECT_EQ(StatusCode::OK_200, res->status);
  6077. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6078. EXPECT_EQ(std::string("aaabbb"), res->body);
  6079. }
  6080. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6081. auto res = cli_.Get("/streamed-without-length",
  6082. Headers{make_range_header({{0, -1}})});
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. EXPECT_EQ(StatusCode::OK_200, res->status);
  6085. EXPECT_EQ(false, res->has_header("Content-Length"));
  6086. EXPECT_EQ(false, res->has_header("Content-Range"));
  6087. EXPECT_EQ(std::string("abcdefg"), res->body);
  6088. }
  6089. TEST_F(ServerTest, GetStreamedWithRange1) {
  6090. auto res =
  6091. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6093. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6094. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6095. EXPECT_EQ(true, res->has_header("Content-Range"));
  6096. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6097. EXPECT_EQ(std::string("def"), res->body);
  6098. }
  6099. TEST_F(ServerTest, GetStreamedWithRange2) {
  6100. auto res =
  6101. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6103. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6104. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6105. EXPECT_EQ(true, res->has_header("Content-Range"));
  6106. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6107. EXPECT_EQ(std::string("bcdefg"), res->body);
  6108. }
  6109. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6110. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6112. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6113. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6114. EXPECT_EQ(true, res->has_header("Content-Range"));
  6115. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6116. EXPECT_EQ(std::string("efg"), res->body);
  6117. }
  6118. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6119. auto res =
  6120. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  6121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6122. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6123. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6124. EXPECT_EQ(false, res->has_header("Content-Range"));
  6125. EXPECT_EQ(0U, res->body.size());
  6126. }
  6127. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6128. // Only a 206 is served as a partial representation. Under any other status
  6129. // `apply_ranges()` reported the full content length, so the body must match
  6130. // that header, and the content provider must never be asked for an offset
  6131. // outside the representation.
  6132. auto check = [&](int status, const char *range) {
  6133. auto path =
  6134. std::string("/streamed-with-range?status=") + std::to_string(status);
  6135. auto ctx = path + " Range: " + range;
  6136. auto res = cli_.Get(path, Headers{{"Range", range}});
  6137. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6138. EXPECT_EQ(status, res->status) << ctx;
  6139. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6140. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6141. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6142. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6143. };
  6144. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6145. check(403, "bytes=3-5");
  6146. // The offset is far past the representation.
  6147. check(403, "bytes=100000-100200");
  6148. // `first_pos` is still -1 here, and the bounds asserts in
  6149. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6150. check(403, "bytes=-3");
  6151. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6152. // multipart branch would have written one that is empty.
  6153. check(403, "bytes=1-2, 4-5");
  6154. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6155. // covers the whole representation.
  6156. check(200, "bytes=3-5");
  6157. check(200, "bytes=1-2, 4-5");
  6158. }
  6159. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6160. auto res =
  6161. cli_.Get("/streamed-with-range",
  6162. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6163. "92233720368547758079223372036854775807"}});
  6164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6165. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6166. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6167. EXPECT_EQ(false, res->has_header("Content-Range"));
  6168. EXPECT_EQ(0U, res->body.size());
  6169. }
  6170. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6171. auto res = cli_.Get(
  6172. "/with-range",
  6173. Headers{{"Range",
  6174. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6175. {"Accept-Encoding", ""}});
  6176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6177. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6178. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6179. EXPECT_EQ(true, res->has_header("Content-Range"));
  6180. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6181. EXPECT_EQ(std::string("abcdefg"), res->body);
  6182. }
  6183. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6184. auto res = cli_.Get("/with-range", Headers{
  6185. {"Range", "bytes=0-"},
  6186. {"Accept-Encoding", ""},
  6187. });
  6188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6189. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6190. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6191. EXPECT_EQ(true, res->has_header("Content-Range"));
  6192. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6193. EXPECT_EQ(std::string("abcdefg"), res->body);
  6194. }
  6195. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6196. auto res = cli_.Get("/streamed-with-range",
  6197. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6200. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6201. EXPECT_EQ(false, res->has_header("Content-Range"));
  6202. EXPECT_EQ(267U, res->body.size());
  6203. // Check that both range contents are present
  6204. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6205. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6206. // Check that Content-Range headers are present for both ranges
  6207. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6208. std::string::npos);
  6209. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6210. std::string::npos);
  6211. }
  6212. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6213. Ranges ranges;
  6214. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6215. ranges.emplace_back(0, -1);
  6216. }
  6217. auto res = cli_.Get("/streamed-with-range?error",
  6218. Headers{{make_range_header(ranges)}});
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6221. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6222. EXPECT_EQ(false, res->has_header("Content-Range"));
  6223. EXPECT_EQ(0U, res->body.size());
  6224. }
  6225. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6226. auto res = cli_.Get("/streamed-with-range",
  6227. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6229. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6230. EXPECT_EQ(5U, res->body.size());
  6231. // Check that overlapping ranges are coalesced into a single range
  6232. EXPECT_EQ("bcdef", res->body);
  6233. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6234. // Should be single range, not multipart
  6235. EXPECT_TRUE(res->has_header("Content-Range"));
  6236. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6237. }
  6238. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6239. auto res = cli_.Get("/streamed-with-range",
  6240. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6242. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6243. EXPECT_EQ(268U, res->body.size());
  6244. // Check that both range contents are present
  6245. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6246. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6247. // Check that Content-Range headers are present for both ranges
  6248. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6249. std::string::npos);
  6250. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6251. std::string::npos);
  6252. }
  6253. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6254. auto res = cli_.Get("/streamed-with-range",
  6255. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6257. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6258. EXPECT_EQ(269U, res->body.size());
  6259. // Check that both duplicate range contents are present
  6260. size_t first_abc = res->body.find("abc\r\n");
  6261. EXPECT_TRUE(first_abc != std::string::npos);
  6262. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6263. EXPECT_TRUE(second_abc != std::string::npos);
  6264. // Check that Content-Range headers are present for both ranges
  6265. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6266. EXPECT_TRUE(first_range != std::string::npos);
  6267. size_t second_range =
  6268. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6269. EXPECT_TRUE(second_range != std::string::npos);
  6270. }
  6271. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6272. auto res =
  6273. cli_.Get("/streamed-with-range?error",
  6274. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6276. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6277. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6278. EXPECT_EQ(false, res->has_header("Content-Range"));
  6279. EXPECT_EQ(0U, res->body.size());
  6280. }
  6281. TEST_F(ServerTest, GetStreamedEndless) {
  6282. uint64_t offset = 0;
  6283. auto res = cli_.Get("/streamed-cancel",
  6284. [&](const char * /*data*/, uint64_t data_length) {
  6285. if (offset < 100) {
  6286. offset += data_length;
  6287. return true;
  6288. }
  6289. return false;
  6290. });
  6291. ASSERT_TRUE(!res);
  6292. EXPECT_EQ(Error::Canceled, res.error());
  6293. }
  6294. TEST_F(ServerTest, ClientStop) {
  6295. std::atomic_size_t count{4};
  6296. std::vector<std::thread> threads;
  6297. for (auto i = count.load(); i != 0; --i) {
  6298. threads.emplace_back([&]() {
  6299. auto res = cli_.Get("/streamed-cancel",
  6300. [&](const char *, uint64_t) { return true; });
  6301. --count;
  6302. ASSERT_TRUE(!res);
  6303. EXPECT_TRUE(res.error() == Error::Canceled ||
  6304. res.error() == Error::Read || res.error() == Error::Write);
  6305. });
  6306. }
  6307. std::this_thread::sleep_for(std::chrono::seconds(2));
  6308. while (count != 0) {
  6309. cli_.stop();
  6310. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6311. }
  6312. for (auto &t : threads) {
  6313. t.join();
  6314. }
  6315. }
  6316. TEST_F(ServerTest, GetWithRange1) {
  6317. auto res = cli_.Get("/with-range", Headers{
  6318. make_range_header({{3, 5}}),
  6319. {"Accept-Encoding", ""},
  6320. });
  6321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6322. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6323. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6324. EXPECT_EQ(true, res->has_header("Content-Range"));
  6325. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6326. EXPECT_EQ(std::string("def"), res->body);
  6327. }
  6328. TEST_F(ServerTest, GetWithRange2) {
  6329. auto res = cli_.Get("/with-range", Headers{
  6330. make_range_header({{1, -1}}),
  6331. {"Accept-Encoding", ""},
  6332. });
  6333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6334. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6335. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6336. EXPECT_EQ(true, res->has_header("Content-Range"));
  6337. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6338. EXPECT_EQ(std::string("bcdefg"), res->body);
  6339. }
  6340. TEST_F(ServerTest, GetWithRange3) {
  6341. auto res = cli_.Get("/with-range", Headers{
  6342. make_range_header({{0, 0}}),
  6343. {"Accept-Encoding", ""},
  6344. });
  6345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6346. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6347. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6348. EXPECT_EQ(true, res->has_header("Content-Range"));
  6349. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6350. EXPECT_EQ(std::string("a"), res->body);
  6351. }
  6352. TEST_F(ServerTest, GetWithRange4) {
  6353. auto res = cli_.Get("/with-range", Headers{
  6354. make_range_header({{-1, 2}}),
  6355. {"Accept-Encoding", ""},
  6356. });
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6359. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6360. EXPECT_EQ(true, res->has_header("Content-Range"));
  6361. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6362. EXPECT_EQ(std::string("fg"), res->body);
  6363. }
  6364. TEST_F(ServerTest, GetWithRange5) {
  6365. auto res = cli_.Get("/with-range", Headers{
  6366. make_range_header({{0, 5}}),
  6367. {"Accept-Encoding", ""},
  6368. });
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6371. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6372. EXPECT_EQ(true, res->has_header("Content-Range"));
  6373. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6374. EXPECT_EQ(std::string("abcdef"), res->body);
  6375. }
  6376. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6377. auto res =
  6378. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6380. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6381. }
  6382. TEST_F(ServerTest, GetWithRangeMultipart) {
  6383. auto res =
  6384. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6387. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6388. EXPECT_EQ(false, res->has_header("Content-Range"));
  6389. EXPECT_EQ(267U, res->body.size());
  6390. }
  6391. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6392. auto res = cli_.Get("/with-range",
  6393. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6395. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6396. }
  6397. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6398. auto res = cli_.Get("/with-range-customized-response",
  6399. Headers{{make_range_header({{1, 2}})}});
  6400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6401. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6402. EXPECT_EQ(true, res->has_header("Content-Length"));
  6403. EXPECT_EQ(false, res->has_header("Content-Range"));
  6404. EXPECT_EQ(JSON_DATA, res->body);
  6405. }
  6406. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6407. auto res = cli_.Get("/with-range-customized-response",
  6408. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6410. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6411. EXPECT_EQ(true, res->has_header("Content-Length"));
  6412. EXPECT_EQ(false, res->has_header("Content-Range"));
  6413. EXPECT_EQ(JSON_DATA, res->body);
  6414. }
  6415. TEST_F(ServerTest, Issue1772) {
  6416. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6419. }
  6420. TEST_F(ServerTest, Issue609) {
  6421. auto res = cli_.Delete("/issue609");
  6422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6423. EXPECT_EQ(StatusCode::OK_200, res->status);
  6424. EXPECT_EQ(std::string("ok"), res->body);
  6425. }
  6426. TEST_F(ServerTest, GetStreamedChunked) {
  6427. auto res = cli_.Get("/streamed-chunked");
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. EXPECT_EQ(StatusCode::OK_200, res->status);
  6430. EXPECT_EQ(std::string("123456789"), res->body);
  6431. }
  6432. TEST_F(ServerTest, GetStreamedChunked2) {
  6433. auto res = cli_.Get("/streamed-chunked2");
  6434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6435. EXPECT_EQ(StatusCode::OK_200, res->status);
  6436. EXPECT_EQ(std::string("123456789"), res->body);
  6437. }
  6438. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6439. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ(std::string("123456789"), res->body);
  6443. EXPECT_TRUE(res->has_header("Trailer"));
  6444. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6445. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6446. // Trailers are now stored separately from headers (security fix)
  6447. EXPECT_EQ(2U, res->trailers.size());
  6448. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6449. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6450. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6451. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6452. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6453. // Verify trailers are NOT in headers (security verification)
  6454. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6455. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6456. }
  6457. TEST_F(ServerTest, LargeChunkedPost) {
  6458. Request req;
  6459. req.method = "POST";
  6460. req.path = "/large-chunked";
  6461. std::string host_and_port;
  6462. host_and_port += HOST;
  6463. host_and_port += ":";
  6464. host_and_port += std::to_string(PORT);
  6465. req.headers.emplace("Host", host_and_port.c_str());
  6466. req.headers.emplace("Accept", "*/*");
  6467. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6468. req.headers.emplace("Content-Type", "text/plain");
  6469. req.headers.emplace("Content-Length", "0");
  6470. req.headers.emplace("Transfer-Encoding", "chunked");
  6471. std::string long_string(30 * 1024u, 'a');
  6472. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6473. // Attempt to make a large enough post to exceed OS buffers, to test that
  6474. // the server handles short reads if the full chunk data isn't available.
  6475. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6476. auto res = std::make_shared<Response>();
  6477. auto error = Error::Success;
  6478. auto ret = cli_.send(req, *res, error);
  6479. ASSERT_TRUE(ret);
  6480. EXPECT_EQ(StatusCode::OK_200, res->status);
  6481. }
  6482. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6483. auto res = cli_.Get("/remote_addr");
  6484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6485. EXPECT_EQ(StatusCode::OK_200, res->status);
  6486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6487. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6488. }
  6489. TEST_F(ServerTest, GetMethodLocalAddr) {
  6490. auto res = cli_.Get("/local_addr");
  6491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6492. EXPECT_EQ(StatusCode::OK_200, res->status);
  6493. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6494. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6495. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6496. }
  6497. TEST_F(ServerTest, HTTPResponseSplitting) {
  6498. auto res = cli_.Get("/http_response_splitting");
  6499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6500. EXPECT_EQ(StatusCode::OK_200, res->status);
  6501. }
  6502. TEST_F(ServerTest, SlowRequest) {
  6503. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6504. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6505. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6506. }
  6507. #if 0
  6508. TEST_F(ServerTest, SlowPost) {
  6509. char buffer[64 * 1024];
  6510. memset(buffer, 0x42, sizeof(buffer));
  6511. auto res = cli_.Post(
  6512. "/slowpost", 64 * 1024 * 1024,
  6513. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6514. auto ret = sink.write(buffer, sizeof(buffer));
  6515. EXPECT_TRUE(ret);
  6516. return true;
  6517. },
  6518. "text/plain");
  6519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6520. EXPECT_EQ(StatusCode::OK_200, res->status);
  6521. }
  6522. TEST_F(ServerTest, SlowPostFail) {
  6523. char buffer[64 * 1024];
  6524. memset(buffer, 0x42, sizeof(buffer));
  6525. cli_.set_write_timeout(std::chrono::seconds(0));
  6526. auto res = cli_.Post(
  6527. "/slowpost", 64 * 1024 * 1024,
  6528. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6529. sink.write(buffer, sizeof(buffer));
  6530. return true;
  6531. },
  6532. "text/plain");
  6533. ASSERT_TRUE(!res);
  6534. EXPECT_EQ(Error::Write, res.error());
  6535. }
  6536. #endif
  6537. TEST_F(ServerTest, Put) {
  6538. auto res = cli_.Put("/put", "PUT", "text/plain");
  6539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6540. EXPECT_EQ(StatusCode::OK_200, res->status);
  6541. EXPECT_EQ("PUT", res->body);
  6542. }
  6543. TEST_F(ServerTest, PutWithContentProvider) {
  6544. auto res = cli_.Put(
  6545. "/put", 3,
  6546. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6547. sink.os << "PUT";
  6548. return true;
  6549. },
  6550. "text/plain");
  6551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6552. EXPECT_EQ(StatusCode::OK_200, res->status);
  6553. EXPECT_EQ("PUT", res->body);
  6554. }
  6555. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6556. auto res = cli_.Post(
  6557. "/post", 42,
  6558. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6559. return false;
  6560. },
  6561. "text/plain");
  6562. ASSERT_TRUE(!res);
  6563. EXPECT_EQ(Error::Canceled, res.error());
  6564. }
  6565. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6566. auto res = cli_.Put(
  6567. "/put",
  6568. [](size_t /*offset*/, DataSink &sink) {
  6569. sink.os << "PUT";
  6570. sink.done();
  6571. return true;
  6572. },
  6573. "text/plain");
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::OK_200, res->status);
  6576. EXPECT_EQ("PUT", res->body);
  6577. }
  6578. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6579. auto res = cli_.Post(
  6580. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6581. "text/plain");
  6582. ASSERT_TRUE(!res);
  6583. EXPECT_EQ(Error::Canceled, res.error());
  6584. }
  6585. TEST_F(ServerTest, PostLoopBack) {
  6586. std::string body;
  6587. auto res = cli_.Post(
  6588. "/post-loopback", 9,
  6589. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6590. EXPECT_EQ(9u, length);
  6591. sink.write("123", 3);
  6592. sink.write("456", 3);
  6593. sink.write("789", 3);
  6594. return true;
  6595. },
  6596. "text/plain",
  6597. [&body](const char *data, size_t data_length) {
  6598. body.append(data, data_length);
  6599. return true;
  6600. });
  6601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6602. EXPECT_EQ(StatusCode::OK_200, res->status);
  6603. EXPECT_EQ("123456789", body);
  6604. }
  6605. TEST_F(ServerTest, PutLoopBack) {
  6606. std::string body;
  6607. auto res = cli_.Put(
  6608. "/put-loopback", 9,
  6609. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6610. EXPECT_EQ(9u, length);
  6611. sink.write("123", 3);
  6612. sink.write("456", 3);
  6613. sink.write("789", 3);
  6614. return true;
  6615. },
  6616. "text/plain",
  6617. [&body](const char *data, size_t data_length) {
  6618. body.append(data, data_length);
  6619. return true;
  6620. });
  6621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6622. EXPECT_EQ(StatusCode::OK_200, res->status);
  6623. EXPECT_EQ("123456789", body);
  6624. }
  6625. TEST_F(ServerTest, PatchLoopBack) {
  6626. std::string body;
  6627. auto res = cli_.Patch(
  6628. "/patch-loopback", 9,
  6629. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6630. EXPECT_EQ(9u, length);
  6631. sink.write("123", 3);
  6632. sink.write("456", 3);
  6633. sink.write("789", 3);
  6634. return true;
  6635. },
  6636. "text/plain",
  6637. [&body](const char *data, size_t data_length) {
  6638. body.append(data, data_length);
  6639. return true;
  6640. });
  6641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6642. EXPECT_EQ(StatusCode::OK_200, res->status);
  6643. EXPECT_EQ("123456789", body);
  6644. }
  6645. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6646. std::string body;
  6647. auto res = cli_.Post(
  6648. "/post-loopback",
  6649. [](size_t /*offset*/, DataSink &sink) {
  6650. sink.write("123", 3);
  6651. sink.write("456", 3);
  6652. sink.write("789", 3);
  6653. sink.done();
  6654. return true;
  6655. },
  6656. "text/plain",
  6657. [&body](const char *data, size_t data_length) {
  6658. body.append(data, data_length);
  6659. return true;
  6660. });
  6661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6662. EXPECT_EQ(StatusCode::OK_200, res->status);
  6663. EXPECT_EQ("123456789", body);
  6664. }
  6665. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6666. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6667. cli_.set_compress(true);
  6668. auto res = cli_.Put(
  6669. "/put", 3,
  6670. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6671. sink.os << "PUT";
  6672. return true;
  6673. },
  6674. "text/plain");
  6675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6676. EXPECT_EQ(StatusCode::OK_200, res->status);
  6677. EXPECT_EQ("PUT", res->body);
  6678. }
  6679. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6680. cli_.set_compress(true);
  6681. auto res = cli_.Post(
  6682. "/post", 42,
  6683. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6684. return false;
  6685. },
  6686. "text/plain");
  6687. ASSERT_TRUE(!res);
  6688. EXPECT_EQ(Error::Canceled, res.error());
  6689. }
  6690. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6691. cli_.set_compress(true);
  6692. auto res = cli_.Put(
  6693. "/put",
  6694. [](size_t /*offset*/, DataSink &sink) {
  6695. sink.os << "PUT";
  6696. sink.done();
  6697. return true;
  6698. },
  6699. "text/plain");
  6700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6701. EXPECT_EQ(StatusCode::OK_200, res->status);
  6702. EXPECT_EQ("PUT", res->body);
  6703. }
  6704. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6705. cli_.set_compress(true);
  6706. auto res = cli_.Post(
  6707. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6708. "text/plain");
  6709. ASSERT_TRUE(!res);
  6710. EXPECT_EQ(Error::Canceled, res.error());
  6711. }
  6712. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6713. cli_.set_compress(true);
  6714. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. EXPECT_EQ(StatusCode::OK_200, res->status);
  6717. EXPECT_EQ(LARGE_DATA, res->body);
  6718. }
  6719. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6720. #ifdef CPPHTTPLIB_SSL_ENABLED
  6721. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6722. Client cli(s.c_str());
  6723. cli.enable_server_certificate_verification(false);
  6724. #else
  6725. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6726. Client cli(s.c_str());
  6727. #endif
  6728. cli.set_compress(true);
  6729. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6731. EXPECT_EQ(StatusCode::OK_200, res->status);
  6732. EXPECT_EQ(LARGE_DATA, res->body);
  6733. // The compressed size should be less than a 10th of the original. May vary
  6734. // depending on the zlib library.
  6735. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6736. static_cast<uint64_t>(10 * 1024 * 1024));
  6737. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6738. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6739. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6740. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6741. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6742. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6743. #endif
  6744. }
  6745. TEST_F(ServerTest, PutContentWithDeflate) {
  6746. cli_.set_compress(false);
  6747. Headers headers;
  6748. headers.emplace("Content-Encoding", "deflate");
  6749. // PUT in deflate format:
  6750. auto res = cli_.Put("/put", headers,
  6751. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6753. EXPECT_EQ(StatusCode::OK_200, res->status);
  6754. EXPECT_EQ("PUT", res->body);
  6755. }
  6756. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6757. Headers headers;
  6758. headers.emplace("Accept-Encoding", "gzip, deflate");
  6759. auto res = cli_.Get("/streamed-chunked", headers);
  6760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6761. EXPECT_EQ(StatusCode::OK_200, res->status);
  6762. EXPECT_EQ(std::string("123456789"), res->body);
  6763. }
  6764. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6765. Headers headers;
  6766. headers.emplace("Accept-Encoding", "gzip, deflate");
  6767. auto res = cli_.Get("/streamed-chunked2", headers);
  6768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6769. EXPECT_EQ(StatusCode::OK_200, res->status);
  6770. EXPECT_EQ(std::string("123456789"), res->body);
  6771. }
  6772. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6773. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6775. EXPECT_EQ(StatusCode::OK_200, res->status);
  6776. }
  6777. TEST(GzipDecompressor, ChunkedDecompression) {
  6778. std::string data;
  6779. for (size_t i = 0; i < 32 * 1024; ++i) {
  6780. data.push_back(static_cast<char>('a' + i % 26));
  6781. }
  6782. std::string compressed_data;
  6783. {
  6784. httplib::detail::gzip_compressor compressor;
  6785. bool result = compressor.compress(
  6786. data.data(), data.size(),
  6787. /*last=*/true,
  6788. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6789. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6790. compressed_data_size);
  6791. return true;
  6792. });
  6793. ASSERT_TRUE(result);
  6794. }
  6795. std::string decompressed_data;
  6796. {
  6797. httplib::detail::gzip_decompressor decompressor;
  6798. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6799. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6800. size_t chunk_size = 130;
  6801. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6802. chunk_begin += chunk_size) {
  6803. size_t current_chunk_size =
  6804. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6805. bool result = decompressor.decompress(
  6806. compressed_data.data() + chunk_begin, current_chunk_size,
  6807. [&](const char *decompressed_data_chunk,
  6808. size_t decompressed_data_chunk_size) {
  6809. decompressed_data.insert(decompressed_data.size(),
  6810. decompressed_data_chunk,
  6811. decompressed_data_chunk_size);
  6812. return true;
  6813. });
  6814. ASSERT_TRUE(result);
  6815. }
  6816. }
  6817. ASSERT_EQ(data, decompressed_data);
  6818. }
  6819. TEST(GzipDecompressor, DeflateDecompression) {
  6820. std::string original_text = "Raw deflate without gzip";
  6821. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6822. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6823. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6824. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6825. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6826. std::string decompressed_data;
  6827. {
  6828. httplib::detail::gzip_decompressor decompressor;
  6829. bool result = decompressor.decompress(
  6830. compressed_data.data(), compressed_data.size(),
  6831. [&](const char *decompressed_data_chunk,
  6832. size_t decompressed_data_chunk_size) {
  6833. decompressed_data.insert(decompressed_data.size(),
  6834. decompressed_data_chunk,
  6835. decompressed_data_chunk_size);
  6836. return true;
  6837. });
  6838. ASSERT_TRUE(result);
  6839. }
  6840. ASSERT_EQ(original_text, decompressed_data);
  6841. }
  6842. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6843. std::string original_text = "Raw deflate without gzip";
  6844. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6845. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6846. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6847. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6848. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6849. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6850. std::string decompressed_data;
  6851. {
  6852. httplib::detail::gzip_decompressor decompressor;
  6853. bool result = decompressor.decompress(
  6854. compressed_data.data(), compressed_data.size(),
  6855. [&](const char *decompressed_data_chunk,
  6856. size_t decompressed_data_chunk_size) {
  6857. decompressed_data.insert(decompressed_data.size(),
  6858. decompressed_data_chunk,
  6859. decompressed_data_chunk_size);
  6860. return true;
  6861. });
  6862. ASSERT_TRUE(result);
  6863. }
  6864. ASSERT_EQ(original_text, decompressed_data);
  6865. }
  6866. #endif
  6867. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6868. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6869. Headers headers;
  6870. headers.emplace("Accept-Encoding", "br");
  6871. auto res = cli_.Get("/streamed-chunked", headers);
  6872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6873. EXPECT_EQ(StatusCode::OK_200, res->status);
  6874. EXPECT_EQ(std::string("123456789"), res->body);
  6875. }
  6876. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6877. Headers headers;
  6878. headers.emplace("Accept-Encoding", "br");
  6879. auto res = cli_.Get("/streamed-chunked2", headers);
  6880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6881. EXPECT_EQ(StatusCode::OK_200, res->status);
  6882. EXPECT_EQ(std::string("123456789"), res->body);
  6883. }
  6884. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6885. cli_.set_compress(true);
  6886. auto res = cli_.Put(
  6887. "/put", 3,
  6888. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6889. sink.os << "PUT";
  6890. return true;
  6891. },
  6892. "text/plain");
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. EXPECT_EQ(StatusCode::OK_200, res->status);
  6895. EXPECT_EQ("PUT", res->body);
  6896. }
  6897. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6898. cli_.set_compress(true);
  6899. auto res = cli_.Put(
  6900. "/put",
  6901. [](size_t /*offset*/, DataSink &sink) {
  6902. sink.os << "PUT";
  6903. sink.done();
  6904. return true;
  6905. },
  6906. "text/plain");
  6907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6908. EXPECT_EQ(StatusCode::OK_200, res->status);
  6909. EXPECT_EQ("PUT", res->body);
  6910. }
  6911. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6912. cli_.set_compress(true);
  6913. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6915. EXPECT_EQ(StatusCode::OK_200, res->status);
  6916. EXPECT_EQ(LARGE_DATA, res->body);
  6917. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6918. }
  6919. #endif
  6920. TEST_F(ServerTest, Patch) {
  6921. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. EXPECT_EQ("PATCH", res->body);
  6925. }
  6926. TEST_F(ServerTest, Delete) {
  6927. auto res = cli_.Delete("/delete");
  6928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6929. EXPECT_EQ(StatusCode::OK_200, res->status);
  6930. EXPECT_EQ("DELETE", res->body);
  6931. }
  6932. TEST_F(ServerTest, DeleteContentReceiver) {
  6933. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6935. EXPECT_EQ(StatusCode::OK_200, res->status);
  6936. EXPECT_EQ("content", res->body);
  6937. }
  6938. TEST_F(ServerTest, Options) {
  6939. auto res = cli_.Options("*");
  6940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6941. EXPECT_EQ(StatusCode::OK_200, res->status);
  6942. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6943. EXPECT_TRUE(res->body.empty());
  6944. }
  6945. TEST_F(ServerTest, URL) {
  6946. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6948. EXPECT_EQ(StatusCode::OK_200, res->status);
  6949. }
  6950. TEST_F(ServerTest, ArrayParam) {
  6951. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6953. EXPECT_EQ(StatusCode::OK_200, res->status);
  6954. }
  6955. TEST_F(ServerTest, ArrayParamValues) {
  6956. auto res =
  6957. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6959. EXPECT_EQ(StatusCode::OK_200, res->status);
  6960. }
  6961. TEST_F(ServerTest, NoMultipleHeaders) {
  6962. Headers headers = {{"Content-Length", "5"}};
  6963. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6964. "text/plain");
  6965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6966. EXPECT_EQ(StatusCode::OK_200, res->status);
  6967. }
  6968. TEST_F(ServerTest, PostContentReceiver) {
  6969. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6971. ASSERT_EQ(StatusCode::OK_200, res->status);
  6972. ASSERT_EQ("content", res->body);
  6973. }
  6974. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6975. UploadFormDataItems items = {
  6976. {"text1", "text default", "", ""},
  6977. {"text2", "aωb", "", ""},
  6978. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6979. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6980. {"file3", "", "", "application/octet-stream"},
  6981. };
  6982. auto res = cli_.Post("/content_receiver", items);
  6983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6984. EXPECT_EQ(StatusCode::OK_200, res->status);
  6985. }
  6986. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6987. UploadFormDataItems items = {
  6988. {"text1", "text default", "", ""},
  6989. {"text2", "aωb", "", ""},
  6990. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6991. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6992. {"file3", "", "", "application/octet-stream"},
  6993. };
  6994. auto boundary = std::string("+++++");
  6995. std::string body;
  6996. for (const auto &item : items) {
  6997. body += "--" + boundary + "\r\n";
  6998. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6999. if (!item.filename.empty()) {
  7000. body += "; filename=\"" + item.filename + "\"";
  7001. }
  7002. body += "\r\n";
  7003. if (!item.content_type.empty()) {
  7004. body += "Content-Type: " + item.content_type + "\r\n";
  7005. }
  7006. body += "\r\n";
  7007. body += item.content + "\r\n";
  7008. }
  7009. body += "--" + boundary + "--\r\n";
  7010. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7011. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7013. EXPECT_EQ(StatusCode::OK_200, res->status);
  7014. }
  7015. TEST(MultipartFormDataTest, FieldEscaping) {
  7016. Server svr;
  7017. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7018. const ContentReader &content_reader) {
  7019. ASSERT_TRUE(req.is_multipart_form_data());
  7020. std::vector<FormData> received;
  7021. content_reader(
  7022. [&](const FormData &file) {
  7023. received.push_back(file);
  7024. return true;
  7025. },
  7026. [&](const char *data, size_t data_length) {
  7027. received.back().content.append(data, data_length);
  7028. return true;
  7029. });
  7030. // '"', CR and LF in names and filenames are escaped following the
  7031. // WHATWG HTML standard, so each part still parses as a single part
  7032. // with no injected headers. Content types get CR/LF escaped too,
  7033. // while '"' (legal there, e.g. quoted charset) is preserved.
  7034. ASSERT_EQ(4U, received.size());
  7035. EXPECT_EQ("na%22me", received[0].name);
  7036. EXPECT_EQ("quoted name", received[0].content);
  7037. EXPECT_EQ("file", received[1].name);
  7038. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7039. received[1].filename);
  7040. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7041. EXPECT_EQ("injected", received[1].content);
  7042. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7043. EXPECT_EQ("my%22file.txt", received[2].filename);
  7044. EXPECT_EQ("cr lf name", received[2].content);
  7045. EXPECT_EQ("typed", received[3].name);
  7046. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7047. received[3].content_type);
  7048. EXPECT_EQ("typed content", received[3].content);
  7049. });
  7050. auto port = svr.bind_to_any_port("localhost");
  7051. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7052. auto se = detail::scope_exit([&] {
  7053. svr.stop();
  7054. t.join();
  7055. ASSERT_FALSE(svr.is_running());
  7056. });
  7057. svr.wait_until_ready();
  7058. Client cli("localhost", port);
  7059. UploadFormDataItems items = {
  7060. {"na\"me", "quoted name", "", ""},
  7061. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7062. "application/octet-stream"},
  7063. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7064. {"typed", "typed content", "",
  7065. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7066. };
  7067. auto res = cli.Post("/post", items);
  7068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7069. EXPECT_EQ(StatusCode::OK_200, res->status);
  7070. }
  7071. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7072. const UploadFormDataItems items = {
  7073. {"name1", "Content 1", "", ""},
  7074. {"name2", "Content 2", "file2.txt", "text/plain"},
  7075. };
  7076. Server svr;
  7077. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7078. const ContentReader &content_reader) {
  7079. ASSERT_TRUE(req.is_multipart_form_data());
  7080. std::vector<FormData> received;
  7081. content_reader(
  7082. [&](const FormData &file) {
  7083. received.push_back(file);
  7084. return true;
  7085. },
  7086. [&](const char *data, size_t data_length) {
  7087. received.back().content.append(data, data_length);
  7088. return true;
  7089. });
  7090. ASSERT_EQ(2U, received.size());
  7091. EXPECT_EQ("name1", received[0].name);
  7092. EXPECT_EQ("Content 1", received[0].content);
  7093. EXPECT_EQ("name2", received[1].name);
  7094. EXPECT_EQ("Content 2", received[1].content);
  7095. EXPECT_EQ("file2.txt", received[1].filename);
  7096. EXPECT_EQ("text/plain", received[1].content_type);
  7097. });
  7098. auto port = svr.bind_to_any_port("localhost");
  7099. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7100. auto se = detail::scope_exit([&] {
  7101. svr.stop();
  7102. t.join();
  7103. ASSERT_FALSE(svr.is_running());
  7104. });
  7105. svr.wait_until_ready();
  7106. Client cli("localhost", port);
  7107. // Whole-body serialization with a generated boundary
  7108. {
  7109. MultipartFormDataWriter writer;
  7110. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7111. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7112. writer.content_type());
  7113. auto body = writer.serialize(items);
  7114. EXPECT_EQ(body.size(), writer.content_length(items));
  7115. auto res = cli.Post("/post", body, writer.content_type());
  7116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7117. EXPECT_EQ(StatusCode::OK_200, res->status);
  7118. }
  7119. // Per-part framing with a custom boundary via a content provider
  7120. {
  7121. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7122. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7123. MultipartFormDataWriter writer("custom-boundary_123");
  7124. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7125. std::string body;
  7126. for (const auto &item : items) {
  7127. body += writer.item_begin(item);
  7128. body += item.content;
  7129. body += MultipartFormDataWriter::item_end();
  7130. }
  7131. body += writer.finish();
  7132. EXPECT_EQ(body.size(), writer.content_length(items));
  7133. auto res = cli.Post(
  7134. "/post", body.size(),
  7135. [&](size_t offset, size_t length, DataSink &sink) {
  7136. sink.write(body.data() + offset, length);
  7137. return true;
  7138. },
  7139. writer.content_type());
  7140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7141. EXPECT_EQ(StatusCode::OK_200, res->status);
  7142. }
  7143. }
  7144. TEST_F(ServerTest, PostContentReceiverGzip) {
  7145. cli_.set_compress(true);
  7146. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7148. ASSERT_EQ(StatusCode::OK_200, res->status);
  7149. ASSERT_EQ("content", res->body);
  7150. }
  7151. TEST_F(ServerTest, PutContentReceiver) {
  7152. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. ASSERT_EQ(StatusCode::OK_200, res->status);
  7155. ASSERT_EQ("content", res->body);
  7156. }
  7157. TEST_F(ServerTest, PatchContentReceiver) {
  7158. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7160. ASSERT_EQ(StatusCode::OK_200, res->status);
  7161. ASSERT_EQ("content", res->body);
  7162. }
  7163. template <typename ClientType>
  7164. void TestWithHeadersAndContentReceiver(
  7165. ClientType &cli,
  7166. std::function<Result(ClientType &, const std::string &, const Headers &,
  7167. const std::string &, const std::string &,
  7168. ContentReceiver, DownloadProgress)>
  7169. request_func) {
  7170. Headers headers;
  7171. headers.emplace("X-Custom-Header", "test-value");
  7172. std::string received_body;
  7173. auto res = request_func(
  7174. cli, "/content_receiver", headers, "content", "application/json",
  7175. [&](const char *data, size_t data_length) {
  7176. received_body.append(data, data_length);
  7177. return true;
  7178. },
  7179. nullptr);
  7180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7181. EXPECT_EQ(StatusCode::OK_200, res->status);
  7182. EXPECT_EQ("content", received_body);
  7183. }
  7184. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7185. #ifdef CPPHTTPLIB_SSL_ENABLED
  7186. using ClientT = SSLClient;
  7187. #else
  7188. using ClientT = Client;
  7189. #endif
  7190. TestWithHeadersAndContentReceiver<ClientT>(
  7191. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7192. const std::string &body, const std::string &content_type,
  7193. ContentReceiver receiver, DownloadProgress progress) {
  7194. return cli.Post(path, headers, body, content_type, receiver, progress);
  7195. });
  7196. }
  7197. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7198. #ifdef CPPHTTPLIB_SSL_ENABLED
  7199. using ClientT = SSLClient;
  7200. #else
  7201. using ClientT = Client;
  7202. #endif
  7203. TestWithHeadersAndContentReceiver<ClientT>(
  7204. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7205. const std::string &body, const std::string &content_type,
  7206. ContentReceiver receiver, DownloadProgress progress) {
  7207. return cli.Put(path, headers, body, content_type, receiver, progress);
  7208. });
  7209. }
  7210. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7211. #ifdef CPPHTTPLIB_SSL_ENABLED
  7212. using ClientT = SSLClient;
  7213. #else
  7214. using ClientT = Client;
  7215. #endif
  7216. TestWithHeadersAndContentReceiver<ClientT>(
  7217. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7218. const std::string &body, const std::string &content_type,
  7219. ContentReceiver receiver, DownloadProgress progress) {
  7220. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7221. });
  7222. }
  7223. template <typename ClientType>
  7224. void TestWithHeadersAndContentReceiverWithProgress(
  7225. ClientType &cli,
  7226. std::function<Result(ClientType &, const std::string &, const Headers &,
  7227. const std::string &, const std::string &,
  7228. ContentReceiver, DownloadProgress)>
  7229. request_func) {
  7230. Headers headers;
  7231. headers.emplace("X-Test-Header", "progress-test");
  7232. std::string received_body;
  7233. auto progress_called = false;
  7234. auto res = request_func(
  7235. cli, "/content_receiver", headers, "content", "text/plain",
  7236. [&](const char *data, size_t data_length) {
  7237. received_body.append(data, data_length);
  7238. return true;
  7239. },
  7240. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7241. progress_called = true;
  7242. return true;
  7243. });
  7244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7245. EXPECT_EQ(StatusCode::OK_200, res->status);
  7246. EXPECT_EQ("content", received_body);
  7247. EXPECT_TRUE(progress_called);
  7248. }
  7249. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7250. #ifdef CPPHTTPLIB_SSL_ENABLED
  7251. using ClientT = SSLClient;
  7252. #else
  7253. using ClientT = Client;
  7254. #endif
  7255. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7256. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7257. const std::string &body, const std::string &content_type,
  7258. ContentReceiver receiver, DownloadProgress progress) {
  7259. return cli.Post(path, headers, body, content_type, receiver, progress);
  7260. });
  7261. }
  7262. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7263. #ifdef CPPHTTPLIB_SSL_ENABLED
  7264. using ClientT = SSLClient;
  7265. #else
  7266. using ClientT = Client;
  7267. #endif
  7268. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7269. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7270. const std::string &body, const std::string &content_type,
  7271. ContentReceiver receiver, DownloadProgress progress) {
  7272. return cli.Put(path, headers, body, content_type, receiver, progress);
  7273. });
  7274. }
  7275. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7276. #ifdef CPPHTTPLIB_SSL_ENABLED
  7277. using ClientT = SSLClient;
  7278. #else
  7279. using ClientT = Client;
  7280. #endif
  7281. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7282. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7283. const std::string &body, const std::string &content_type,
  7284. ContentReceiver receiver, DownloadProgress progress) {
  7285. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7286. });
  7287. }
  7288. template <typename ClientType>
  7289. void TestWithHeadersAndContentReceiverError(
  7290. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7291. const Headers &, const std::string &,
  7292. const std::string &, ContentReceiver)>
  7293. request_func) {
  7294. Headers headers;
  7295. headers.emplace("X-Error-Test", "true");
  7296. std::string received_body;
  7297. auto receiver_failed = false;
  7298. auto res =
  7299. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7300. [&](const char *data, size_t data_length) {
  7301. received_body.append(data, data_length);
  7302. receiver_failed = true;
  7303. return false;
  7304. });
  7305. ASSERT_FALSE(res);
  7306. EXPECT_TRUE(receiver_failed);
  7307. }
  7308. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7309. #ifdef CPPHTTPLIB_SSL_ENABLED
  7310. using ClientT = SSLClient;
  7311. #else
  7312. using ClientT = Client;
  7313. #endif
  7314. TestWithHeadersAndContentReceiverError<ClientT>(
  7315. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7316. const std::string &body, const std::string &content_type,
  7317. ContentReceiver receiver) {
  7318. return cli.Post(path, headers, body, content_type, receiver);
  7319. });
  7320. }
  7321. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7322. #ifdef CPPHTTPLIB_SSL_ENABLED
  7323. using ClientT = SSLClient;
  7324. #else
  7325. using ClientT = Client;
  7326. #endif
  7327. TestWithHeadersAndContentReceiverError<ClientT>(
  7328. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7329. const std::string &body, const std::string &content_type,
  7330. ContentReceiver receiver) {
  7331. return cli.Put(path, headers, body, content_type, receiver);
  7332. });
  7333. }
  7334. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7335. #ifdef CPPHTTPLIB_SSL_ENABLED
  7336. using ClientT = SSLClient;
  7337. #else
  7338. using ClientT = Client;
  7339. #endif
  7340. TestWithHeadersAndContentReceiverError<ClientT>(
  7341. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7342. const std::string &body, const std::string &content_type,
  7343. ContentReceiver receiver) {
  7344. return cli.Patch(path, headers, body, content_type, receiver);
  7345. });
  7346. }
  7347. TEST_F(ServerTest, PostQueryStringAndBody) {
  7348. auto res =
  7349. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7351. ASSERT_EQ(StatusCode::OK_200, res->status);
  7352. }
  7353. TEST_F(ServerTest, HTTP2Magic) {
  7354. Request req;
  7355. req.method = "PRI";
  7356. req.path = "*";
  7357. req.body = "SM";
  7358. auto res = std::make_shared<Response>();
  7359. auto error = Error::Success;
  7360. auto ret = cli_.send(req, *res, error);
  7361. ASSERT_TRUE(ret);
  7362. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7363. }
  7364. TEST_F(ServerTest, KeepAlive) {
  7365. auto res = cli_.Get("/hi");
  7366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7367. EXPECT_EQ(StatusCode::OK_200, res->status);
  7368. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7369. EXPECT_EQ("Hello World!", res->body);
  7370. res = cli_.Get("/hi");
  7371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7372. EXPECT_EQ(StatusCode::OK_200, res->status);
  7373. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7374. EXPECT_EQ("Hello World!", res->body);
  7375. res = cli_.Get("/hi");
  7376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7377. EXPECT_EQ(StatusCode::OK_200, res->status);
  7378. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7379. EXPECT_EQ("Hello World!", res->body);
  7380. res = cli_.Get("/not-exist");
  7381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7382. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7383. res = cli_.Post("/empty", "", "text/plain");
  7384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7385. EXPECT_EQ(StatusCode::OK_200, res->status);
  7386. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7387. EXPECT_EQ("empty", res->body);
  7388. EXPECT_EQ("close", res->get_header_value("Connection"));
  7389. res = cli_.Post(
  7390. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7391. "text/plain");
  7392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7393. EXPECT_EQ(StatusCode::OK_200, res->status);
  7394. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7395. EXPECT_EQ("empty", res->body);
  7396. cli_.set_keep_alive(false);
  7397. res = cli_.Get("/last-request");
  7398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7399. EXPECT_EQ(StatusCode::OK_200, res->status);
  7400. EXPECT_EQ("close", res->get_header_value("Connection"));
  7401. }
  7402. TEST_F(ServerTest, TooManyRedirect) {
  7403. cli_.set_follow_location(true);
  7404. auto res = cli_.Get("/redirect/0");
  7405. ASSERT_TRUE(!res);
  7406. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7407. }
  7408. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7409. Request req;
  7410. req.method = "FOOBAR";
  7411. req.path = "/hi";
  7412. cli_.set_keep_alive(true);
  7413. auto res = cli_.send(req);
  7414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7415. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7416. EXPECT_EQ("close", res->get_header_value("Connection"));
  7417. EXPECT_FALSE(cli_.is_socket_open());
  7418. }
  7419. TEST_F(ServerTest, CustomRouteReadsBody) {
  7420. const std::string xml =
  7421. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7422. Request req;
  7423. req.method = "PROPFIND";
  7424. req.path = "/dav/dir";
  7425. req.set_header("Depth", "1");
  7426. req.body = xml;
  7427. auto res = cli_.send(req);
  7428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7429. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7430. EXPECT_EQ(xml, res->body);
  7431. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7432. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7433. }
  7434. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7435. Request req;
  7436. req.method = "PROPFIND";
  7437. req.path = "/dav/42";
  7438. auto res = cli_.send(req);
  7439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7440. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7441. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7442. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7443. }
  7444. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7445. Request req;
  7446. req.method = "PROPFIND";
  7447. req.path = "/dav-re/123";
  7448. auto res = cli_.send(req);
  7449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7450. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7451. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7452. }
  7453. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7454. Request req;
  7455. req.method = "MKCOL";
  7456. req.path = "/dav-mkcol";
  7457. auto res = cli_.send(req);
  7458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7459. EXPECT_EQ(StatusCode::Created_201, res->status);
  7460. }
  7461. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7462. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7463. Request req;
  7464. req.method = "REPORT";
  7465. req.path = "/dav-report";
  7466. req.body = xml;
  7467. auto res = cli_.send(req);
  7468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7469. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7470. EXPECT_EQ(xml, res->body);
  7471. }
  7472. // A content reader route must fire even when the request carries no body,
  7473. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7474. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7475. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7476. Request req;
  7477. req.method = "REPORT";
  7478. req.path = "/dav-report";
  7479. auto res = cli_.send(req);
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7482. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7483. }
  7484. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7485. Request req;
  7486. req.method = "PROPFIND";
  7487. req.path = "/not-dav";
  7488. auto res = cli_.send(req);
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7491. }
  7492. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7493. Request req;
  7494. req.method = "UNLOCK";
  7495. req.path = "/dav/dir";
  7496. cli_.set_keep_alive(true);
  7497. auto res = cli_.send(req);
  7498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7499. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7500. EXPECT_EQ("close", res->get_header_value("Connection"));
  7501. EXPECT_FALSE(cli_.is_socket_open());
  7502. }
  7503. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7504. // The mount point serves this path, but only for GET and HEAD.
  7505. auto get_res = cli_.Get("/dir/index.html");
  7506. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7507. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7508. Request req;
  7509. req.method = "PROPFIND";
  7510. req.path = "/dir/index.html";
  7511. auto res = cli_.send(req);
  7512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7513. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7514. }
  7515. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7516. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7517. cli_.set_keep_alive(true);
  7518. for (auto i = 0; i < 2; i++) {
  7519. Request req;
  7520. req.method = "PROPFIND";
  7521. req.path = "/dav/dir";
  7522. req.body = xml;
  7523. auto res = cli_.send(req);
  7524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7525. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7526. EXPECT_EQ(xml, res->body);
  7527. EXPECT_TRUE(cli_.is_socket_open());
  7528. }
  7529. // A built-in method must still be served on the same connection.
  7530. cli_.set_keep_alive(false);
  7531. auto res = cli_.Get("/hi");
  7532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7533. EXPECT_EQ(StatusCode::OK_200, res->status);
  7534. EXPECT_EQ("close", res->get_header_value("Connection"));
  7535. }
  7536. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7537. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7538. Request req;
  7539. req.method = "PROPFIND";
  7540. req.path = "/dav/dir";
  7541. req.set_header("Expect", "100-continue");
  7542. req.body = xml;
  7543. auto res = cli_.send(req);
  7544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7545. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7546. EXPECT_EQ(xml, res->body);
  7547. }
  7548. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7549. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7550. TEST_F(ServerTest, Gzip) {
  7551. Headers headers;
  7552. headers.emplace("Accept-Encoding", "gzip, deflate");
  7553. auto res = cli_.Get("/compress", headers);
  7554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7555. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7556. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7557. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7558. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7559. "7890123456789012345678901234567890",
  7560. res->body);
  7561. EXPECT_EQ(StatusCode::OK_200, res->status);
  7562. }
  7563. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7564. Headers headers;
  7565. headers.emplace("Accept-Encoding", "gzip, deflate");
  7566. auto res = cli_.Get("/compress-with-charset", headers);
  7567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7568. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7569. EXPECT_EQ("application/json; charset=utf-8",
  7570. res->get_header_value("Content-Type"));
  7571. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7572. "7890123456789012345678901234567890",
  7573. res->body);
  7574. EXPECT_EQ(StatusCode::OK_200, res->status);
  7575. }
  7576. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7577. Headers headers;
  7578. headers.emplace("Accept-Encoding", "");
  7579. auto res = cli_.Get("/compress", headers);
  7580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7581. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7583. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7584. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7585. "7890123456789012345678901234567890",
  7586. res->body);
  7587. EXPECT_EQ(StatusCode::OK_200, res->status);
  7588. }
  7589. TEST_F(ServerTest, GzipWithContentReceiver) {
  7590. Headers headers;
  7591. headers.emplace("Accept-Encoding", "gzip, deflate");
  7592. std::string body;
  7593. auto res = cli_.Get("/compress", headers,
  7594. [&](const char *data, uint64_t data_length) {
  7595. EXPECT_EQ(100U, data_length);
  7596. body.append(data, data_length);
  7597. return true;
  7598. });
  7599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7600. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7602. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7603. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7604. "7890123456789012345678901234567890",
  7605. body);
  7606. EXPECT_EQ(StatusCode::OK_200, res->status);
  7607. }
  7608. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7609. Headers headers;
  7610. headers.emplace("Accept-Encoding", "gzip, deflate");
  7611. cli_.set_decompress(false);
  7612. auto res = cli_.Get("/compress", headers);
  7613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7614. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7615. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7616. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7617. EXPECT_EQ(33U, res->body.size());
  7618. EXPECT_EQ(StatusCode::OK_200, res->status);
  7619. }
  7620. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7621. Headers headers;
  7622. headers.emplace("Accept-Encoding", "");
  7623. std::string body;
  7624. auto res = cli_.Get("/compress", headers,
  7625. [&](const char *data, uint64_t data_length) {
  7626. EXPECT_EQ(100U, data_length);
  7627. body.append(data, data_length);
  7628. return true;
  7629. });
  7630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7631. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7632. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7633. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7634. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7635. "7890123456789012345678901234567890",
  7636. body);
  7637. EXPECT_EQ(StatusCode::OK_200, res->status);
  7638. }
  7639. TEST_F(ServerTest, NoGzip) {
  7640. Headers headers;
  7641. headers.emplace("Accept-Encoding", "gzip, deflate");
  7642. auto res = cli_.Get("/nocompress", headers);
  7643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7644. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7645. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7646. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7647. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7648. "7890123456789012345678901234567890",
  7649. res->body);
  7650. EXPECT_EQ(StatusCode::OK_200, res->status);
  7651. }
  7652. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7653. Headers headers;
  7654. headers.emplace("Accept-Encoding", "gzip, deflate");
  7655. std::string body;
  7656. auto res = cli_.Get("/nocompress", headers,
  7657. [&](const char *data, uint64_t data_length) {
  7658. EXPECT_EQ(100U, data_length);
  7659. body.append(data, data_length);
  7660. return true;
  7661. });
  7662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7663. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7664. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7665. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7666. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7667. "7890123456789012345678901234567890",
  7668. body);
  7669. EXPECT_EQ(StatusCode::OK_200, res->status);
  7670. }
  7671. TEST_F(ServerTest, MultipartFormDataGzip) {
  7672. UploadFormDataItems items = {
  7673. {"key1", "test", "", ""},
  7674. {"key2", "--abcdefg123", "", ""},
  7675. };
  7676. cli_.set_compress(true);
  7677. auto res = cli_.Post("/compress-multipart", items);
  7678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7679. EXPECT_EQ(StatusCode::OK_200, res->status);
  7680. }
  7681. #endif
  7682. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7683. // Static file compression is opt-in, so these run their own server rather than
  7684. // flipping it on for the shared ServerTest fixture, which would silently
  7685. // rewrite what every other static file test is asserting.
  7686. class StaticFileCompressionTest : public ::testing::Test {
  7687. protected:
  7688. void TearDown() override {
  7689. if (t_.joinable()) {
  7690. svr_.stop();
  7691. t_.join();
  7692. }
  7693. }
  7694. int start(const std::function<void(Server &)> &configure = nullptr) {
  7695. // Serves the same tree as a directory of build-time compressed assets
  7696. // would be served: the mount point names the coding the files are already
  7697. // stored in. Registered before "/" so it is the one that matches.
  7698. svr_.set_mount_point("/pre-encoded", "./www",
  7699. {{"Content-Encoding", "gzip"}});
  7700. svr_.set_mount_point("/", "./www");
  7701. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7702. res.set_file_content("./www/dir/index.html", "text/html");
  7703. });
  7704. svr_.Get("/pre-encoded-file-content",
  7705. [](const Request & /*req*/, Response &res) {
  7706. res.set_header("Content-Encoding", "gzip");
  7707. res.set_file_content("./www/dir/index.html", "text/html");
  7708. });
  7709. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7710. res.set_content_provider(
  7711. 6, "text/plain",
  7712. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7713. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7714. return true;
  7715. });
  7716. });
  7717. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7718. res.set_content_provider(
  7719. 1000, "text/plain",
  7720. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7721. if (offset < 100) {
  7722. std::string data(100, 'A');
  7723. sink.write(data.data(), data.size());
  7724. return true;
  7725. }
  7726. std::this_thread::sleep_for(std::chrono::seconds(2));
  7727. std::string data(900, 'B');
  7728. sink.write(data.data(), data.size());
  7729. return true;
  7730. });
  7731. });
  7732. if (configure) { configure(svr_); }
  7733. auto port = svr_.bind_to_any_port(HOST);
  7734. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7735. svr_.wait_until_ready();
  7736. return port;
  7737. }
  7738. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7739. // Every file under ./www except 1MB.txt is smaller than the default
  7740. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7741. // it out of the way.
  7742. static void enable_without_floor(Server &svr) {
  7743. svr.set_static_file_compression(true);
  7744. svr.set_static_file_compression_min_length(0);
  7745. }
  7746. Server svr_;
  7747. std::thread t_;
  7748. };
  7749. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7750. auto port = start();
  7751. Client cli(HOST, port);
  7752. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7754. EXPECT_EQ(StatusCode::OK_200, res->status);
  7755. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7756. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7757. EXPECT_EQ(1048576U, res->body.size());
  7758. }
  7759. TEST_F(StaticFileCompressionTest, MountPoint) {
  7760. auto port = start(enable);
  7761. Client cli(HOST, port);
  7762. cli.set_decompress(false);
  7763. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7765. EXPECT_EQ(StatusCode::OK_200, res->status);
  7766. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7767. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7768. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7769. // The response stays self-delimiting: a length, not a chunked body.
  7770. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7771. EXPECT_EQ(std::to_string(res->body.size()),
  7772. res->get_header_value("Content-Length"));
  7773. EXPECT_LT(res->body.size(), 1048576U);
  7774. EXPECT_FALSE(res->body.empty());
  7775. }
  7776. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7777. auto port = start(enable);
  7778. Client cli(HOST, port);
  7779. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7781. EXPECT_EQ(StatusCode::OK_200, res->status);
  7782. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7783. EXPECT_EQ(1048576U, res->body.size());
  7784. }
  7785. TEST_F(StaticFileCompressionTest, FileContent) {
  7786. auto port = start(enable_without_floor);
  7787. Client cli(HOST, port);
  7788. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7790. EXPECT_EQ(StatusCode::OK_200, res->status);
  7791. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7792. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7793. EXPECT_EQ(104U, res->body.size());
  7794. }
  7795. // A handler that serves an already-encoded file names the coding itself. The
  7796. // file-backed path decided its coding from Accept-Encoding and the content
  7797. // type alone, so it compressed the stored bytes a second time and appended a
  7798. // second Content-Encoding field line.
  7799. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7800. auto port = start(enable_without_floor);
  7801. Client cli(HOST, port);
  7802. cli.set_decompress(false);
  7803. auto res = cli.Get("/pre-encoded-file-content",
  7804. Headers{{"Accept-Encoding", "gzip"}});
  7805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7806. EXPECT_EQ(StatusCode::OK_200, res->status);
  7807. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7808. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7809. // Vary belongs to a coding the server chose, and it chose none here.
  7810. EXPECT_FALSE(res->has_header("Vary"));
  7811. // The file travels exactly as it is stored on disk.
  7812. EXPECT_EQ(104U, res->body.size());
  7813. }
  7814. // The 1MB file clears the default floor, so this one runs the configuration a
  7815. // deployment would actually have.
  7816. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7817. auto port = start(enable);
  7818. Client cli(HOST, port);
  7819. cli.set_decompress(false);
  7820. auto res =
  7821. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7823. EXPECT_EQ(StatusCode::OK_200, res->status);
  7824. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7825. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7826. EXPECT_FALSE(res->has_header("Vary"));
  7827. EXPECT_EQ(1048576U, res->body.size());
  7828. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7829. }
  7830. TEST_F(StaticFileCompressionTest, Head) {
  7831. auto port = start(enable);
  7832. Client cli(HOST, port);
  7833. cli.set_decompress(false);
  7834. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7835. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7836. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7838. EXPECT_EQ(StatusCode::OK_200, res->status);
  7839. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7840. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7841. // HEAD still reports the size a GET would return.
  7842. EXPECT_EQ(get->get_header_value("Content-Length"),
  7843. res->get_header_value("Content-Length"));
  7844. EXPECT_TRUE(res->body.empty());
  7845. }
  7846. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7847. auto port = start(enable);
  7848. Client cli(HOST, port);
  7849. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7850. {"Accept-Encoding", "gzip"}});
  7851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7852. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7853. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7854. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7855. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7856. EXPECT_EQ("cd", res->body);
  7857. }
  7858. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7859. auto port = start(enable);
  7860. Client cli(HOST, port);
  7861. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7863. EXPECT_EQ(StatusCode::OK_200, res->status);
  7864. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7865. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7866. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7867. }
  7868. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7869. auto port = start(enable);
  7870. Client cli(HOST, port);
  7871. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7873. EXPECT_EQ(StatusCode::OK_200, res->status);
  7874. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7875. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7876. EXPECT_TRUE(res->body.empty());
  7877. }
  7878. TEST_F(StaticFileCompressionTest, MinLength) {
  7879. auto port = start(enable);
  7880. Client cli(HOST, port);
  7881. // 104 bytes, well under the default floor. Compressing it would add the
  7882. // gzip header and trailer to a body that already fits in one packet.
  7883. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7885. EXPECT_EQ(StatusCode::OK_200, res->status);
  7886. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7887. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7888. }
  7889. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7890. auto port = start([](Server &svr) {
  7891. svr.set_static_file_compression(true);
  7892. svr.set_static_file_compression_min_length(1);
  7893. });
  7894. Client cli(HOST, port);
  7895. cli.set_decompress(false);
  7896. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7898. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7899. // A 9-byte file comes back larger than it went in, because gzip's header and
  7900. // trailer outweigh anything deflate can save. That is the end of the range
  7901. // the floor exists to keep out.
  7902. EXPECT_GT(res->body.size(), 9U);
  7903. }
  7904. TEST_F(StaticFileCompressionTest, MaxLength) {
  7905. auto port = start([](Server &svr) {
  7906. svr.set_static_file_compression(true);
  7907. svr.set_static_file_compression_min_length(0);
  7908. svr.set_static_file_compression_max_length(1024);
  7909. });
  7910. Client cli(HOST, port);
  7911. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7912. // defines `small` as a macro on Windows.
  7913. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7914. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7915. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7916. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7917. // Under it: compressed.
  7918. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7919. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7920. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7921. }
  7922. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7923. auto port = start(enable_without_floor);
  7924. Client cli(HOST, port);
  7925. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7926. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7927. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7928. auto identity_etag = identity->get_header_value("ETag");
  7929. ASSERT_FALSE(identity_etag.empty());
  7930. auto gzipped =
  7931. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7932. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7933. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7934. auto gzip_etag = gzipped->get_header_value("ETag");
  7935. ASSERT_FALSE(gzip_etag.empty());
  7936. // Two representations, two validators.
  7937. EXPECT_NE(identity_etag, gzip_etag);
  7938. // Each one revalidates against the request that would produce it...
  7939. auto fresh =
  7940. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7941. {"If-None-Match", gzip_etag}});
  7942. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7943. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7944. auto fresh_identity =
  7945. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7946. {"If-None-Match", identity_etag}});
  7947. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7948. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7949. // ...and not against the other representation.
  7950. auto crossed =
  7951. cli.Get("/dir/index.html",
  7952. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7953. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7954. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7955. }
  7956. // The opt-in covers responses the server reads off disk itself. A caller's own
  7957. // known-length provider keeps its Content-Length and, more importantly, keeps
  7958. // delivering incrementally: routing it through a compressor would hold every
  7959. // write back until zlib's window filled.
  7960. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7961. auto port = start(enable);
  7962. Client cli(HOST, port);
  7963. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7965. EXPECT_EQ(StatusCode::OK_200, res->status);
  7966. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7967. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7968. EXPECT_EQ("aaabbb", res->body);
  7969. }
  7970. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7971. auto port = start(enable);
  7972. Client cli(HOST, port);
  7973. cli.set_read_timeout(1, 0);
  7974. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7975. Headers{{"Accept-Encoding", "gzip"}});
  7976. ASSERT_TRUE(handle.is_valid());
  7977. // The provider writes 100 bytes and then stalls for longer than the read
  7978. // timeout. Those first bytes have to arrive anyway: run the response through
  7979. // a compressor and zlib holds them until its window fills, so the read would
  7980. // come back empty instead.
  7981. char buf[256];
  7982. auto n = handle.read(buf, sizeof(buf));
  7983. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7984. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7985. }
  7986. #endif
  7987. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7988. TEST_F(ServerTest, Brotli) {
  7989. Headers headers;
  7990. headers.emplace("Accept-Encoding", "br");
  7991. auto res = cli_.Get("/compress", headers);
  7992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7993. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7994. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7995. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7996. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7997. "7890123456789012345678901234567890",
  7998. res->body);
  7999. EXPECT_EQ(StatusCode::OK_200, res->status);
  8000. }
  8001. #endif
  8002. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8003. TEST_F(ServerTest, Zstd) {
  8004. Headers headers;
  8005. headers.emplace("Accept-Encoding", "zstd");
  8006. auto res = cli_.Get("/compress", headers);
  8007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8008. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8009. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8010. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8011. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8012. "7890123456789012345678901234567890",
  8013. res->body);
  8014. EXPECT_EQ(StatusCode::OK_200, res->status);
  8015. }
  8016. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8017. Headers headers;
  8018. headers.emplace("Accept-Encoding", "");
  8019. auto res = cli_.Get("/compress", headers);
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8022. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8023. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8024. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8025. "7890123456789012345678901234567890",
  8026. res->body);
  8027. EXPECT_EQ(StatusCode::OK_200, res->status);
  8028. }
  8029. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8030. Headers headers;
  8031. headers.emplace("Accept-Encoding", "zstd");
  8032. std::string body;
  8033. auto res = cli_.Get("/compress", headers,
  8034. [&](const char *data, uint64_t data_length) {
  8035. EXPECT_EQ(100U, data_length);
  8036. body.append(data, data_length);
  8037. return true;
  8038. });
  8039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8040. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8041. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8042. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8043. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8044. "7890123456789012345678901234567890",
  8045. body);
  8046. EXPECT_EQ(StatusCode::OK_200, res->status);
  8047. }
  8048. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8049. Headers headers;
  8050. headers.emplace("Accept-Encoding", "zstd");
  8051. cli_.set_decompress(false);
  8052. auto res = cli_.Get("/compress", headers);
  8053. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8054. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8055. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8056. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8058. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8059. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8060. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8061. EXPECT_EQ(StatusCode::OK_200, res->status);
  8062. ASSERT_EQ(26U, res->body.size());
  8063. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8064. 0);
  8065. }
  8066. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8067. Headers headers;
  8068. headers.emplace("Accept-Encoding", "");
  8069. std::string body;
  8070. auto res = cli_.Get("/compress", headers,
  8071. [&](const char *data, uint64_t data_length) {
  8072. EXPECT_EQ(100U, data_length);
  8073. body.append(data, data_length);
  8074. return true;
  8075. });
  8076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8077. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8079. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8080. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8081. "7890123456789012345678901234567890",
  8082. body);
  8083. EXPECT_EQ(StatusCode::OK_200, res->status);
  8084. }
  8085. TEST_F(ServerTest, NoZstd) {
  8086. Headers headers;
  8087. headers.emplace("Accept-Encoding", "zstd");
  8088. auto res = cli_.Get("/nocompress", headers);
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8091. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8092. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8093. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8094. "7890123456789012345678901234567890",
  8095. res->body);
  8096. EXPECT_EQ(StatusCode::OK_200, res->status);
  8097. }
  8098. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8099. Headers headers;
  8100. headers.emplace("Accept-Encoding", "zstd");
  8101. std::string body;
  8102. auto res = cli_.Get("/nocompress", headers,
  8103. [&](const char *data, uint64_t data_length) {
  8104. EXPECT_EQ(100U, data_length);
  8105. body.append(data, data_length);
  8106. return true;
  8107. });
  8108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8109. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8110. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8111. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8112. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8113. "7890123456789012345678901234567890",
  8114. body);
  8115. EXPECT_EQ(StatusCode::OK_200, res->status);
  8116. }
  8117. // TODO: How to enable zstd ??
  8118. TEST_F(ServerTest, MultipartFormDataZstd) {
  8119. UploadFormDataItems items = {
  8120. {"key1", "test", "", ""},
  8121. {"key2", "--abcdefg123", "", ""},
  8122. };
  8123. Headers headers;
  8124. headers.emplace("Accept-Encoding", "zstd");
  8125. cli_.set_compress(true);
  8126. auto res = cli_.Post("/compress-multipart", headers, items);
  8127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8128. EXPECT_EQ(StatusCode::OK_200, res->status);
  8129. }
  8130. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8131. Headers headers;
  8132. headers.emplace("Accept-Encoding", "zstd");
  8133. cli_.set_compress(true);
  8134. auto res = cli_.Put(
  8135. "/put", headers, 3,
  8136. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8137. sink.os << "PUT";
  8138. return true;
  8139. },
  8140. "text/plain");
  8141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8142. EXPECT_EQ(StatusCode::OK_200, res->status);
  8143. EXPECT_EQ("PUT", res->body);
  8144. }
  8145. // Pre-compression logging tests
  8146. TEST_F(ServerTest, PreCompressionLogging) {
  8147. // Test data for compression (matches the actual /compress endpoint content)
  8148. const std::string test_content =
  8149. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8150. "3456789012345678901234567890";
  8151. // Variables to capture logging data
  8152. std::string pre_compression_body;
  8153. std::string pre_compression_content_type;
  8154. std::string pre_compression_content_encoding;
  8155. std::string post_compression_body;
  8156. std::string post_compression_content_type;
  8157. std::string post_compression_content_encoding;
  8158. // Set up pre-compression logger
  8159. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8160. const Response &res) {
  8161. pre_compression_body = res.body;
  8162. pre_compression_content_type = res.get_header_value("Content-Type");
  8163. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8164. });
  8165. // Set up post-compression logger
  8166. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8167. post_compression_body = res.body;
  8168. post_compression_content_type = res.get_header_value("Content-Type");
  8169. post_compression_content_encoding =
  8170. res.get_header_value("Content-Encoding");
  8171. });
  8172. // Test with gzip compression
  8173. Headers headers;
  8174. headers.emplace("Accept-Encoding", "gzip");
  8175. auto res = cli_.Get("/compress", headers);
  8176. // Verify response was compressed
  8177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8178. EXPECT_EQ(StatusCode::OK_200, res->status);
  8179. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8180. // Verify pre-compression logger captured uncompressed content
  8181. EXPECT_EQ(test_content, pre_compression_body);
  8182. EXPECT_EQ("text/plain", pre_compression_content_type);
  8183. EXPECT_TRUE(pre_compression_content_encoding
  8184. .empty()); // No encoding header before compression
  8185. // Verify post-compression logger captured compressed content
  8186. EXPECT_NE(test_content,
  8187. post_compression_body); // Should be different after compression
  8188. EXPECT_EQ("text/plain", post_compression_content_type);
  8189. EXPECT_EQ("gzip", post_compression_content_encoding);
  8190. // Verify compressed content is smaller
  8191. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8192. }
  8193. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8194. const std::string test_content =
  8195. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8196. "3456789012345678901234567890";
  8197. std::string pre_compression_body;
  8198. std::string post_compression_body;
  8199. svr_.set_pre_compression_logger(
  8200. [&](const Request & /*req*/, const Response &res) {
  8201. pre_compression_body = res.body;
  8202. });
  8203. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8204. post_compression_body = res.body;
  8205. });
  8206. Headers headers;
  8207. headers.emplace("Accept-Encoding", "br");
  8208. auto res = cli_.Get("/compress", headers);
  8209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8210. EXPECT_EQ(StatusCode::OK_200, res->status);
  8211. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8212. // Verify pre-compression content is uncompressed
  8213. EXPECT_EQ(test_content, pre_compression_body);
  8214. // Verify post-compression content is compressed
  8215. EXPECT_NE(test_content, post_compression_body);
  8216. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8217. }
  8218. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8219. const std::string test_content =
  8220. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8221. "3456789012345678901234567890";
  8222. std::string pre_compression_body;
  8223. std::string post_compression_body;
  8224. svr_.set_pre_compression_logger(
  8225. [&](const Request & /*req*/, const Response &res) {
  8226. pre_compression_body = res.body;
  8227. });
  8228. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8229. post_compression_body = res.body;
  8230. });
  8231. // Request without compression (use /nocompress endpoint)
  8232. Headers headers;
  8233. auto res = cli_.Get("/nocompress", headers);
  8234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8235. EXPECT_EQ(StatusCode::OK_200, res->status);
  8236. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8237. // Pre-compression logger should not be called when no compression is applied
  8238. EXPECT_TRUE(
  8239. pre_compression_body.empty()); // Pre-compression logger not called
  8240. EXPECT_EQ(
  8241. test_content,
  8242. post_compression_body); // Post-compression logger captures final content
  8243. }
  8244. TEST_F(ServerTest, LoggerSeesContentLength) {
  8245. size_t logged_content_length = 0;
  8246. std::string logged_content_length_header;
  8247. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8248. logged_content_length = res.content_length_;
  8249. logged_content_length_header = res.get_header_value("Content-Length");
  8250. });
  8251. auto res = cli_.Get("/nocompress");
  8252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8253. EXPECT_EQ(StatusCode::OK_200, res->status);
  8254. EXPECT_EQ(res->body.size(), logged_content_length);
  8255. EXPECT_EQ(std::to_string(logged_content_length),
  8256. logged_content_length_header);
  8257. }
  8258. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8259. const std::string test_content =
  8260. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8261. "3456789012345678901234567890";
  8262. std::string pre_compression_body;
  8263. bool pre_logger_called = false;
  8264. // Set only pre-compression logger
  8265. svr_.set_pre_compression_logger(
  8266. [&](const Request & /*req*/, const Response &res) {
  8267. pre_compression_body = res.body;
  8268. pre_logger_called = true;
  8269. });
  8270. Headers headers;
  8271. headers.emplace("Accept-Encoding", "gzip");
  8272. auto res = cli_.Get("/compress", headers);
  8273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8274. EXPECT_EQ(StatusCode::OK_200, res->status);
  8275. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8276. // Verify pre-compression logger was called
  8277. EXPECT_TRUE(pre_logger_called);
  8278. EXPECT_EQ(test_content, pre_compression_body);
  8279. }
  8280. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8281. {
  8282. // Test with Expect: 100-continue header - success case
  8283. // Server returns 100 Continue, client sends body, server returns 200 OK
  8284. Request req;
  8285. req.method = "POST";
  8286. req.path = "/post-large";
  8287. req.set_header("Expect", "100-continue");
  8288. req.body = LARGE_DATA;
  8289. Response res;
  8290. auto error = Error::Success;
  8291. cli_.set_keep_alive(true);
  8292. auto ret = cli_.send(req, res, error);
  8293. EXPECT_TRUE(ret);
  8294. EXPECT_EQ(StatusCode::OK_200, res.status);
  8295. EXPECT_EQ(LARGE_DATA, res.body);
  8296. }
  8297. {
  8298. // Test with Expect: 100-continue header - error case
  8299. // Client should not send the body when server returns an error
  8300. Request req;
  8301. req.method = "POST";
  8302. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8303. req.set_header("Expect", "100-continue");
  8304. req.body = LARGE_DATA;
  8305. Response res;
  8306. auto error = Error::Success;
  8307. auto start = std::chrono::high_resolution_clock::now();
  8308. cli_.set_keep_alive(true);
  8309. auto ret = cli_.send(req, res, error);
  8310. auto end = std::chrono::high_resolution_clock::now();
  8311. auto elapsed =
  8312. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8313. .count();
  8314. // With Expect: 100-continue, request completes successfully but with error
  8315. EXPECT_TRUE(ret);
  8316. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8317. EXPECT_EQ("close", res.get_header_value("Connection"));
  8318. EXPECT_FALSE(cli_.is_socket_open());
  8319. EXPECT_LE(elapsed, 2000);
  8320. }
  8321. {
  8322. // Send an extra GET request to ensure error recovery without hanging
  8323. Request req;
  8324. req.method = "GET";
  8325. req.path = "/hi";
  8326. auto start = std::chrono::high_resolution_clock::now();
  8327. auto res = cli_.send(req);
  8328. auto end = std::chrono::high_resolution_clock::now();
  8329. auto elapsed =
  8330. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8331. .count();
  8332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8333. EXPECT_EQ(StatusCode::OK_200, res->status);
  8334. EXPECT_EQ("Hello World!", res->body);
  8335. EXPECT_LE(elapsed, 500);
  8336. }
  8337. }
  8338. TEST(ZstdDecompressor, ChunkedDecompression) {
  8339. std::string data;
  8340. for (size_t i = 0; i < 32 * 1024; ++i) {
  8341. data.push_back(static_cast<char>('a' + i % 26));
  8342. }
  8343. std::string compressed_data;
  8344. {
  8345. httplib::detail::zstd_compressor compressor;
  8346. bool result = compressor.compress(
  8347. data.data(), data.size(),
  8348. /*last=*/true,
  8349. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8350. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8351. compressed_data_size);
  8352. return true;
  8353. });
  8354. ASSERT_TRUE(result);
  8355. }
  8356. std::string decompressed_data;
  8357. {
  8358. httplib::detail::zstd_decompressor decompressor;
  8359. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8360. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8361. size_t chunk_size = 130;
  8362. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8363. chunk_begin += chunk_size) {
  8364. size_t current_chunk_size =
  8365. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8366. bool result = decompressor.decompress(
  8367. compressed_data.data() + chunk_begin, current_chunk_size,
  8368. [&](const char *decompressed_data_chunk,
  8369. size_t decompressed_data_chunk_size) {
  8370. decompressed_data.insert(decompressed_data.size(),
  8371. decompressed_data_chunk,
  8372. decompressed_data_chunk_size);
  8373. return true;
  8374. });
  8375. ASSERT_TRUE(result);
  8376. }
  8377. }
  8378. ASSERT_EQ(data, decompressed_data);
  8379. }
  8380. TEST(ZstdDecompressor, Decompress) {
  8381. std::string original_text = "Compressed with ZSTD";
  8382. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8383. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8384. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8385. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8386. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8387. std::string decompressed_data;
  8388. {
  8389. httplib::detail::zstd_decompressor decompressor;
  8390. bool result = decompressor.decompress(
  8391. compressed_data.data(), compressed_data.size(),
  8392. [&](const char *decompressed_data_chunk,
  8393. size_t decompressed_data_chunk_size) {
  8394. decompressed_data.insert(decompressed_data.size(),
  8395. decompressed_data_chunk,
  8396. decompressed_data_chunk_size);
  8397. return true;
  8398. });
  8399. ASSERT_TRUE(result);
  8400. }
  8401. ASSERT_EQ(original_text, decompressed_data);
  8402. }
  8403. #endif
  8404. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8405. // separate chunks so that the server sees each part in its own read(). Used to
  8406. // place a read boundary at a specific offset of a request body.
  8407. static bool send_request_in_parts(time_t read_timeout_sec,
  8408. const std::vector<std::string> &parts,
  8409. std::string *resp = nullptr,
  8410. int port = PORT) {
  8411. auto error = Error::Success;
  8412. auto client_sock = detail::create_client_socket(
  8413. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8414. /*connection_timeout_sec=*/5, 0,
  8415. /*read_timeout_sec=*/5, 0,
  8416. /*write_timeout_sec=*/5, 0, std::string(), error);
  8417. if (client_sock == INVALID_SOCKET) { return false; }
  8418. auto ret = detail::process_client_socket(
  8419. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8420. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8421. for (size_t i = 0; i < parts.size(); i++) {
  8422. const auto &part = parts[i];
  8423. if (part.size() !=
  8424. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8425. return false;
  8426. }
  8427. if (i + 1 < parts.size()) {
  8428. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8429. }
  8430. }
  8431. char buf[512];
  8432. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8433. while (line_reader.getline()) {
  8434. if (resp) { *resp += line_reader.ptr(); }
  8435. }
  8436. return true;
  8437. });
  8438. detail::close_socket(client_sock);
  8439. return ret;
  8440. }
  8441. // Sends a raw request to a server listening at HOST:PORT.
  8442. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8443. std::string *resp = nullptr, int port = PORT) {
  8444. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8445. }
  8446. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8447. Server svr;
  8448. std::string header_value;
  8449. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8450. header_value = req.get_header_value("foo");
  8451. res.set_content("ok", "text/plain");
  8452. });
  8453. thread t = thread([&] { svr.listen(HOST, PORT); });
  8454. auto se = detail::scope_exit([&] {
  8455. svr.stop();
  8456. t.join();
  8457. ASSERT_FALSE(svr.is_running());
  8458. });
  8459. svr.wait_until_ready();
  8460. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8461. // like characters are not treated the same - use vertical tab and escape.
  8462. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8463. "foo: \t \v bar \x1B\t \r\n"
  8464. "Connection: close\r\n"
  8465. "\r\n";
  8466. std::string res;
  8467. ASSERT_TRUE(send_request(5, req, &res));
  8468. EXPECT_EQ(header_value, "");
  8469. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8470. }
  8471. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8472. Server svr;
  8473. std::string received;
  8474. svr.Get("/order", [&](const Request &req, Response &res) {
  8475. received = entries_to_string(req.headers);
  8476. res.set_content("ok", "text/plain");
  8477. });
  8478. auto port = svr.bind_to_any_port(HOST);
  8479. thread t = thread([&] { svr.listen_after_bind(); });
  8480. auto se = detail::scope_exit([&] {
  8481. svr.stop();
  8482. t.join();
  8483. ASSERT_FALSE(svr.is_running());
  8484. });
  8485. svr.wait_until_ready();
  8486. const std::string req = "GET /order HTTP/1.1\r\n"
  8487. "X-First: 1\r\n"
  8488. "X-Dup: a\r\n"
  8489. "X-Second: 2\r\n"
  8490. "X-Dup: b\r\n"
  8491. "Connection: close\r\n"
  8492. "\r\n";
  8493. std::string res;
  8494. ASSERT_TRUE(send_request(5, req, &res, port));
  8495. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8496. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8497. }
  8498. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8499. Server svr;
  8500. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8501. res.set_header("Set-Cookie", "first=1");
  8502. res.set_header("X-Between", "y");
  8503. res.set_header("Set-Cookie", "second=2");
  8504. res.set_content("ok", "text/plain");
  8505. });
  8506. auto port = svr.bind_to_any_port(HOST);
  8507. thread t = thread([&] { svr.listen_after_bind(); });
  8508. auto se = detail::scope_exit([&] {
  8509. svr.stop();
  8510. t.join();
  8511. ASSERT_FALSE(svr.is_running());
  8512. });
  8513. svr.wait_until_ready();
  8514. Client cli(HOST, port);
  8515. auto res = cli.Get("/cookies");
  8516. ASSERT_TRUE(res);
  8517. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8518. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8519. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8520. }
  8521. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8522. Server svr;
  8523. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8524. auto i = new int(0);
  8525. res.set_header("Trailer", "X-Safe, X-Reflected");
  8526. res.set_chunked_content_provider(
  8527. "text/plain",
  8528. [i](size_t /*offset*/, DataSink &sink) {
  8529. if (*i == 0) {
  8530. sink.os << "body";
  8531. } else {
  8532. Headers trailer;
  8533. // A valid trailer that must survive.
  8534. trailer.emplace("X-Safe", "safe");
  8535. // Attacker-controlled value carrying CR/LF (response splitting).
  8536. trailer.emplace("X-Reflected",
  8537. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8538. // Attacker-controlled name carrying CR/LF.
  8539. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8540. sink.done_with_trailer(trailer);
  8541. }
  8542. (*i)++;
  8543. return true;
  8544. },
  8545. [i](bool /*success*/) { delete i; });
  8546. });
  8547. thread t = thread([&] { svr.listen(HOST, PORT); });
  8548. auto se = detail::scope_exit([&] {
  8549. svr.stop();
  8550. t.join();
  8551. ASSERT_FALSE(svr.is_running());
  8552. });
  8553. svr.wait_until_ready();
  8554. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8555. "Host: " + HOST +
  8556. "\r\n"
  8557. "Connection: close\r\n"
  8558. "\r\n";
  8559. std::string res;
  8560. ASSERT_TRUE(send_request(5, req, &res));
  8561. // The injected fields must not appear anywhere in the raw response.
  8562. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8563. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8564. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8565. // Invalid trailers are dropped entirely, matching set_header().
  8566. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8567. // The valid trailer still passes through.
  8568. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8569. }
  8570. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8571. Server svr;
  8572. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8573. // res.headers is a public field an application can populate directly,
  8574. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8575. // A valid header that must survive.
  8576. res.headers.emplace("X-Safe", "safe");
  8577. // Attacker-controlled value carrying CR/LF (response splitting).
  8578. res.headers.emplace("X-Reflected",
  8579. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8580. // Attacker-controlled name carrying CR/LF.
  8581. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8582. res.set_content("body", "text/plain");
  8583. });
  8584. thread t = thread([&] { svr.listen(HOST, PORT); });
  8585. auto se = detail::scope_exit([&] {
  8586. svr.stop();
  8587. t.join();
  8588. ASSERT_FALSE(svr.is_running());
  8589. });
  8590. svr.wait_until_ready();
  8591. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8592. "Host: " + HOST +
  8593. "\r\n"
  8594. "Connection: close\r\n"
  8595. "\r\n";
  8596. std::string res;
  8597. ASSERT_TRUE(send_request(5, req, &res));
  8598. // The injected fields must not appear anywhere in the raw response.
  8599. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8600. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8601. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8602. // Invalid headers are dropped entirely, matching set_header().
  8603. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8604. // The valid header still passes through.
  8605. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8606. }
  8607. // Forward declaration: in split builds split.py strips `inline` and moves the
  8608. // definition into httplib.cc, so detail::write_request_line is not visible from
  8609. // the public httplib.h. Re-declaring it here lets the tests link against the
  8610. // symbol in both header-only and split builds.
  8611. namespace httplib {
  8612. namespace detail {
  8613. ssize_t write_request_line(Stream &strm, const std::string &method,
  8614. const std::string &path);
  8615. } // namespace detail
  8616. } // namespace httplib
  8617. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8618. // A well-formed target is written verbatim.
  8619. {
  8620. detail::BufferStream strm;
  8621. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8622. EXPECT_GT(n, 0);
  8623. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8624. }
  8625. // A target carrying CR/LF, SP or other control octets must be rejected
  8626. // before anything reaches the wire, otherwise it splits the request line and
  8627. // injects a header or a whole request.
  8628. const std::string evil_targets[] = {
  8629. "/a\r\nInjected: pwned",
  8630. "/a\rInjected",
  8631. "/a\nInjected",
  8632. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8633. "/a b",
  8634. "/a\tb",
  8635. "/a\x7f",
  8636. };
  8637. for (const auto &evil : evil_targets) {
  8638. detail::BufferStream strm;
  8639. auto n = detail::write_request_line(strm, "GET", evil);
  8640. EXPECT_LT(n, 0);
  8641. EXPECT_TRUE(strm.get_buffer().empty());
  8642. }
  8643. }
  8644. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8645. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8646. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8647. // target reaches write_request. The client must fail cleanly with
  8648. // Error::Write instead of putting a request-line-less, header-injecting
  8649. // request on the wire.
  8650. Server svr;
  8651. svr.Get("/a", [](const Request &, Response &res) {
  8652. res.set_content("ok", "text/plain");
  8653. });
  8654. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8655. auto se = detail::scope_exit([&] {
  8656. svr.stop();
  8657. thread.join();
  8658. ASSERT_FALSE(svr.is_running());
  8659. });
  8660. svr.wait_until_ready();
  8661. {
  8662. Client cli(HOST, PORT);
  8663. cli.set_path_encode(false);
  8664. // The request is rejected before anything is written, so the connection
  8665. // stays silent and the subsequent response read would otherwise block for
  8666. // the full default read timeout. Shorten it -- the assertion is on the
  8667. // error, not the timeout.
  8668. cli.set_read_timeout(1, 0);
  8669. auto res = cli.Get("/a\r\nInjected: pwned");
  8670. EXPECT_FALSE(res);
  8671. EXPECT_EQ(Error::Write, res.error());
  8672. }
  8673. }
  8674. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8675. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8676. // including extension methods.
  8677. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8678. for (const auto &method : good_methods) {
  8679. detail::BufferStream strm;
  8680. auto n = detail::write_request_line(strm, method, "/");
  8681. EXPECT_GT(n, 0);
  8682. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8683. }
  8684. // A method carrying CR/LF would split the request line and smuggle a whole
  8685. // request ahead of the real one. A space or an empty method corrupts the
  8686. // request line. All must be rejected before anything reaches the wire.
  8687. const std::string evil_methods[] = {
  8688. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8689. "GET\r\nInjected: pwned",
  8690. "GET\r",
  8691. "GET\n",
  8692. "GE T",
  8693. "",
  8694. };
  8695. for (const auto &evil : evil_methods) {
  8696. detail::BufferStream strm;
  8697. auto n = detail::write_request_line(strm, evil, "/");
  8698. EXPECT_LT(n, 0);
  8699. EXPECT_TRUE(strm.get_buffer().empty());
  8700. }
  8701. }
  8702. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8703. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8704. // through Client::send must fail with Error::Write and no request, neither
  8705. // the smuggled one nor the real one, may reach the server.
  8706. Server svr;
  8707. std::atomic<int> request_count(0);
  8708. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8709. request_count++;
  8710. res.status = StatusCode::OK_200;
  8711. return Server::HandlerResponse::Handled;
  8712. });
  8713. auto port = svr.bind_to_any_port(HOST);
  8714. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8715. auto se = detail::scope_exit([&] {
  8716. svr.stop();
  8717. thread.join();
  8718. ASSERT_FALSE(svr.is_running());
  8719. });
  8720. svr.wait_until_ready();
  8721. {
  8722. Client cli(HOST, port);
  8723. const std::string evil_methods[] = {
  8724. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8725. "GE T",
  8726. "",
  8727. };
  8728. for (const auto &evil : evil_methods) {
  8729. Request req;
  8730. req.method = evil;
  8731. req.path = "/";
  8732. auto res = cli.send(req);
  8733. EXPECT_FALSE(res);
  8734. EXPECT_EQ(Error::Write, res.error());
  8735. }
  8736. auto handle =
  8737. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8738. EXPECT_FALSE(handle.is_valid());
  8739. EXPECT_EQ(Error::Write, handle.error);
  8740. // A valid request on the same client still goes through.
  8741. auto res = cli.Get("/");
  8742. ASSERT_TRUE(res);
  8743. EXPECT_EQ(StatusCode::OK_200, res->status);
  8744. }
  8745. EXPECT_EQ(1, request_count.load());
  8746. }
  8747. // Sends a raw request and verifies that there isn't a crash or exception.
  8748. static void test_raw_request(const std::string &req,
  8749. std::string *out = nullptr) {
  8750. Server svr;
  8751. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8752. res.set_content("ok", "text/plain");
  8753. });
  8754. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8755. res.set_content("ok", "text/plain");
  8756. });
  8757. svr.Get("/header_field_value_check",
  8758. [&](const Request & /*req*/, Response &res) {
  8759. res.set_content("ok", "text/plain");
  8760. });
  8761. svr.CustomRoute("PROPFIND", "/dav",
  8762. [&](const Request & /*req*/, Response &res) {
  8763. res.status = StatusCode::MultiStatus_207;
  8764. });
  8765. // Server read timeout must be longer than the client read timeout for the
  8766. // bug to reproduce, probably to force the server to process a request
  8767. // without a trailing blank line.
  8768. const time_t client_read_timeout_sec = 1;
  8769. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8770. bool listen_thread_ok = false;
  8771. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8772. auto se = detail::scope_exit([&] {
  8773. svr.stop();
  8774. t.join();
  8775. ASSERT_FALSE(svr.is_running());
  8776. EXPECT_TRUE(listen_thread_ok);
  8777. });
  8778. svr.wait_until_ready();
  8779. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8780. }
  8781. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8782. // A certain header line causes an exception if the header property is parsed
  8783. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8784. test_raw_request(
  8785. "GET /hi HTTP/1.1\r\n"
  8786. " : "
  8787. " "
  8788. " ");
  8789. }
  8790. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8791. // A certain header line causes an exception if the header property *name* is
  8792. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8793. // greedy matcher and requires backtracking when there are a lot of ":"
  8794. // characters.
  8795. // This occurs with libc++ but not libstdc++.
  8796. test_raw_request(
  8797. "GET /hi HTTP/1.1\r\n"
  8798. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8799. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8800. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8801. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8802. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8803. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8804. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8805. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8806. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8807. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8808. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8809. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8810. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8811. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8812. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8813. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8814. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8815. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8816. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8817. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8818. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8819. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8820. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8821. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8822. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8823. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8824. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8825. "&&&%%%");
  8826. }
  8827. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8828. // Make sure this doesn't crash the server.
  8829. // In a previous version of the header line regex, the "\r" rendered the line
  8830. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8831. // a new position where the leading white space ended and the field value
  8832. // began.
  8833. // The crash occurs with libc++ but not libstdc++.
  8834. test_raw_request("GET /hi HTTP/1.1\r\n"
  8835. "a:" +
  8836. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8837. "\r\n"
  8838. "\r\n");
  8839. }
  8840. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8841. std::string out;
  8842. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8843. "Content-Type: text/plain\r\n"
  8844. "Transfer-Encoding: chunked\r\n"
  8845. "\r\n"
  8846. "nothex\r\n",
  8847. &out);
  8848. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8849. }
  8850. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8851. std::string out;
  8852. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8853. "Content-Type: text/plain\r\n"
  8854. "Transfer-Encoding: chunked\r\n"
  8855. "\r\n"
  8856. "3\r\n"
  8857. "xyz\r\n"
  8858. "NaN\r\n",
  8859. &out);
  8860. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8861. }
  8862. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8863. std::string out;
  8864. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8865. "Content-Type: text/plain\r\n"
  8866. "Transfer-Encoding: chunked\r\n"
  8867. "\r\n"
  8868. // Length is too large for 64 bits.
  8869. "1ffffffffffffffff\r\n"
  8870. "xyz\r\n",
  8871. &out);
  8872. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8873. }
  8874. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8875. test_raw_request("GET /hi HTTP/1.1\r\n"
  8876. "Content-Type: text/plain\r\n\r");
  8877. }
  8878. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8879. std::string out;
  8880. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8881. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8882. }
  8883. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8884. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8885. std::string out;
  8886. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8887. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8888. }
  8889. }
  8890. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8891. std::string out;
  8892. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8893. "Connection: close\r\n\r\n",
  8894. &out);
  8895. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8896. }
  8897. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8898. Server svr;
  8899. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8900. EXPECT_TRUE(!req.remote_addr.empty());
  8901. });
  8902. thread t = thread([&] { svr.listen(HOST, PORT); });
  8903. auto se = detail::scope_exit([&] {
  8904. svr.stop();
  8905. t.join();
  8906. ASSERT_FALSE(svr.is_running());
  8907. });
  8908. svr.wait_until_ready();
  8909. // Send an invalid request line to trigger Bad Request
  8910. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8911. std::string out;
  8912. ASSERT_TRUE(send_request(5, bad_req, &out));
  8913. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8914. }
  8915. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8916. // answered right away rather than blocking on a read that waits for EOF.
  8917. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8918. std::string out;
  8919. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8920. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8921. }
  8922. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8923. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8924. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8925. for (const auto *method : methods) {
  8926. Server svr;
  8927. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8928. EXPECT_FALSE(svr.is_valid()) << method;
  8929. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8930. }
  8931. }
  8932. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8933. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8934. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8935. for (const auto *method : methods) {
  8936. Server svr;
  8937. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8938. EXPECT_FALSE(svr.is_valid()) << method;
  8939. }
  8940. }
  8941. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8942. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8943. "COPY", "MOVE", "LOCK",
  8944. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8945. Server svr;
  8946. for (const auto *method : methods) {
  8947. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8948. }
  8949. EXPECT_TRUE(svr.is_valid());
  8950. }
  8951. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8952. Server svr;
  8953. svr.CustomRoute("POST", "/x",
  8954. [](const Request &, Response &, const ContentReader &) {});
  8955. EXPECT_FALSE(svr.is_valid());
  8956. }
  8957. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8958. Server svr;
  8959. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8960. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8961. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8962. EXPECT_FALSE(svr.is_valid());
  8963. }
  8964. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8965. Server svr;
  8966. auto captured = Error::Success;
  8967. svr.set_error_logger(
  8968. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8969. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8970. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8971. }
  8972. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8973. std::string out;
  8974. std::string request(
  8975. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8976. test_raw_request(request, &out);
  8977. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8978. }
  8979. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8980. std::string out;
  8981. std::string request(
  8982. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8983. test_raw_request(request, &out);
  8984. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8985. }
  8986. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8987. std::string out;
  8988. std::string request(
  8989. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8990. test_raw_request(request, &out);
  8991. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8992. }
  8993. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8994. std::string out;
  8995. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8996. "Test: \r\n\r\n",
  8997. &out);
  8998. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8999. }
  9000. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9001. Server svr;
  9002. std::string x_custom;
  9003. std::string cookie;
  9004. std::string xff;
  9005. std::string x_unicode;
  9006. std::string x_iis;
  9007. svr.Get("/check", [&](const Request &req, Response &res) {
  9008. x_custom = req.get_header_value("X-Custom");
  9009. cookie = req.get_header_value("Cookie");
  9010. xff = req.get_header_value("X-Forwarded-For");
  9011. x_unicode = req.get_header_value("X-Unicode");
  9012. x_iis = req.get_header_value("X-IIS");
  9013. res.set_content("ok", "text/plain");
  9014. });
  9015. thread t = thread([&] { svr.listen(HOST, PORT); });
  9016. auto se = detail::scope_exit([&] {
  9017. svr.stop();
  9018. t.join();
  9019. ASSERT_FALSE(svr.is_running());
  9020. });
  9021. svr.wait_until_ready();
  9022. const std::string req = "GET /check HTTP/1.1\r\n"
  9023. "Host: localhost\r\n"
  9024. "X-Custom: a%0D%0AInjected: b\r\n"
  9025. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9026. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9027. "X-Unicode: %E3%81%82\r\n"
  9028. "X-IIS: %u00E9\r\n"
  9029. "Connection: close\r\n"
  9030. "\r\n";
  9031. std::string res;
  9032. ASSERT_TRUE(send_request(5, req, &res));
  9033. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9034. // Every value must be returned verbatim (wire form), with no decoding.
  9035. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9036. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9037. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9038. EXPECT_EQ("%E3%81%82", x_unicode);
  9039. EXPECT_EQ("%u00E9", x_iis);
  9040. }
  9041. // Applications that previously relied on automatic percent-decoding can
  9042. // reproduce the old behavior by explicitly calling decode_path_component()
  9043. // or, for RFC 3986 conformance, decode_uri_component().
  9044. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9045. Server svr;
  9046. std::string decoded;
  9047. svr.Get("/check", [&](const Request &req, Response &res) {
  9048. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9049. res.set_content("ok", "text/plain");
  9050. });
  9051. thread t = thread([&] { svr.listen(HOST, PORT); });
  9052. auto se = detail::scope_exit([&] {
  9053. svr.stop();
  9054. t.join();
  9055. ASSERT_FALSE(svr.is_running());
  9056. });
  9057. svr.wait_until_ready();
  9058. const std::string req = "GET /check HTTP/1.1\r\n"
  9059. "Host: localhost\r\n"
  9060. "X-Custom: hello%20world\r\n"
  9061. "Connection: close\r\n"
  9062. "\r\n";
  9063. std::string res;
  9064. ASSERT_TRUE(send_request(5, req, &res));
  9065. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9066. EXPECT_EQ("hello world", decoded);
  9067. }
  9068. // Regression test for #2033. Browsers send Referer values that include
  9069. // percent-encoded characters such as %0A inside the URL. Decoding the
  9070. // header value would either trip the post-decode CR/LF/NUL guard (the
  9071. // original bug, returning 400) or, after that guard was relaxed, silently
  9072. // store a literal LF — both unacceptable. The wire form must round-trip.
  9073. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9074. Server svr;
  9075. std::string referer;
  9076. svr.Get("/check", [&](const Request &req, Response &res) {
  9077. referer = req.get_header_value("Referer");
  9078. res.set_content("ok", "text/plain");
  9079. });
  9080. thread t = thread([&] { svr.listen(HOST, PORT); });
  9081. auto se = detail::scope_exit([&] {
  9082. svr.stop();
  9083. t.join();
  9084. ASSERT_FALSE(svr.is_running());
  9085. });
  9086. svr.wait_until_ready();
  9087. const std::string req = "GET /check HTTP/1.1\r\n"
  9088. "Host: localhost\r\n"
  9089. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9090. "Connection: close\r\n"
  9091. "\r\n";
  9092. std::string res;
  9093. ASSERT_TRUE(send_request(5, req, &res));
  9094. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9095. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9096. }
  9097. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9098. Server svr;
  9099. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9100. res.set_header("Cache-Control", "no-cache");
  9101. res.set_chunked_content_provider(
  9102. "text/event-stream", [](size_t offset, DataSink &sink) {
  9103. std::string s = "data:";
  9104. s += std::to_string(offset);
  9105. s += "\n\n";
  9106. auto ret = sink.write(s.data(), s.size());
  9107. EXPECT_TRUE(ret);
  9108. std::this_thread::sleep_for(std::chrono::seconds(1));
  9109. return true;
  9110. });
  9111. });
  9112. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9113. svr.wait_until_ready();
  9114. Client client(HOST, PORT);
  9115. const Headers headers = {{"Accept", "text/event-stream"}};
  9116. auto get_thread = std::thread([&client, &headers]() {
  9117. auto res = client.Get(
  9118. "/events", headers,
  9119. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9120. });
  9121. auto se = detail::scope_exit([&] {
  9122. svr.stop();
  9123. get_thread.join();
  9124. listen_thread.join();
  9125. ASSERT_FALSE(svr.is_running());
  9126. });
  9127. // Give GET time to get a few messages.
  9128. std::this_thread::sleep_for(std::chrono::seconds(2));
  9129. }
  9130. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9131. httplib::Server svr;
  9132. svr.Post("/hi",
  9133. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9134. res.status = StatusCode::OK_200;
  9135. });
  9136. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9137. svr.wait_until_ready();
  9138. Client cli(HOST, PORT);
  9139. auto res = cli.Post("/hi", "data", "text/plain");
  9140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9141. EXPECT_EQ(StatusCode::OK_200, res->status);
  9142. svr.stop();
  9143. thread.join();
  9144. ASSERT_FALSE(svr.is_running());
  9145. res = cli.Post("/hi", "data", "text/plain");
  9146. ASSERT_FALSE(res);
  9147. }
  9148. TEST(ServerStopTest, ListenFailure) {
  9149. Server svr;
  9150. auto t = thread([&]() {
  9151. auto ret = svr.listen("????", PORT);
  9152. EXPECT_FALSE(ret);
  9153. });
  9154. svr.wait_until_ready();
  9155. svr.stop();
  9156. t.join();
  9157. }
  9158. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9159. TEST(ServerStopTest, Decommision) {
  9160. Server svr;
  9161. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9162. for (int i = 0; i < 4; i++) {
  9163. auto is_even = !(i % 2);
  9164. std::thread t{[&] {
  9165. try {
  9166. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9167. if (is_even) {
  9168. throw std::runtime_error("Some thing that happens to go wrong.");
  9169. }
  9170. svr.listen(HOST, PORT);
  9171. } catch (...) { svr.decommission(); }
  9172. }};
  9173. svr.wait_until_ready();
  9174. // Server is up
  9175. {
  9176. Client cli(HOST, PORT);
  9177. auto res = cli.Get("/hi");
  9178. if (is_even) {
  9179. EXPECT_FALSE(res);
  9180. } else {
  9181. EXPECT_TRUE(res);
  9182. EXPECT_EQ("hi...", res->body);
  9183. }
  9184. }
  9185. svr.stop();
  9186. t.join();
  9187. // Server is down...
  9188. {
  9189. Client cli(HOST, PORT);
  9190. auto res = cli.Get("/hi");
  9191. EXPECT_FALSE(res);
  9192. }
  9193. }
  9194. }
  9195. #endif
  9196. // Helper function for string body upload progress tests
  9197. template <typename SetupHandler, typename ClientCall>
  9198. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9199. ClientCall &&client_call,
  9200. const string &body) {
  9201. Server svr;
  9202. setup_handler(svr);
  9203. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9204. auto se = detail::scope_exit([&] {
  9205. svr.stop();
  9206. t.join();
  9207. });
  9208. svr.wait_until_ready();
  9209. Client cli(HOST, PORT);
  9210. vector<uint64_t> progress_values;
  9211. bool progress_called = false;
  9212. auto res =
  9213. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9214. progress_values.push_back(current);
  9215. progress_called = true;
  9216. return true;
  9217. });
  9218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9219. EXPECT_EQ(200, res->status);
  9220. EXPECT_TRUE(progress_called);
  9221. }
  9222. TEST(UploadProgressTest, PostStringBodyBasic) {
  9223. TestStringBodyUploadProgress(
  9224. [](Server &svr) {
  9225. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9226. res.set_content("received", "text/plain");
  9227. });
  9228. },
  9229. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9230. return cli.Post("/test", body, "text/plain", progress_callback);
  9231. },
  9232. "test data for upload progress");
  9233. }
  9234. TEST(UploadProgressTest, PutStringBodyBasic) {
  9235. TestStringBodyUploadProgress(
  9236. [](Server &svr) {
  9237. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9238. res.set_content("put received", "text/plain");
  9239. });
  9240. },
  9241. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9242. return cli.Put("/test", body, "text/plain", progress_callback);
  9243. },
  9244. "put test data for upload progress");
  9245. }
  9246. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9247. TestStringBodyUploadProgress(
  9248. [](Server &svr) {
  9249. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9250. res.set_content("patch received", "text/plain");
  9251. });
  9252. },
  9253. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9254. return cli.Patch("/test", body, "text/plain", progress_callback);
  9255. },
  9256. "patch test data for upload progress");
  9257. }
  9258. // Helper function for content provider upload progress tests
  9259. template <typename SetupHandler, typename ClientCall>
  9260. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9261. ClientCall &&client_call) {
  9262. Server svr;
  9263. setup_handler(svr);
  9264. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9265. auto se = detail::scope_exit([&] {
  9266. svr.stop();
  9267. t.join();
  9268. });
  9269. svr.wait_until_ready();
  9270. Client cli(HOST, PORT);
  9271. vector<uint64_t> progress_values;
  9272. auto res =
  9273. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9274. progress_values.push_back(current);
  9275. return true;
  9276. });
  9277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9278. EXPECT_EQ(200, res->status);
  9279. EXPECT_FALSE(progress_values.empty());
  9280. }
  9281. TEST(UploadProgressTest, PostContentProviderProgress) {
  9282. TestContentProviderUploadProgress(
  9283. [](Server &svr) {
  9284. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9285. res.set_content("provider received", "text/plain");
  9286. });
  9287. },
  9288. [](Client &cli, UploadProgress progress_callback) {
  9289. return cli.Post(
  9290. "/test", 10,
  9291. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9292. sink.os << "test data";
  9293. return true;
  9294. },
  9295. "text/plain", progress_callback);
  9296. });
  9297. }
  9298. // Helper function for multipart upload progress tests
  9299. template <typename SetupHandler, typename ClientCall>
  9300. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9301. ClientCall &&client_call,
  9302. const string &endpoint) {
  9303. Server svr;
  9304. setup_handler(svr);
  9305. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9306. auto se = detail::scope_exit([&] {
  9307. svr.stop();
  9308. t.join();
  9309. });
  9310. svr.wait_until_ready();
  9311. Client cli(HOST, PORT);
  9312. vector<uint64_t> progress_values;
  9313. UploadFormDataItems items = {
  9314. {"field1", "value1", "", ""},
  9315. {"field2", "longer value for progress tracking test", "", ""},
  9316. {"file1", "file content data for upload progress", "test.txt",
  9317. "text/plain"}};
  9318. auto res = client_call(cli, endpoint, items,
  9319. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9320. progress_values.push_back(current);
  9321. return true;
  9322. });
  9323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9324. EXPECT_EQ(200, res->status);
  9325. EXPECT_FALSE(progress_values.empty());
  9326. }
  9327. TEST(UploadProgressTest, PostMultipartProgress) {
  9328. TestMultipartUploadProgress(
  9329. [](Server &svr) {
  9330. svr.Post("/multipart", [](const Request &req, Response &res) {
  9331. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9332. res.set_content("multipart received", "text/plain");
  9333. });
  9334. },
  9335. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9336. UploadProgress progress_callback) {
  9337. return cli.Post(endpoint, items, progress_callback);
  9338. },
  9339. "/multipart");
  9340. }
  9341. // Helper function for basic download progress tests
  9342. template <typename SetupHandler, typename ClientCall>
  9343. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9344. ClientCall &&client_call, const string &endpoint,
  9345. size_t expected_content_size) {
  9346. Server svr;
  9347. setup_handler(svr);
  9348. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9349. auto se = detail::scope_exit([&] {
  9350. svr.stop();
  9351. t.join();
  9352. });
  9353. svr.wait_until_ready();
  9354. Client cli(HOST, PORT);
  9355. vector<uint64_t> progress_values;
  9356. auto res = client_call(cli, endpoint,
  9357. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9358. progress_values.push_back(current);
  9359. return true;
  9360. });
  9361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9362. EXPECT_EQ(200, res->status);
  9363. EXPECT_FALSE(progress_values.empty());
  9364. EXPECT_EQ(expected_content_size, res->body.size());
  9365. }
  9366. TEST(DownloadProgressTest, GetBasic) {
  9367. TestBasicDownloadProgress(
  9368. [](Server &svr) {
  9369. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9370. string content(1000, 'D');
  9371. res.set_content(content, "text/plain");
  9372. });
  9373. },
  9374. [](Client &cli, const string &endpoint,
  9375. DownloadProgress progress_callback) {
  9376. return cli.Get(endpoint, progress_callback);
  9377. },
  9378. "/download", 1000u);
  9379. }
  9380. // Helper function for content receiver download progress tests
  9381. template <typename SetupHandler, typename ClientCall>
  9382. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9383. ClientCall &&client_call,
  9384. const string &endpoint,
  9385. size_t expected_content_size) {
  9386. Server svr;
  9387. setup_handler(svr);
  9388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9389. auto se = detail::scope_exit([&] {
  9390. svr.stop();
  9391. t.join();
  9392. });
  9393. svr.wait_until_ready();
  9394. Client cli(HOST, PORT);
  9395. vector<uint64_t> progress_values;
  9396. string received_body;
  9397. auto res = client_call(
  9398. cli, endpoint,
  9399. [&](const char *data, size_t data_length) -> bool {
  9400. received_body.append(data, data_length);
  9401. return true;
  9402. },
  9403. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9404. progress_values.push_back(current);
  9405. return true;
  9406. });
  9407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9408. EXPECT_EQ(200, res->status);
  9409. EXPECT_FALSE(progress_values.empty());
  9410. EXPECT_EQ(expected_content_size, received_body.size());
  9411. EXPECT_TRUE(res->body.empty());
  9412. }
  9413. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9414. TestContentReceiverDownloadProgress(
  9415. [](Server &svr) {
  9416. svr.Get("/download-receiver",
  9417. [](const Request & /*req*/, Response &res) {
  9418. string content(2000, 'R');
  9419. res.set_content(content, "text/plain");
  9420. });
  9421. },
  9422. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9423. DownloadProgress progress_callback) {
  9424. return cli.Get(endpoint, content_receiver, progress_callback);
  9425. },
  9426. "/download-receiver", 2000u);
  9427. }
  9428. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9429. // A provider reaching a pass with nothing to hand over - an empty buffer
  9430. // popped off a queue, say - must not be taken to mean the body is finished.
  9431. // It used to end the loop with the terminating chunk unwritten while the
  9432. // server still considered the response complete, so the peer waited for an
  9433. // end that never arrived.
  9434. Server svr;
  9435. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9436. auto step = std::make_shared<int>(0);
  9437. res.set_chunked_content_provider("text/plain",
  9438. [step](size_t /*offset*/, DataSink &sink) {
  9439. switch ((*step)++) {
  9440. case 0: sink.write("", 0); break;
  9441. case 1: sink.write("hello", 5); break;
  9442. default: sink.done(); break;
  9443. }
  9444. return true;
  9445. });
  9446. });
  9447. auto port = svr.bind_to_any_port(HOST);
  9448. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9449. auto listen_se = detail::scope_exit([&] {
  9450. svr.stop();
  9451. listen_thread.join();
  9452. ASSERT_FALSE(svr.is_running());
  9453. });
  9454. svr.wait_until_ready();
  9455. Client cli(HOST, port);
  9456. // Without the fix the body is never terminated, so bound the wait rather
  9457. // than letting the test hang on the default read timeout.
  9458. cli.set_read_timeout(5, 0);
  9459. auto res = cli.Get("/stream");
  9460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9461. EXPECT_EQ(StatusCode::OK_200, res->status);
  9462. EXPECT_EQ("hello", res->body);
  9463. }
  9464. TEST(StreamingTest, NoContentLengthStreaming) {
  9465. Server svr;
  9466. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9467. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9468. if (offset < 6) {
  9469. sink.os << (offset < 3 ? "a" : "b");
  9470. } else {
  9471. sink.done();
  9472. }
  9473. return true;
  9474. });
  9475. });
  9476. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9477. auto listen_se = detail::scope_exit([&] {
  9478. svr.stop();
  9479. listen_thread.join();
  9480. ASSERT_FALSE(svr.is_running());
  9481. });
  9482. svr.wait_until_ready();
  9483. Client client(HOST, PORT);
  9484. auto get_thread = std::thread([&client]() {
  9485. std::string s;
  9486. auto res =
  9487. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9488. s += std::string(data, len);
  9489. return true;
  9490. });
  9491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9492. EXPECT_EQ(StatusCode::OK_200, res->status);
  9493. EXPECT_EQ("aaabbb", s);
  9494. });
  9495. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9496. // Give GET time to get a few messages.
  9497. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9498. }
  9499. TEST(MountTest, Unmount) {
  9500. Server svr;
  9501. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9502. auto se = detail::scope_exit([&] {
  9503. svr.stop();
  9504. listen_thread.join();
  9505. ASSERT_FALSE(svr.is_running());
  9506. });
  9507. svr.wait_until_ready();
  9508. Client cli("localhost", PORT);
  9509. svr.set_mount_point("/mount2", "./www2");
  9510. auto res = cli.Get("/");
  9511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9513. res = cli.Get("/mount2/dir/test.html");
  9514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9515. EXPECT_EQ(StatusCode::OK_200, res->status);
  9516. svr.set_mount_point("/", "./www");
  9517. res = cli.Get("/dir/");
  9518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9519. EXPECT_EQ(StatusCode::OK_200, res->status);
  9520. svr.remove_mount_point("/");
  9521. res = cli.Get("/dir/");
  9522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9523. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9524. svr.remove_mount_point("/mount2");
  9525. res = cli.Get("/mount2/dir/test.html");
  9526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9527. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9528. }
  9529. TEST(MountTest, PathSegmentBoundary) {
  9530. Server svr;
  9531. svr.set_mount_point("/mount2", "./www2");
  9532. svr.set_mount_point("/", "./www");
  9533. auto port = svr.bind_to_any_port(HOST);
  9534. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9535. auto se = detail::scope_exit([&] {
  9536. svr.stop();
  9537. listen_thread.join();
  9538. ASSERT_FALSE(svr.is_running());
  9539. });
  9540. svr.wait_until_ready();
  9541. Client cli(HOST, port);
  9542. auto res = cli.Get("/mount2/dir/test.html");
  9543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9544. EXPECT_EQ(StatusCode::OK_200, res->status);
  9545. // "/mount2" must not match part-way through a path segment.
  9546. res = cli.Get("/mount2dir/test.html");
  9547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9548. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9549. // A mount point ending in '/' keeps matching every path below it.
  9550. res = cli.Get("/dir/test.html");
  9551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9552. EXPECT_EQ(StatusCode::OK_200, res->status);
  9553. }
  9554. TEST(MountTest, Redicect) {
  9555. Server svr;
  9556. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9557. auto se = detail::scope_exit([&] {
  9558. svr.stop();
  9559. listen_thread.join();
  9560. ASSERT_FALSE(svr.is_running());
  9561. });
  9562. svr.set_mount_point("/", "./www");
  9563. svr.wait_until_ready();
  9564. Client cli("localhost", PORT);
  9565. auto res = cli.Get("/dir/");
  9566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9567. EXPECT_EQ(StatusCode::OK_200, res->status);
  9568. res = cli.Get("/dir");
  9569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9570. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9571. res = cli.Get("/file");
  9572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9573. EXPECT_EQ(StatusCode::OK_200, res->status);
  9574. res = cli.Get("/file/");
  9575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9576. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9577. cli.set_follow_location(true);
  9578. res = cli.Get("/dir");
  9579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9580. EXPECT_EQ(StatusCode::OK_200, res->status);
  9581. }
  9582. TEST(MountTest, MultibytesPathName) {
  9583. Server svr;
  9584. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9585. auto se = detail::scope_exit([&] {
  9586. svr.stop();
  9587. listen_thread.join();
  9588. ASSERT_FALSE(svr.is_running());
  9589. });
  9590. svr.set_mount_point("/", "./www");
  9591. svr.wait_until_ready();
  9592. Client cli("localhost", PORT);
  9593. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9595. EXPECT_EQ(StatusCode::OK_200, res->status);
  9596. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9597. }
  9598. #ifdef _WIN32
  9599. // Issue #2435: mmap::open() must succeed even when another handle holds
  9600. // the file open for writing (e.g. an active log file).
  9601. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9602. const char *path = "mmap_concurrent_writer_test.txt";
  9603. const char *content = "hello";
  9604. {
  9605. std::ofstream f(path, std::ios::binary);
  9606. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9607. }
  9608. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9609. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9610. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9611. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9612. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9613. detail::mmap m(path);
  9614. ASSERT_TRUE(m.is_open());
  9615. EXPECT_EQ(strlen(content), m.size());
  9616. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9617. }
  9618. #endif
  9619. #ifndef _WIN32
  9620. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9621. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9622. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9623. TEST(MmapTest, FailedMappingIsNotOpen) {
  9624. const char *path = "./mmap_failed_mapping_test_dir";
  9625. ASSERT_EQ(0, ::mkdir(path, 0755));
  9626. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9627. detail::mmap m(path);
  9628. EXPECT_FALSE(m.is_open());
  9629. EXPECT_EQ(0U, m.size());
  9630. EXPECT_NE(static_cast<const void *>(m.data()),
  9631. static_cast<const void *>(MAP_FAILED));
  9632. }
  9633. #endif
  9634. TEST(KeepAliveTest, ReadTimeout) {
  9635. Server svr;
  9636. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9637. std::this_thread::sleep_for(std::chrono::seconds(2));
  9638. res.set_content("a", "text/plain");
  9639. });
  9640. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9641. res.set_content("b", "text/plain");
  9642. });
  9643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9644. auto se = detail::scope_exit([&] {
  9645. svr.stop();
  9646. listen_thread.join();
  9647. ASSERT_FALSE(svr.is_running());
  9648. });
  9649. svr.wait_until_ready();
  9650. Client cli("localhost", PORT);
  9651. cli.set_keep_alive(true);
  9652. cli.set_read_timeout(std::chrono::seconds(1));
  9653. auto resa = cli.Get("/a");
  9654. ASSERT_FALSE(resa);
  9655. EXPECT_EQ(Error::Read, resa.error());
  9656. auto resb = cli.Get("/b");
  9657. ASSERT_TRUE(resb);
  9658. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9659. EXPECT_EQ("b", resb->body);
  9660. }
  9661. TEST(KeepAliveTest, MaxCount) {
  9662. size_t keep_alive_max_count = 3;
  9663. Server svr;
  9664. svr.set_keep_alive_max_count(keep_alive_max_count);
  9665. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9666. res.set_content("Hello World!", "text/plain");
  9667. });
  9668. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9669. auto se = detail::scope_exit([&] {
  9670. svr.stop();
  9671. listen_thread.join();
  9672. ASSERT_FALSE(svr.is_running());
  9673. });
  9674. svr.wait_until_ready();
  9675. Client cli(HOST, PORT);
  9676. cli.set_keep_alive(true);
  9677. for (size_t i = 0; i < 5; i++) {
  9678. auto result = cli.Get("/hi");
  9679. ASSERT_TRUE(result);
  9680. EXPECT_EQ(StatusCode::OK_200, result->status);
  9681. if (i == keep_alive_max_count - 1) {
  9682. EXPECT_EQ("close", result->get_header_value("Connection"));
  9683. } else {
  9684. EXPECT_FALSE(result->has_header("Connection"));
  9685. }
  9686. }
  9687. }
  9688. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9689. // can pull the next one into the server's buffer. The server must serve it
  9690. // without waiting for the socket to become readable again. The keep-alive
  9691. // timeout outlasts the client's read timeout, so a request left waiting for it
  9692. // shows up as a missing response.
  9693. static void serve_pipelining_routes(Server &svr,
  9694. const std::function<void(int)> &client) {
  9695. svr.set_keep_alive_timeout(5);
  9696. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9697. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9698. });
  9699. svr.Post("/echo", [](const Request &req, Response &res) {
  9700. res.set_content("echo " + req.body, "text/plain");
  9701. });
  9702. auto port = svr.bind_to_any_port(HOST);
  9703. thread t = thread([&] { svr.listen_after_bind(); });
  9704. auto se = detail::scope_exit([&] {
  9705. svr.stop();
  9706. t.join();
  9707. });
  9708. svr.wait_until_ready();
  9709. client(port);
  9710. }
  9711. static std::string
  9712. send_pipelined_requests(const std::vector<std::string> &parts) {
  9713. Server svr;
  9714. std::string res;
  9715. serve_pipelining_routes(svr, [&](int port) {
  9716. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9717. });
  9718. return res;
  9719. }
  9720. static void expect_in_order(const std::string &res,
  9721. const std::vector<std::string> &bodies) {
  9722. size_t pos = 0;
  9723. for (const auto &body : bodies) {
  9724. pos = res.find(body, pos);
  9725. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9726. pos += body.size();
  9727. }
  9728. }
  9729. TEST(KeepAliveTest, PipelinedRequests) {
  9730. auto res = send_pipelined_requests(
  9731. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9732. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9733. "Content-Length: 4\r\n\r\nbody"
  9734. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9735. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9736. }
  9737. // The second request starts in the server's buffer and ends on the socket.
  9738. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9739. auto res =
  9740. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9741. "GET /hi/2 HTTP/1.1\r\nHo",
  9742. "st: localhost\r\nConnection: close\r\n\r\n"});
  9743. expect_in_order(res, {"hi 1", "hi 2"});
  9744. }
  9745. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9746. // CRLF after a body does not turn into a 400 for the next request.
  9747. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9748. auto res = send_pipelined_requests(
  9749. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9750. "Content-Length: 4\r\n\r\nbody\r\n"
  9751. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9752. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9753. expect_in_order(res, {"echo body", "hi 2"});
  9754. }
  9755. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9756. // must not be served as the next request.
  9757. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9758. auto res = send_pipelined_requests(
  9759. {"INVALID REQUEST LINE\r\n\r\n"
  9760. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9761. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9762. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9763. }
  9764. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9765. // Over TLS, the next request is held by the TLS library as already decrypted
  9766. // data rather than on the socket.
  9767. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9769. std::string res;
  9770. serve_pipelining_routes(svr, [&](int port) {
  9771. auto error = Error::Success;
  9772. auto sock = detail::create_client_socket(
  9773. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9774. /*connection_timeout_sec=*/5, 0,
  9775. /*read_timeout_sec=*/2, 0,
  9776. /*write_timeout_sec=*/5, 0, std::string(), error);
  9777. ASSERT_NE(INVALID_SOCKET, sock);
  9778. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9779. auto ctx = SSL_CTX_new(TLS_client_method());
  9780. auto ssl = SSL_new(ctx);
  9781. auto ssl_se = detail::scope_exit([&] {
  9782. SSL_free(ssl);
  9783. SSL_CTX_free(ctx);
  9784. });
  9785. SSL_set_fd(ssl, static_cast<int>(sock));
  9786. ASSERT_EQ(1, SSL_connect(ssl));
  9787. // One write, so all three requests arrive in one TLS record
  9788. const std::string req =
  9789. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9790. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9791. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9792. ASSERT_EQ(static_cast<int>(req.size()),
  9793. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9794. char buf[512];
  9795. int n;
  9796. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9797. res.append(buf, static_cast<size_t>(n));
  9798. }
  9799. });
  9800. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9801. }
  9802. #endif
  9803. TEST(KeepAliveTest, Issue1041) {
  9804. Server svr;
  9805. svr.set_keep_alive_timeout(3);
  9806. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9807. res.set_content("Hello World!", "text/plain");
  9808. });
  9809. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9810. auto se = detail::scope_exit([&] {
  9811. svr.stop();
  9812. listen_thread.join();
  9813. ASSERT_FALSE(svr.is_running());
  9814. });
  9815. svr.wait_until_ready();
  9816. Client cli(HOST, PORT);
  9817. cli.set_keep_alive(true);
  9818. auto result = cli.Get("/hi");
  9819. ASSERT_TRUE(result);
  9820. EXPECT_EQ(StatusCode::OK_200, result->status);
  9821. std::this_thread::sleep_for(std::chrono::seconds(5));
  9822. result = cli.Get("/hi");
  9823. ASSERT_TRUE(result);
  9824. EXPECT_EQ(StatusCode::OK_200, result->status);
  9825. }
  9826. TEST(KeepAliveTest, Issue1959) {
  9827. Server svr;
  9828. svr.set_keep_alive_timeout(5);
  9829. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9830. res.set_content("a", "text/plain");
  9831. });
  9832. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9833. auto se = detail::scope_exit([&] {
  9834. if (!svr.is_running()) return;
  9835. svr.stop();
  9836. listen_thread.join();
  9837. ASSERT_FALSE(svr.is_running());
  9838. });
  9839. svr.wait_until_ready();
  9840. Client cli("localhost", PORT);
  9841. cli.set_keep_alive(true);
  9842. using namespace std::chrono;
  9843. auto start = steady_clock::now();
  9844. cli.Get("/a");
  9845. svr.stop();
  9846. listen_thread.join();
  9847. auto end = steady_clock::now();
  9848. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9849. EXPECT_LT(elapsed, 5000);
  9850. }
  9851. #ifdef CPPHTTPLIB_SSL_ENABLED
  9852. TEST(KeepAliveTest, SSLClientReconnection) {
  9853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9854. ASSERT_TRUE(svr.is_valid());
  9855. svr.set_keep_alive_timeout(1);
  9856. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9857. res.set_content("Hello World!", "text/plain");
  9858. });
  9859. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9860. auto se = detail::scope_exit([&] {
  9861. svr.stop();
  9862. listen_thread.join();
  9863. ASSERT_FALSE(svr.is_running());
  9864. });
  9865. svr.wait_until_ready();
  9866. SSLClient cli(HOST, PORT);
  9867. cli.enable_server_certificate_verification(false);
  9868. cli.set_keep_alive(true);
  9869. auto result = cli.Get("/hi");
  9870. ASSERT_TRUE(result);
  9871. EXPECT_EQ(StatusCode::OK_200, result->status);
  9872. result = cli.Get("/hi");
  9873. ASSERT_TRUE(result);
  9874. EXPECT_EQ(StatusCode::OK_200, result->status);
  9875. std::this_thread::sleep_for(std::chrono::seconds(2));
  9876. // Recoonect
  9877. result = cli.Get("/hi");
  9878. ASSERT_TRUE(result);
  9879. EXPECT_EQ(StatusCode::OK_200, result->status);
  9880. result = cli.Get("/hi");
  9881. ASSERT_TRUE(result);
  9882. EXPECT_EQ(StatusCode::OK_200, result->status);
  9883. }
  9884. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9886. ASSERT_TRUE(svr.is_valid());
  9887. svr.set_keep_alive_timeout(1);
  9888. std::string content = "reconnect";
  9889. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9890. res.set_content("Hello World!", "text/plain");
  9891. });
  9892. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9893. auto se = detail::scope_exit([&] {
  9894. svr.stop();
  9895. listen_thread.join();
  9896. ASSERT_FALSE(svr.is_running());
  9897. });
  9898. svr.wait_until_ready();
  9899. SSLClient cli(HOST, PORT);
  9900. cli.enable_server_certificate_verification(false);
  9901. cli.set_keep_alive(true);
  9902. auto result = cli.Post(
  9903. "/hi", content.size(),
  9904. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9905. sink.write(content.c_str(), content.size());
  9906. return true;
  9907. },
  9908. "text/plain");
  9909. ASSERT_TRUE(result);
  9910. EXPECT_EQ(200, result->status);
  9911. std::this_thread::sleep_for(std::chrono::seconds(2));
  9912. // Recoonect
  9913. result = cli.Post(
  9914. "/hi", content.size(),
  9915. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9916. sink.write(content.c_str(), content.size());
  9917. return true;
  9918. },
  9919. "text/plain");
  9920. ASSERT_TRUE(result);
  9921. EXPECT_EQ(200, result->status);
  9922. result = cli.Post(
  9923. "/hi", content.size(),
  9924. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9925. sink.write(content.c_str(), content.size());
  9926. return true;
  9927. },
  9928. "text/plain");
  9929. ASSERT_TRUE(result);
  9930. EXPECT_EQ(200, result->status);
  9931. }
  9932. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9933. using namespace httplib::tls;
  9934. {
  9935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9936. ASSERT_TRUE(svr.is_valid());
  9937. svr.Get("/sni", [&](const Request &req, Response &res) {
  9938. std::string expected = req.sni();
  9939. EXPECT_EQ(expected, req.get_param_value("expected"));
  9940. res.set_content("ok", "text/plain");
  9941. });
  9942. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9943. auto se = detail::scope_exit([&] {
  9944. svr.stop();
  9945. listen_thread.join();
  9946. ASSERT_FALSE(svr.is_running());
  9947. });
  9948. svr.wait_until_ready();
  9949. {
  9950. SSLClient cli("localhost", PORT);
  9951. cli.enable_server_certificate_verification(false);
  9952. auto res = cli.Get("/sni?expected=localhost");
  9953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9954. }
  9955. {
  9956. SSLClient cli("::1", PORT);
  9957. cli.enable_server_certificate_verification(false);
  9958. auto res = cli.Get("/sni?expected=");
  9959. // NOTE: This may fail if the server is listening on IPv4 only
  9960. // (e.g., when localhost resolves to 127.0.0.1 only)
  9961. if (res) {
  9962. EXPECT_EQ(StatusCode::OK_200, res->status);
  9963. } else {
  9964. EXPECT_EQ(Error::Connection, res.error());
  9965. }
  9966. }
  9967. }
  9968. }
  9969. #endif
  9970. TEST(ClientProblemDetectionTest, ContentProvider) {
  9971. Server svr;
  9972. size_t content_length = 1024 * 1024;
  9973. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9974. res.set_content_provider(
  9975. content_length, "text/plain",
  9976. [&](size_t offset, size_t length, DataSink &sink) {
  9977. auto out_len = std::min(length, static_cast<size_t>(1024));
  9978. std::string out(out_len, '@');
  9979. sink.write(out.data(), out_len);
  9980. return offset < 4096;
  9981. },
  9982. [](bool success) { ASSERT_FALSE(success); });
  9983. });
  9984. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9985. res.set_content_provider(
  9986. 0, "text/plain",
  9987. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9988. EXPECT_TRUE(false);
  9989. return true;
  9990. },
  9991. [](bool success) { ASSERT_FALSE(success); });
  9992. });
  9993. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9994. auto se = detail::scope_exit([&] {
  9995. svr.stop();
  9996. listen_thread.join();
  9997. ASSERT_FALSE(svr.is_running());
  9998. });
  9999. svr.wait_until_ready();
  10000. Client cli("localhost", PORT);
  10001. {
  10002. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10003. size_t /*data_length*/) { return false; });
  10004. ASSERT_FALSE(res);
  10005. }
  10006. {
  10007. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10008. size_t /*data_length*/) { return false; });
  10009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10010. }
  10011. }
  10012. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10013. // A provider that reports success without writing anything and without
  10014. // calling done() used to be handed the same offset and length again on every
  10015. // pass, so it spun for as long as the peer stayed connected.
  10016. Server svr;
  10017. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10018. res.set_content("ok", "text/plain");
  10019. });
  10020. auto port = svr.bind_to_any_port(HOST);
  10021. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10022. auto se = detail::scope_exit([&] {
  10023. svr.stop();
  10024. listen_thread.join();
  10025. ASSERT_FALSE(svr.is_running());
  10026. });
  10027. svr.wait_until_ready();
  10028. std::atomic<int> call_count{0};
  10029. Client cli(HOST, port);
  10030. auto res = cli.Post(
  10031. "/", 1024,
  10032. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10033. // Give up after enough passes to show the spin, so that losing the
  10034. // check below fails this test instead of hanging it.
  10035. return ++call_count < 100;
  10036. },
  10037. "text/plain");
  10038. ASSERT_FALSE(res);
  10039. EXPECT_EQ(Error::Write, res.error());
  10040. EXPECT_EQ(1, call_count.load());
  10041. }
  10042. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10043. // A writer only has to assign `write`. The other three used to be left as
  10044. // empty std::functions, so a provider calling one threw
  10045. // std::bad_function_call out of the thread running it and took the whole
  10046. // process down.
  10047. DataSink sink;
  10048. std::string written;
  10049. sink.write = [&](const char *data, size_t data_len) {
  10050. written.append(data, data_len);
  10051. return true;
  10052. };
  10053. EXPECT_TRUE(sink.is_writable());
  10054. sink.done();
  10055. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10056. EXPECT_TRUE(written.empty());
  10057. }
  10058. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10059. // A sink that cannot carry trailers still has to finish.
  10060. DataSink sink;
  10061. auto done_count = 0;
  10062. sink.done = [&]() { done_count++; };
  10063. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10064. EXPECT_EQ(1, done_count);
  10065. }
  10066. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10067. Server svr;
  10068. const std::string body(4096, 'x');
  10069. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10070. res.set_content_provider(body.size(), "text/plain",
  10071. [&](size_t offset, size_t length, DataSink &sink) {
  10072. sink.write(body.data() + offset, length);
  10073. sink.done();
  10074. return true;
  10075. });
  10076. });
  10077. auto port = svr.bind_to_any_port(HOST);
  10078. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10079. auto se = detail::scope_exit([&] {
  10080. svr.stop();
  10081. listen_thread.join();
  10082. ASSERT_FALSE(svr.is_running());
  10083. });
  10084. svr.wait_until_ready();
  10085. Client cli(HOST, port);
  10086. auto res = cli.Get("/");
  10087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10088. EXPECT_EQ(StatusCode::OK_200, res->status);
  10089. EXPECT_EQ(body, res->body);
  10090. }
  10091. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10092. Server svr;
  10093. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10094. res.set_content_provider(
  10095. 1024, "text/plain",
  10096. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10097. sink.write("hello", 5);
  10098. sink.done(); // short of the 1024 bytes the response promised
  10099. return true;
  10100. });
  10101. });
  10102. auto port = svr.bind_to_any_port(HOST);
  10103. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10104. auto se = detail::scope_exit([&] {
  10105. svr.stop();
  10106. listen_thread.join();
  10107. ASSERT_FALSE(svr.is_running());
  10108. });
  10109. svr.wait_until_ready();
  10110. Client cli(HOST, port);
  10111. cli.set_read_timeout(5, 0);
  10112. // The response is short of its Content-Length, so the client cannot read a
  10113. // complete body. What matters is that this returns at all: a no-op done()
  10114. // would leave the writer looping over a provider that never makes progress.
  10115. auto res = cli.Get("/");
  10116. EXPECT_FALSE(res);
  10117. }
  10118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10119. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10120. // The compressed path builds the whole body before connecting, so this
  10121. // fails client-side and never reaches a server.
  10122. Client cli(HOST, PORT);
  10123. cli.set_compress(true);
  10124. auto res = cli.Post(
  10125. "/", 1024,
  10126. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10127. sink.write("hello", 5);
  10128. sink.done(); // short of the 1024 bytes the request announced
  10129. return true;
  10130. },
  10131. "text/plain");
  10132. ASSERT_FALSE(res);
  10133. EXPECT_EQ(Error::Write, res.error());
  10134. }
  10135. #endif
  10136. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10137. Server svr;
  10138. svr.set_error_handler([](Request const &, Response &res) -> void {
  10139. res.set_chunked_content_provider(
  10140. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10141. sink.os << "hello";
  10142. sink.os << "world";
  10143. sink.done();
  10144. return true;
  10145. });
  10146. });
  10147. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10148. auto se = detail::scope_exit([&] {
  10149. svr.stop();
  10150. listen_thread.join();
  10151. ASSERT_FALSE(svr.is_running());
  10152. });
  10153. svr.wait_until_ready();
  10154. Client cli("localhost", PORT);
  10155. auto res = cli.Get("/");
  10156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10157. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10158. EXPECT_EQ("helloworld", res->body);
  10159. }
  10160. TEST(LongPollingTest, ClientCloseDetection) {
  10161. Server svr;
  10162. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10163. res.set_chunked_content_provider(
  10164. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10165. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10166. sink.os << "hello";
  10167. auto count = 10;
  10168. while (count > 0 && sink.is_writable()) {
  10169. this_thread::sleep_for(chrono::milliseconds(10));
  10170. count--;
  10171. }
  10172. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10173. return true;
  10174. });
  10175. });
  10176. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10177. auto se = detail::scope_exit([&] {
  10178. svr.stop();
  10179. listen_thread.join();
  10180. ASSERT_FALSE(svr.is_running());
  10181. });
  10182. svr.wait_until_ready();
  10183. Client cli("localhost", PORT);
  10184. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10185. EXPECT_EQ("hello", string(data, data_length));
  10186. return false; // close the socket immediately.
  10187. });
  10188. ASSERT_FALSE(res);
  10189. }
  10190. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10191. Server svr;
  10192. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10193. res.set_chunked_content_provider(
  10194. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10195. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10196. sink.os << "hello";
  10197. EXPECT_TRUE(sink.os.good());
  10198. // Wait for the client to close the connection
  10199. auto count = 10;
  10200. while (count > 0 && sink.is_writable()) {
  10201. this_thread::sleep_for(chrono::milliseconds(10));
  10202. count--;
  10203. }
  10204. // After client disconnect, write repeatedly until the socket
  10205. // write actually fails (small writes may be absorbed by the
  10206. // kernel buffer)
  10207. std::string chunk(1024, 'x');
  10208. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10209. sink.os << chunk;
  10210. }
  10211. EXPECT_TRUE(sink.os.fail());
  10212. return true;
  10213. });
  10214. });
  10215. auto port = svr.bind_to_any_port("localhost");
  10216. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10217. auto se = detail::scope_exit([&] {
  10218. svr.stop();
  10219. listen_thread.join();
  10220. ASSERT_FALSE(svr.is_running());
  10221. });
  10222. svr.wait_until_ready();
  10223. Client cli("localhost", port);
  10224. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10225. EXPECT_EQ("hello", string(data, data_length));
  10226. return false; // close the socket immediately.
  10227. });
  10228. ASSERT_FALSE(res);
  10229. }
  10230. TEST(GetWithParametersTest, GetWithParameters) {
  10231. Server svr;
  10232. svr.Get("/", [&](const Request &req, Response &) {
  10233. EXPECT_EQ("world", req.get_param_value("hello"));
  10234. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10235. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10236. });
  10237. svr.Get("/params", [&](const Request &req, Response &) {
  10238. EXPECT_EQ("world", req.get_param_value("hello"));
  10239. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10240. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10241. });
  10242. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10243. EXPECT_EQ("resource-id", req.matches[1]);
  10244. EXPECT_EQ("foo", req.get_param_value("param1"));
  10245. EXPECT_EQ("bar", req.get_param_value("param2"));
  10246. });
  10247. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10248. EXPECT_EQ("user-id", req.path_params.at("id"));
  10249. EXPECT_EQ("foo", req.get_param_value("param1"));
  10250. EXPECT_EQ("bar", req.get_param_value("param2"));
  10251. });
  10252. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10253. auto se = detail::scope_exit([&] {
  10254. svr.stop();
  10255. listen_thread.join();
  10256. ASSERT_FALSE(svr.is_running());
  10257. });
  10258. svr.wait_until_ready();
  10259. {
  10260. Client cli(HOST, PORT);
  10261. Params params;
  10262. params.emplace("hello", "world");
  10263. params.emplace("hello2", "world2");
  10264. params.emplace("hello3", "world3");
  10265. auto res = cli.Get("/", params, Headers{});
  10266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10267. EXPECT_EQ(StatusCode::OK_200, res->status);
  10268. }
  10269. {
  10270. Client cli(HOST, PORT);
  10271. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10273. EXPECT_EQ(StatusCode::OK_200, res->status);
  10274. }
  10275. {
  10276. Client cli(HOST, PORT);
  10277. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10279. EXPECT_EQ(StatusCode::OK_200, res->status);
  10280. }
  10281. {
  10282. Client cli(HOST, PORT);
  10283. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10285. EXPECT_EQ(StatusCode::OK_200, res->status);
  10286. }
  10287. }
  10288. TEST(GetWithParametersTest, GetWithParameters2) {
  10289. Server svr;
  10290. svr.Get("/", [&](const Request &req, Response &res) {
  10291. auto text = req.get_param_value("hello");
  10292. res.set_content(text, "text/plain");
  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. Params params;
  10303. params.emplace("hello", "world");
  10304. std::string body;
  10305. auto res = cli.Get("/", params, Headers{},
  10306. [&](const char *data, size_t data_length) {
  10307. body.append(data, data_length);
  10308. return true;
  10309. });
  10310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10311. EXPECT_EQ(StatusCode::OK_200, res->status);
  10312. EXPECT_EQ("world", body);
  10313. }
  10314. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10315. Server svr;
  10316. svr.Get("/search", [&](const Request &req, Response &res) {
  10317. auto q = req.get_param_value("q");
  10318. res.set_content(q, "text/plain");
  10319. });
  10320. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10321. auto se = detail::scope_exit([&] {
  10322. svr.stop();
  10323. listen_thread.join();
  10324. ASSERT_FALSE(svr.is_running());
  10325. });
  10326. svr.wait_until_ready();
  10327. Client cli("localhost", PORT);
  10328. // Verify that Get(path, params) works without requiring Headers argument
  10329. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10331. EXPECT_EQ(StatusCode::OK_200, res->status);
  10332. EXPECT_EQ("cpp-httplib", res->body);
  10333. }
  10334. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10335. auto host = "httpbingo.org";
  10336. auto path = std::string{"/range/32"};
  10337. #ifdef CPPHTTPLIB_SSL_ENABLED
  10338. SSLClient cli(host);
  10339. #else
  10340. Client cli(host);
  10341. #endif
  10342. cli.set_default_headers({make_range_header({{1, 10}})});
  10343. cli.set_connection_timeout(5);
  10344. {
  10345. auto res = cli.Get(path);
  10346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10347. EXPECT_EQ("bcdefghijk", res->body);
  10348. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10349. }
  10350. {
  10351. auto res = cli.Get(path);
  10352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10353. EXPECT_EQ("bcdefghijk", res->body);
  10354. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10355. }
  10356. }
  10357. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10358. Server svr;
  10359. svr.set_default_headers({{"Hello", "World"}});
  10360. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10361. res.set_content("ok", "text/plain");
  10362. });
  10363. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10364. auto se = detail::scope_exit([&] {
  10365. svr.stop();
  10366. listen_thread.join();
  10367. ASSERT_FALSE(svr.is_running());
  10368. });
  10369. svr.wait_until_ready();
  10370. Client cli("localhost", PORT);
  10371. auto res = cli.Get("/");
  10372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10373. EXPECT_EQ(StatusCode::OK_200, res->status);
  10374. EXPECT_EQ("ok", res->body);
  10375. EXPECT_EQ("World", res->get_header_value("Hello"));
  10376. }
  10377. #ifdef CPPHTTPLIB_SSL_ENABLED
  10378. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10380. ASSERT_TRUE(svr.is_valid());
  10381. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10382. std::this_thread::sleep_for(std::chrono::seconds(2));
  10383. res.set_content("a", "text/plain");
  10384. });
  10385. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10386. res.set_content("b", "text/plain");
  10387. });
  10388. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10389. auto se = detail::scope_exit([&] {
  10390. svr.stop();
  10391. listen_thread.join();
  10392. ASSERT_FALSE(svr.is_running());
  10393. });
  10394. svr.wait_until_ready();
  10395. SSLClient cli("localhost", PORT);
  10396. cli.enable_server_certificate_verification(false);
  10397. cli.set_keep_alive(true);
  10398. cli.set_read_timeout(std::chrono::seconds(1));
  10399. auto resa = cli.Get("/a");
  10400. ASSERT_TRUE(!resa);
  10401. EXPECT_EQ(Error::Read, resa.error());
  10402. auto resb = cli.Get("/b");
  10403. ASSERT_TRUE(resb);
  10404. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10405. EXPECT_EQ("b", resb->body);
  10406. }
  10407. // Closing an idle keep-alive connection sends close_notify and returns. The
  10408. // server must not wait for the client's close_notify: an idle client never
  10409. // sends one, so the worker would be held until the read timeout expires, and
  10410. // stop() would wait for it.
  10411. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10413. ASSERT_TRUE(svr.is_valid());
  10414. svr.set_keep_alive_timeout(1);
  10415. svr.set_read_timeout(10, 0);
  10416. svr.Get("/", [](const Request &, Response &res) {
  10417. res.set_content("ok", "text/plain");
  10418. });
  10419. auto port = svr.bind_to_any_port(HOST);
  10420. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10421. auto se = detail::scope_exit([&] {
  10422. if (listen_thread.joinable()) {
  10423. svr.stop();
  10424. listen_thread.join();
  10425. }
  10426. });
  10427. svr.wait_until_ready();
  10428. SSLClient cli(HOST, port);
  10429. cli.enable_server_certificate_verification(false);
  10430. cli.set_keep_alive(true);
  10431. auto res = cli.Get("/");
  10432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10433. EXPECT_EQ(StatusCode::OK_200, res->status);
  10434. // Stay idle past the keep-alive timeout so the server closes the connection.
  10435. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10436. auto start = std::chrono::steady_clock::now();
  10437. svr.stop();
  10438. listen_thread.join();
  10439. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10440. std::chrono::steady_clock::now() - start)
  10441. .count();
  10442. EXPECT_LT(elapsed, 3000);
  10443. }
  10444. #endif
  10445. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10446. protected:
  10447. ServerTestWithAI_PASSIVE()
  10448. : cli_(HOST, PORT)
  10449. #ifdef CPPHTTPLIB_SSL_ENABLED
  10450. ,
  10451. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10452. #endif
  10453. {
  10454. #ifdef CPPHTTPLIB_SSL_ENABLED
  10455. cli_.enable_server_certificate_verification(false);
  10456. #endif
  10457. }
  10458. virtual void SetUp() {
  10459. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10460. res.set_content("Hello World!", "text/plain");
  10461. });
  10462. t_ = thread(
  10463. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10464. svr_.wait_until_ready();
  10465. }
  10466. virtual void TearDown() {
  10467. svr_.stop();
  10468. t_.join();
  10469. }
  10470. #ifdef CPPHTTPLIB_SSL_ENABLED
  10471. SSLClient cli_;
  10472. SSLServer svr_;
  10473. #else
  10474. Client cli_;
  10475. Server svr_;
  10476. #endif
  10477. thread t_;
  10478. };
  10479. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10480. auto res = cli_.Get("/hi");
  10481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10482. EXPECT_EQ(StatusCode::OK_200, res->status);
  10483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10484. EXPECT_EQ("Hello World!", res->body);
  10485. }
  10486. class ServerUpDownTest : public ::testing::Test {
  10487. protected:
  10488. ServerUpDownTest() : cli_(HOST, PORT) {}
  10489. virtual void SetUp() {
  10490. t_ = thread([&]() {
  10491. svr_.bind_to_any_port(HOST);
  10492. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10493. ASSERT_TRUE(svr_.listen_after_bind());
  10494. });
  10495. svr_.wait_until_ready();
  10496. }
  10497. virtual void TearDown() {
  10498. svr_.stop();
  10499. t_.join();
  10500. }
  10501. Client cli_;
  10502. Server svr_;
  10503. thread t_;
  10504. };
  10505. TEST_F(ServerUpDownTest, QuickStartStop) {
  10506. // Should not crash, especially when run with
  10507. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10508. }
  10509. class PayloadMaxLengthTest : public ::testing::Test {
  10510. protected:
  10511. PayloadMaxLengthTest()
  10512. : cli_(HOST, PORT)
  10513. #ifdef CPPHTTPLIB_SSL_ENABLED
  10514. ,
  10515. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10516. #endif
  10517. {
  10518. #ifdef CPPHTTPLIB_SSL_ENABLED
  10519. cli_.enable_server_certificate_verification(false);
  10520. #endif
  10521. }
  10522. virtual void SetUp() {
  10523. svr_.set_payload_max_length(8);
  10524. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10525. res.set_content("test", "text/plain");
  10526. });
  10527. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10528. svr_.wait_until_ready();
  10529. }
  10530. virtual void TearDown() {
  10531. svr_.stop();
  10532. t_.join();
  10533. }
  10534. #ifdef CPPHTTPLIB_SSL_ENABLED
  10535. SSLClient cli_;
  10536. SSLServer svr_;
  10537. #else
  10538. Client cli_;
  10539. Server svr_;
  10540. #endif
  10541. thread t_;
  10542. };
  10543. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10544. auto res = cli_.Post("/test", "123456789", "text/plain");
  10545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10546. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10547. res = cli_.Post("/test", "12345678", "text/plain");
  10548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10549. EXPECT_EQ(StatusCode::OK_200, res->status);
  10550. }
  10551. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10552. // Test chunked encoding with payload exceeding the 8-byte limit
  10553. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10554. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10556. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10557. }
  10558. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10559. // Test chunked encoding with payload within the 8-byte limit
  10560. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10561. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10563. EXPECT_EQ(StatusCode::OK_200, res->status);
  10564. }
  10565. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10566. // Test using send_request to send chunked data exceeding payload limit
  10567. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10568. "Host: " +
  10569. std::string(HOST) + ":" + std::to_string(PORT) +
  10570. "\r\n"
  10571. "Transfer-Encoding: chunked\r\n"
  10572. "Connection: close\r\n"
  10573. "\r\n"
  10574. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10575. "0123456789\r\n"
  10576. "0\r\n" // End chunk
  10577. "\r\n";
  10578. std::string response;
  10579. bool result = send_request(1, chunked_request, &response);
  10580. if (!result) {
  10581. // If send_request fails, it might be because the server closed the
  10582. // connection due to payload limit enforcement, which is acceptable
  10583. SUCCEED()
  10584. << "Server rejected oversized chunked request (connection closed)";
  10585. } else {
  10586. // If we got a response, check if it's an error response or connection was
  10587. // closed early Short response length indicates connection was closed due to
  10588. // payload limit
  10589. if (response.length() <= 10) {
  10590. SUCCEED() << "Server closed connection for oversized chunked request";
  10591. } else {
  10592. // Check for error status codes
  10593. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10594. response.find("Payload Too Large") != std::string::npos ||
  10595. response.find("400") != std::string::npos);
  10596. }
  10597. }
  10598. }
  10599. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10600. // Test request without Content-Length header exceeding payload limit
  10601. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10602. "Host: " +
  10603. std::string(HOST) + ":" +
  10604. std::to_string(PORT) +
  10605. "\r\n"
  10606. "Connection: close\r\n"
  10607. "\r\n";
  10608. // Add payload exceeding the 8-byte limit
  10609. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10610. request_without_content_length += large_payload;
  10611. std::string response;
  10612. bool result = send_request(1, request_without_content_length, &response);
  10613. if (!result) {
  10614. // If send_request fails, server likely closed connection due to payload
  10615. // limit
  10616. SUCCEED() << "Server rejected oversized request without Content-Length "
  10617. "(connection closed)";
  10618. } else {
  10619. // Check if server responded with error or closed connection early
  10620. if (response.length() <= 10) {
  10621. SUCCEED() << "Server closed connection for oversized request without "
  10622. "Content-Length";
  10623. } else {
  10624. // Check for error status codes
  10625. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10626. response.find("Payload Too Large") != std::string::npos ||
  10627. response.find("400") != std::string::npos);
  10628. }
  10629. }
  10630. }
  10631. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10632. // Test request without Content-Length header within payload limit
  10633. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10634. "Host: " +
  10635. std::string(HOST) + ":" +
  10636. std::to_string(PORT) +
  10637. "\r\n"
  10638. "Connection: close\r\n"
  10639. "\r\n";
  10640. // Add payload within the 8-byte limit
  10641. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10642. request_without_content_length += small_payload;
  10643. std::string response;
  10644. bool result = send_request(1, request_without_content_length, &response);
  10645. // For requests without Content-Length, the server may have different behavior
  10646. // The key is that it should not reject due to payload limit for small
  10647. // payloads
  10648. if (result) {
  10649. // Check for any HTTP response (success or error, but not connection closed)
  10650. if (response.length() > 10) {
  10651. SUCCEED()
  10652. << "Server processed request without Content-Length within limit";
  10653. } else {
  10654. // Short response might indicate connection closed, which is acceptable
  10655. SUCCEED() << "Server closed connection for request without "
  10656. "Content-Length (acceptable behavior)";
  10657. }
  10658. } else {
  10659. // Connection failure might be due to protocol requirements
  10660. SUCCEED() << "Connection issue with request without Content-Length "
  10661. "(environment-specific)";
  10662. }
  10663. }
  10664. class LargePayloadMaxLengthTest : public ::testing::Test {
  10665. protected:
  10666. LargePayloadMaxLengthTest()
  10667. : cli_(HOST, PORT)
  10668. #ifdef CPPHTTPLIB_SSL_ENABLED
  10669. ,
  10670. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10671. #endif
  10672. {
  10673. #ifdef CPPHTTPLIB_SSL_ENABLED
  10674. cli_.enable_server_certificate_verification(false);
  10675. #endif
  10676. }
  10677. virtual void SetUp() {
  10678. // Set 10MB payload limit
  10679. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10680. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10681. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10682. res.set_content("Large payload test", "text/plain");
  10683. });
  10684. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10685. svr_.wait_until_ready();
  10686. }
  10687. virtual void TearDown() {
  10688. svr_.stop();
  10689. t_.join();
  10690. }
  10691. #ifdef CPPHTTPLIB_SSL_ENABLED
  10692. SSLClient cli_;
  10693. SSLServer svr_;
  10694. #else
  10695. Client cli_;
  10696. Server svr_;
  10697. #endif
  10698. thread t_;
  10699. };
  10700. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10701. // Test chunked encoding with payload within 10MB limit
  10702. std::string medium_payload(5 * 1024 * 1024,
  10703. 'A'); // 5MB payload, within 10MB limit
  10704. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10706. EXPECT_EQ(StatusCode::OK_200, res->status);
  10707. }
  10708. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10709. // Test chunked encoding with payload exceeding 10MB limit
  10710. std::string large_payload(12 * 1024 * 1024,
  10711. 'B'); // 12MB payload, exceeds 10MB limit
  10712. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10713. // Server may either return 413 or close the connection
  10714. if (res) {
  10715. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10716. } else {
  10717. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10718. }
  10719. }
  10720. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10721. // Test request without Content-Length header within 10MB limit
  10722. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10723. "Host: " +
  10724. std::string(HOST) + ":" +
  10725. std::to_string(PORT) +
  10726. "\r\n"
  10727. "Connection: close\r\n"
  10728. "\r\n";
  10729. // Add 1MB payload (within 10MB limit)
  10730. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10731. request_without_content_length += medium_payload;
  10732. std::string response;
  10733. bool result = send_request(5, request_without_content_length, &response);
  10734. if (result) {
  10735. // Should get a proper HTTP response for payloads within limit
  10736. if (response.length() > 10) {
  10737. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10738. "10MB limit";
  10739. } else {
  10740. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10741. "Content-Length)";
  10742. }
  10743. } else {
  10744. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10745. }
  10746. }
  10747. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10748. // Test request without Content-Length header exceeding 10MB limit
  10749. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10750. "Host: " +
  10751. std::string(HOST) + ":" +
  10752. std::to_string(PORT) +
  10753. "\r\n"
  10754. "Connection: close\r\n"
  10755. "\r\n";
  10756. // Add 12MB payload (exceeds 10MB limit)
  10757. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10758. request_without_content_length += large_payload;
  10759. std::string response;
  10760. bool result = send_request(10, request_without_content_length, &response);
  10761. if (!result) {
  10762. // Server should close connection due to payload limit
  10763. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10764. "(connection closed)";
  10765. } else {
  10766. // Check for error response
  10767. if (response.length() <= 10) {
  10768. SUCCEED()
  10769. << "Server closed connection for 12MB request exceeding 10MB limit";
  10770. } else {
  10771. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10772. response.find("Payload Too Large") != std::string::npos ||
  10773. response.find("400") != std::string::npos);
  10774. }
  10775. }
  10776. }
  10777. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10778. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10779. // path.
  10780. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10781. Server svr;
  10782. const size_t LIMIT = 64 * 1024; // 64KB
  10783. svr.set_payload_max_length(LIMIT);
  10784. size_t total = 0;
  10785. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10786. const ContentReader &content_reader) {
  10787. content_reader([&](const char * /*data*/, size_t len) {
  10788. total += len;
  10789. return true;
  10790. });
  10791. res.status = 200;
  10792. res.set_content("stream_ok", "text/plain");
  10793. });
  10794. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10795. auto se = detail::scope_exit([&] {
  10796. svr.stop();
  10797. thread.join();
  10798. ASSERT_FALSE(svr.is_running());
  10799. });
  10800. svr.wait_until_ready();
  10801. // Prepare 256KB raw data and gzip-compress it
  10802. std::string raw(256 * 1024, 'A');
  10803. std::string gz;
  10804. {
  10805. z_stream zs{};
  10806. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10807. Z_DEFAULT_STRATEGY);
  10808. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10809. zs.avail_in = static_cast<uInt>(raw.size());
  10810. char outbuf[4096];
  10811. int ret;
  10812. do {
  10813. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10814. zs.avail_out = sizeof(outbuf);
  10815. ret = deflate(&zs, Z_FINISH);
  10816. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10817. } while (ret != Z_STREAM_END);
  10818. deflateEnd(&zs);
  10819. }
  10820. Client cli(HOST, PORT);
  10821. cli.set_connection_timeout(std::chrono::seconds(5));
  10822. Headers headers = {{"Content-Encoding", "gzip"}};
  10823. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10824. "application/octet-stream");
  10825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10826. // Server must reject oversized decompressed payloads with 413.
  10827. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10828. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10829. EXPECT_LE(total, LIMIT);
  10830. }
  10831. #ifndef CPPHTTPLIB_SSL_ENABLED
  10832. // For a request with neither Content-Length nor Transfer-Encoding, the
  10833. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10834. // compressed wire bytes straight to the ContentReader without ever routing
  10835. // them through the decompressor, so payload_max_length_ only bounded the
  10836. // compressed size on the wire, not the decompressed size.
  10837. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10838. Server svr;
  10839. const size_t LIMIT = 64 * 1024; // 64KB
  10840. svr.set_payload_max_length(LIMIT);
  10841. size_t total = 0;
  10842. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10843. const ContentReader &content_reader) {
  10844. content_reader([&](const char * /*data*/, size_t len) {
  10845. total += len;
  10846. return true;
  10847. });
  10848. res.status = 200;
  10849. res.set_content("stream_ok", "text/plain");
  10850. });
  10851. auto port = svr.bind_to_any_port(HOST);
  10852. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10853. auto se = detail::scope_exit([&] {
  10854. svr.stop();
  10855. thread.join();
  10856. ASSERT_FALSE(svr.is_running());
  10857. });
  10858. svr.wait_until_ready();
  10859. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10860. // StreamingGzipDecompression test above.
  10861. std::string raw(256 * 1024, 'A');
  10862. std::string gz;
  10863. {
  10864. httplib::detail::gzip_compressor compressor;
  10865. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10866. [&](const char *chunk, size_t len) {
  10867. gz.append(chunk, len);
  10868. return true;
  10869. });
  10870. ASSERT_TRUE(result);
  10871. }
  10872. // Send the gzip body over raw TCP with neither Content-Length nor
  10873. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10874. // kicks in.
  10875. std::string req = "POST /stream HTTP/1.1\r\n"
  10876. "Host: " +
  10877. std::string(HOST) + ":" + std::to_string(port) +
  10878. "\r\n"
  10879. "Content-Encoding: gzip\r\n"
  10880. "Connection: close\r\n"
  10881. "\r\n" +
  10882. gz;
  10883. std::string response;
  10884. ASSERT_TRUE(send_request(5, req, &response, port));
  10885. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10886. EXPECT_LE(total, LIMIT);
  10887. }
  10888. #endif
  10889. #endif
  10890. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10891. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10892. // the payload must be passed through untouched instead of being rejected.
  10893. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10894. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10895. Server svr;
  10896. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10897. res.set_content(body, "image/jpeg");
  10898. res.set_header("Content-Encoding", "UTF-8");
  10899. });
  10900. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10901. res.set_content(body, "image/jpeg");
  10902. res.set_header("Content-Encoding", "identity");
  10903. });
  10904. svr.Post("/echo", [](const Request &req, Response &res) {
  10905. res.set_content(req.body, "image/jpeg");
  10906. });
  10907. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10908. auto se = detail::scope_exit([&] {
  10909. svr.stop();
  10910. t.join();
  10911. ASSERT_FALSE(svr.is_running());
  10912. });
  10913. svr.wait_until_ready();
  10914. Client cli(HOST, PORT);
  10915. {
  10916. auto res = cli.Get("/image");
  10917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10918. EXPECT_EQ(StatusCode::OK_200, res->status);
  10919. EXPECT_EQ(body, res->body);
  10920. }
  10921. {
  10922. auto res = cli.Get("/identity");
  10923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10924. EXPECT_EQ(StatusCode::OK_200, res->status);
  10925. EXPECT_EQ(body, res->body);
  10926. }
  10927. {
  10928. // The same applies to a request body reaching the server.
  10929. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10930. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10932. EXPECT_EQ(StatusCode::OK_200, res->status);
  10933. EXPECT_EQ(body, res->body);
  10934. }
  10935. }
  10936. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10937. // gzip-encoded response even when the build has no zlib support.
  10938. static const char GZIPPED_HELLO_WORLD[] = {
  10939. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10940. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10941. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10942. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10943. // A content coding is a whole token, not something the field value merely
  10944. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10945. // as "fibre" look like Brotli, and turned a multi-coding value like
  10946. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10947. // it was never meant to see.
  10948. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10949. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10950. Server svr;
  10951. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10952. res.set_content(body, "image/jpeg");
  10953. res.set_header("Content-Encoding", "fibre");
  10954. });
  10955. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10956. res.set_content(body, "image/jpeg");
  10957. res.set_header("Content-Encoding", "gzip, br");
  10958. });
  10959. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10960. res.set_content(body, "image/jpeg");
  10961. res.set_header("Content-Encoding", "x-zstd-ish");
  10962. });
  10963. auto port = svr.bind_to_any_port(HOST);
  10964. thread t = thread([&]() { svr.listen_after_bind(); });
  10965. auto se = detail::scope_exit([&] {
  10966. svr.stop();
  10967. t.join();
  10968. ASSERT_FALSE(svr.is_running());
  10969. });
  10970. svr.wait_until_ready();
  10971. Client cli(HOST, port);
  10972. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10973. auto res = cli.Get(path);
  10974. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10975. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10976. // Not a coding we recognize, so the payload comes back untouched
  10977. EXPECT_EQ(body, res->body) << path;
  10978. }
  10979. }
  10980. // A content coding cpp-httplib recognizes but was not built with must be
  10981. // reported as such. Handing the still-compressed payload back to the caller
  10982. // would silently corrupt it.
  10983. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10984. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10985. Server svr;
  10986. // "image/jpeg" keeps the server from applying a content coding of its own,
  10987. // so the hand-crafted Content-Encoding below survives.
  10988. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10989. res.set_content(gzipped, "image/jpeg");
  10990. res.set_header("Content-Encoding", "gzip");
  10991. });
  10992. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10993. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10994. res.set_content(gzipped, "image/jpeg");
  10995. res.set_header("Content-Encoding", "GZIP");
  10996. });
  10997. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10998. auto se = detail::scope_exit([&] {
  10999. svr.stop();
  11000. t.join();
  11001. ASSERT_FALSE(svr.is_running());
  11002. });
  11003. svr.wait_until_ready();
  11004. Client cli(HOST, PORT);
  11005. {
  11006. auto res = cli.Get("/gzipped");
  11007. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11009. EXPECT_EQ("Hello World!", res->body);
  11010. #else
  11011. ASSERT_FALSE(res);
  11012. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11013. #endif
  11014. }
  11015. {
  11016. // open_stream() must behave the same way.
  11017. auto handle = cli.open_stream("GET", "/gzipped");
  11018. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11019. ASSERT_TRUE(handle.is_valid());
  11020. std::string received;
  11021. char buf[256];
  11022. ssize_t n;
  11023. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11024. received.append(buf, static_cast<size_t>(n));
  11025. }
  11026. EXPECT_EQ("Hello World!", received);
  11027. #else
  11028. EXPECT_FALSE(handle.is_valid());
  11029. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11030. #endif
  11031. }
  11032. {
  11033. // A differently-cased coding must not be mistaken for an unknown one, or
  11034. // the body would be handed back still compressed.
  11035. auto res = cli.Get("/gzipped-uppercase");
  11036. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11038. EXPECT_EQ("Hello World!", res->body);
  11039. #else
  11040. ASSERT_FALSE(res);
  11041. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11042. #endif
  11043. }
  11044. }
  11045. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11046. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11047. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11048. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11049. // body a second time and appending a second Content-Encoding field line, so
  11050. // clients that decode one coding per listed value handed back raw gzip bytes.
  11051. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11052. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11053. Server svr;
  11054. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11055. // keeps the server from applying a coding of its own.
  11056. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11057. res.set_content(gzipped, "text/plain");
  11058. res.set_header("Content-Encoding", "gzip");
  11059. });
  11060. auto port = svr.bind_to_any_port(HOST);
  11061. thread t = thread([&]() { svr.listen_after_bind(); });
  11062. auto se = detail::scope_exit([&] {
  11063. svr.stop();
  11064. t.join();
  11065. ASSERT_FALSE(svr.is_running());
  11066. });
  11067. svr.wait_until_ready();
  11068. Client cli(HOST, port);
  11069. Headers headers = {{"Accept-Encoding", "gzip"}};
  11070. auto res = cli.Get("/pre-gzipped", headers);
  11071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11072. EXPECT_EQ(StatusCode::OK_200, res->status);
  11073. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11074. EXPECT_EQ("Hello World!", res->body);
  11075. }
  11076. // A chunked provider settles its coding where the headers are written and
  11077. // reuses it at write time. Both ends of that have to hold: a handler's own
  11078. // Content-Encoding suppresses the coding, and a response without one is still
  11079. // compressed as it always was.
  11080. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11081. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11082. const std::string plain = "Hello World! Hello World! Hello World!";
  11083. Server svr;
  11084. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11085. res.set_header("Content-Encoding", "gzip");
  11086. res.set_chunked_content_provider(
  11087. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11088. sink.write(gzipped.data(), gzipped.size());
  11089. sink.done();
  11090. return true;
  11091. });
  11092. });
  11093. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11094. res.set_chunked_content_provider(
  11095. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11096. sink.write(plain.data(), plain.size());
  11097. sink.done();
  11098. return true;
  11099. });
  11100. });
  11101. auto port = svr.bind_to_any_port(HOST);
  11102. thread t = thread([&]() { svr.listen_after_bind(); });
  11103. auto se = detail::scope_exit([&] {
  11104. svr.stop();
  11105. t.join();
  11106. ASSERT_FALSE(svr.is_running());
  11107. });
  11108. svr.wait_until_ready();
  11109. Client cli(HOST, port);
  11110. Headers headers = {{"Accept-Encoding", "gzip"}};
  11111. {
  11112. auto res = cli.Get("/pre-gzipped", headers);
  11113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11114. EXPECT_EQ(StatusCode::OK_200, res->status);
  11115. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11116. EXPECT_EQ("Hello World!", res->body);
  11117. }
  11118. {
  11119. auto res = cli.Get("/negotiated", headers);
  11120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11121. EXPECT_EQ(StatusCode::OK_200, res->status);
  11122. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11123. EXPECT_EQ(plain, res->body);
  11124. }
  11125. }
  11126. #endif
  11127. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11128. // the same message as the comma-joined one, so both have to be read the same
  11129. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11130. // single gzip coding, and a body the sender says was encoded twice was handed
  11131. // back after one pass, still compressed but presented as decoded.
  11132. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11133. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11134. Server svr;
  11135. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11136. res.set_content(body, "image/jpeg");
  11137. res.headers.emplace("Content-Encoding", "gzip");
  11138. res.headers.emplace("Content-Encoding", "gzip");
  11139. });
  11140. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11141. res.set_content(body, "image/jpeg");
  11142. res.set_header("Content-Encoding", "gzip, gzip");
  11143. });
  11144. auto port = svr.bind_to_any_port(HOST);
  11145. thread t = thread([&]() { svr.listen_after_bind(); });
  11146. auto se = detail::scope_exit([&] {
  11147. svr.stop();
  11148. t.join();
  11149. ASSERT_FALSE(svr.is_running());
  11150. });
  11151. svr.wait_until_ready();
  11152. Client cli(HOST, port);
  11153. // Two codings is not something cpp-httplib decodes, so both representations
  11154. // take the pass-through path rather than one of them being gunzipped once.
  11155. for (const char *path : {"/split", "/joined"}) {
  11156. auto res = cli.Get(path);
  11157. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11158. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11159. EXPECT_EQ(body, res->body) << path;
  11160. }
  11161. }
  11162. // Regression test for DoS vulnerability: a malicious server sending a response
  11163. // without Content-Length header must not cause unbounded memory consumption on
  11164. // the client side. The client should stop reading after a reasonable limit,
  11165. // similar to the server-side set_payload_max_length protection.
  11166. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11167. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11168. #ifndef _WIN32
  11169. signal(SIGPIPE, SIG_IGN);
  11170. #endif
  11171. auto server_thread = std::thread([] {
  11172. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11173. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11174. default_socket_options(srv);
  11175. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11176. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11177. sockaddr_in addr{};
  11178. addr.sin_family = AF_INET;
  11179. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11180. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11181. int opt = 1;
  11182. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11183. #ifdef _WIN32
  11184. reinterpret_cast<const char *>(&opt),
  11185. #else
  11186. &opt,
  11187. #endif
  11188. sizeof(opt));
  11189. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11190. ::listen(srv, 1);
  11191. sockaddr_in cli_addr{};
  11192. socklen_t cli_len = sizeof(cli_addr);
  11193. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11194. if (cli != INVALID_SOCKET) {
  11195. char buf[4096];
  11196. ::recv(cli, buf, sizeof(buf), 0);
  11197. // Malicious response: no Content-Length, no chunked encoding
  11198. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11199. "Connection: close\r\n"
  11200. "\r\n";
  11201. ::send(cli,
  11202. #ifdef _WIN32
  11203. static_cast<const char *>(response_header.c_str()),
  11204. static_cast<int>(response_header.size()),
  11205. #else
  11206. response_header.c_str(), response_header.size(),
  11207. #endif
  11208. 0);
  11209. // Send 10MB of data
  11210. std::string chunk(64 * 1024, 'A');
  11211. size_t total_sent = 0;
  11212. while (total_sent < MALICIOUS_DATA_SIZE) {
  11213. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11214. auto sent = ::send(cli,
  11215. #ifdef _WIN32
  11216. static_cast<const char *>(chunk.c_str()),
  11217. static_cast<int>(to_send),
  11218. #else
  11219. chunk.c_str(), to_send,
  11220. #endif
  11221. 0);
  11222. if (sent <= 0) break;
  11223. total_sent += static_cast<size_t>(sent);
  11224. }
  11225. detail::close_socket(cli);
  11226. }
  11227. detail::close_socket(srv);
  11228. });
  11229. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11230. size_t total_read = 0;
  11231. {
  11232. Client cli("127.0.0.1", PORT + 2);
  11233. cli.set_read_timeout(5, 0);
  11234. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11235. auto stream = cli.open_stream("GET", "/malicious");
  11236. ASSERT_TRUE(stream.is_valid());
  11237. char buffer[64 * 1024];
  11238. ssize_t n;
  11239. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11240. total_read += static_cast<size_t>(n);
  11241. }
  11242. } // StreamHandle and Client destroyed here, closing the socket
  11243. server_thread.join();
  11244. // With set_payload_max_length, the client must stop reading before consuming
  11245. // all 10MB. The read loop should be cut off at or near the configured limit.
  11246. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11247. << "Client read " << total_read << " bytes, exceeding the configured "
  11248. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11249. }
  11250. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11251. // the entire response body without truncation.
  11252. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11253. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11254. #ifndef _WIN32
  11255. signal(SIGPIPE, SIG_IGN);
  11256. #endif
  11257. auto server_thread = std::thread([] {
  11258. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11259. default_socket_options(srv);
  11260. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11261. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11262. sockaddr_in addr{};
  11263. addr.sin_family = AF_INET;
  11264. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11265. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11266. int opt = 1;
  11267. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11268. #ifdef _WIN32
  11269. reinterpret_cast<const char *>(&opt),
  11270. #else
  11271. &opt,
  11272. #endif
  11273. sizeof(opt));
  11274. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11275. ::listen(srv, 1);
  11276. sockaddr_in cli_addr{};
  11277. socklen_t cli_len = sizeof(cli_addr);
  11278. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11279. if (cli != INVALID_SOCKET) {
  11280. char buf[4096];
  11281. ::recv(cli, buf, sizeof(buf), 0);
  11282. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11283. "Connection: close\r\n"
  11284. "\r\n";
  11285. ::send(cli,
  11286. #ifdef _WIN32
  11287. static_cast<const char *>(response_header.c_str()),
  11288. static_cast<int>(response_header.size()),
  11289. #else
  11290. response_header.c_str(), response_header.size(),
  11291. #endif
  11292. 0);
  11293. std::string chunk(64 * 1024, 'A');
  11294. size_t total_sent = 0;
  11295. while (total_sent < DATA_SIZE) {
  11296. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11297. auto sent = ::send(cli,
  11298. #ifdef _WIN32
  11299. static_cast<const char *>(chunk.c_str()),
  11300. static_cast<int>(to_send),
  11301. #else
  11302. chunk.c_str(), to_send,
  11303. #endif
  11304. 0);
  11305. if (sent <= 0) break;
  11306. total_sent += static_cast<size_t>(sent);
  11307. }
  11308. #ifdef _WIN32
  11309. ::shutdown(cli, SD_SEND);
  11310. #else
  11311. ::shutdown(cli, SHUT_WR);
  11312. #endif
  11313. // Drain until the client closes its end, ensuring all data is delivered
  11314. char drain[1024];
  11315. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11316. detail::close_socket(cli);
  11317. }
  11318. detail::close_socket(srv);
  11319. });
  11320. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11321. size_t total_read = 0;
  11322. {
  11323. Client cli("127.0.0.1", PORT + 2);
  11324. cli.set_read_timeout(5, 0);
  11325. cli.set_payload_max_length(0); // 0 means no limit
  11326. auto stream = cli.open_stream("GET", "/data");
  11327. ASSERT_TRUE(stream.is_valid());
  11328. char buffer[64 * 1024];
  11329. ssize_t n;
  11330. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11331. total_read += static_cast<size_t>(n);
  11332. }
  11333. }
  11334. server_thread.join();
  11335. EXPECT_EQ(total_read, DATA_SIZE)
  11336. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11337. << " bytes without truncation, but only read " << total_read << " bytes.";
  11338. }
  11339. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11340. // enormous Content-Length must not cause the client to pre-allocate a huge
  11341. // response body buffer. The reservation is capped at payload_max_length_, and
  11342. // the read itself fails when the body exceeds the limit.
  11343. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11344. #ifndef _WIN32
  11345. signal(SIGPIPE, SIG_IGN);
  11346. #endif
  11347. auto server_thread = std::thread([] {
  11348. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11349. default_socket_options(srv);
  11350. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11351. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11352. sockaddr_in addr{};
  11353. addr.sin_family = AF_INET;
  11354. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11355. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11356. int opt = 1;
  11357. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11358. #ifdef _WIN32
  11359. reinterpret_cast<const char *>(&opt),
  11360. #else
  11361. &opt,
  11362. #endif
  11363. sizeof(opt));
  11364. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11365. ::listen(srv, 1);
  11366. sockaddr_in cli_addr{};
  11367. socklen_t cli_len = sizeof(cli_addr);
  11368. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11369. if (cli != INVALID_SOCKET) {
  11370. char buf[4096];
  11371. ::recv(cli, buf, sizeof(buf), 0);
  11372. // Malicious response: claim a 20GB body but send only a tiny payload.
  11373. std::string response = "HTTP/1.1 200 OK\r\n"
  11374. "Content-Length: 20000000000\r\n"
  11375. "\r\n"
  11376. "abc";
  11377. ::send(cli,
  11378. #ifdef _WIN32
  11379. static_cast<const char *>(response.c_str()),
  11380. static_cast<int>(response.size()),
  11381. #else
  11382. response.c_str(), response.size(),
  11383. #endif
  11384. 0);
  11385. detail::close_socket(cli);
  11386. }
  11387. detail::close_socket(srv);
  11388. });
  11389. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11390. {
  11391. Client cli("127.0.0.1", PORT + 2);
  11392. cli.set_read_timeout(5, 0);
  11393. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11394. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11395. // (server claims more bytes than payload_max_length permits), but it must
  11396. // not exhaust memory before getting there.
  11397. auto res = cli.Get("/malicious");
  11398. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11399. }
  11400. server_thread.join();
  11401. }
  11402. // Verify that content_receiver bypasses the default payload_max_length,
  11403. // allowing streaming downloads larger than 100MB without requiring an explicit
  11404. // set_payload_max_length call.
  11405. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11406. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11407. #ifndef _WIN32
  11408. signal(SIGPIPE, SIG_IGN);
  11409. #endif
  11410. auto server_thread = std::thread([] {
  11411. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11412. default_socket_options(srv);
  11413. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11414. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11415. sockaddr_in addr{};
  11416. addr.sin_family = AF_INET;
  11417. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11418. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11419. int opt = 1;
  11420. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11421. #ifdef _WIN32
  11422. reinterpret_cast<const char *>(&opt),
  11423. #else
  11424. &opt,
  11425. #endif
  11426. sizeof(opt));
  11427. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11428. ::listen(srv, 1);
  11429. sockaddr_in cli_addr{};
  11430. socklen_t cli_len = sizeof(cli_addr);
  11431. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11432. if (cli != INVALID_SOCKET) {
  11433. char buf[4096];
  11434. ::recv(cli, buf, sizeof(buf), 0);
  11435. // Response with Content-Length larger than default 100MB limit
  11436. auto content_length = std::to_string(DATA_SIZE);
  11437. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11438. "Content-Length: " +
  11439. content_length +
  11440. "\r\n"
  11441. "Connection: close\r\n"
  11442. "\r\n";
  11443. ::send(cli,
  11444. #ifdef _WIN32
  11445. static_cast<const char *>(response_header.c_str()),
  11446. static_cast<int>(response_header.size()),
  11447. #else
  11448. response_header.c_str(), response_header.size(),
  11449. #endif
  11450. 0);
  11451. std::string chunk(64 * 1024, 'A');
  11452. size_t total_sent = 0;
  11453. while (total_sent < DATA_SIZE) {
  11454. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11455. auto sent = ::send(cli,
  11456. #ifdef _WIN32
  11457. static_cast<const char *>(chunk.c_str()),
  11458. static_cast<int>(to_send),
  11459. #else
  11460. chunk.c_str(), to_send,
  11461. #endif
  11462. 0);
  11463. if (sent <= 0) break;
  11464. total_sent += static_cast<size_t>(sent);
  11465. }
  11466. detail::close_socket(cli);
  11467. }
  11468. detail::close_socket(srv);
  11469. });
  11470. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11471. size_t total_received = 0;
  11472. {
  11473. Client cli("127.0.0.1", PORT + 2);
  11474. cli.set_read_timeout(10, 0);
  11475. // Do NOT call set_payload_max_length — use the default 100MB limit
  11476. auto res =
  11477. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11478. total_received += data_length;
  11479. return true;
  11480. });
  11481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11482. EXPECT_EQ(StatusCode::OK_200, res->status);
  11483. }
  11484. server_thread.join();
  11485. EXPECT_EQ(total_received, DATA_SIZE)
  11486. << "With content_receiver, the client should read all " << DATA_SIZE
  11487. << " bytes despite the default 100MB payload_max_length, but only read "
  11488. << total_received << " bytes.";
  11489. }
  11490. // Verify that an explicit set_payload_max_length smaller than the response is
  11491. // enforced even when a content_receiver is used.
  11492. TEST(ClientVulnerabilityTest,
  11493. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11494. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11495. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11496. #ifndef _WIN32
  11497. signal(SIGPIPE, SIG_IGN);
  11498. #endif
  11499. auto server_thread = std::thread([] {
  11500. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11501. default_socket_options(srv);
  11502. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11503. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11504. sockaddr_in addr{};
  11505. addr.sin_family = AF_INET;
  11506. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11507. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11508. int opt = 1;
  11509. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11510. #ifdef _WIN32
  11511. reinterpret_cast<const char *>(&opt),
  11512. #else
  11513. &opt,
  11514. #endif
  11515. sizeof(opt));
  11516. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11517. ::listen(srv, 1);
  11518. sockaddr_in cli_addr{};
  11519. socklen_t cli_len = sizeof(cli_addr);
  11520. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11521. if (cli != INVALID_SOCKET) {
  11522. char buf[4096];
  11523. ::recv(cli, buf, sizeof(buf), 0);
  11524. auto content_length = std::to_string(DATA_SIZE);
  11525. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11526. "Content-Length: " +
  11527. content_length +
  11528. "\r\n"
  11529. "Connection: close\r\n"
  11530. "\r\n";
  11531. ::send(cli,
  11532. #ifdef _WIN32
  11533. static_cast<const char *>(response_header.c_str()),
  11534. static_cast<int>(response_header.size()),
  11535. #else
  11536. response_header.c_str(), response_header.size(),
  11537. #endif
  11538. 0);
  11539. std::string chunk(64 * 1024, 'A');
  11540. size_t total_sent = 0;
  11541. while (total_sent < DATA_SIZE) {
  11542. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11543. auto sent = ::send(cli,
  11544. #ifdef _WIN32
  11545. static_cast<const char *>(chunk.c_str()),
  11546. static_cast<int>(to_send),
  11547. #else
  11548. chunk.c_str(), to_send,
  11549. #endif
  11550. 0);
  11551. if (sent <= 0) break;
  11552. total_sent += static_cast<size_t>(sent);
  11553. }
  11554. detail::close_socket(cli);
  11555. }
  11556. detail::close_socket(srv);
  11557. });
  11558. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11559. size_t total_received = 0;
  11560. {
  11561. Client cli("127.0.0.1", PORT + 2);
  11562. cli.set_read_timeout(10, 0);
  11563. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11564. auto res =
  11565. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11566. total_received += data_length;
  11567. return true;
  11568. });
  11569. // Should fail because 200MB exceeds the explicit 150MB limit
  11570. EXPECT_FALSE(res);
  11571. }
  11572. server_thread.join();
  11573. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11574. << "Client with content_receiver should respect the explicit "
  11575. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11576. << total_received << " bytes.";
  11577. }
  11578. // Verify that an explicit set_payload_max_length larger than the response
  11579. // allows the content_receiver to read all data successfully.
  11580. TEST(ClientVulnerabilityTest,
  11581. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11582. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11583. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11584. #ifndef _WIN32
  11585. signal(SIGPIPE, SIG_IGN);
  11586. #endif
  11587. auto server_thread = std::thread([] {
  11588. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11589. default_socket_options(srv);
  11590. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11591. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11592. sockaddr_in addr{};
  11593. addr.sin_family = AF_INET;
  11594. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11595. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11596. int opt = 1;
  11597. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11598. #ifdef _WIN32
  11599. reinterpret_cast<const char *>(&opt),
  11600. #else
  11601. &opt,
  11602. #endif
  11603. sizeof(opt));
  11604. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11605. ::listen(srv, 1);
  11606. sockaddr_in cli_addr{};
  11607. socklen_t cli_len = sizeof(cli_addr);
  11608. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11609. if (cli != INVALID_SOCKET) {
  11610. char buf[4096];
  11611. ::recv(cli, buf, sizeof(buf), 0);
  11612. auto content_length = std::to_string(DATA_SIZE);
  11613. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11614. "Content-Length: " +
  11615. content_length +
  11616. "\r\n"
  11617. "Connection: close\r\n"
  11618. "\r\n";
  11619. ::send(cli,
  11620. #ifdef _WIN32
  11621. static_cast<const char *>(response_header.c_str()),
  11622. static_cast<int>(response_header.size()),
  11623. #else
  11624. response_header.c_str(), response_header.size(),
  11625. #endif
  11626. 0);
  11627. std::string chunk(64 * 1024, 'A');
  11628. size_t total_sent = 0;
  11629. while (total_sent < DATA_SIZE) {
  11630. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11631. auto sent = ::send(cli,
  11632. #ifdef _WIN32
  11633. static_cast<const char *>(chunk.c_str()),
  11634. static_cast<int>(to_send),
  11635. #else
  11636. chunk.c_str(), to_send,
  11637. #endif
  11638. 0);
  11639. if (sent <= 0) break;
  11640. total_sent += static_cast<size_t>(sent);
  11641. }
  11642. #ifdef _WIN32
  11643. ::shutdown(cli, SD_SEND);
  11644. #else
  11645. ::shutdown(cli, SHUT_WR);
  11646. #endif
  11647. char drain[1024];
  11648. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11649. detail::close_socket(cli);
  11650. }
  11651. detail::close_socket(srv);
  11652. });
  11653. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11654. size_t total_received = 0;
  11655. {
  11656. Client cli("127.0.0.1", PORT + 2);
  11657. cli.set_read_timeout(10, 0);
  11658. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11659. auto res =
  11660. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11661. total_received += data_length;
  11662. return true;
  11663. });
  11664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11665. EXPECT_EQ(StatusCode::OK_200, res->status);
  11666. }
  11667. server_thread.join();
  11668. EXPECT_EQ(total_received, DATA_SIZE)
  11669. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11670. << " bytes (larger than " << DATA_SIZE
  11671. << " bytes response), content_receiver should read all data, but only "
  11672. "read "
  11673. << total_received << " bytes.";
  11674. }
  11675. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11676. // Regression test for "zip bomb" attack on the client side: a malicious server
  11677. // sends a small gzip-compressed response that decompresses to a huge payload.
  11678. // The client must enforce payload_max_length on the decompressed size.
  11679. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11680. constexpr size_t DECOMPRESSED_SIZE =
  11681. 10 * 1024 * 1024; // 10MB after decompression
  11682. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11683. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11684. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11685. std::string compressed;
  11686. {
  11687. httplib::detail::gzip_compressor compressor;
  11688. bool ok =
  11689. compressor.compress(uncompressed.data(), uncompressed.size(),
  11690. /*last=*/true, [&](const char *buf, size_t len) {
  11691. compressed.append(buf, len);
  11692. return true;
  11693. });
  11694. ASSERT_TRUE(ok);
  11695. }
  11696. // Sanity: compressed data should be much smaller than the decompressed size
  11697. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11698. #ifndef _WIN32
  11699. signal(SIGPIPE, SIG_IGN);
  11700. #endif
  11701. // Set up the listening socket in the main thread so the server is guaranteed
  11702. // to be ready before the client connects (eliminates race condition).
  11703. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11704. default_socket_options(srv);
  11705. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11706. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11707. sockaddr_in addr{};
  11708. addr.sin_family = AF_INET;
  11709. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11710. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11711. int opt = 1;
  11712. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11713. #ifdef _WIN32
  11714. reinterpret_cast<const char *>(&opt),
  11715. #else
  11716. &opt,
  11717. #endif
  11718. sizeof(opt));
  11719. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11720. ASSERT_EQ(0, ::listen(srv, 1));
  11721. auto server_thread = std::thread([&compressed, srv] {
  11722. sockaddr_in cli_addr{};
  11723. socklen_t cli_len = sizeof(cli_addr);
  11724. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11725. if (cli != INVALID_SOCKET) {
  11726. // Read the full HTTP request (until \r\n\r\n)
  11727. char buf[4096];
  11728. size_t total = 0;
  11729. while (total < sizeof(buf)) {
  11730. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11731. if (n <= 0) break;
  11732. total += static_cast<size_t>(n);
  11733. // Check for end of headers
  11734. if (total >= 4) {
  11735. std::string req(buf, total);
  11736. if (req.find("\r\n\r\n") != std::string::npos) break;
  11737. }
  11738. }
  11739. // Malicious response: gzip-compressed body, no Content-Length
  11740. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11741. "Content-Encoding: gzip\r\n"
  11742. "Connection: close\r\n"
  11743. "\r\n";
  11744. ::send(cli,
  11745. #ifdef _WIN32
  11746. static_cast<const char *>(response_header.c_str()),
  11747. static_cast<int>(response_header.size()),
  11748. #else
  11749. response_header.c_str(), response_header.size(),
  11750. #endif
  11751. 0);
  11752. // Send the compressed payload (small on the wire, huge when decompressed)
  11753. size_t total_sent = 0;
  11754. while (total_sent < compressed.size()) {
  11755. auto to_send = std::min(compressed.size() - total_sent,
  11756. static_cast<size_t>(64 * 1024));
  11757. auto sent =
  11758. ::send(cli,
  11759. #ifdef _WIN32
  11760. static_cast<const char *>(compressed.c_str() + total_sent),
  11761. static_cast<int>(to_send),
  11762. #else
  11763. compressed.c_str() + total_sent, to_send,
  11764. #endif
  11765. 0);
  11766. if (sent <= 0) break;
  11767. total_sent += static_cast<size_t>(sent);
  11768. }
  11769. detail::close_socket(cli);
  11770. }
  11771. });
  11772. auto se = detail::scope_exit([&] {
  11773. detail::close_socket(srv);
  11774. server_thread.join();
  11775. });
  11776. size_t total_decompressed = 0;
  11777. {
  11778. Client cli("127.0.0.1", PORT + 3);
  11779. cli.set_read_timeout(5, 0);
  11780. cli.set_decompress(true);
  11781. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11782. auto stream = cli.open_stream("GET", "/zipbomb");
  11783. ASSERT_TRUE(stream.is_valid());
  11784. char buffer[64 * 1024];
  11785. ssize_t n;
  11786. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11787. total_decompressed += static_cast<size_t>(n);
  11788. }
  11789. }
  11790. // The decompressed size must be capped by payload_max_length. Without
  11791. // protection, the client would decompress the full 10MB from a tiny
  11792. // compressed payload, enabling a zip bomb DoS attack.
  11793. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11794. << "Client decompressed " << total_decompressed
  11795. << " bytes from a gzip response. The decompressed size should be "
  11796. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11797. }
  11798. #endif
  11799. TEST(HostAndPortPropertiesTest, NoSSL) {
  11800. httplib::Client cli("www.google.com", 1234);
  11801. ASSERT_EQ("www.google.com", cli.host());
  11802. ASSERT_EQ(1234, cli.port());
  11803. }
  11804. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11805. httplib::Client cli("www.google.com:1234");
  11806. ASSERT_EQ("www.google.com", cli.host());
  11807. ASSERT_EQ(1234, cli.port());
  11808. }
  11809. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11810. // Port number that overflows int — should not crash, client becomes invalid
  11811. httplib::Client cli("http://www.google.com:99999999999999999999");
  11812. ASSERT_FALSE(cli.is_valid());
  11813. }
  11814. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11815. // Port 99999 exceeds valid range (1-65535) — should not crash
  11816. httplib::Client cli("http://www.google.com:99999");
  11817. ASSERT_FALSE(cli.is_valid());
  11818. }
  11819. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  11820. httplib::Client cli("http://www.google.com:80abc");
  11821. ASSERT_FALSE(cli.is_valid());
  11822. }
  11823. #ifdef CPPHTTPLIB_SSL_ENABLED
  11824. TEST(HostAndPortPropertiesTest, SSL) {
  11825. httplib::SSLClient cli("www.google.com");
  11826. ASSERT_EQ("www.google.com", cli.host());
  11827. ASSERT_EQ(443, cli.port());
  11828. }
  11829. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11830. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11831. std::string cert;
  11832. read_file(CA_CERT_FILE, cert);
  11833. httplib::SSLClient httplib_client("www.google.com");
  11834. // Load CA store first time
  11835. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11836. // Load CA store second time (update)
  11837. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11838. // Verify client is still valid and can make connections
  11839. httplib_client.enable_server_certificate_verification(true);
  11840. auto res = httplib_client.Get("/");
  11841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11842. // Google may return 200 or 301 depending on various factors
  11843. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11844. res->status == StatusCode::MovedPermanently_301);
  11845. }
  11846. TEST(SSLClientTest, ServerNameIndication_Online) {
  11847. auto host = "httpbingo.org";
  11848. auto path = std::string{"/get"};
  11849. SSLClient cli(host, 443);
  11850. auto res = cli.Get(path);
  11851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11852. ASSERT_EQ(StatusCode::OK_200, res->status);
  11853. }
  11854. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11855. // Use a site that will cause SSL verification failure due to self-signed cert
  11856. SSLClient cli("self-signed.badssl.com", 443);
  11857. cli.enable_server_certificate_verification(true);
  11858. auto res = cli.Get("/");
  11859. ASSERT_TRUE(!res);
  11860. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11861. // Verify backend error is captured for SSLServerVerification
  11862. // This occurs when certificate verification fails
  11863. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11864. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11865. EXPECT_NE(0UL, res.ssl_backend_error());
  11866. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11867. // For OpenSSL, ssl_error is 0 for verification errors
  11868. EXPECT_EQ(0, res.ssl_error());
  11869. #if !defined(_WIN32) || \
  11870. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11871. // On non-Windows or when Windows Schannel is disabled, the error comes
  11872. // from OpenSSL's verification
  11873. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11874. res.ssl_backend_error());
  11875. #endif
  11876. #endif
  11877. }
  11878. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11879. // Use a site where hostname doesn't match the certificate
  11880. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11881. SSLClient cli("wrong.host.badssl.com", 443);
  11882. cli.enable_server_certificate_verification(true);
  11883. cli.enable_server_hostname_verification(true);
  11884. auto res = cli.Get("/");
  11885. ASSERT_TRUE(!res);
  11886. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11887. // Verify backend error is captured for hostname verification failure
  11888. EXPECT_NE(0UL, res.ssl_backend_error());
  11889. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11890. // For OpenSSL, ssl_error is 0 for verification errors
  11891. EXPECT_EQ(0, res.ssl_error());
  11892. #if !defined(_WIN32) || \
  11893. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11894. // On non-Windows or when Windows Schannel is disabled, the error comes
  11895. // from OpenSSL's hostname verification
  11896. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11897. res.ssl_backend_error());
  11898. #endif
  11899. #endif
  11900. }
  11901. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11902. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11903. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11904. SSLClient cli("www.google.com", 443);
  11905. cli.enable_server_certificate_verification(true);
  11906. auto res = cli.Get("/");
  11907. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11908. }
  11909. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11910. SSLClient cli("www.google.com", 443);
  11911. cli.enable_server_certificate_verification(true);
  11912. cli.enable_windows_certificate_verification(false);
  11913. auto res = cli.Get("/");
  11914. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11915. }
  11916. // The server sends an intermediate cross-signed by a root Windows trusts,
  11917. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  11918. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  11919. SSLClient cli("accounts.spotify.com", 443);
  11920. auto res = cli.Get("/");
  11921. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  11922. << " ssl_backend_error=" << res.ssl_backend_error();
  11923. }
  11924. // Windows, not the backend, decides on the chain: the error carries a
  11925. // CryptoAPI trust status, which no backend error for a self-signed
  11926. // certificate has.
  11927. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  11928. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11929. ASSERT_TRUE(svr.is_valid());
  11930. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11931. auto se = detail::scope_exit([&] {
  11932. svr.stop();
  11933. t.join();
  11934. ASSERT_FALSE(svr.is_running());
  11935. });
  11936. svr.wait_until_ready();
  11937. SSLClient cli("127.0.0.1", PORT);
  11938. cli.set_connection_timeout(30);
  11939. auto res = cli.Get("/");
  11940. ASSERT_FALSE(res);
  11941. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11942. EXPECT_NE(0u, res.ssl_backend_error() & CERT_TRUST_IS_UNTRUSTED_ROOT)
  11943. << "ssl_backend_error=" << res.ssl_backend_error();
  11944. }
  11945. #endif
  11946. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11947. Client cli("https://google.com");
  11948. auto res = cli.Get("/");
  11949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11950. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11951. }
  11952. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11953. SSLClient cli("google.com");
  11954. cli.set_ca_cert_path(CA_CERT_FILE);
  11955. auto res = cli.Get("/");
  11956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11957. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11958. }
  11959. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11960. SSLClient cli("google.com");
  11961. cli.enable_server_certificate_verification(true);
  11962. cli.set_ca_cert_path("hello");
  11963. auto res = cli.Get("/");
  11964. ASSERT_TRUE(!res);
  11965. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11966. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11967. // should be set
  11968. EXPECT_EQ(0, res.ssl_error());
  11969. // Verify backend error is captured for SSLLoadingCerts
  11970. // This error occurs when loading CA certificates fails
  11971. EXPECT_NE(0UL, res.ssl_backend_error());
  11972. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11973. // OpenSSL specific error codes:
  11974. // > openssl errstr 0x80000002
  11975. // error:80000002:system library::No such file or directory
  11976. // > openssl errstr 0xA000126
  11977. // error:0A000126:SSL routines::unexpected eof while reading
  11978. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11979. res.ssl_backend_error() == 0xA000126);
  11980. #endif
  11981. }
  11982. TEST(SSLClientTest, ServerCertificateVerification4) {
  11983. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11984. ASSERT_TRUE(svr.is_valid());
  11985. svr.Get("/test", [&](const Request &, Response &res) {
  11986. res.set_content("test", "text/plain");
  11987. svr.stop();
  11988. ASSERT_TRUE(true);
  11989. });
  11990. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11991. auto se = detail::scope_exit([&] {
  11992. t.join();
  11993. ASSERT_FALSE(svr.is_running());
  11994. });
  11995. svr.wait_until_ready();
  11996. SSLClient cli("127.0.0.1", PORT);
  11997. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11998. cli.enable_server_certificate_verification(true);
  11999. cli.set_connection_timeout(30);
  12000. auto res = cli.Get("/test");
  12001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12002. ASSERT_EQ(StatusCode::OK_200, res->status);
  12003. }
  12004. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12005. std::string cert;
  12006. read_file(CA_CERT_FILE, cert);
  12007. SSLClient cli("google.com");
  12008. cli.load_ca_cert_store(cert.data(), cert.size());
  12009. const auto res = cli.Get("/");
  12010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12011. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12012. }
  12013. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12014. // clang-format off
  12015. static constexpr char cert[] =
  12016. "GlobalSign Root CA\n"
  12017. "==================\n"
  12018. "-----BEGIN CERTIFICATE-----\n"
  12019. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12020. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12021. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12022. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12023. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12024. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12025. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12026. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12027. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12028. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12029. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12030. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12031. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12032. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12033. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12034. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12035. "-----END CERTIFICATE-----\n";
  12036. // clang-format on
  12037. SSLClient cli("google.com");
  12038. cli.load_ca_cert_store(cert, sizeof(cert));
  12039. const auto res = cli.Get("/");
  12040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12041. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12042. }
  12043. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12044. SSLClient cli("www.youtube.com");
  12045. cli.set_ca_cert_path(CA_CERT_FILE);
  12046. cli.enable_server_certificate_verification(true);
  12047. cli.set_follow_location(true);
  12048. auto res = cli.Get("/");
  12049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12050. ASSERT_EQ(StatusCode::OK_200, res->status);
  12051. }
  12052. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12053. SSLClient cli("wWw.YouTube.Com");
  12054. cli.set_ca_cert_path(CA_CERT_FILE);
  12055. cli.enable_server_certificate_verification(true);
  12056. cli.enable_server_hostname_verification(true);
  12057. cli.set_follow_location(true);
  12058. auto res = cli.Get("/");
  12059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12060. ASSERT_EQ(StatusCode::OK_200, res->status);
  12061. }
  12062. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12063. SSLClient cli("gOoGlE.COm");
  12064. cli.enable_server_certificate_verification(true);
  12065. cli.enable_server_hostname_verification(true);
  12066. cli.set_follow_location(true);
  12067. auto res = cli.Get("/");
  12068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12069. ASSERT_EQ(StatusCode::OK_200, res->status);
  12070. }
  12071. TEST(SSLClientTest, Issue2004_Online) {
  12072. Client client("https://google.com");
  12073. client.set_follow_location(true);
  12074. auto res = client.Get("/");
  12075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12076. ASSERT_EQ(StatusCode::OK_200, res->status);
  12077. auto body = res->body;
  12078. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12079. }
  12080. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12081. // Create SSLClient with invalid cert/key to make is_valid() return false
  12082. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12083. "nonexistent_key.pem");
  12084. // is_valid() should be false due to cert loading failure
  12085. ASSERT_FALSE(cli.is_valid());
  12086. auto res = cli.Get("/");
  12087. ASSERT_FALSE(res);
  12088. EXPECT_EQ(Error::SSLConnection, res.error());
  12089. }
  12090. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12091. // Test for Issue #2251: SSL error not properly reported when client cert
  12092. // and key paths are swapped or mismatched
  12093. // This simulates the scenario where user accidentally swaps the cert and key
  12094. // files
  12095. // Using client cert file as private key and vice versa (completely wrong)
  12096. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12097. // Should fail validation due to cert/key mismatch
  12098. ASSERT_FALSE(cli.is_valid());
  12099. // Attempt to make a request should fail with proper error
  12100. auto res = cli.Get("/");
  12101. ASSERT_FALSE(res);
  12102. EXPECT_EQ(Error::SSLConnection, res.error());
  12103. // SSL error should be recorded in the Result object (this is the key fix for
  12104. // Issue #2251)
  12105. auto backend_error = res.ssl_backend_error();
  12106. EXPECT_NE(0u, backend_error);
  12107. }
  12108. // Tests cert/key mismatch detection at the TLS context level
  12109. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12110. // Test that using mismatched cert/key causes connection failure.
  12111. // We verify this at the SSLClient level rather than through internal
  12112. // TLS API functions.
  12113. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12114. cli.enable_server_certificate_verification(false);
  12115. cli.set_connection_timeout(2);
  12116. // The mismatch should cause a connection or handshake error
  12117. auto res = cli.Get("/test");
  12118. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12119. // Either way, the request should fail
  12120. EXPECT_FALSE(res);
  12121. }
  12122. #endif
  12123. #if 0
  12124. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12125. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12126. ASSERT_TRUE(cli != nullptr);
  12127. cli->set_address_family(AF_INET6);
  12128. cli->set_interface("en0");
  12129. auto res = cli->Get("/get");
  12130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12131. ASSERT_EQ(StatusCode::OK_200, res->status);
  12132. }
  12133. #endif
  12134. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12135. #ifdef CPPHTTPLIB_SSL_ENABLED
  12136. void ClientCertPresent(
  12137. const std::string &client_cert_file,
  12138. const std::string &client_private_key_file,
  12139. const std::string &client_encrypted_private_key_pass = std::string()) {
  12140. using namespace httplib::tls;
  12141. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12142. CLIENT_CA_CERT_DIR);
  12143. ASSERT_TRUE(svr.is_valid());
  12144. svr.Get("/test", [&](const Request &req, Response &res) {
  12145. res.set_content("test", "text/plain");
  12146. auto cert = req.peer_cert();
  12147. ASSERT_TRUE(static_cast<bool>(cert));
  12148. std::string common_name = cert.subject_cn();
  12149. EXPECT_EQ("Common Name", common_name);
  12150. });
  12151. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12152. auto se = detail::scope_exit([&] {
  12153. svr.stop();
  12154. t.join();
  12155. ASSERT_FALSE(svr.is_running());
  12156. });
  12157. svr.wait_until_ready();
  12158. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12159. client_encrypted_private_key_pass);
  12160. cli.enable_server_certificate_verification(false);
  12161. cli.set_connection_timeout(30);
  12162. auto res = cli.Get("/test");
  12163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12164. ASSERT_EQ(StatusCode::OK_200, res->status);
  12165. }
  12166. TEST(SSLClientServerTest, ClientCertPresent) {
  12167. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12168. }
  12169. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12170. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12171. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12172. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12173. }
  12174. // PEM memory-based constructor tests (works with all TLS backends)
  12175. void PemMemoryClientCertPresent(
  12176. const std::string &client_cert_file,
  12177. const std::string &client_private_key_file,
  12178. const std::string &client_encrypted_private_key_pass = std::string()) {
  12179. // Read PEM files into memory
  12180. std::string server_cert_pem, server_key_pem;
  12181. std::string client_ca_pem;
  12182. std::string client_cert_pem, client_key_pem;
  12183. read_file(SERVER_CERT_FILE, server_cert_pem);
  12184. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12185. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12186. read_file(client_cert_file, client_cert_pem);
  12187. read_file(client_private_key_file, client_key_pem);
  12188. // Create server with PEM memory
  12189. SSLServer::PemMemory server_pem = {
  12190. server_cert_pem.c_str(),
  12191. server_cert_pem.size(),
  12192. server_key_pem.c_str(),
  12193. server_key_pem.size(),
  12194. client_ca_pem.c_str(),
  12195. client_ca_pem.size(),
  12196. nullptr // no password for server key
  12197. };
  12198. SSLServer svr(server_pem);
  12199. ASSERT_TRUE(svr.is_valid());
  12200. svr.Get("/test", [&](const Request &, Response &res) {
  12201. res.set_content("test", "text/plain");
  12202. });
  12203. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12204. auto se = detail::scope_exit([&] {
  12205. svr.stop();
  12206. t.join();
  12207. ASSERT_FALSE(svr.is_running());
  12208. });
  12209. svr.wait_until_ready();
  12210. // Create client with PEM memory
  12211. const char *password = client_encrypted_private_key_pass.empty()
  12212. ? nullptr
  12213. : client_encrypted_private_key_pass.c_str();
  12214. SSLClient::PemMemory client_pem = {
  12215. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12216. client_key_pem.size(), password};
  12217. SSLClient cli(HOST, PORT, client_pem);
  12218. cli.enable_server_certificate_verification(false);
  12219. cli.set_connection_timeout(30);
  12220. auto res = cli.Get("/test");
  12221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12222. ASSERT_EQ(StatusCode::OK_200, res->status);
  12223. }
  12224. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12225. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12226. }
  12227. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12228. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12229. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12230. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12231. }
  12232. TEST(SSLClientServerTest, ClientCertMissing) {
  12233. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12234. CLIENT_CA_CERT_DIR);
  12235. ASSERT_TRUE(svr.is_valid());
  12236. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12237. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12238. auto se = detail::scope_exit([&] {
  12239. svr.stop();
  12240. t.join();
  12241. ASSERT_FALSE(svr.is_running());
  12242. });
  12243. svr.wait_until_ready();
  12244. SSLClient cli(HOST, PORT);
  12245. cli.set_connection_timeout(30);
  12246. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12247. // the chain check on Windows, so the result does not depend on the order.
  12248. cli.enable_server_hostname_verification(false);
  12249. auto res = cli.Get("/test");
  12250. ASSERT_TRUE(!res);
  12251. // When client cert is missing and server requires it, connection fails
  12252. // Error type depends on backend implementation
  12253. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12254. res.error() == Error::SSLConnection);
  12255. // Verify backend error is captured
  12256. // Note: This test may have different error codes depending on the exact
  12257. // verification failure
  12258. EXPECT_NE(0UL, res.ssl_backend_error());
  12259. }
  12260. TEST(SSLClientServerTest, TrustDirOptional) {
  12261. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12262. ASSERT_TRUE(svr.is_valid());
  12263. svr.Get("/test", [&](const Request &, Response &res) {
  12264. res.set_content("test", "text/plain");
  12265. });
  12266. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12267. auto se = detail::scope_exit([&] {
  12268. svr.stop();
  12269. t.join();
  12270. ASSERT_FALSE(svr.is_running());
  12271. });
  12272. svr.wait_until_ready();
  12273. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12274. cli.enable_server_certificate_verification(false);
  12275. cli.set_connection_timeout(30);
  12276. auto res = cli.Get("/test");
  12277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12278. ASSERT_EQ(StatusCode::OK_200, res->status);
  12279. }
  12280. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12281. class NoListenSSLServer : public SSLServer {
  12282. public:
  12283. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12284. const char *client_ca_cert_file_path,
  12285. const char *client_ca_cert_dir_path = nullptr)
  12286. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12287. client_ca_cert_dir_path),
  12288. stop_(false) {}
  12289. std::atomic_bool stop_;
  12290. private:
  12291. bool process_and_close_socket(socket_t /*sock*/) override {
  12292. // Don't create SSL context
  12293. while (!stop_.load()) {
  12294. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12295. }
  12296. return true;
  12297. }
  12298. };
  12299. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12300. CLIENT_CA_CERT_FILE);
  12301. ASSERT_TRUE(svr.is_valid());
  12302. svr.Get("/test", [&](const Request &, Response &res) {
  12303. res.set_content("test", "text/plain");
  12304. });
  12305. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12306. auto se = detail::scope_exit([&] {
  12307. svr.stop_ = true;
  12308. svr.stop();
  12309. t.join();
  12310. ASSERT_FALSE(svr.is_running());
  12311. });
  12312. svr.wait_until_ready();
  12313. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12314. cli.enable_server_certificate_verification(false);
  12315. cli.set_connection_timeout(1);
  12316. auto res = cli.Get("/test");
  12317. ASSERT_TRUE(!res);
  12318. EXPECT_EQ(Error::SSLConnection, res.error());
  12319. // Timeout results in WantRead error code (maps to backend-specific value)
  12320. EXPECT_NE(0, res.ssl_error());
  12321. }
  12322. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12323. // Test SSLServer with client certificate verification using the standard
  12324. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12326. CLIENT_CA_CERT_DIR);
  12327. ASSERT_TRUE(svr.is_valid());
  12328. svr.Get("/test", [&](const Request &req, Response &res) {
  12329. res.set_content("test", "text/plain");
  12330. auto cert = req.peer_cert();
  12331. ASSERT_TRUE(static_cast<bool>(cert));
  12332. auto common_name = cert.subject_cn();
  12333. EXPECT_EQ("Common Name", common_name);
  12334. });
  12335. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12336. auto se = detail::scope_exit([&] {
  12337. svr.stop();
  12338. t.join();
  12339. ASSERT_FALSE(svr.is_running());
  12340. });
  12341. svr.wait_until_ready();
  12342. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12343. cli.enable_server_certificate_verification(false);
  12344. cli.set_connection_timeout(30);
  12345. auto res = cli.Get("/test");
  12346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12347. ASSERT_EQ(StatusCode::OK_200, res->status);
  12348. }
  12349. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12350. // Verifies that wildcard matching and exact matching work consistently
  12351. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12352. using namespace httplib::tls;
  12353. // We need a running server to test against
  12354. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12355. ASSERT_TRUE(svr.is_valid());
  12356. svr.Get("/test", [](const Request &, Response &res) {
  12357. res.set_content("ok", "text/plain");
  12358. });
  12359. thread t([&]() { svr.listen(HOST, PORT); });
  12360. auto se = detail::scope_exit([&] {
  12361. svr.stop();
  12362. t.join();
  12363. });
  12364. svr.wait_until_ready();
  12365. bool verify_callback_called = false;
  12366. bool verify_result_wrong = false;
  12367. SSLClient cli(HOST, PORT);
  12368. cli.enable_server_certificate_verification(true);
  12369. cli.set_ca_cert_path(CA_CERT_FILE);
  12370. cli.set_connection_timeout(5);
  12371. // Note: Test certificate has CN="Common Name", not "localhost"
  12372. bool verify_result_cn = false;
  12373. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12374. verify_callback_called = true;
  12375. if (!ctx.cert) return false;
  12376. // Test 1: "Common Name" should match (our test server cert CN)
  12377. verify_result_cn = ctx.check_hostname("Common Name");
  12378. // Test 2: wrong hostname should not match
  12379. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12380. return true; // Accept for the purpose of this test
  12381. });
  12382. auto res = cli.Get("/test");
  12383. // The request may succeed or fail depending on cert configuration
  12384. // but the callback should have been called
  12385. ASSERT_TRUE(verify_callback_called)
  12386. << "Verify callback should have been called";
  12387. // CN="Common Name" should match our test certificate
  12388. //
  12389. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12390. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12391. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12392. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12393. // <openssl/base.h>, which is included transitively when
  12394. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12395. #if defined(OPENSSL_IS_BORINGSSL)
  12396. EXPECT_FALSE(verify_result_cn)
  12397. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12398. #else
  12399. EXPECT_TRUE(verify_result_cn)
  12400. << "verify_hostname should match 'Common Name' (certificate CN)";
  12401. #endif
  12402. // Wrong hostname should not match
  12403. EXPECT_FALSE(verify_result_wrong)
  12404. << "verify_hostname should not match 'wronghost.example.com'";
  12405. }
  12406. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12407. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12408. // X509_check_ip behavior and must hold for every backend.
  12409. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12410. using namespace httplib::tls;
  12411. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12412. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12413. ASSERT_TRUE(svr.is_valid());
  12414. svr.Get("/test", [](const Request &, Response &res) {
  12415. res.set_content("ok", "text/plain");
  12416. });
  12417. thread t([&]() { svr.listen(HOST, PORT); });
  12418. auto se = detail::scope_exit([&] {
  12419. svr.stop();
  12420. t.join();
  12421. });
  12422. svr.wait_until_ready();
  12423. bool verify_callback_called = false;
  12424. bool ip_matched_via_cn = true;
  12425. SSLClient cli(HOST, PORT);
  12426. cli.enable_server_certificate_verification(true);
  12427. cli.set_ca_cert_path(CA_CERT_FILE);
  12428. cli.set_connection_timeout(5);
  12429. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12430. verify_callback_called = true;
  12431. if (!ctx.cert) return false;
  12432. // The IP appears only in the CN, so it must NOT be accepted.
  12433. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12434. return true; // Accept for the purpose of this test
  12435. });
  12436. cli.Get("/test");
  12437. ASSERT_TRUE(verify_callback_called)
  12438. << "Verify callback should have been called";
  12439. EXPECT_FALSE(ip_matched_via_cn)
  12440. << "An IP host must not be authenticated via the certificate CN";
  12441. }
  12442. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12443. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12444. using namespace httplib::tls;
  12445. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12446. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12447. ASSERT_TRUE(svr.is_valid());
  12448. svr.Get("/test", [](const Request &, Response &res) {
  12449. res.set_content("ok", "text/plain");
  12450. });
  12451. thread t([&]() { svr.listen(HOST, PORT); });
  12452. auto se = detail::scope_exit([&] {
  12453. svr.stop();
  12454. t.join();
  12455. });
  12456. svr.wait_until_ready();
  12457. bool verify_callback_called = false;
  12458. bool san_matched = false;
  12459. bool wrong_ipv6_matched = true;
  12460. bool cn_ipv6_matched = true;
  12461. SSLClient cli(HOST, PORT);
  12462. cli.enable_server_certificate_verification(true);
  12463. cli.set_ca_cert_path(CA_CERT_FILE);
  12464. cli.set_connection_timeout(5);
  12465. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12466. verify_callback_called = true;
  12467. if (!ctx.cert) return false;
  12468. // Matches the IPv6 iPAddress SAN.
  12469. san_matched = ctx.check_hostname("2001:db8::1");
  12470. // A different IPv6 address must not match.
  12471. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12472. // "::1" lives only in the CN, so it must not be accepted.
  12473. cn_ipv6_matched = ctx.check_hostname("::1");
  12474. return true; // Accept for the purpose of this test
  12475. });
  12476. cli.Get("/test");
  12477. ASSERT_TRUE(verify_callback_called)
  12478. << "Verify callback should have been called";
  12479. EXPECT_TRUE(san_matched)
  12480. << "verify_hostname should match an IPv6 iPAddress SAN";
  12481. EXPECT_FALSE(wrong_ipv6_matched)
  12482. << "verify_hostname should not match a non-matching IPv6 address";
  12483. EXPECT_FALSE(cn_ipv6_matched)
  12484. << "An IPv6 host must not be authenticated via the certificate CN";
  12485. }
  12486. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12487. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12488. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12489. using namespace httplib::tls;
  12490. // SANs: DNS:a.zz, IP:42.46.122.122
  12491. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12492. ASSERT_TRUE(svr.is_valid());
  12493. svr.Get("/test", [](const Request &, Response &res) {
  12494. res.set_content("ok", "text/plain");
  12495. });
  12496. auto port = svr.bind_to_any_port(HOST);
  12497. thread t([&]() { svr.listen_after_bind(); });
  12498. auto se = detail::scope_exit([&] {
  12499. svr.stop();
  12500. t.join();
  12501. });
  12502. svr.wait_until_ready();
  12503. bool verify_callback_called = false;
  12504. bool dns_san_matched = false;
  12505. bool ip_san_matched = false;
  12506. bool ip_matched_via_dns_san = true;
  12507. bool dns_matched_via_ip_san = true;
  12508. SSLClient cli(HOST, port);
  12509. cli.enable_server_certificate_verification(true);
  12510. cli.set_ca_cert_path(CA_CERT_FILE);
  12511. cli.set_connection_timeout(5);
  12512. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12513. verify_callback_called = true;
  12514. if (!ctx.cert) return false;
  12515. dns_san_matched = ctx.check_hostname("a.zz");
  12516. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12517. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12518. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12519. return true; // Accept for the purpose of this test
  12520. });
  12521. cli.Get("/test");
  12522. ASSERT_TRUE(verify_callback_called)
  12523. << "Verify callback should have been called";
  12524. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12525. EXPECT_TRUE(ip_san_matched)
  12526. << "verify_hostname should match an iPAddress SAN";
  12527. EXPECT_FALSE(ip_matched_via_dns_san)
  12528. << "An IP host must not be authenticated via a dNSName SAN";
  12529. EXPECT_FALSE(dns_matched_via_ip_san)
  12530. << "A DNS host must not be authenticated via an iPAddress SAN";
  12531. }
  12532. // sans() must report each SAN entry under its own type.
  12533. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12534. using namespace httplib::tls;
  12535. // SANs: DNS:a.zz, IP:42.46.122.122
  12536. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12537. ASSERT_TRUE(svr.is_valid());
  12538. svr.Get("/test", [](const Request &, Response &res) {
  12539. res.set_content("ok", "text/plain");
  12540. });
  12541. auto port = svr.bind_to_any_port(HOST);
  12542. thread t([&]() { svr.listen_after_bind(); });
  12543. auto se = detail::scope_exit([&] {
  12544. svr.stop();
  12545. t.join();
  12546. });
  12547. svr.wait_until_ready();
  12548. bool verify_callback_called = false;
  12549. std::vector<SanEntry> sans;
  12550. SSLClient cli(HOST, port);
  12551. cli.enable_server_certificate_verification(true);
  12552. cli.set_ca_cert_path(CA_CERT_FILE);
  12553. cli.set_connection_timeout(5);
  12554. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12555. verify_callback_called = true;
  12556. if (!ctx.cert) return false;
  12557. sans = ctx.sans();
  12558. return true; // Accept for the purpose of this test
  12559. });
  12560. cli.Get("/test");
  12561. ASSERT_TRUE(verify_callback_called)
  12562. << "Verify callback should have been called";
  12563. auto has_san = [&](SanType type, const std::string &value) {
  12564. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12565. return san.type == type && san.value == value;
  12566. });
  12567. };
  12568. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12569. << "sans() should report the dNSName SAN";
  12570. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12571. << "sans() should report the iPAddress SAN";
  12572. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12573. << "sans() must not report the dNSName SAN as an address";
  12574. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12575. << "sans() must not report the iPAddress SAN as a DNS name";
  12576. }
  12577. #endif
  12578. // mbedTLS-specific callback constructor test
  12579. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12580. #ifdef CPPHTTPLIB_SSL_ENABLED
  12581. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12583. ASSERT_TRUE(svr.is_valid());
  12584. // Set up a handler to verify client certificate is present
  12585. bool client_cert_verified = false;
  12586. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12587. // Verify that client certificate was provided
  12588. client_cert_verified = true;
  12589. res.set_content("success", "text/plain");
  12590. });
  12591. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12592. auto se = detail::scope_exit([&] {
  12593. svr.stop();
  12594. t.join();
  12595. ASSERT_FALSE(svr.is_running());
  12596. });
  12597. svr.wait_until_ready();
  12598. // Client with certificate
  12599. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12600. cli.enable_server_certificate_verification(false);
  12601. cli.set_connection_timeout(30);
  12602. auto res = cli.Get("/test");
  12603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12604. ASSERT_EQ(StatusCode::OK_200, res->status);
  12605. ASSERT_TRUE(client_cert_verified);
  12606. EXPECT_EQ("success", res->body);
  12607. }
  12608. #endif
  12609. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12610. // backends
  12611. #ifdef CPPHTTPLIB_SSL_ENABLED
  12612. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12613. using namespace httplib::tls;
  12614. // Test that when client CA cert file is provided,
  12615. // the server properly requests and validates client certificates
  12616. // Create a server with client authentication
  12617. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12618. ASSERT_TRUE(svr.is_valid());
  12619. bool handler_called = false;
  12620. svr.Get("/test", [&](const Request &req, Response &res) {
  12621. handler_called = true;
  12622. // Verify that a client certificate was provided
  12623. auto cert = req.peer_cert();
  12624. ASSERT_TRUE(static_cast<bool>(cert));
  12625. // Get the issuer name
  12626. std::string issuer_str = cert.issuer_name();
  12627. ASSERT_FALSE(issuer_str.empty());
  12628. // The client certificate should be issued by our test CA
  12629. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12630. res.set_content("authenticated", "text/plain");
  12631. });
  12632. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12633. auto se = detail::scope_exit([&] {
  12634. svr.stop();
  12635. t.join();
  12636. ASSERT_FALSE(svr.is_running());
  12637. });
  12638. svr.wait_until_ready();
  12639. // Connect with a client certificate issued by the CA
  12640. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12641. cli.enable_server_certificate_verification(false);
  12642. cli.set_connection_timeout(30);
  12643. auto res = cli.Get("/test");
  12644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12645. ASSERT_EQ(StatusCode::OK_200, res->status);
  12646. ASSERT_TRUE(handler_called);
  12647. EXPECT_EQ("authenticated", res->body);
  12648. }
  12649. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12650. using namespace httplib::tls;
  12651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12652. ASSERT_TRUE(svr.is_valid());
  12653. svr.Get("/test", [](const Request &, Response &res) {
  12654. res.set_content("ok", "text/plain");
  12655. });
  12656. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12657. auto se = detail::scope_exit([&] {
  12658. svr.stop();
  12659. t.join();
  12660. });
  12661. svr.wait_until_ready();
  12662. SSLClient cli(HOST, PORT);
  12663. cli.enable_server_certificate_verification(false);
  12664. cli.set_connection_timeout(30);
  12665. bool cert_checked = false;
  12666. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12667. if (ctx.cert) {
  12668. auto sans = ctx.sans();
  12669. // Test certificate may or may not have SANs - just verify the API
  12670. // works If SANs exist, verify the types are valid
  12671. for (const auto &san : sans) {
  12672. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12673. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12674. san.type == SanType::OTHER);
  12675. EXPECT_FALSE(san.value.empty());
  12676. }
  12677. cert_checked = true;
  12678. }
  12679. return true;
  12680. });
  12681. auto res = cli.Get("/test");
  12682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12683. EXPECT_TRUE(cert_checked);
  12684. }
  12685. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12686. using namespace httplib::tls;
  12687. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12688. ASSERT_TRUE(svr.is_valid());
  12689. svr.Get("/test", [](const Request &, Response &res) {
  12690. res.set_content("ok", "text/plain");
  12691. });
  12692. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12693. auto se = detail::scope_exit([&] {
  12694. svr.stop();
  12695. t.join();
  12696. });
  12697. svr.wait_until_ready();
  12698. SSLClient cli(HOST, PORT);
  12699. cli.enable_server_certificate_verification(false);
  12700. cli.set_connection_timeout(30);
  12701. bool validity_checked = false;
  12702. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12703. if (ctx.cert) {
  12704. time_t not_before = 0, not_after = 0;
  12705. bool result = ctx.validity(not_before, not_after);
  12706. EXPECT_TRUE(result);
  12707. // Verify that not_before < now < not_after for a valid cert
  12708. time_t now = time(nullptr);
  12709. EXPECT_LT(not_before, now);
  12710. EXPECT_GT(not_after, now);
  12711. validity_checked = true;
  12712. }
  12713. return true;
  12714. });
  12715. auto res = cli.Get("/test");
  12716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12717. EXPECT_TRUE(validity_checked);
  12718. }
  12719. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12720. using namespace httplib::tls;
  12721. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12722. ASSERT_TRUE(svr.is_valid());
  12723. svr.Get("/test", [](const Request &, Response &res) {
  12724. res.set_content("ok", "text/plain");
  12725. });
  12726. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12727. auto se = detail::scope_exit([&] {
  12728. svr.stop();
  12729. t.join();
  12730. });
  12731. svr.wait_until_ready();
  12732. SSLClient cli(HOST, PORT);
  12733. cli.enable_server_certificate_verification(false);
  12734. cli.set_connection_timeout(30);
  12735. bool serial_checked = false;
  12736. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12737. if (ctx.cert) {
  12738. std::string serial = ctx.serial();
  12739. EXPECT_FALSE(serial.empty());
  12740. // Serial should be a hex string
  12741. for (char c : serial) {
  12742. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12743. (c >= 'a' && c <= 'f'));
  12744. }
  12745. serial_checked = true;
  12746. }
  12747. return true;
  12748. });
  12749. auto res = cli.Get("/test");
  12750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12751. EXPECT_TRUE(serial_checked);
  12752. }
  12753. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12754. // Test 1: Valid CA file - no error should be recorded
  12755. {
  12756. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12757. CLIENT_CA_CERT_FILE);
  12758. ASSERT_TRUE(svr.is_valid());
  12759. // With valid setup, last_ssl_error should be 0
  12760. EXPECT_EQ(0, svr.ssl_last_error());
  12761. }
  12762. // Test 2: Invalid CA file content
  12763. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12764. {
  12765. // Create a temporary file with completely invalid content
  12766. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12767. {
  12768. std::ofstream ofs(temp_invalid_ca);
  12769. ofs << "This is not a certificate file at all\n";
  12770. ofs << "Just plain text content\n";
  12771. }
  12772. // Create server with invalid CA file
  12773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12774. // Clean up temporary file
  12775. std::remove(temp_invalid_ca);
  12776. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12777. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12778. // Note: SSL_CTX_load_verify_locations typically fails first,
  12779. // but our error handling code path is still exercised
  12780. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12781. }
  12782. }
  12783. TEST(VerifyCallbackTest, VerifyContextFields) {
  12784. using namespace httplib::tls;
  12785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12786. ASSERT_TRUE(svr.is_valid());
  12787. svr.Get("/test", [](const Request &, Response &res) {
  12788. res.set_content("ok", "text/plain");
  12789. });
  12790. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12791. auto se = detail::scope_exit([&] {
  12792. svr.stop();
  12793. t.join();
  12794. });
  12795. svr.wait_until_ready();
  12796. SSLClient cli(HOST, PORT);
  12797. cli.enable_server_certificate_verification(false);
  12798. cli.set_connection_timeout(30);
  12799. int callback_count = 0;
  12800. bool saw_leaf_cert = false;
  12801. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12802. if (ctx.cert) {
  12803. callback_count++;
  12804. // We should see at least one certificate (the leaf)
  12805. std::string cn = ctx.subject_cn();
  12806. if (!cn.empty()) { saw_leaf_cert = true; }
  12807. // Verify context fields are populated
  12808. EXPECT_NE(ctx.session, nullptr);
  12809. EXPECT_GE(ctx.depth, 0);
  12810. }
  12811. return true;
  12812. });
  12813. auto res = cli.Get("/test");
  12814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12815. EXPECT_GT(callback_count, 0);
  12816. EXPECT_TRUE(saw_leaf_cert);
  12817. }
  12818. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12819. using httplib::tls::TlsError;
  12820. // Test that verify_error_to_string returns empty for success
  12821. std::string success_str = TlsError::verify_error_to_string(0);
  12822. EXPECT_TRUE(success_str.empty());
  12823. // Test that verify_error_to_string returns non-empty for error codes
  12824. // Using a common error code (certificate expired)
  12825. std::string error_str =
  12826. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12827. EXPECT_FALSE(error_str.empty());
  12828. }
  12829. TEST(SessionVerifierTest, CertificateAccepted) {
  12830. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12831. ASSERT_TRUE(svr.is_valid());
  12832. svr.Get("/test", [](const Request &, Response &res) {
  12833. res.set_content("ok", "text/plain");
  12834. });
  12835. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12836. auto se = detail::scope_exit([&] {
  12837. svr.stop();
  12838. t.join();
  12839. });
  12840. svr.wait_until_ready();
  12841. SSLClient cli(HOST, PORT);
  12842. cli.enable_server_certificate_verification(false);
  12843. cli.set_connection_timeout(30);
  12844. bool callback_called = false;
  12845. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12846. EXPECT_NE(session, nullptr);
  12847. callback_called = true;
  12848. return SSLVerifierResponse::CertificateAccepted;
  12849. });
  12850. auto res = cli.Get("/test");
  12851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12852. EXPECT_EQ(200, res->status);
  12853. EXPECT_TRUE(callback_called);
  12854. }
  12855. TEST(SessionVerifierTest, CertificateRejected) {
  12856. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12857. ASSERT_TRUE(svr.is_valid());
  12858. svr.Get("/test", [](const Request &, Response &res) {
  12859. res.set_content("ok", "text/plain");
  12860. });
  12861. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12862. auto se = detail::scope_exit([&] {
  12863. svr.stop();
  12864. t.join();
  12865. });
  12866. svr.wait_until_ready();
  12867. SSLClient cli(HOST, PORT);
  12868. cli.enable_server_certificate_verification(false);
  12869. cli.set_connection_timeout(30);
  12870. bool callback_called = false;
  12871. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12872. EXPECT_NE(session, nullptr);
  12873. callback_called = true;
  12874. return SSLVerifierResponse::CertificateRejected;
  12875. });
  12876. auto res = cli.Get("/test");
  12877. EXPECT_FALSE(res);
  12878. EXPECT_TRUE(callback_called);
  12879. }
  12880. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12881. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12882. ASSERT_TRUE(svr.is_valid());
  12883. svr.Get("/test", [](const Request &, Response &res) {
  12884. res.set_content("ok", "text/plain");
  12885. });
  12886. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12887. auto se = detail::scope_exit([&] {
  12888. svr.stop();
  12889. t.join();
  12890. });
  12891. svr.wait_until_ready();
  12892. // NoDecisionMade with verification disabled should succeed (no default check)
  12893. SSLClient cli(HOST, PORT);
  12894. cli.enable_server_certificate_verification(false);
  12895. cli.set_connection_timeout(30);
  12896. bool callback_called = false;
  12897. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12898. EXPECT_NE(session, nullptr);
  12899. callback_called = true;
  12900. return SSLVerifierResponse::NoDecisionMade;
  12901. });
  12902. auto res = cli.Get("/test");
  12903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12904. EXPECT_EQ(200, res->status);
  12905. EXPECT_TRUE(callback_called);
  12906. }
  12907. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12908. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12909. ASSERT_TRUE(svr.is_valid());
  12910. svr.Get("/test", [](const Request &, Response &res) {
  12911. res.set_content("ok", "text/plain");
  12912. });
  12913. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12914. auto se = detail::scope_exit([&] {
  12915. svr.stop();
  12916. t.join();
  12917. });
  12918. svr.wait_until_ready();
  12919. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12920. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12921. // so we only check that the request fails, not whether the callback was
  12922. // called.
  12923. SSLClient cli(HOST, PORT);
  12924. cli.enable_server_certificate_verification(true);
  12925. cli.set_connection_timeout(30);
  12926. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12927. EXPECT_NE(session, nullptr);
  12928. return SSLVerifierResponse::NoDecisionMade;
  12929. });
  12930. auto res = cli.Get("/test");
  12931. EXPECT_FALSE(res);
  12932. }
  12933. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12934. // Test SSL server using PemMemory constructor with client CA certificates
  12935. // Read PEM files
  12936. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12937. read_file(SERVER_CERT_FILE, server_cert_pem);
  12938. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12939. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12940. // Create SSLServer with PemMemory constructor including client CA
  12941. SSLServer::PemMemory server_pem = {
  12942. server_cert_pem.c_str(),
  12943. server_cert_pem.size(),
  12944. server_key_pem.c_str(),
  12945. server_key_pem.size(),
  12946. client_ca_pem.c_str(),
  12947. client_ca_pem.size(),
  12948. nullptr // no password for server key
  12949. };
  12950. SSLServer svr(server_pem);
  12951. ASSERT_TRUE(svr.is_valid());
  12952. // No SSL error should be recorded for valid setup
  12953. EXPECT_EQ(0, svr.ssl_last_error());
  12954. // Set up server endpoints
  12955. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12956. res.set_content("ok", "text/plain");
  12957. });
  12958. // Start server in a thread
  12959. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12960. svr.wait_until_ready();
  12961. // Connect with client certificate (using constructor with paths)
  12962. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12963. cli.enable_server_certificate_verification(false);
  12964. auto res = cli.Get("/test-pem-ca");
  12965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12966. EXPECT_EQ(200, res->status);
  12967. EXPECT_EQ("ok", res->body);
  12968. svr.stop();
  12969. server_thread.join();
  12970. }
  12971. #endif
  12972. #ifdef _WIN32
  12973. TEST(CleanupTest, WSACleanup) {
  12974. int ret = WSACleanup();
  12975. ASSERT_EQ(0, ret);
  12976. }
  12977. #endif
  12978. #ifndef CPPHTTPLIB_SSL_ENABLED
  12979. TEST(NoSSLSupport, SimpleInterface) {
  12980. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12981. }
  12982. #endif
  12983. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12984. TEST(InvalidScheme, SimpleInterface) {
  12985. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12986. }
  12987. #endif
  12988. TEST(NoScheme, SimpleInterface) {
  12989. Client cli("yahoo.com:80");
  12990. ASSERT_TRUE(cli.is_valid());
  12991. }
  12992. TEST(SendAPI, SimpleInterface_Online) {
  12993. Client cli("http://yahoo.com");
  12994. Request req;
  12995. req.method = "GET";
  12996. req.path = "/";
  12997. auto res = cli.send(req);
  12998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12999. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13000. }
  13001. TEST(SendAPI, WithParamsInRequest) {
  13002. Server svr;
  13003. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13004. EXPECT_TRUE(req.has_param("test"));
  13005. EXPECT_EQ("test_value", req.get_param_value("test"));
  13006. });
  13007. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13008. auto se = detail::scope_exit([&] {
  13009. svr.stop();
  13010. t.join();
  13011. ASSERT_FALSE(svr.is_running());
  13012. });
  13013. svr.wait_until_ready();
  13014. Client cli(HOST, PORT);
  13015. {
  13016. Request req;
  13017. req.method = "GET";
  13018. req.path = "/";
  13019. req.params.emplace("test", "test_value");
  13020. auto res = cli.send(req);
  13021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13022. }
  13023. {
  13024. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13026. }
  13027. }
  13028. TEST(ClientImplMethods, GetSocketTest) {
  13029. httplib::Server svr;
  13030. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13031. res.status = StatusCode::OK_200;
  13032. });
  13033. auto port = svr.bind_to_any_port("127.0.0.1");
  13034. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13035. auto se = detail::scope_exit([&] {
  13036. svr.stop();
  13037. thread.join();
  13038. ASSERT_FALSE(svr.is_running());
  13039. });
  13040. svr.wait_until_ready();
  13041. {
  13042. httplib::Client cli("127.0.0.1", port);
  13043. cli.set_keep_alive(true);
  13044. // Use the behavior of cpp-httplib of opening the connection
  13045. // only when the first request happens. If that changes,
  13046. // this test would be obsolete.
  13047. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13048. // This also implicitly tests the server. But other tests would fail much
  13049. // earlier than this one to be considered.
  13050. auto res = cli.Get("/");
  13051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13052. EXPECT_EQ(StatusCode::OK_200, res->status);
  13053. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13054. }
  13055. }
  13056. #ifdef CPPHTTPLIB_SSL_ENABLED
  13057. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13058. Client cli("http://yahoo.com");
  13059. auto res = cli.Get("/");
  13060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13061. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13062. cli.set_follow_location(true);
  13063. res = cli.Get("/");
  13064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13065. EXPECT_EQ(StatusCode::OK_200, res->status);
  13066. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13067. }
  13068. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13069. Client cli("https://yahoo.com");
  13070. auto res = cli.Get("/");
  13071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13072. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13073. cli.set_follow_location(true);
  13074. res = cli.Get("/");
  13075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13076. EXPECT_EQ(StatusCode::OK_200, res->status);
  13077. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13078. }
  13079. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13080. Client cli("https://yahoo.com");
  13081. auto res = cli.Get("/");
  13082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13083. ASSERT_FALSE(!res);
  13084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13085. ASSERT_FALSE(res == nullptr);
  13086. ASSERT_TRUE(res != nullptr);
  13087. EXPECT_EQ(Error::Success, res.error());
  13088. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13089. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13090. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13091. cli.set_follow_location(true);
  13092. res = cli.Get("/");
  13093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13094. EXPECT_EQ(Error::Success, res.error());
  13095. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13096. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13097. EXPECT_EQ(StatusCode::OK_200, res->status);
  13098. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13099. }
  13100. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13101. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13102. Client cli("https://cdnjs.cloudflare.com");
  13103. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13104. Headers{{"Accept-Encoding", "br"}});
  13105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13106. EXPECT_EQ(StatusCode::OK_200, res->status);
  13107. EXPECT_EQ(287630U, res->body.size());
  13108. EXPECT_EQ("application/javascript; charset=utf-8",
  13109. res->get_header_value("Content-Type"));
  13110. }
  13111. #endif
  13112. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13113. #undef REDIR_HOST // Silence compiler warning
  13114. #define REDIR_HOST "https://httpbingo.org"
  13115. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13116. Client cli(REDIR_HOST);
  13117. cli.set_follow_location(true);
  13118. auto res =
  13119. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13121. EXPECT_EQ(StatusCode::OK_200, res->status);
  13122. }
  13123. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13124. Client cli(REDIR_HOST);
  13125. cli.set_follow_location(true);
  13126. Params params;
  13127. params.emplace("url", "http://example.com");
  13128. params.emplace("status_code", "302");
  13129. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13131. EXPECT_EQ(StatusCode::OK_200, res->status);
  13132. }
  13133. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13134. Client cli(REDIR_HOST);
  13135. cli.set_follow_location(true);
  13136. Params params;
  13137. params.emplace("url", "http://example.com");
  13138. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13140. EXPECT_EQ(StatusCode::OK_200, res->status);
  13141. }
  13142. TEST(HttpToHttpsRedirectTest, CertFile) {
  13143. auto ssl_port = PORT + 1;
  13144. Server svr;
  13145. ASSERT_TRUE(svr.is_valid());
  13146. svr.Get("/index", [&](const Request &, Response &res) {
  13147. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13148. "/index");
  13149. svr.stop();
  13150. });
  13151. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13152. ASSERT_TRUE(ssl_svr.is_valid());
  13153. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13154. res.set_content("test", "text/plain");
  13155. ssl_svr.stop();
  13156. });
  13157. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13158. thread t2 =
  13159. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13160. auto se = detail::scope_exit([&] {
  13161. t2.join();
  13162. t.join();
  13163. ASSERT_FALSE(svr.is_running());
  13164. });
  13165. svr.wait_until_ready();
  13166. ssl_svr.wait_until_ready();
  13167. Client cli("127.0.0.1", PORT);
  13168. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13169. cli.enable_server_certificate_verification(true);
  13170. cli.set_follow_location(true);
  13171. cli.set_connection_timeout(30);
  13172. auto res = cli.Get("/index");
  13173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13174. ASSERT_EQ(StatusCode::OK_200, res->status);
  13175. }
  13176. TEST(SSLClientRedirectTest, CertFile) {
  13177. auto ssl_port = PORT + 1;
  13178. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13179. ASSERT_TRUE(ssl_svr1.is_valid());
  13180. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13181. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13182. "/index");
  13183. ssl_svr1.stop();
  13184. });
  13185. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13186. ASSERT_TRUE(ssl_svr2.is_valid());
  13187. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13188. res.set_content("test", "text/plain");
  13189. ssl_svr2.stop();
  13190. });
  13191. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13192. thread t2 =
  13193. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13194. auto se = detail::scope_exit([&] {
  13195. t2.join();
  13196. t.join();
  13197. ASSERT_FALSE(ssl_svr1.is_running());
  13198. });
  13199. ssl_svr1.wait_until_ready();
  13200. ssl_svr2.wait_until_ready();
  13201. SSLClient cli("127.0.0.1", PORT);
  13202. std::string cert;
  13203. read_file(SERVER_CERT2_FILE, cert);
  13204. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13205. cli.enable_server_certificate_verification(true);
  13206. cli.set_follow_location(true);
  13207. cli.set_connection_timeout(30);
  13208. auto res = cli.Get("/index");
  13209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13210. ASSERT_EQ(StatusCode::OK_200, res->status);
  13211. }
  13212. #endif
  13213. #ifdef CPPHTTPLIB_SSL_ENABLED
  13214. // Test that set_ca_cert_store() skips system certs (consistent with
  13215. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13216. // should be trusted - system certs should NOT be loaded.
  13217. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13218. // Load a specific cert that is NOT a system CA cert
  13219. std::string cert;
  13220. read_file(SERVER_CERT2_FILE, cert);
  13221. SSLClient cli("google.com");
  13222. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13223. cli.enable_server_certificate_verification(true);
  13224. // This should FAIL because:
  13225. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13226. // 2. System certs should NOT be loaded when custom store is set
  13227. // If system certs WERE loaded, this would succeed
  13228. auto res = cli.Get("/");
  13229. ASSERT_FALSE(res);
  13230. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13231. }
  13232. // Same as above, but through the native store handle path. Regression test:
  13233. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13234. // merged system certs into the user-provided store.
  13235. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13236. std::string cert;
  13237. read_file(SERVER_CERT2_FILE, cert);
  13238. SSLClient cli("google.com");
  13239. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13240. cli.enable_server_certificate_verification(true);
  13241. auto res = cli.Get("/");
  13242. ASSERT_FALSE(res);
  13243. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13244. }
  13245. // A custom store set via the native handle must still verify a server whose
  13246. // cert it does contain.
  13247. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13248. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13249. ASSERT_TRUE(svr.is_valid());
  13250. svr.Get("/test", [&](const Request &, Response &res) {
  13251. res.set_content("test", "text/plain");
  13252. });
  13253. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13254. auto se = detail::scope_exit([&] {
  13255. svr.stop();
  13256. t.join();
  13257. ASSERT_FALSE(svr.is_running());
  13258. });
  13259. svr.wait_until_ready();
  13260. SSLClient cli("127.0.0.1", PORT);
  13261. std::string cert;
  13262. read_file(SERVER_CERT2_FILE, cert);
  13263. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13264. cli.enable_server_certificate_verification(true);
  13265. cli.set_connection_timeout(30);
  13266. auto res = cli.Get("/test");
  13267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13268. ASSERT_EQ(StatusCode::OK_200, res->status);
  13269. }
  13270. // CA certs loaded through the universal Client must be transferred to the
  13271. // client created internally for following an HTTPS redirect. Regression test:
  13272. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13273. // the CA data for redirect transfer.
  13274. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13275. auto ssl_port = PORT + 1;
  13276. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13277. ASSERT_TRUE(ssl_svr1.is_valid());
  13278. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13279. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13280. "/index");
  13281. });
  13282. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13283. ASSERT_TRUE(ssl_svr2.is_valid());
  13284. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13285. res.set_content("test", "text/plain");
  13286. });
  13287. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13288. thread t2 =
  13289. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13290. auto se = detail::scope_exit([&] {
  13291. ssl_svr2.stop();
  13292. ssl_svr1.stop();
  13293. t2.join();
  13294. t.join();
  13295. ASSERT_FALSE(ssl_svr1.is_running());
  13296. });
  13297. ssl_svr1.wait_until_ready();
  13298. ssl_svr2.wait_until_ready();
  13299. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13300. std::string cert;
  13301. read_file(SERVER_CERT2_FILE, cert);
  13302. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13303. cli.enable_server_certificate_verification(true);
  13304. cli.set_follow_location(true);
  13305. cli.set_connection_timeout(30);
  13306. auto res = cli.Get("/index");
  13307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13308. ASSERT_EQ(StatusCode::OK_200, res->status);
  13309. }
  13310. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13311. // so a host signed by a system CA verifies even though a custom CA is set
  13312. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13313. std::string cert;
  13314. read_file(SERVER_CERT2_FILE, cert);
  13315. SSLClient cli("google.com");
  13316. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13317. cli.enable_system_ca(true);
  13318. cli.enable_server_certificate_verification(true);
  13319. auto res = cli.Get("/");
  13320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13321. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13322. }
  13323. // The custom CA remains effective when combined with the system CA
  13324. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13325. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13326. ASSERT_TRUE(svr.is_valid());
  13327. svr.Get("/test", [&](const Request &, Response &res) {
  13328. res.set_content("test", "text/plain");
  13329. });
  13330. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13331. auto se = detail::scope_exit([&] {
  13332. svr.stop();
  13333. t.join();
  13334. ASSERT_FALSE(svr.is_running());
  13335. });
  13336. svr.wait_until_ready();
  13337. SSLClient cli("127.0.0.1", PORT);
  13338. std::string cert;
  13339. read_file(SERVER_CERT2_FILE, cert);
  13340. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13341. cli.enable_system_ca(true);
  13342. cli.enable_server_certificate_verification(true);
  13343. cli.set_connection_timeout(30);
  13344. auto res = cli.Get("/test");
  13345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13346. ASSERT_EQ(StatusCode::OK_200, res->status);
  13347. }
  13348. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13349. // skip chain verification entirely (only the certificate identity was
  13350. // checked), so a server presenting an untrusted certificate with a matching
  13351. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13352. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13353. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13354. ASSERT_TRUE(svr.is_valid());
  13355. svr.Get("/test", [&](const Request &, Response &res) {
  13356. res.set_content("test", "text/plain");
  13357. });
  13358. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13359. auto se = detail::scope_exit([&] {
  13360. svr.stop();
  13361. t.join();
  13362. ASSERT_FALSE(svr.is_running());
  13363. });
  13364. svr.wait_until_ready();
  13365. SSLClient cli("127.0.0.1", PORT);
  13366. std::string cert;
  13367. // A trusted CA that did not sign the server certificate. The server cert
  13368. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13369. // this connection.
  13370. read_file(CLIENT_CA_CERT_FILE, cert);
  13371. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13372. cli.enable_server_certificate_verification(true);
  13373. cli.set_connection_timeout(30);
  13374. auto res = cli.Get("/test");
  13375. ASSERT_FALSE(res);
  13376. }
  13377. // enable_system_ca(false) prevents system CA loading entirely
  13378. TEST(SSLClientTest, DisableSystemCa_Online) {
  13379. SSLClient cli("google.com");
  13380. cli.enable_system_ca(false);
  13381. cli.enable_server_certificate_verification(true);
  13382. auto res = cli.Get("/");
  13383. ASSERT_FALSE(res);
  13384. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13385. // itself when the CA chain is empty
  13386. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13387. res.error() == Error::SSLConnection);
  13388. }
  13389. // The universal Client forwards enable_system_ca()
  13390. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13391. std::string cert;
  13392. read_file(SERVER_CERT2_FILE, cert);
  13393. Client cli("https://google.com");
  13394. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13395. cli.enable_system_ca(true);
  13396. cli.enable_server_certificate_verification(true);
  13397. auto res = cli.Get("/");
  13398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13399. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13400. }
  13401. // The system CA policy must carry over to the client created internally for
  13402. // following a cross-host HTTPS redirect
  13403. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13404. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13405. ASSERT_TRUE(svr.is_valid());
  13406. svr.Get("/index", [&](const Request &, Response &res) {
  13407. res.set_redirect("https://www.google.com/");
  13408. });
  13409. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13410. auto se = detail::scope_exit([&] {
  13411. svr.stop();
  13412. t.join();
  13413. ASSERT_FALSE(svr.is_running());
  13414. });
  13415. svr.wait_until_ready();
  13416. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13417. std::string cert;
  13418. read_file(SERVER_CERT2_FILE, cert);
  13419. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13420. cli.enable_system_ca(true);
  13421. cli.enable_server_certificate_verification(true);
  13422. cli.set_follow_location(true);
  13423. cli.set_connection_timeout(30);
  13424. // Receiving any response proves the redirect client completed the TLS
  13425. // handshake with a system-CA-signed host
  13426. auto res = cli.Get("/index");
  13427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13428. }
  13429. TEST(MultipartFormDataTest, LargeData) {
  13430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13431. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13432. const ContentReader &content_reader) {
  13433. if (req.is_multipart_form_data()) {
  13434. std::vector<FormData> items;
  13435. content_reader(
  13436. [&](const FormData &file) {
  13437. items.push_back(file);
  13438. return true;
  13439. },
  13440. [&](const char *data, size_t data_length) {
  13441. items.back().content.append(data, data_length);
  13442. return true;
  13443. });
  13444. EXPECT_TRUE(std::string(items[0].name) == "document");
  13445. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13446. EXPECT_TRUE(items[0].filename == "2MB_data");
  13447. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13448. EXPECT_TRUE(items[1].name == "hello");
  13449. EXPECT_TRUE(items[1].content == "world");
  13450. EXPECT_TRUE(items[1].filename == "");
  13451. EXPECT_TRUE(items[1].content_type == "");
  13452. } else {
  13453. std::string body;
  13454. content_reader([&](const char *data, size_t data_length) {
  13455. body.append(data, data_length);
  13456. return true;
  13457. });
  13458. }
  13459. });
  13460. auto port = svr.bind_to_any_port(HOST);
  13461. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13462. auto se = detail::scope_exit([&] {
  13463. svr.stop();
  13464. t.join();
  13465. ASSERT_FALSE(svr.is_running());
  13466. });
  13467. svr.wait_until_ready();
  13468. {
  13469. std::string data(1024 * 1024 * 2, '.');
  13470. std::stringstream buffer;
  13471. buffer << data;
  13472. SSLClient cli(HOST, port);
  13473. cli.enable_server_certificate_verification(false);
  13474. UploadFormDataItems items{
  13475. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13476. {"hello", "world", "", ""},
  13477. };
  13478. auto res = cli.Post("/post", items);
  13479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13480. ASSERT_EQ(StatusCode::OK_200, res->status);
  13481. }
  13482. }
  13483. TEST(MultipartFormDataTest, DataProviderItems) {
  13484. std::random_device seed_gen;
  13485. std::mt19937 random(seed_gen());
  13486. std::string rand1;
  13487. rand1.resize(1000);
  13488. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13489. std::string rand2;
  13490. rand2.resize(3000);
  13491. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13493. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13494. const ContentReader &content_reader) {
  13495. ASSERT_FALSE(req.is_multipart_form_data());
  13496. std::string body;
  13497. content_reader([&](const char *data, size_t data_length) {
  13498. body.append(data, data_length);
  13499. return true;
  13500. });
  13501. EXPECT_EQ(body, "");
  13502. });
  13503. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13504. const ContentReader &content_reader) {
  13505. ASSERT_TRUE(req.is_multipart_form_data());
  13506. std::vector<FormData> items;
  13507. content_reader(
  13508. [&](const FormData &file) {
  13509. items.push_back(file);
  13510. return true;
  13511. },
  13512. [&](const char *data, size_t data_length) {
  13513. items.back().content.append(data, data_length);
  13514. return true;
  13515. });
  13516. ASSERT_TRUE(items.size() == 2);
  13517. EXPECT_EQ(std::string(items[0].name), "name1");
  13518. EXPECT_EQ(items[0].content, "Testing123");
  13519. EXPECT_EQ(items[0].filename, "filename1");
  13520. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13521. EXPECT_EQ(items[1].name, "name2");
  13522. EXPECT_EQ(items[1].content, "Testing456");
  13523. EXPECT_EQ(items[1].filename, "");
  13524. EXPECT_EQ(items[1].content_type, "");
  13525. });
  13526. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13527. const ContentReader &content_reader) {
  13528. ASSERT_TRUE(req.is_multipart_form_data());
  13529. std::vector<FormData> items;
  13530. content_reader(
  13531. [&](const FormData &file) {
  13532. items.push_back(file);
  13533. return true;
  13534. },
  13535. [&](const char *data, size_t data_length) {
  13536. items.back().content.append(data, data_length);
  13537. return true;
  13538. });
  13539. ASSERT_TRUE(items.size() == 2);
  13540. EXPECT_EQ(items[0].name, "name3");
  13541. EXPECT_EQ(items[0].content, rand1);
  13542. EXPECT_EQ(items[0].filename, "filename3");
  13543. EXPECT_EQ(items[0].content_type, "");
  13544. EXPECT_EQ(items[1].name, "name4");
  13545. EXPECT_EQ(items[1].content, rand2);
  13546. EXPECT_EQ(items[1].filename, "filename4");
  13547. EXPECT_EQ(items[1].content_type, "");
  13548. });
  13549. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13550. const ContentReader &content_reader) {
  13551. ASSERT_TRUE(req.is_multipart_form_data());
  13552. std::vector<FormData> items;
  13553. content_reader(
  13554. [&](const FormData &file) {
  13555. items.push_back(file);
  13556. return true;
  13557. },
  13558. [&](const char *data, size_t data_length) {
  13559. items.back().content.append(data, data_length);
  13560. return true;
  13561. });
  13562. ASSERT_TRUE(items.size() == 4);
  13563. EXPECT_EQ(std::string(items[0].name), "name1");
  13564. EXPECT_EQ(items[0].content, "Testing123");
  13565. EXPECT_EQ(items[0].filename, "filename1");
  13566. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13567. EXPECT_EQ(items[1].name, "name2");
  13568. EXPECT_EQ(items[1].content, "Testing456");
  13569. EXPECT_EQ(items[1].filename, "");
  13570. EXPECT_EQ(items[1].content_type, "");
  13571. EXPECT_EQ(items[2].name, "name3");
  13572. EXPECT_EQ(items[2].content, rand1);
  13573. EXPECT_EQ(items[2].filename, "filename3");
  13574. EXPECT_EQ(items[2].content_type, "");
  13575. EXPECT_EQ(items[3].name, "name4");
  13576. EXPECT_EQ(items[3].content, rand2);
  13577. EXPECT_EQ(items[3].filename, "filename4");
  13578. EXPECT_EQ(items[3].content_type, "");
  13579. });
  13580. auto port = svr.bind_to_any_port("localhost");
  13581. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13582. auto se = detail::scope_exit([&] {
  13583. svr.stop();
  13584. t.join();
  13585. ASSERT_FALSE(svr.is_running());
  13586. });
  13587. svr.wait_until_ready();
  13588. {
  13589. SSLClient cli("localhost", port);
  13590. cli.enable_server_certificate_verification(false);
  13591. UploadFormDataItems items{
  13592. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13593. {"name2", "Testing456", "", ""}, // not a file
  13594. };
  13595. {
  13596. auto res = cli.Post("/post-none", {}, {}, {});
  13597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13598. ASSERT_EQ(StatusCode::OK_200, res->status);
  13599. }
  13600. FormDataProviderItems providers;
  13601. {
  13602. auto res =
  13603. cli.Post("/post-items", {}, items, providers); // empty providers
  13604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13605. ASSERT_EQ(StatusCode::OK_200, res->status);
  13606. }
  13607. providers.push_back({"name3",
  13608. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13609. // test the offset is given correctly at each step
  13610. if (!offset)
  13611. sink.os.write(rand1.data(), 30);
  13612. else if (offset == 30)
  13613. sink.os.write(rand1.data() + 30, 300);
  13614. else if (offset == 330)
  13615. sink.os.write(rand1.data() + 330, 670);
  13616. else if (offset == rand1.size())
  13617. sink.done();
  13618. return true;
  13619. },
  13620. "filename3",
  13621. {}});
  13622. providers.push_back({"name4",
  13623. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13624. // test the offset is given correctly at each step
  13625. if (!offset)
  13626. sink.os.write(rand2.data(), 2000);
  13627. else if (offset == 2000)
  13628. sink.os.write(rand2.data() + 2000, 1);
  13629. else if (offset == 2001)
  13630. sink.os.write(rand2.data() + 2001, 999);
  13631. else if (offset == rand2.size())
  13632. sink.done();
  13633. return true;
  13634. },
  13635. "filename4",
  13636. {}});
  13637. {
  13638. auto res = cli.Post("/post-providers", {}, {}, providers);
  13639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13640. ASSERT_EQ(StatusCode::OK_200, res->status);
  13641. }
  13642. {
  13643. auto res = cli.Post("/post-both", {}, items, providers);
  13644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13645. ASSERT_EQ(StatusCode::OK_200, res->status);
  13646. }
  13647. }
  13648. }
  13649. TEST(MultipartFormDataTest, BadHeader) {
  13650. Server svr;
  13651. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13652. res.set_content("ok", "text/plain");
  13653. });
  13654. thread t = thread([&] { svr.listen(HOST, PORT); });
  13655. auto se = detail::scope_exit([&] {
  13656. svr.stop();
  13657. t.join();
  13658. ASSERT_FALSE(svr.is_running());
  13659. });
  13660. svr.wait_until_ready();
  13661. const std::string body =
  13662. "This is the preamble. It is to be ignored, though it\r\n"
  13663. "is a handy place for composition agents to include an\r\n"
  13664. "explanatory note to non-MIME conformant readers.\r\n"
  13665. "\r\n"
  13666. "\r\n"
  13667. "--simple boundary\r\n"
  13668. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13669. ": BAD...\r\n"
  13670. "\r\n"
  13671. "value1\r\n"
  13672. "--simple boundary\r\n"
  13673. "Content-Disposition: form-data; name=\"field2\"; "
  13674. "filename=\"example.txt\"\r\n"
  13675. "\r\n"
  13676. "value2\r\n"
  13677. "--simple boundary--\r\n"
  13678. "This is the epilogue. It is also to be ignored.\r\n";
  13679. std::string content_type =
  13680. R"(multipart/form-data; boundary="simple boundary")";
  13681. Client cli(HOST, PORT);
  13682. auto res = cli.Post("/post", body, content_type.c_str());
  13683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13684. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13685. }
  13686. TEST(MultipartFormDataTest, WithPreamble) {
  13687. Server svr;
  13688. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13689. res.set_content("ok", "text/plain");
  13690. });
  13691. thread t = thread([&] { svr.listen(HOST, PORT); });
  13692. auto se = detail::scope_exit([&] {
  13693. svr.stop();
  13694. t.join();
  13695. ASSERT_FALSE(svr.is_running());
  13696. });
  13697. svr.wait_until_ready();
  13698. const std::string body =
  13699. "This is the preamble. It is to be ignored, though it\r\n"
  13700. "is a handy place for composition agents to include an\r\n"
  13701. "explanatory note to non-MIME conformant readers.\r\n"
  13702. "\r\n"
  13703. "\r\n"
  13704. "--simple boundary\r\n"
  13705. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13706. "\r\n"
  13707. "value1\r\n"
  13708. "--simple boundary\r\n"
  13709. "Content-Disposition: form-data; name=\"field2\"; "
  13710. "filename=\"example.txt\"\r\n"
  13711. "\r\n"
  13712. "value2\r\n"
  13713. "--simple boundary--\r\n"
  13714. "This is the epilogue. It is also to be ignored.\r\n";
  13715. std::string content_type =
  13716. R"(multipart/form-data; boundary="simple boundary")";
  13717. Client cli(HOST, PORT);
  13718. auto res = cli.Post("/post", body, content_type.c_str());
  13719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13720. EXPECT_EQ(StatusCode::OK_200, res->status);
  13721. }
  13722. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13723. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13724. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13725. const ContentReader &content_reader) {
  13726. if (req.is_multipart_form_data()) {
  13727. std::vector<FormData> items;
  13728. content_reader(
  13729. [&](const FormData &file) {
  13730. items.push_back(file);
  13731. return true;
  13732. },
  13733. [&](const char *data, size_t data_length) {
  13734. items.back().content.append(data, data_length);
  13735. return true;
  13736. });
  13737. EXPECT_TRUE(std::string(items[0].name) == "document");
  13738. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13739. EXPECT_TRUE(items[0].filename == "2MB_data");
  13740. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13741. EXPECT_TRUE(items[1].name == "hello");
  13742. EXPECT_TRUE(items[1].content == "world");
  13743. EXPECT_TRUE(items[1].filename == "");
  13744. EXPECT_TRUE(items[1].content_type == "");
  13745. } else {
  13746. std::string body;
  13747. content_reader([&](const char *data, size_t data_length) {
  13748. body.append(data, data_length);
  13749. return true;
  13750. });
  13751. }
  13752. });
  13753. auto port = svr.bind_to_any_port("localhost");
  13754. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13755. auto se = detail::scope_exit([&] {
  13756. svr.stop();
  13757. t.join();
  13758. ASSERT_FALSE(svr.is_running());
  13759. });
  13760. svr.wait_until_ready();
  13761. {
  13762. std::string data(1024 * 1024 * 2, '.');
  13763. std::stringstream buffer;
  13764. buffer << data;
  13765. SSLClient cli("localhost", port);
  13766. cli.enable_server_certificate_verification(false);
  13767. UploadFormDataItems items{
  13768. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13769. {"hello", "world", "", ""},
  13770. };
  13771. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13773. ASSERT_EQ(StatusCode::OK_200, res->status);
  13774. }
  13775. }
  13776. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13777. std::string data(1024 * 1024 * 2, '&');
  13778. std::stringstream buffer;
  13779. buffer << data;
  13780. Client cli("https://localhost:8080");
  13781. UploadFormDataItems items{
  13782. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13783. {"hello", "world", "", ""},
  13784. };
  13785. for (const char &c : " \t\r\n") {
  13786. auto res =
  13787. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13788. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13789. ASSERT_FALSE(res);
  13790. }
  13791. }
  13792. TEST(MultipartFormDataTest, PutFormData) {
  13793. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13794. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13795. const ContentReader &content_reader) {
  13796. if (req.is_multipart_form_data()) {
  13797. std::vector<FormData> items;
  13798. content_reader(
  13799. [&](const FormData &file) {
  13800. items.push_back(file);
  13801. return true;
  13802. },
  13803. [&](const char *data, size_t data_length) {
  13804. items.back().content.append(data, data_length);
  13805. return true;
  13806. });
  13807. EXPECT_TRUE(std::string(items[0].name) == "document");
  13808. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13809. EXPECT_TRUE(items[0].filename == "2MB_data");
  13810. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13811. EXPECT_TRUE(items[1].name == "hello");
  13812. EXPECT_TRUE(items[1].content == "world");
  13813. EXPECT_TRUE(items[1].filename == "");
  13814. EXPECT_TRUE(items[1].content_type == "");
  13815. } else {
  13816. std::string body;
  13817. content_reader([&](const char *data, size_t data_length) {
  13818. body.append(data, data_length);
  13819. return true;
  13820. });
  13821. }
  13822. });
  13823. auto port = svr.bind_to_any_port("localhost");
  13824. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13825. auto se = detail::scope_exit([&] {
  13826. svr.stop();
  13827. t.join();
  13828. ASSERT_FALSE(svr.is_running());
  13829. });
  13830. svr.wait_until_ready();
  13831. {
  13832. std::string data(1024 * 1024 * 2, '&');
  13833. std::stringstream buffer;
  13834. buffer << data;
  13835. SSLClient cli("localhost", port);
  13836. cli.enable_server_certificate_verification(false);
  13837. UploadFormDataItems items{
  13838. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13839. {"hello", "world", "", ""},
  13840. };
  13841. auto res = cli.Put("/put", items);
  13842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13843. ASSERT_EQ(StatusCode::OK_200, res->status);
  13844. }
  13845. }
  13846. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13848. svr.Put("/put_customboundary",
  13849. [&](const Request &req, const Response & /*res*/,
  13850. const ContentReader &content_reader) {
  13851. if (req.is_multipart_form_data()) {
  13852. std::vector<FormData> items;
  13853. content_reader(
  13854. [&](const FormData &file) {
  13855. items.push_back(file);
  13856. return true;
  13857. },
  13858. [&](const char *data, size_t data_length) {
  13859. items.back().content.append(data, data_length);
  13860. return true;
  13861. });
  13862. EXPECT_TRUE(std::string(items[0].name) == "document");
  13863. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13864. EXPECT_TRUE(items[0].filename == "2MB_data");
  13865. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13866. EXPECT_TRUE(items[1].name == "hello");
  13867. EXPECT_TRUE(items[1].content == "world");
  13868. EXPECT_TRUE(items[1].filename == "");
  13869. EXPECT_TRUE(items[1].content_type == "");
  13870. } else {
  13871. std::string body;
  13872. content_reader([&](const char *data, size_t data_length) {
  13873. body.append(data, data_length);
  13874. return true;
  13875. });
  13876. }
  13877. });
  13878. auto port = svr.bind_to_any_port("localhost");
  13879. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13880. auto se = detail::scope_exit([&] {
  13881. svr.stop();
  13882. t.join();
  13883. ASSERT_FALSE(svr.is_running());
  13884. });
  13885. svr.wait_until_ready();
  13886. {
  13887. std::string data(1024 * 1024 * 2, '&');
  13888. std::stringstream buffer;
  13889. buffer << data;
  13890. SSLClient cli("localhost", port);
  13891. cli.enable_server_certificate_verification(false);
  13892. UploadFormDataItems items{
  13893. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13894. {"hello", "world", "", ""},
  13895. };
  13896. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13898. ASSERT_EQ(StatusCode::OK_200, res->status);
  13899. }
  13900. }
  13901. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13902. std::string data(1024 * 1024 * 2, '&');
  13903. std::stringstream buffer;
  13904. buffer << data;
  13905. Client cli("https://localhost:8080");
  13906. cli.enable_server_certificate_verification(false);
  13907. UploadFormDataItems items{
  13908. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13909. {"hello", "world", "", ""},
  13910. };
  13911. for (const char &c : " \t\r\n") {
  13912. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13913. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13914. ASSERT_FALSE(res);
  13915. }
  13916. }
  13917. TEST(MultipartFormDataTest, AlternateFilename) {
  13918. auto handled = false;
  13919. Server svr;
  13920. svr.Post("/test", [&](const Request &req, Response &res) {
  13921. ASSERT_EQ(2u, req.form.files.size());
  13922. ASSERT_EQ(1u, req.form.fields.size());
  13923. // Test files
  13924. const auto &file1 = req.form.get_file("file1");
  13925. ASSERT_EQ("file1", file1.name);
  13926. ASSERT_EQ("A.txt", file1.filename);
  13927. ASSERT_EQ("text/plain", file1.content_type);
  13928. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13929. const auto &file2 = req.form.get_file("file2");
  13930. ASSERT_EQ("file2", file2.name);
  13931. ASSERT_EQ("a.html", file2.filename);
  13932. ASSERT_EQ("text/html", file2.content_type);
  13933. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13934. file2.content);
  13935. // Test text field
  13936. const auto &text = req.form.get_field("text");
  13937. ASSERT_EQ("text default", text);
  13938. res.set_content("ok", "text/plain");
  13939. handled = true;
  13940. });
  13941. thread t = thread([&] { svr.listen(HOST, PORT); });
  13942. auto se = detail::scope_exit([&] {
  13943. svr.stop();
  13944. t.join();
  13945. ASSERT_FALSE(svr.is_running());
  13946. ASSERT_TRUE(handled);
  13947. });
  13948. svr.wait_until_ready();
  13949. auto req = "POST /test HTTP/1.1\r\n"
  13950. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13951. "Content-Length: 399\r\n"
  13952. "\r\n"
  13953. "----------\r\n"
  13954. "Content-Disposition: form-data; name=\"text\"\r\n"
  13955. "\r\n"
  13956. "text default\r\n"
  13957. "----------\r\n"
  13958. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13959. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13960. "Content-Type: text/plain\r\n"
  13961. "\r\n"
  13962. "Content of a.txt.\r\n"
  13963. "\r\n"
  13964. "----------\r\n"
  13965. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13966. "\"a.html\"\r\n"
  13967. "Content-Type: text/html\r\n"
  13968. "\r\n"
  13969. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13970. "\r\n"
  13971. "------------\r\n";
  13972. ASSERT_TRUE(send_request(1, req));
  13973. }
  13974. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13975. auto handled = false;
  13976. Server svr;
  13977. svr.Post("/test", [&](const Request &req, Response &res) {
  13978. // Case-insensitive "utf-8''" prefix with a long value
  13979. const auto &file = req.form.get_file("file1");
  13980. ASSERT_EQ("file1", file.name);
  13981. // 8000 chars exercises both the Content-Disposition parser and the
  13982. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13983. // Prior to the fix, std::regex_match on this header would cause O(N)
  13984. // stack recursion in libstdc++, leading to SIGSEGV.
  13985. std::string expected_filename(8000, 'A');
  13986. ASSERT_EQ(expected_filename, file.filename);
  13987. res.set_content("ok", "text/plain");
  13988. handled = true;
  13989. });
  13990. thread t = thread([&] { svr.listen(HOST, PORT); });
  13991. auto se = detail::scope_exit([&] {
  13992. svr.stop();
  13993. t.join();
  13994. ASSERT_FALSE(svr.is_running());
  13995. ASSERT_TRUE(handled);
  13996. });
  13997. svr.wait_until_ready();
  13998. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13999. // Regression test for GHSA-qq6v-r583-3h69
  14000. std::string long_filename(8000, 'A');
  14001. std::string body = "----------\r\n"
  14002. "Content-Disposition: form-data; name=\"file1\"; "
  14003. "filename*=\"Utf-8''" +
  14004. long_filename +
  14005. "\"\r\n"
  14006. "\r\n"
  14007. "hello\r\n"
  14008. "------------\r\n";
  14009. auto req = "POST /test HTTP/1.1\r\n"
  14010. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14011. "Content-Length: " +
  14012. std::to_string(body.size()) + "\r\n\r\n" + body;
  14013. ASSERT_TRUE(send_request(1, req));
  14014. }
  14015. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14016. auto handled = false;
  14017. Server svr;
  14018. svr.Post("/test", [&](const Request &req, Response &) {
  14019. ASSERT_EQ(2u, req.form.fields.size());
  14020. const auto &text1 = req.form.get_field("text1");
  14021. ASSERT_EQ("text1", text1);
  14022. const auto &text2 = req.form.get_field("text2");
  14023. ASSERT_EQ("text2", text2);
  14024. handled = true;
  14025. });
  14026. thread t = thread([&] { svr.listen(HOST, PORT); });
  14027. auto se = detail::scope_exit([&] {
  14028. svr.stop();
  14029. t.join();
  14030. ASSERT_FALSE(svr.is_running());
  14031. ASSERT_TRUE(handled);
  14032. });
  14033. svr.wait_until_ready();
  14034. auto req = "POST /test HTTP/1.1\r\n"
  14035. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14036. "Content-Length: 146\r\n"
  14037. "\r\n----------\r\n"
  14038. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14039. "\r\n"
  14040. "text1"
  14041. "\r\n----------\r\n"
  14042. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14043. "\r\n"
  14044. "text2"
  14045. "\r\n------------";
  14046. std::string response;
  14047. ASSERT_TRUE(send_request(1, req, &response));
  14048. ASSERT_EQ("200", response.substr(9, 3));
  14049. }
  14050. TEST(MultipartFormDataTest, ContentLength) {
  14051. auto handled = false;
  14052. Server svr;
  14053. svr.Post("/test", [&](const Request &req, Response &) {
  14054. ASSERT_EQ(2u, req.form.fields.size());
  14055. const auto &text1 = req.form.get_field("text1");
  14056. ASSERT_EQ("text1", text1);
  14057. const auto &text2 = req.form.get_field("text2");
  14058. ASSERT_EQ("text2", text2);
  14059. handled = true;
  14060. });
  14061. thread t = thread([&] { svr.listen(HOST, PORT); });
  14062. auto se = detail::scope_exit([&] {
  14063. svr.stop();
  14064. t.join();
  14065. ASSERT_FALSE(svr.is_running());
  14066. ASSERT_TRUE(handled);
  14067. });
  14068. svr.wait_until_ready();
  14069. auto req = "POST /test HTTP/1.1\r\n"
  14070. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14071. "Content-Length: 167\r\n"
  14072. "\r\n----------\r\n"
  14073. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14074. "Content-Length: 5\r\n"
  14075. "\r\n"
  14076. "text1"
  14077. "\r\n----------\r\n"
  14078. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14079. "\r\n"
  14080. "text2"
  14081. "\r\n------------\r\n";
  14082. std::string response;
  14083. ASSERT_TRUE(send_request(1, req, &response));
  14084. ASSERT_EQ("200", response.substr(9, 3));
  14085. }
  14086. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14087. auto handled = false;
  14088. Server svr;
  14089. svr.Post("/test", [&](const Request &req, Response &) {
  14090. ASSERT_EQ(2u, req.form.fields.size());
  14091. const auto &text1 = req.form.get_field("text1");
  14092. ASSERT_EQ("text1", text1);
  14093. // TODO: Add header access for text fields if needed
  14094. const auto &text2 = req.form.get_field("text2");
  14095. ASSERT_EQ("text2", text2);
  14096. // TODO: Header access for text fields needs to be implemented
  14097. // auto &headers = it->second.headers;
  14098. // ASSERT_EQ(3U, headers.size());
  14099. // auto custom_header = headers.find("x-whatever");
  14100. // ASSERT_TRUE(custom_header != headers.end());
  14101. // ASSERT_NE("customvalue", custom_header->second);
  14102. // ASSERT_EQ("CustomValue", custom_header->second);
  14103. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14104. handled = true;
  14105. });
  14106. thread t = thread([&] { svr.listen(HOST, PORT); });
  14107. auto se = detail::scope_exit([&] {
  14108. svr.stop();
  14109. t.join();
  14110. ASSERT_FALSE(svr.is_running());
  14111. ASSERT_TRUE(handled);
  14112. });
  14113. svr.wait_until_ready();
  14114. auto req = "POST /test HTTP/1.1\r\n"
  14115. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14116. "Content-Length: 232\r\n"
  14117. "\r\n----------\r\n"
  14118. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14119. "Content-Length: 5\r\n"
  14120. "X-Test: 1\r\n"
  14121. "\r\n"
  14122. "text1"
  14123. "\r\n----------\r\n"
  14124. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14125. "Content-Type: text/plain\r\n"
  14126. "X-Whatever: CustomValue\r\n"
  14127. "\r\n"
  14128. "text2"
  14129. "\r\n------------\r\n"
  14130. "That should be disregarded. Not even read";
  14131. std::string response;
  14132. ASSERT_TRUE(send_request(1, req, &response));
  14133. ASSERT_EQ("200", response.substr(9, 3));
  14134. }
  14135. TEST(MultipartFormDataTest, LargeHeader) {
  14136. auto handled = false;
  14137. Server svr;
  14138. svr.Post("/test", [&](const Request &req, Response &) {
  14139. ASSERT_EQ(1u, req.form.fields.size());
  14140. const auto &text = req.form.get_field("name1");
  14141. ASSERT_EQ("text1", text);
  14142. handled = true;
  14143. });
  14144. thread t = thread([&] { svr.listen(HOST, PORT); });
  14145. auto se = detail::scope_exit([&] {
  14146. svr.stop();
  14147. t.join();
  14148. ASSERT_FALSE(svr.is_running());
  14149. ASSERT_TRUE(handled);
  14150. });
  14151. svr.wait_until_ready();
  14152. auto boundary = std::string("cpp-httplib-multipart-data");
  14153. std::string content = "--" + boundary +
  14154. "\r\n"
  14155. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14156. "\r\n"
  14157. "text1\r\n"
  14158. "--" +
  14159. boundary + "--\r\n";
  14160. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14161. "Content-Type: multipart/form-data;boundary=" +
  14162. boundary +
  14163. "\r\n"
  14164. "Content-Length: " +
  14165. std::to_string(content.size()) +
  14166. "\r\n"
  14167. "Dummy-Header: ";
  14168. std::string header_suffix = "\r\n"
  14169. "\r\n";
  14170. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14171. size_t header_dummy_size =
  14172. read_buff_size -
  14173. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14174. auto header_dummy = std::string(header_dummy_size, '@');
  14175. auto req = header_prefix + header_dummy + header_suffix + content;
  14176. std::string response;
  14177. ASSERT_TRUE(send_request(1, req, &response));
  14178. ASSERT_EQ("200", response.substr(9, 3));
  14179. }
  14180. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14181. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14182. // (not chunked Transfer-Encoding) after the streaming refactor.
  14183. auto handled = false;
  14184. Server svr;
  14185. svr.Post("/upload", [&](const Request &req, Response &res) {
  14186. auto cl_it = req.headers.find("Content-Length");
  14187. EXPECT_TRUE(cl_it != req.headers.end());
  14188. auto te_it = req.headers.find("Transfer-Encoding");
  14189. EXPECT_TRUE(te_it == req.headers.end());
  14190. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14191. res.set_content("ok", "text/plain");
  14192. handled = true;
  14193. });
  14194. auto port = svr.bind_to_any_port(HOST);
  14195. auto t = thread([&] { svr.listen_after_bind(); });
  14196. auto se = detail::scope_exit([&] {
  14197. svr.stop();
  14198. t.join();
  14199. ASSERT_FALSE(svr.is_running());
  14200. ASSERT_TRUE(handled);
  14201. });
  14202. svr.wait_until_ready();
  14203. UploadFormDataItems items = {
  14204. {"field1", "hello", "", "text/plain"},
  14205. {"file1", "world", "test.txt", "application/octet-stream"},
  14206. };
  14207. Client cli(HOST, port);
  14208. auto res = cli.Post("/upload", {}, items);
  14209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14210. EXPECT_EQ(StatusCode::OK_200, res->status);
  14211. }
  14212. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14213. // Verify that make_multipart_content_provider coalesces many small segments
  14214. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14215. constexpr size_t kItemCount = 1000;
  14216. UploadFormDataItems items;
  14217. items.reserve(kItemCount);
  14218. for (size_t i = 0; i < kItemCount; i++) {
  14219. items.push_back(
  14220. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14221. }
  14222. const std::string boundary = "----test-boundary";
  14223. auto content_length = detail::get_multipart_content_length(items, boundary);
  14224. auto provider = detail::make_multipart_content_provider(items, boundary);
  14225. // Drive the provider the same way write_content_with_progress does
  14226. size_t write_count = 0;
  14227. size_t total_bytes = 0;
  14228. DataSink sink;
  14229. size_t offset = 0;
  14230. sink.write = [&](const char *d, size_t l) -> bool {
  14231. (void)d;
  14232. write_count++;
  14233. total_bytes += l;
  14234. offset += l;
  14235. return true;
  14236. };
  14237. sink.is_writable = []() -> bool { return true; };
  14238. while (offset < content_length) {
  14239. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14240. }
  14241. EXPECT_EQ(content_length, total_bytes);
  14242. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14243. // With buffering into 64KB blocks, write_count should be much smaller.
  14244. auto segment_count = 3 * kItemCount + 1;
  14245. EXPECT_LT(write_count, segment_count / 10);
  14246. }
  14247. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14248. // Integration test: send many UploadFormDataItems and verify the server
  14249. // receives all of them correctly (#2410).
  14250. constexpr size_t kItemCount = 500;
  14251. auto handled = false;
  14252. Server svr;
  14253. svr.Post("/upload", [&](const Request &req, Response &res) {
  14254. EXPECT_EQ(kItemCount, req.form.fields.size());
  14255. for (size_t i = 0; i < kItemCount; i++) {
  14256. auto key = "field" + std::to_string(i);
  14257. auto val = "value" + std::to_string(i);
  14258. auto it = req.form.fields.find(key);
  14259. if (it != req.form.fields.end()) {
  14260. EXPECT_EQ(val, it->second.content);
  14261. } else {
  14262. ADD_FAILURE() << "Missing field: " << key;
  14263. }
  14264. }
  14265. res.set_content("ok", "text/plain");
  14266. handled = true;
  14267. });
  14268. auto port = svr.bind_to_any_port(HOST);
  14269. auto t = thread([&] { svr.listen_after_bind(); });
  14270. auto se = detail::scope_exit([&] {
  14271. svr.stop();
  14272. t.join();
  14273. ASSERT_FALSE(svr.is_running());
  14274. ASSERT_TRUE(handled);
  14275. });
  14276. svr.wait_until_ready();
  14277. UploadFormDataItems items;
  14278. items.reserve(kItemCount);
  14279. for (size_t i = 0; i < kItemCount; i++) {
  14280. items.push_back(
  14281. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14282. }
  14283. Client cli(HOST, port);
  14284. auto res = cli.Post("/upload", items);
  14285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14286. EXPECT_EQ(StatusCode::OK_200, res->status);
  14287. }
  14288. TEST(MultipartFormDataTest, MakeFileProvider) {
  14289. // Verify make_file_provider sends a file's contents correctly.
  14290. const std::string file_content(4096, 'Z');
  14291. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14292. {
  14293. std::ofstream ofs(tmp_path, std::ios::binary);
  14294. ofs.write(file_content.data(),
  14295. static_cast<std::streamsize>(file_content.size()));
  14296. }
  14297. auto handled = false;
  14298. Server svr;
  14299. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14300. const ContentReader &content_reader) {
  14301. ASSERT_TRUE(req.is_multipart_form_data());
  14302. std::vector<FormData> items;
  14303. content_reader(
  14304. [&](const FormData &file) {
  14305. items.push_back(file);
  14306. return true;
  14307. },
  14308. [&](const char *data, size_t data_length) {
  14309. items.back().content.append(data, data_length);
  14310. return true;
  14311. });
  14312. ASSERT_EQ(1u, items.size());
  14313. EXPECT_EQ("myfile", items[0].name);
  14314. EXPECT_EQ("data.bin", items[0].filename);
  14315. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14316. EXPECT_EQ(file_content, items[0].content);
  14317. handled = true;
  14318. });
  14319. auto port = svr.bind_to_any_port(HOST);
  14320. auto t = thread([&] { svr.listen_after_bind(); });
  14321. auto se = detail::scope_exit([&] {
  14322. svr.stop();
  14323. t.join();
  14324. ASSERT_FALSE(svr.is_running());
  14325. ASSERT_TRUE(handled);
  14326. std::remove(tmp_path.c_str());
  14327. });
  14328. svr.wait_until_ready();
  14329. FormDataProviderItems providers;
  14330. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14331. "application/octet-stream"));
  14332. Client cli(HOST, port);
  14333. auto res = cli.Post("/upload", {}, {}, providers);
  14334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14335. EXPECT_EQ(StatusCode::OK_200, res->status);
  14336. }
  14337. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14338. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14339. // (100) headers is rejected with a 400 Bad Request response.
  14340. Server svr;
  14341. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14342. res.set_content("ok", "text/plain");
  14343. });
  14344. thread t = thread([&] { svr.listen(HOST, PORT); });
  14345. auto se = detail::scope_exit([&] {
  14346. svr.stop();
  14347. t.join();
  14348. ASSERT_FALSE(svr.is_running());
  14349. });
  14350. svr.wait_until_ready();
  14351. // Build a multipart part with 101 custom headers (exceeding
  14352. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14353. std::stringstream body;
  14354. body << "--simpleboundary\r\n"
  14355. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14356. for (int i = 0; i < 101; i++) {
  14357. body << "X-Custom-Header-" << i << ": value\r\n";
  14358. }
  14359. body << "\r\n"
  14360. << "value1\r\n"
  14361. << "--simpleboundary--\r\n";
  14362. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14363. Client cli(HOST, PORT);
  14364. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14366. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14367. }
  14368. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14369. // A body that never contains the declared boundary must not be accumulated
  14370. // while the parser waits for it. Buffering it would also make every read
  14371. // rescan everything seen so far, which is quadratic in the body size.
  14372. Server svr;
  14373. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14374. res.set_content("ok", "text/plain");
  14375. });
  14376. auto port = svr.bind_to_any_port(HOST);
  14377. thread t = thread([&] { svr.listen_after_bind(); });
  14378. auto se = detail::scope_exit([&] {
  14379. svr.stop();
  14380. t.join();
  14381. ASSERT_FALSE(svr.is_running());
  14382. });
  14383. svr.wait_until_ready();
  14384. Client cli(HOST, port);
  14385. cli.set_read_timeout(60, 0);
  14386. cli.set_write_timeout(60, 0);
  14387. // '-' is the worst case: it matches the first character of the boundary, so
  14388. // every position has to be checked against it.
  14389. auto post_dashes = [&](size_t size) {
  14390. const std::string body(size, '-');
  14391. auto start = std::chrono::steady_clock::now();
  14392. auto res =
  14393. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14394. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14395. std::chrono::steady_clock::now() - start)
  14396. .count();
  14397. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14398. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14399. return ms;
  14400. };
  14401. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14402. // Windows.
  14403. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14404. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14405. // Comparing the two sizes rather than checking an absolute duration keeps
  14406. // this meaningful across build types and CI load, both of which move the
  14407. // absolute numbers by more than an order of magnitude. Four times the bytes
  14408. // costs about four times the time when parsing is linear, and about sixteen
  14409. // times when the body is buffered and rescanned.
  14410. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14411. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14412. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14413. << "ms, which suggests the body is being buffered and rescanned";
  14414. }
  14415. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14416. // A boundary can only be followed by CRLF or by "--", so anything else is
  14417. // malformed no matter what comes next. The parser must say so right away
  14418. // instead of buffering the rest of the declared body.
  14419. Server svr;
  14420. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14421. res.set_content("ok", "text/plain");
  14422. });
  14423. auto port = svr.bind_to_any_port(HOST);
  14424. thread t = thread([&] { svr.listen_after_bind(); });
  14425. auto se = detail::scope_exit([&] {
  14426. svr.stop();
  14427. t.join();
  14428. ASSERT_FALSE(svr.is_running());
  14429. });
  14430. svr.wait_until_ready();
  14431. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14432. // buffers instead of failing would still be waiting for the remaining bytes.
  14433. const std::string body = "--zzzz\r\n"
  14434. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14435. "\r\n"
  14436. "text1"
  14437. "\r\n--zzzzXX";
  14438. const std::string req = "POST /post HTTP/1.1\r\n"
  14439. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14440. "Content-Length: 1048576\r\n"
  14441. "\r\n" +
  14442. body;
  14443. std::string response;
  14444. ASSERT_TRUE(send_request(3, req, &response, port));
  14445. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14446. EXPECT_EQ("400", response.substr(9, 3));
  14447. }
  14448. // Posts a multipart body split into two writes, so that the server sees the
  14449. // split at whatever offset the caller chose, and expects the single "text1"
  14450. // field to come through.
  14451. static void expect_split_multipart_ok(const std::string &body1,
  14452. const std::string &body2) {
  14453. auto handled = false;
  14454. Server svr;
  14455. svr.Post("/post", [&](const Request &req, Response &) {
  14456. EXPECT_EQ(1u, req.form.fields.size());
  14457. EXPECT_EQ("text1", req.form.get_field("text1"));
  14458. handled = true;
  14459. });
  14460. auto port = svr.bind_to_any_port(HOST);
  14461. thread t = thread([&] { svr.listen_after_bind(); });
  14462. auto se = detail::scope_exit([&] {
  14463. svr.stop();
  14464. t.join();
  14465. ASSERT_FALSE(svr.is_running());
  14466. ASSERT_TRUE(handled);
  14467. });
  14468. svr.wait_until_ready();
  14469. // "Connection: close" makes the server close once it has answered, so the
  14470. // response drain ends immediately instead of idling until the read timeout.
  14471. const std::string head =
  14472. "POST /post HTTP/1.1\r\n"
  14473. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14474. "Connection: close\r\n"
  14475. "Content-Length: " +
  14476. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14477. std::string response;
  14478. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14479. ASSERT_GE(response.size(), 12u) << "no response";
  14480. EXPECT_EQ("200", response.substr(9, 3));
  14481. }
  14482. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14483. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14484. // ignored, including when it does not arrive in the same read as the
  14485. // close-delimiter itself.
  14486. expect_split_multipart_ok("--zzzz\r\n"
  14487. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14488. "\r\n"
  14489. "text1"
  14490. "\r\n--zzzz--",
  14491. "\r\nthis epilogue must be ignored\r\n");
  14492. }
  14493. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14494. // The initial boundary may be preceded by a preamble of any length and may
  14495. // straddle a read boundary. Discarding data while waiting for it must not
  14496. // throw away a partial boundary sitting at the end of the buffer.
  14497. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14498. "zz\r\n"
  14499. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14500. "\r\n"
  14501. "text1"
  14502. "\r\n--zzzz--\r\n");
  14503. }
  14504. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14505. // The received boundary was only checked for being non-empty, so it could be
  14506. // as long as a header is allowed to be. The parser scans the body for
  14507. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14508. // costs a nearly full comparison at nearly every position, making the
  14509. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14510. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14511. Server svr;
  14512. svr.Post("/post", [](const Request &req, Response &res) {
  14513. EXPECT_EQ(1u, req.form.fields.size());
  14514. EXPECT_EQ("text1", req.form.get_field("text1"));
  14515. res.set_content("ok", "text/plain");
  14516. });
  14517. auto port = svr.bind_to_any_port(HOST);
  14518. thread t = 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. Client cli(HOST, port);
  14526. auto post_with_boundary_of_length = [&](size_t len) {
  14527. const std::string boundary(len, 'a');
  14528. const std::string body =
  14529. "--" + boundary +
  14530. "\r\n"
  14531. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14532. "\r\n"
  14533. "text1"
  14534. "\r\n--" +
  14535. boundary + "--\r\n";
  14536. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14537. };
  14538. auto res = post_with_boundary_of_length(70);
  14539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14540. EXPECT_EQ(StatusCode::OK_200, res->status);
  14541. res = post_with_boundary_of_length(71);
  14542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14543. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14544. }
  14545. TEST(MakeFileBodyTest, Basic) {
  14546. const std::string file_content(4096, 'Z');
  14547. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14548. {
  14549. std::ofstream ofs(tmp_path, std::ios::binary);
  14550. ofs.write(file_content.data(),
  14551. static_cast<std::streamsize>(file_content.size()));
  14552. }
  14553. auto handled = false;
  14554. Server svr;
  14555. svr.Post("/upload", [&](const Request &req, Response &res) {
  14556. EXPECT_EQ(file_content, req.body);
  14557. handled = true;
  14558. res.status = StatusCode::OK_200;
  14559. });
  14560. auto port = svr.bind_to_any_port(HOST);
  14561. auto t = thread([&] { svr.listen_after_bind(); });
  14562. auto se = detail::scope_exit([&] {
  14563. svr.stop();
  14564. t.join();
  14565. ASSERT_FALSE(svr.is_running());
  14566. ASSERT_TRUE(handled);
  14567. std::remove(tmp_path.c_str());
  14568. });
  14569. svr.wait_until_ready();
  14570. auto fb = make_file_body(tmp_path);
  14571. ASSERT_GT(fb.first, 0u);
  14572. Client cli(HOST, port);
  14573. auto res =
  14574. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14576. EXPECT_EQ(StatusCode::OK_200, res->status);
  14577. }
  14578. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14579. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14580. {
  14581. std::ofstream ofs(path, std::ios::binary);
  14582. const std::string content(100, 'A');
  14583. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14584. }
  14585. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14586. auto body = make_file_body(path);
  14587. ASSERT_EQ(100u, body.first);
  14588. ASSERT_TRUE(static_cast<bool>(body.second));
  14589. // Rewritten shorter after its length was measured - and, on a server, after
  14590. // that length has already gone out as Content-Length.
  14591. {
  14592. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14593. const std::string content(10, 'A');
  14594. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14595. }
  14596. std::string written;
  14597. DataSink sink;
  14598. sink.write = [&](const char *d, size_t l) {
  14599. written.append(d, l);
  14600. return true;
  14601. };
  14602. // The provider has to report failure. write_content_with_progress() advances
  14603. // its offset only by what was written, so a provider that returns true
  14604. // without completing the length it promised is called again straight away,
  14605. // and again.
  14606. EXPECT_FALSE(body.second(0, body.first, sink));
  14607. EXPECT_EQ(std::string(10, 'A'), written);
  14608. }
  14609. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14610. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14611. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14612. {
  14613. std::ofstream ofs(path, std::ios::binary);
  14614. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14615. }
  14616. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14617. auto body = make_file_body(path);
  14618. ASSERT_EQ(content.size(), body.first);
  14619. ASSERT_TRUE(static_cast<bool>(body.second));
  14620. std::string written;
  14621. DataSink sink;
  14622. sink.write = [&](const char *d, size_t l) {
  14623. written.append(d, l);
  14624. return true;
  14625. };
  14626. EXPECT_TRUE(body.second(0, body.first, sink));
  14627. EXPECT_EQ(content, written);
  14628. }
  14629. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14630. static constexpr unsigned int number_of_tasks{1000000};
  14631. std::atomic_uint count{0};
  14632. std::unique_ptr<TaskQueue> task_queue{
  14633. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14634. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14635. auto queued = task_queue->enqueue(
  14636. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14637. EXPECT_TRUE(queued);
  14638. }
  14639. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14640. task_queue->shutdown();
  14641. #else
  14642. EXPECT_NO_THROW(task_queue->shutdown());
  14643. #endif
  14644. EXPECT_EQ(number_of_tasks, count.load());
  14645. }
  14646. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14647. static constexpr unsigned int number_of_tasks{1000000};
  14648. static constexpr unsigned int qlimit{2};
  14649. unsigned int queued_count{0};
  14650. std::atomic_uint count{0};
  14651. std::unique_ptr<TaskQueue> task_queue{
  14652. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14653. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14654. if (task_queue->enqueue(
  14655. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14656. queued_count++;
  14657. }
  14658. }
  14659. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14660. task_queue->shutdown();
  14661. #else
  14662. EXPECT_NO_THROW(task_queue->shutdown());
  14663. #endif
  14664. EXPECT_EQ(queued_count, count.load());
  14665. EXPECT_TRUE(queued_count <= number_of_tasks);
  14666. EXPECT_TRUE(queued_count >= qlimit);
  14667. }
  14668. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14669. // Use a short idle timeout so a dynamic thread spawns, times out and
  14670. // exits during the test, and the pool keeps working afterwards.
  14671. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14672. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14673. /*idle_timeout_sec=*/1}};
  14674. std::atomic_uint count{0};
  14675. std::condition_variable cv;
  14676. std::mutex mtx;
  14677. bool release = false;
  14678. // Block the base thread so the second task spawns a dynamic thread.
  14679. EXPECT_TRUE(task_queue->enqueue([&] {
  14680. std::unique_lock<std::mutex> lock(mtx);
  14681. while (!release) {
  14682. cv.wait(lock);
  14683. }
  14684. count++;
  14685. }));
  14686. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14687. // Let the dynamic thread finish its task and exceed the idle timeout.
  14688. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14689. {
  14690. std::unique_lock<std::mutex> lock(mtx);
  14691. release = true;
  14692. }
  14693. cv.notify_all();
  14694. // The pool must still accept and run tasks after the dynamic thread exited.
  14695. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14696. task_queue->shutdown();
  14697. EXPECT_EQ(3u, count.load());
  14698. }
  14699. TEST(TaskQueueTest, MaxQueuedRequests) {
  14700. static constexpr unsigned int qlimit{3};
  14701. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14702. std::condition_variable sem_cv;
  14703. std::mutex sem_mtx;
  14704. int credits = 0;
  14705. bool queued;
  14706. /* Fill up the queue with tasks that will block until we give them credits to
  14707. * complete. */
  14708. for (unsigned int n = 0; n <= qlimit;) {
  14709. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14710. std::unique_lock<std::mutex> lock(sem_mtx);
  14711. while (credits <= 0) {
  14712. sem_cv.wait(lock);
  14713. }
  14714. /* Consume the credit and signal the test code if they are all gone. */
  14715. if (--credits == 0) { sem_cv.notify_one(); }
  14716. });
  14717. if (n < qlimit) {
  14718. /* The first qlimit enqueues must succeed. */
  14719. EXPECT_TRUE(queued);
  14720. } else {
  14721. /* The last one will succeed only when the worker thread
  14722. * starts and dequeues the first blocking task. Although
  14723. * not necessary for the correctness of this test, we sleep for
  14724. * a short while to avoid busy waiting. */
  14725. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14726. }
  14727. if (queued) { n++; }
  14728. }
  14729. /* Further enqueues must fail since the queue is full. */
  14730. for (auto i = 0; i < 4; i++) {
  14731. queued = task_queue->enqueue([] {});
  14732. EXPECT_FALSE(queued);
  14733. }
  14734. /* Give the credits to allow the previous tasks to complete. */
  14735. {
  14736. std::unique_lock<std::mutex> lock(sem_mtx);
  14737. credits += qlimit + 1;
  14738. }
  14739. sem_cv.notify_all();
  14740. /* Wait for all the credits to be consumed. */
  14741. {
  14742. std::unique_lock<std::mutex> lock(sem_mtx);
  14743. while (credits > 0) {
  14744. sem_cv.wait(lock);
  14745. }
  14746. }
  14747. /* Check that we are able again to enqueue at least qlimit tasks. */
  14748. for (unsigned int i = 0; i < qlimit; i++) {
  14749. queued = task_queue->enqueue([] {});
  14750. EXPECT_TRUE(queued);
  14751. }
  14752. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14753. task_queue->shutdown();
  14754. #else
  14755. EXPECT_NO_THROW(task_queue->shutdown());
  14756. #endif
  14757. }
  14758. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  14759. Server svr;
  14760. std::string method;
  14761. std::string body;
  14762. auto has_content_length = false;
  14763. auto has_transfer_encoding = false;
  14764. std::atomic<int> bad_requests{0};
  14765. // Leftover body bytes get parsed as a malformed request and answered with
  14766. // 400
  14767. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  14768. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  14769. });
  14770. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  14771. res.set_redirect("/down", StatusCode::SeeOther_303);
  14772. });
  14773. svr.Get("/down", [&](const Request &req, Response &res) {
  14774. method = req.method;
  14775. body = req.body;
  14776. has_content_length = req.has_header("Content-Length");
  14777. has_transfer_encoding = req.has_header("Transfer-Encoding");
  14778. res.set_content("ok", "text/plain");
  14779. });
  14780. auto port = svr.bind_to_any_port(HOST);
  14781. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14782. auto se = detail::scope_exit([&] {
  14783. svr.stop();
  14784. thread.join();
  14785. ASSERT_FALSE(svr.is_running());
  14786. });
  14787. svr.wait_until_ready();
  14788. const std::string payload = "SECRET-BODY";
  14789. auto check = [&](Client &cli, const Result &res) {
  14790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14791. EXPECT_EQ(StatusCode::OK_200, res->status);
  14792. EXPECT_EQ("ok", res->body);
  14793. EXPECT_EQ("GET", method);
  14794. EXPECT_TRUE(body.empty());
  14795. EXPECT_FALSE(has_content_length);
  14796. EXPECT_FALSE(has_transfer_encoding);
  14797. // Nothing of the original body may be left on the connection
  14798. auto res2 = cli.Get("/down");
  14799. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  14800. EXPECT_EQ(StatusCode::OK_200, res2->status);
  14801. EXPECT_EQ("ok", res2->body);
  14802. EXPECT_EQ(0, bad_requests);
  14803. };
  14804. // With content length
  14805. {
  14806. Client cli(HOST, port);
  14807. cli.set_keep_alive(true);
  14808. cli.set_follow_location(true);
  14809. auto res = cli.Post(
  14810. "/up", payload.size(),
  14811. [&](size_t offset, size_t length, DataSink &sink) {
  14812. return sink.write(payload.data() + offset, length);
  14813. },
  14814. "text/plain");
  14815. check(cli, res);
  14816. }
  14817. // Without content length (chunked)
  14818. {
  14819. Client cli(HOST, port);
  14820. cli.set_keep_alive(true);
  14821. cli.set_follow_location(true);
  14822. auto res = cli.Post(
  14823. "/up",
  14824. [&](size_t /*offset*/, DataSink &sink) {
  14825. sink.write(payload.data(), payload.size());
  14826. sink.done();
  14827. return true;
  14828. },
  14829. "text/plain");
  14830. check(cli, res);
  14831. }
  14832. }
  14833. TEST(RedirectTest, LocationPathIsNotDecoded) {
  14834. Server svr;
  14835. std::string target;
  14836. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  14837. // Echo the still-encoded name back in the Location
  14838. const std::string prefix = "/start/";
  14839. res.status = StatusCode::Found_302;
  14840. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  14841. });
  14842. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  14843. target = req.target;
  14844. res.set_content("ok", "text/plain");
  14845. });
  14846. auto port = svr.bind_to_any_port(HOST);
  14847. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14848. auto se = detail::scope_exit([&] {
  14849. svr.stop();
  14850. thread.join();
  14851. ASSERT_FALSE(svr.is_running());
  14852. });
  14853. svr.wait_until_ready();
  14854. // Decoding the Location path would turn the first four into a path
  14855. // separator, a query delimiter, a fragment delimiter and a different
  14856. // percent-encoded octet. The rest must keep reaching the server as they are.
  14857. const std::vector<std::string> names = {
  14858. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  14859. };
  14860. for (auto path_encode : {true, false}) {
  14861. Client cli(HOST, port);
  14862. cli.set_follow_location(true);
  14863. cli.set_path_encode(path_encode);
  14864. for (const auto &name : names) {
  14865. target.clear();
  14866. auto res = cli.Get("/start/" + name);
  14867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14868. EXPECT_EQ(StatusCode::OK_200, res->status);
  14869. EXPECT_EQ("/dest/" + name, target);
  14870. }
  14871. }
  14872. }
  14873. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14874. Server svr;
  14875. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14876. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14877. });
  14878. svr.Get("/hello", [](const Request &req, Response &res) {
  14879. res.set_content(req.get_param_value("key"), "text/plain");
  14880. });
  14881. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14882. auto se = detail::scope_exit([&] {
  14883. svr.stop();
  14884. thread.join();
  14885. ASSERT_FALSE(svr.is_running());
  14886. });
  14887. svr.wait_until_ready();
  14888. {
  14889. Client cli(HOST, PORT);
  14890. cli.set_follow_location(true);
  14891. auto res = cli.Get("/");
  14892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14893. EXPECT_EQ(StatusCode::OK_200, res->status);
  14894. EXPECT_EQ("val&key2=val2", res->body);
  14895. }
  14896. }
  14897. #endif
  14898. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14899. Server svr;
  14900. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14901. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14902. });
  14903. svr.Get("/hello", [](const Request &req, Response &res) {
  14904. res.set_content(req.get_param_value("key"), "text/plain");
  14905. });
  14906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14907. auto se = detail::scope_exit([&] {
  14908. svr.stop();
  14909. thread.join();
  14910. ASSERT_FALSE(svr.is_running());
  14911. });
  14912. svr.wait_until_ready();
  14913. {
  14914. Client cli(HOST, PORT);
  14915. cli.set_follow_location(true);
  14916. auto res = cli.Get("/");
  14917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14918. EXPECT_EQ(StatusCode::OK_200, res->status);
  14919. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14920. }
  14921. }
  14922. TEST(RedirectTest, RedirectWithPlusInPath) {
  14923. Server svr;
  14924. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14925. res.set_redirect("/a+b");
  14926. });
  14927. // Route pattern uses regex; escape + as \\+
  14928. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14929. res.set_content(req.path, "text/plain");
  14930. });
  14931. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14932. auto se = detail::scope_exit([&] {
  14933. svr.stop();
  14934. thread.join();
  14935. ASSERT_FALSE(svr.is_running());
  14936. });
  14937. svr.wait_until_ready();
  14938. {
  14939. Client cli(HOST, PORT);
  14940. cli.set_follow_location(true);
  14941. auto res = cli.Get("/");
  14942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14943. EXPECT_EQ(StatusCode::OK_200, res->status);
  14944. EXPECT_EQ("/a+b", res->body);
  14945. }
  14946. }
  14947. TEST(RedirectTest, ResolveRelativeLocation) {
  14948. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14949. const std::vector<std::pair<std::string, std::string>> cases = {
  14950. {"g", "/b/c/g"},
  14951. {"./g", "/b/c/g"},
  14952. {"g/", "/b/c/g/"},
  14953. {"?y", "/b/c/d;p?y"},
  14954. {"g?y", "/b/c/g?y"},
  14955. {"#s", "/b/c/d;p?q#s"},
  14956. {"g#s", "/b/c/g#s"},
  14957. {"g?y#s", "/b/c/g?y#s"},
  14958. {";x", "/b/c/;x"},
  14959. {"g;x", "/b/c/g;x"},
  14960. {".", "/b/c/"},
  14961. {"./", "/b/c/"},
  14962. {"..", "/b/"},
  14963. {"../", "/b/"},
  14964. {"../g", "/b/g"},
  14965. {"../..", "/"},
  14966. {"../../", "/"},
  14967. {"../../g", "/g"},
  14968. {"../../../g", "/g"},
  14969. {"g.", "/b/c/g."},
  14970. {".g", "/b/c/.g"},
  14971. {"g..", "/b/c/g.."},
  14972. {"..g", "/b/c/..g"},
  14973. {"./../g", "/b/g"},
  14974. {"./g/.", "/b/c/g/"},
  14975. {"g/./h", "/b/c/g/h"},
  14976. {"g/../h", "/b/c/h"},
  14977. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14978. {"g;x=1/../y", "/b/c/y"},
  14979. {"g?y/./x", "/b/c/g?y/./x"},
  14980. {"g#s/../x", "/b/c/g#s/../x"},
  14981. // Not relative-path references, so left for parse_url.
  14982. {"/g", "/g"},
  14983. {"//g", "//g"},
  14984. {"http://g/x", "http://g/x"},
  14985. {"g:h", "g:h"},
  14986. };
  14987. for (const auto &c : cases) {
  14988. EXPECT_EQ(c.second,
  14989. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  14990. << c.first;
  14991. }
  14992. }
  14993. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  14994. Server svr;
  14995. svr.Get("/dir/page", [](const Request &req, Response &res) {
  14996. res.set_redirect(req.get_param_value("to"));
  14997. });
  14998. svr.Get("/dir/next", [](const Request &req, Response &res) {
  14999. res.set_content(req.target, "text/plain");
  15000. });
  15001. svr.Get("/other", [](const Request &req, Response &res) {
  15002. res.set_content(req.target, "text/plain");
  15003. });
  15004. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15005. auto se = detail::scope_exit([&] {
  15006. svr.stop();
  15007. thread.join();
  15008. ASSERT_FALSE(svr.is_running());
  15009. });
  15010. svr.wait_until_ready();
  15011. const std::vector<std::pair<std::string, std::string>> cases = {
  15012. {"next", "/dir/next"},
  15013. {"./next?x=1", "/dir/next?x=1"},
  15014. {"../other", "/other"},
  15015. };
  15016. for (const auto &c : cases) {
  15017. Client cli(HOST, PORT);
  15018. cli.set_follow_location(true);
  15019. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15020. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15021. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15022. EXPECT_EQ(c.second, res->body) << c.first;
  15023. }
  15024. }
  15025. #ifdef CPPHTTPLIB_SSL_ENABLED
  15026. TEST(RedirectTest, Issue2185_Online) {
  15027. SSLClient client("github.com");
  15028. client.set_follow_location(true);
  15029. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15030. "Coollab-Windows.zip");
  15031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15032. EXPECT_EQ(StatusCode::OK_200, res->status);
  15033. EXPECT_EQ(9920427U, res->body.size());
  15034. }
  15035. #endif
  15036. TEST(VulnerabilityTest, CRLFInjection) {
  15037. Server svr;
  15038. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15039. res.set_content("Hello 1", "text/plain");
  15040. });
  15041. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15042. res.set_content("Hello 2", "text/plain");
  15043. });
  15044. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15045. res.set_content("Hello 3", "text/plain");
  15046. });
  15047. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15048. res.set_content("Hello 4", "text/plain");
  15049. });
  15050. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15051. for (const auto &x : req.headers) {
  15052. auto key = x.first;
  15053. EXPECT_STRNE("evil", key.c_str());
  15054. }
  15055. });
  15056. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15057. auto se = detail::scope_exit([&] {
  15058. svr.stop();
  15059. thread.join();
  15060. ASSERT_FALSE(svr.is_running());
  15061. });
  15062. svr.wait_until_ready();
  15063. {
  15064. Client cli(HOST, PORT);
  15065. cli.Post("/test1", "A=B",
  15066. "application/x-www-form-urlencoded\r\nevil: hello1");
  15067. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15068. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15069. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15070. }
  15071. }
  15072. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15073. auto server_thread = std::thread([] {
  15074. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15075. default_socket_options(srv);
  15076. sockaddr_in addr{};
  15077. addr.sin_family = AF_INET;
  15078. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15079. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15080. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15081. ::listen(srv, 1);
  15082. sockaddr_in cli_addr{};
  15083. socklen_t cli_len = sizeof(cli_addr);
  15084. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15085. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15086. std::string buf_all;
  15087. char buf[2048];
  15088. ssize_t n;
  15089. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15090. buf_all.append(buf, static_cast<size_t>(n));
  15091. size_t pos;
  15092. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15093. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15094. auto e = request_block.find("\r\n");
  15095. if (e != std::string::npos) {
  15096. auto request_line = request_block.substr(0, e);
  15097. std::string msg =
  15098. "CRLF injection detected in request line: '" + request_line + "'";
  15099. EXPECT_FALSE(true) << msg;
  15100. }
  15101. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15102. ::send(cli,
  15103. #ifdef _WIN32
  15104. static_cast<const char *>(resp.c_str()),
  15105. static_cast<int>(resp.size()),
  15106. #else
  15107. resp.c_str(), resp.size(),
  15108. #endif
  15109. 0);
  15110. buf_all.erase(0, pos + 4);
  15111. }
  15112. }
  15113. detail::close_socket(cli);
  15114. detail::close_socket(srv);
  15115. });
  15116. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15117. auto cli = Client("127.0.0.1", PORT + 1);
  15118. auto headers = Headers{
  15119. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15120. {"Connection", "keep-alive"}};
  15121. auto res = cli.Get("/hi", headers);
  15122. EXPECT_FALSE(res);
  15123. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15124. server_thread.join();
  15125. }
  15126. // A request rejected before any byte reaches the socket must fail right away
  15127. // instead of waiting for a response the server will never send.
  15128. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15129. // The kernel completes the TCP handshake from the listen backlog, so the
  15130. // client connects, but nothing ever reads, responds or closes.
  15131. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15132. default_socket_options(srv);
  15133. sockaddr_in addr{};
  15134. addr.sin_family = AF_INET;
  15135. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15136. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15137. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15138. ASSERT_EQ(0, ::listen(srv, 8));
  15139. auto cli = Client("127.0.0.1", PORT + 1);
  15140. cli.set_read_timeout(10, 0);
  15141. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15142. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15143. std::chrono::steady_clock::now() - start)
  15144. .count();
  15145. };
  15146. {
  15147. Request req;
  15148. req.method = "GE T";
  15149. req.path = "/";
  15150. auto start = std::chrono::steady_clock::now();
  15151. auto res = cli.send(req);
  15152. EXPECT_FALSE(res);
  15153. EXPECT_EQ(Error::Write, res.error());
  15154. EXPECT_LT(elapsed_ms(start), 1000);
  15155. }
  15156. {
  15157. auto start = std::chrono::steady_clock::now();
  15158. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15159. EXPECT_FALSE(res);
  15160. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15161. EXPECT_LT(elapsed_ms(start), 1000);
  15162. }
  15163. EXPECT_FALSE(cli.is_socket_open());
  15164. detail::close_socket(srv);
  15165. }
  15166. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15167. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15168. default_socket_options(srv);
  15169. sockaddr_in addr{};
  15170. addr.sin_family = AF_INET;
  15171. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15172. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15173. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15174. ASSERT_EQ(0, ::listen(srv, 1));
  15175. std::string received;
  15176. auto server_thread = std::thread([&] {
  15177. auto sock = ::accept(srv, nullptr, nullptr);
  15178. if (sock == INVALID_SOCKET) { return; }
  15179. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15180. char buf[2048];
  15181. ssize_t n;
  15182. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15183. received.append(buf, static_cast<size_t>(n));
  15184. }
  15185. detail::close_socket(sock);
  15186. });
  15187. {
  15188. auto cli = Client("127.0.0.1", PORT + 1);
  15189. // "Z" sorts after the default headers, so writing straight to the socket
  15190. // would have sent the request line and those headers before the rejection.
  15191. auto handle =
  15192. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15193. EXPECT_FALSE(handle.is_valid());
  15194. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15195. }
  15196. server_thread.join();
  15197. detail::close_socket(srv);
  15198. EXPECT_TRUE(received.empty()) << received;
  15199. }
  15200. TEST(PathParamsTest, StaticMatch) {
  15201. const auto pattern = "/users/all";
  15202. detail::PathParamsMatcher matcher(pattern);
  15203. Request request;
  15204. request.path = "/users/all";
  15205. ASSERT_TRUE(matcher.match(request));
  15206. std::unordered_map<std::string, std::string> expected_params = {};
  15207. EXPECT_EQ(request.path_params, expected_params);
  15208. }
  15209. TEST(PathParamsTest, StaticMismatch) {
  15210. const auto pattern = "/users/all";
  15211. detail::PathParamsMatcher matcher(pattern);
  15212. Request request;
  15213. request.path = "/users/1";
  15214. ASSERT_FALSE(matcher.match(request));
  15215. }
  15216. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15217. const auto pattern = "/users/:id/subscriptions";
  15218. detail::PathParamsMatcher matcher(pattern);
  15219. Request request;
  15220. request.path = "/users/42/subscriptions";
  15221. ASSERT_TRUE(matcher.match(request));
  15222. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15223. EXPECT_EQ(request.path_params, expected_params);
  15224. }
  15225. TEST(PathParamsTest, SingleParamInTheEnd) {
  15226. const auto pattern = "/users/:id";
  15227. detail::PathParamsMatcher matcher(pattern);
  15228. Request request;
  15229. request.path = "/users/24";
  15230. ASSERT_TRUE(matcher.match(request));
  15231. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15232. EXPECT_EQ(request.path_params, expected_params);
  15233. }
  15234. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15235. const auto pattern = "/users/:id/";
  15236. detail::PathParamsMatcher matcher(pattern);
  15237. Request request;
  15238. request.path = "/users/42/";
  15239. ASSERT_TRUE(matcher.match(request));
  15240. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15241. EXPECT_EQ(request.path_params, expected_params);
  15242. }
  15243. TEST(PathParamsTest, EmptyParam) {
  15244. const auto pattern = "/users/:id/";
  15245. detail::PathParamsMatcher matcher(pattern);
  15246. Request request;
  15247. request.path = "/users//";
  15248. ASSERT_TRUE(matcher.match(request));
  15249. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15250. EXPECT_EQ(request.path_params, expected_params);
  15251. }
  15252. TEST(PathParamsTest, FragmentMismatch) {
  15253. const auto pattern = "/users/:id/";
  15254. detail::PathParamsMatcher matcher(pattern);
  15255. Request request;
  15256. request.path = "/admins/24/";
  15257. ASSERT_FALSE(matcher.match(request));
  15258. }
  15259. TEST(PathParamsTest, ExtraFragments) {
  15260. const auto pattern = "/users/:id";
  15261. detail::PathParamsMatcher matcher(pattern);
  15262. Request request;
  15263. request.path = "/users/42/subscriptions";
  15264. ASSERT_FALSE(matcher.match(request));
  15265. }
  15266. TEST(PathParamsTest, MissingTrailingParam) {
  15267. const auto pattern = "/users/:id";
  15268. detail::PathParamsMatcher matcher(pattern);
  15269. Request request;
  15270. request.path = "/users";
  15271. ASSERT_FALSE(matcher.match(request));
  15272. }
  15273. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15274. const auto pattern = "/users/:id/subscriptions";
  15275. detail::PathParamsMatcher matcher(pattern);
  15276. Request request;
  15277. request.path = "/users/subscriptions";
  15278. ASSERT_FALSE(matcher.match(request));
  15279. }
  15280. TEST(PathParamsTest, MultipleParams) {
  15281. const auto pattern = "/users/:userid/subscriptions/:subid";
  15282. detail::PathParamsMatcher matcher(pattern);
  15283. Request request;
  15284. request.path = "/users/42/subscriptions/2";
  15285. ASSERT_TRUE(matcher.match(request));
  15286. std::unordered_map<std::string, std::string> expected_params = {
  15287. {"userid", "42"}, {"subid", "2"}};
  15288. EXPECT_EQ(request.path_params, expected_params);
  15289. }
  15290. TEST(PathParamsTest, SequenceOfParams) {
  15291. const auto pattern = "/values/:x/:y/:z";
  15292. detail::PathParamsMatcher matcher(pattern);
  15293. Request request;
  15294. request.path = "/values/1/2/3";
  15295. ASSERT_TRUE(matcher.match(request));
  15296. std::unordered_map<std::string, std::string> expected_params = {
  15297. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15298. EXPECT_EQ(request.path_params, expected_params);
  15299. }
  15300. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15301. const auto pattern = "/prefix:suffix";
  15302. detail::PathParamsMatcher matcher(pattern);
  15303. Request request;
  15304. request.path = "/prefix:suffix";
  15305. ASSERT_TRUE(matcher.match(request));
  15306. const std::unordered_map<std::string, std::string> expected_params = {};
  15307. EXPECT_EQ(request.path_params, expected_params);
  15308. }
  15309. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15310. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15311. // calling thread's stack on a long enough path for a quantified pattern;
  15312. // RegexMatcher must refuse to run regex matching on paths beyond
  15313. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15314. detail::RegexMatcher matcher("/files/(.*)");
  15315. Request within_limit;
  15316. within_limit.path = "/files/" + std::string(10, 'A');
  15317. EXPECT_TRUE(matcher.match(within_limit));
  15318. Request over_limit;
  15319. over_limit.path =
  15320. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15321. EXPECT_FALSE(matcher.match(over_limit));
  15322. }
  15323. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15324. Server svr;
  15325. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15326. res.set_content("ok", "text/plain");
  15327. });
  15328. auto port = svr.bind_to_any_port(HOST);
  15329. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15330. auto se = detail::scope_exit([&] {
  15331. svr.stop();
  15332. thread.join();
  15333. ASSERT_FALSE(svr.is_running());
  15334. });
  15335. svr.wait_until_ready();
  15336. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15337. // request URI limit; this used to be able to crash the process.
  15338. std::string path =
  15339. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15340. std::string req = "GET " + path +
  15341. " HTTP/1.1\r\n"
  15342. "Host: " +
  15343. std::string(HOST) + ":" + std::to_string(port) +
  15344. "\r\n"
  15345. "Connection: close\r\n"
  15346. "\r\n";
  15347. std::string response;
  15348. ASSERT_TRUE(send_request(5, req, &response, port));
  15349. EXPECT_NE(std::string::npos, response.find("404"));
  15350. }
  15351. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15352. Server svr;
  15353. auto handler = [](const Request & /*req*/, Response &res) {
  15354. res.set_content("hit", "text/plain");
  15355. };
  15356. // No regex metacharacter, so this one is compared literally
  15357. svr.Get("/literal/route", handler);
  15358. // '.' is a regex metacharacter, so this one must keep regex semantics
  15359. svr.Get("/a.c", handler);
  15360. auto port = svr.bind_to_any_port(HOST);
  15361. std::thread t([&]() { svr.listen_after_bind(); });
  15362. auto se = detail::scope_exit([&] {
  15363. svr.stop();
  15364. t.join();
  15365. ASSERT_FALSE(svr.is_running());
  15366. });
  15367. svr.wait_until_ready();
  15368. Client cli(HOST, port);
  15369. struct {
  15370. const char *path;
  15371. int status;
  15372. } cases[] = {
  15373. {"/literal/route", StatusCode::OK_200},
  15374. {"/literal/routes", StatusCode::NotFound_404},
  15375. {"/literal/rout", StatusCode::NotFound_404},
  15376. {"/abc", StatusCode::OK_200},
  15377. {"/a.c", StatusCode::OK_200},
  15378. };
  15379. for (const auto &x : cases) {
  15380. auto res = cli.Get(x.path);
  15381. ASSERT_TRUE(res) << x.path;
  15382. EXPECT_EQ(x.status, res->status) << x.path;
  15383. }
  15384. }
  15385. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15386. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15387. // from exhausting the stack, so it must only constrain routes that actually
  15388. // run a regular expression. A literal route is matched by comparison and
  15389. // stays usable at any length.
  15390. Server svr;
  15391. const std::string pattern =
  15392. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15393. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15394. res.set_content("hit", "text/plain");
  15395. });
  15396. auto port = svr.bind_to_any_port(HOST);
  15397. std::thread t([&]() { svr.listen_after_bind(); });
  15398. auto se = detail::scope_exit([&] {
  15399. svr.stop();
  15400. t.join();
  15401. ASSERT_FALSE(svr.is_running());
  15402. });
  15403. svr.wait_until_ready();
  15404. Client cli(HOST, port);
  15405. auto res = cli.Get(pattern);
  15406. ASSERT_TRUE(res);
  15407. EXPECT_EQ(StatusCode::OK_200, res->status);
  15408. }
  15409. TEST(ParseUrlTest, VariousPatterns) {
  15410. {
  15411. detail::UrlComponents uc;
  15412. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15413. EXPECT_EQ("http", uc.scheme);
  15414. EXPECT_EQ("example.com", uc.host);
  15415. EXPECT_EQ("8080", uc.port);
  15416. EXPECT_EQ("/path", uc.path);
  15417. EXPECT_EQ("?q=1", uc.query);
  15418. }
  15419. {
  15420. detail::UrlComponents uc;
  15421. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15422. EXPECT_EQ("https", uc.scheme);
  15423. EXPECT_EQ("example.com", uc.host);
  15424. EXPECT_TRUE(uc.port.empty());
  15425. EXPECT_EQ("/path", uc.path);
  15426. }
  15427. {
  15428. detail::UrlComponents uc;
  15429. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15430. EXPECT_EQ("::1", uc.host);
  15431. EXPECT_EQ("8080", uc.port);
  15432. EXPECT_EQ("/path", uc.path);
  15433. }
  15434. {
  15435. detail::UrlComponents uc;
  15436. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15437. }
  15438. {
  15439. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15440. // the path while the connection still targets the bracketed host.
  15441. detail::UrlComponents uc;
  15442. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15443. }
  15444. {
  15445. detail::UrlComponents uc;
  15446. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15447. }
  15448. {
  15449. detail::UrlComponents uc;
  15450. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15451. EXPECT_EQ("::1", uc.host);
  15452. EXPECT_TRUE(uc.port.empty());
  15453. EXPECT_EQ("/path", uc.path);
  15454. }
  15455. {
  15456. detail::UrlComponents uc;
  15457. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15458. EXPECT_TRUE(uc.scheme.empty());
  15459. EXPECT_EQ("example.com", uc.host);
  15460. EXPECT_EQ("/path", uc.path);
  15461. EXPECT_EQ("?q=1", uc.query);
  15462. }
  15463. {
  15464. detail::UrlComponents uc;
  15465. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15466. EXPECT_TRUE(uc.host.empty());
  15467. EXPECT_EQ("/path", uc.path);
  15468. EXPECT_EQ("?q=1", uc.query);
  15469. }
  15470. {
  15471. detail::UrlComponents uc;
  15472. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15473. EXPECT_EQ("example.com", uc.host);
  15474. EXPECT_EQ("8080", uc.port);
  15475. }
  15476. {
  15477. // Unix socket path — must not be parsed as host
  15478. detail::UrlComponents uc;
  15479. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15480. EXPECT_TRUE(uc.host.empty());
  15481. }
  15482. {
  15483. detail::UrlComponents uc;
  15484. ASSERT_TRUE(detail::parse_url("", uc));
  15485. EXPECT_TRUE(uc.host.empty());
  15486. EXPECT_TRUE(uc.path.empty());
  15487. }
  15488. {
  15489. detail::UrlComponents uc;
  15490. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15491. }
  15492. {
  15493. detail::UrlComponents uc;
  15494. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15495. }
  15496. {
  15497. // Accepted by parse_url; callers restrict to http/https
  15498. detail::UrlComponents uc;
  15499. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15500. EXPECT_EQ("ftp", uc.scheme);
  15501. }
  15502. {
  15503. detail::UrlComponents uc;
  15504. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15505. }
  15506. {
  15507. detail::UrlComponents uc;
  15508. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15509. }
  15510. }
  15511. TEST(ParseUrlTest, FragmentHandling) {
  15512. {
  15513. detail::UrlComponents uc;
  15514. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15515. EXPECT_EQ("/path", uc.path);
  15516. EXPECT_TRUE(uc.query.empty());
  15517. }
  15518. {
  15519. detail::UrlComponents uc;
  15520. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15521. EXPECT_TRUE(uc.path.empty());
  15522. EXPECT_TRUE(uc.query.empty());
  15523. }
  15524. }
  15525. TEST(ParseUrlTest, UserinfoHandling) {
  15526. // Userinfo with @ but no colon — host includes @
  15527. detail::UrlComponents uc;
  15528. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15529. EXPECT_EQ("user@host.com", uc.host);
  15530. EXPECT_EQ("/path", uc.path);
  15531. }
  15532. TEST(ParseUrlTest, IPv6EdgeCases) {
  15533. {
  15534. detail::UrlComponents uc;
  15535. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15536. EXPECT_TRUE(uc.scheme.empty());
  15537. EXPECT_EQ("::1", uc.host);
  15538. EXPECT_EQ("8080", uc.port);
  15539. }
  15540. {
  15541. // Zone ID '%25' is not in [a-fA-F0-9:]
  15542. detail::UrlComponents uc;
  15543. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15544. }
  15545. }
  15546. TEST(ParseUrlTest, SchemeEdgeCases) {
  15547. {
  15548. detail::UrlComponents uc;
  15549. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15550. }
  15551. {
  15552. detail::UrlComponents uc;
  15553. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15554. }
  15555. {
  15556. detail::UrlComponents uc;
  15557. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15558. }
  15559. }
  15560. TEST(ParseUrlTest, PortEdgeCases) {
  15561. {
  15562. detail::UrlComponents uc;
  15563. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15564. EXPECT_TRUE(uc.port.empty());
  15565. EXPECT_EQ("/path", uc.path);
  15566. }
  15567. {
  15568. // parse_url accepts any port string; validation is done by parse_port
  15569. detail::UrlComponents uc;
  15570. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15571. EXPECT_EQ("abc", uc.port);
  15572. }
  15573. }
  15574. TEST(ParseUrlTest, WebSocketPatterns) {
  15575. {
  15576. detail::UrlComponents uc;
  15577. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15578. EXPECT_EQ("ws", uc.scheme);
  15579. EXPECT_EQ("echo.example.com", uc.host);
  15580. EXPECT_EQ("8080", uc.port);
  15581. EXPECT_EQ("/ws", uc.path);
  15582. }
  15583. {
  15584. detail::UrlComponents uc;
  15585. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15586. EXPECT_EQ("wss", uc.scheme);
  15587. EXPECT_EQ("echo.example.com", uc.host);
  15588. EXPECT_TRUE(uc.port.empty());
  15589. EXPECT_EQ("/ws", uc.path);
  15590. }
  15591. }
  15592. TEST(ParseUrlTest, QueryOnly) {
  15593. detail::UrlComponents uc;
  15594. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15595. EXPECT_TRUE(uc.host.empty());
  15596. EXPECT_TRUE(uc.path.empty());
  15597. EXPECT_EQ("?q=1&r=2", uc.query);
  15598. }
  15599. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15600. detail::UrlComponents uc;
  15601. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15602. EXPECT_TRUE(uc.scheme.empty());
  15603. EXPECT_EQ("example.com", uc.host);
  15604. EXPECT_EQ("443", uc.port);
  15605. EXPECT_EQ("/path", uc.path);
  15606. }
  15607. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15608. // If ipv6 regex working, regex match codepath is taken.
  15609. // else port will default to 80 in Client impl
  15610. int clientImplMagicPort = 80;
  15611. int port = 4321;
  15612. // above ports must be different to avoid false negative
  15613. EXPECT_NE(clientImplMagicPort, port);
  15614. std::string ipV6TestURL = "http://[ff06::c3]";
  15615. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15616. CLIENT_PRIVATE_KEY_FILE);
  15617. EXPECT_EQ(cli.port(), port);
  15618. }
  15619. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15620. auto file_path = "./www/dir/index.html";
  15621. auto dir_path = "./www/dir";
  15622. detail::FileStat stat_file(file_path);
  15623. EXPECT_TRUE(stat_file.is_file());
  15624. EXPECT_FALSE(stat_file.is_dir());
  15625. detail::FileStat stat_dir(dir_path);
  15626. EXPECT_FALSE(stat_dir.is_file());
  15627. EXPECT_TRUE(stat_dir.is_dir());
  15628. }
  15629. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15630. // IPv4 with default HTTP port (80)
  15631. EXPECT_EQ("example.com",
  15632. detail::make_host_and_port_string("example.com", 80, false));
  15633. // IPv4 with default HTTPS port (443)
  15634. EXPECT_EQ("example.com",
  15635. detail::make_host_and_port_string("example.com", 443, true));
  15636. // IPv4 with non-default HTTP port
  15637. EXPECT_EQ("example.com:8080",
  15638. detail::make_host_and_port_string("example.com", 8080, false));
  15639. // IPv4 with non-default HTTPS port
  15640. EXPECT_EQ("example.com:8443",
  15641. detail::make_host_and_port_string("example.com", 8443, true));
  15642. // IPv6 with default HTTP port (80)
  15643. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15644. // IPv6 with default HTTPS port (443)
  15645. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15646. // IPv6 with non-default HTTP port
  15647. EXPECT_EQ("[::1]:8080",
  15648. detail::make_host_and_port_string("::1", 8080, false));
  15649. // IPv6 with non-default HTTPS port
  15650. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15651. // IPv6 full address with default port
  15652. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15653. detail::make_host_and_port_string(
  15654. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15655. // IPv6 full address with non-default port
  15656. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15657. detail::make_host_and_port_string(
  15658. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15659. // IPv6 localhost with non-default port
  15660. EXPECT_EQ("[::1]:3000",
  15661. detail::make_host_and_port_string("::1", 3000, false));
  15662. // IPv6 with zone ID (link-local address) with default port
  15663. EXPECT_EQ("[fe80::1%eth0]",
  15664. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15665. // IPv6 with zone ID (link-local address) with non-default port
  15666. EXPECT_EQ("[fe80::1%eth0]:8080",
  15667. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15668. // Edge case: Port 443 with is_ssl=false (should add port)
  15669. EXPECT_EQ("example.com:443",
  15670. detail::make_host_and_port_string("example.com", 443, false));
  15671. // Edge case: Port 80 with is_ssl=true (should add port)
  15672. EXPECT_EQ("example.com:80",
  15673. detail::make_host_and_port_string("example.com", 80, true));
  15674. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15675. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15676. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15677. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15678. // Security fix: Already bracketed IPv6 should not get double brackets
  15679. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15680. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15681. EXPECT_EQ("[::1]:8080",
  15682. detail::make_host_and_port_string("[::1]", 8080, false));
  15683. EXPECT_EQ("[2001:db8::1]:8080",
  15684. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15685. EXPECT_EQ("[fe80::1%eth0]",
  15686. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15687. EXPECT_EQ("[fe80::1%eth0]:8080",
  15688. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15689. // Edge case: Empty host (should return as-is)
  15690. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15691. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15692. // This is a known limitation but shouldn't crash
  15693. EXPECT_EQ("[host:name]",
  15694. detail::make_host_and_port_string("host:name", 80, false));
  15695. // Port number edge cases (no validation, but should not crash)
  15696. EXPECT_EQ("example.com:0",
  15697. detail::make_host_and_port_string("example.com", 0, false));
  15698. EXPECT_EQ("example.com:-1",
  15699. detail::make_host_and_port_string("example.com", -1, false));
  15700. EXPECT_EQ("example.com:65535",
  15701. detail::make_host_and_port_string("example.com", 65535, false));
  15702. EXPECT_EQ("example.com:65536",
  15703. detail::make_host_and_port_string("example.com", 65536, false));
  15704. }
  15705. #ifdef CPPHTTPLIB_SSL_ENABLED
  15706. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15707. httplib::SSLClient cli("roblox.com", 443);
  15708. cli.set_follow_location(true);
  15709. auto res = cli.Get("/");
  15710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15711. EXPECT_EQ(StatusCode::OK_200, res->status);
  15712. }
  15713. #endif
  15714. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15715. Server svr;
  15716. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15717. EXPECT_EQ(res.status, 400);
  15718. });
  15719. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15720. auto se = detail::scope_exit([&] {
  15721. svr.stop();
  15722. thread.join();
  15723. ASSERT_FALSE(svr.is_running());
  15724. });
  15725. svr.wait_until_ready();
  15726. Client cli(HOST, PORT);
  15727. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15728. }
  15729. TEST(InvalidHeaderCharsTest, is_field_name) {
  15730. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15731. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15732. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15733. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15734. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15735. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15736. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15737. EXPECT_FALSE(detail::fields::is_field_name(""));
  15738. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15739. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15740. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15741. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15742. }
  15743. TEST(InvalidHeaderCharsTest, is_field_value) {
  15744. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15745. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15746. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15747. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15748. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15749. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15750. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15751. EXPECT_TRUE(detail::fields::is_field_value(""));
  15752. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15753. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15754. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15755. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15756. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15757. }
  15758. TEST(InvalidHeaderCharsTest, OnServer) {
  15759. Server svr;
  15760. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15761. std::string header = "Not Set";
  15762. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15763. res.set_header(header, "value");
  15764. res.set_content("Page Content Page Content", "text/plain");
  15765. });
  15766. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15767. std::string header = "Not Set";
  15768. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15769. res.set_header("X-Test", header);
  15770. res.set_content("Page Content Page Content", "text/plain");
  15771. });
  15772. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15773. auto se = detail::scope_exit([&] {
  15774. svr.stop();
  15775. thread.join();
  15776. ASSERT_FALSE(svr.is_running());
  15777. });
  15778. svr.wait_until_ready();
  15779. Client cli(HOST, PORT);
  15780. {
  15781. auto res = cli.Get(
  15782. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15784. EXPECT_EQ("Page Content Page Content", res->body);
  15785. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15786. }
  15787. {
  15788. auto res = cli.Get(
  15789. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15791. EXPECT_EQ("Page Content Page Content", res->body);
  15792. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15793. }
  15794. }
  15795. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15796. auto handled = false;
  15797. Server svr;
  15798. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15799. thread t = thread([&] { svr.listen(HOST, PORT); });
  15800. auto se = detail::scope_exit([&] {
  15801. svr.stop();
  15802. t.join();
  15803. ASSERT_FALSE(svr.is_running());
  15804. ASSERT_FALSE(handled);
  15805. });
  15806. svr.wait_until_ready();
  15807. auto req = "POST /test HTTP/1.1\r\n"
  15808. "Content-Length: x\r\n"
  15809. "\r\n";
  15810. std::string response;
  15811. ASSERT_TRUE(send_request(1, req, &response));
  15812. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15813. response.substr(0, response.find("\r\n")));
  15814. }
  15815. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15816. // case-insensitive, and a server that receives a 100-continue expectation in
  15817. // an HTTP/1.0 request MUST ignore it.
  15818. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15819. std::string response;
  15820. ASSERT_TRUE(send_request(1, req, &response, port));
  15821. *got_100 = response.find("100 Continue") != std::string::npos;
  15822. }
  15823. class ExpectTokenTest : public ::testing::Test {
  15824. protected:
  15825. void SetUp() override {
  15826. svr_.Post("/p", [](const Request &, Response &res) {
  15827. res.set_content("ok", "text/plain");
  15828. });
  15829. port_ = svr_.bind_to_any_port(HOST);
  15830. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15831. svr_.wait_until_ready();
  15832. }
  15833. void TearDown() override {
  15834. svr_.stop();
  15835. if (thread_.joinable()) { thread_.join(); }
  15836. }
  15837. std::string request(const char *version, const char *expect_value) const {
  15838. return std::string("POST /p ") + version +
  15839. "\r\n"
  15840. "Host: localhost\r\n"
  15841. "Content-Length: 2\r\n"
  15842. "Connection: close\r\n"
  15843. "Expect: " +
  15844. expect_value +
  15845. "\r\n"
  15846. "\r\n"
  15847. "hi";
  15848. }
  15849. Server svr_;
  15850. int port_ = 0;
  15851. thread thread_;
  15852. };
  15853. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15854. bool got_100 = false;
  15855. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15856. EXPECT_TRUE(got_100);
  15857. }
  15858. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15859. bool got_100 = true;
  15860. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15861. EXPECT_FALSE(got_100);
  15862. }
  15863. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15864. bool got_100 = false;
  15865. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15866. EXPECT_TRUE(got_100);
  15867. }
  15868. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15869. bool got_100 = false;
  15870. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15871. EXPECT_TRUE(got_100);
  15872. }
  15873. // `100 Continue` is sent only when the server starts reading the body, so a
  15874. // request rejected before that never invites the client to send it. The
  15875. // requests below carry the expectation but withhold the body, as a client
  15876. // waiting for `100 Continue` would.
  15877. // A POST that expects `100 Continue` and withholds its two-byte body.
  15878. static std::string expect_headers_only(const std::string &path) {
  15879. return "POST " + path +
  15880. " HTTP/1.1\r\n"
  15881. "Host: localhost\r\n"
  15882. "Content-Length: 2\r\n"
  15883. "Expect: 100-continue\r\n"
  15884. "\r\n";
  15885. }
  15886. class ExpectLazyContinueTest : public ::testing::Test {
  15887. protected:
  15888. void SetUp() override {
  15889. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15890. if (req.path == "/pre-routing") {
  15891. res.status = StatusCode::Unauthorized_401;
  15892. return Server::HandlerResponse::Handled;
  15893. }
  15894. return Server::HandlerResponse::Unhandled;
  15895. });
  15896. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15897. if (req.matched_route == "/pre-request") {
  15898. res.status = StatusCode::Forbidden_403;
  15899. return Server::HandlerResponse::Handled;
  15900. }
  15901. return Server::HandlerResponse::Unhandled;
  15902. });
  15903. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15904. res.set_content("ok", "text/plain");
  15905. });
  15906. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15907. res.set_content("ok", "text/plain");
  15908. });
  15909. svr_.Post("/reader-used", [](const Request &, Response &res,
  15910. const ContentReader &content_reader) {
  15911. std::string body;
  15912. content_reader([&](const char *data, size_t len) {
  15913. body.append(data, len);
  15914. return true;
  15915. });
  15916. res.set_content(body, "text/plain");
  15917. });
  15918. svr_.Post("/reader-unused",
  15919. [](const Request &, Response &res, const ContentReader &) {
  15920. res.set_content("ignored", "text/plain");
  15921. });
  15922. port_ = svr_.bind_to_any_port(HOST);
  15923. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15924. svr_.wait_until_ready();
  15925. }
  15926. void TearDown() override {
  15927. svr_.stop();
  15928. if (thread_.joinable()) { thread_.join(); }
  15929. }
  15930. // Sends `req` and reads until the server closes the connection. Returns
  15931. // false if the read had to wait for the client-side timeout instead.
  15932. bool send_until_closed(const std::string &req, std::string *resp) const {
  15933. auto start = std::chrono::steady_clock::now();
  15934. if (!send_request(3, req, resp, port_)) { return false; }
  15935. auto elapsed = std::chrono::steady_clock::now() - start;
  15936. return elapsed < std::chrono::seconds(2);
  15937. }
  15938. // The final response comes without `100 Continue`, and the server closes
  15939. // the connection since the body may or may not follow.
  15940. void expect_final_without_interim(const std::string &path,
  15941. const char *status_line) const {
  15942. std::string resp;
  15943. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15944. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15945. EXPECT_EQ(0u, resp.find(status_line));
  15946. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15947. }
  15948. Server svr_;
  15949. int port_ = 0;
  15950. thread thread_;
  15951. };
  15952. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15953. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15954. }
  15955. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15956. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15957. }
  15958. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15959. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15960. }
  15961. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15962. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15963. }
  15964. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15965. // The body follows once `100 Continue` has had time to arrive.
  15966. auto req = expect_headers_only("/reader-used");
  15967. req.insert(req.size() - 2, "Connection: close\r\n");
  15968. std::string resp;
  15969. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15970. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15971. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15972. EXPECT_NE(std::string::npos, resp.find("hi"));
  15973. }
  15974. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15975. // Large enough for the client to add `Expect: 100-continue` itself.
  15976. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15977. std::atomic<bool> body_sent{false};
  15978. Client cli(HOST, port_);
  15979. auto res = cli.Post(
  15980. "/pre-request", length,
  15981. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15982. body_sent = true;
  15983. std::string chunk(len, 'x');
  15984. sink.write(chunk.data(), chunk.size());
  15985. return true;
  15986. },
  15987. "application/octet-stream");
  15988. ASSERT_TRUE(res);
  15989. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15990. EXPECT_FALSE(body_sent);
  15991. }
  15992. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15993. Server svr;
  15994. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15995. return StatusCode::ExpectationFailed_417;
  15996. });
  15997. svr.Post("/p", [](const Request &, Response &res) {
  15998. res.set_content("ok", "text/plain");
  15999. });
  16000. auto port = svr.bind_to_any_port(HOST);
  16001. thread t = thread([&] { svr.listen_after_bind(); });
  16002. auto se = detail::scope_exit([&] {
  16003. svr.stop();
  16004. t.join();
  16005. });
  16006. svr.wait_until_ready();
  16007. std::string resp;
  16008. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16009. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16010. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16011. // Exactly one response: the route handler must not run after the 417.
  16012. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16013. }
  16014. #ifndef _WIN32
  16015. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16016. static constexpr char reject[] = "Unauthorized";
  16017. static constexpr char accept[] = "Upload accepted";
  16018. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16019. Server svr;
  16020. svr.set_expect_100_continue_handler(
  16021. [](const Request & /*req*/, Response &res) {
  16022. res.status = StatusCode::Unauthorized_401;
  16023. res.set_content(reject, "text/plain");
  16024. return res.status;
  16025. });
  16026. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16027. res.set_content(accept, "text/plain");
  16028. });
  16029. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16030. auto se = detail::scope_exit([&] {
  16031. svr.stop();
  16032. thread.join();
  16033. ASSERT_FALSE(svr.is_running());
  16034. });
  16035. svr.wait_until_ready();
  16036. {
  16037. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16038. curl_easy_init(), &curl_easy_cleanup};
  16039. ASSERT_NE(curl, nullptr);
  16040. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16041. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16042. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16043. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16044. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16045. &curl_slist_free_all};
  16046. ASSERT_NE(list, nullptr);
  16047. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16048. struct read_data {
  16049. size_t read_size;
  16050. size_t total_size;
  16051. } data = {0, total_size};
  16052. using read_callback_t =
  16053. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16054. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16055. void *userdata) -> size_t {
  16056. read_data *d = (read_data *)userdata;
  16057. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16058. std::fill_n(ptr, size * nmemb, 'A');
  16059. d->read_size += size * nmemb;
  16060. return size * nmemb;
  16061. };
  16062. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16063. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16064. std::vector<char> buffer;
  16065. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16066. using write_callback_t =
  16067. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16068. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16069. void *userdata) -> size_t {
  16070. std::vector<char> *buf = (std::vector<char> *)userdata;
  16071. buf->reserve(buf->size() + size * nmemb + 1);
  16072. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16073. return size * nmemb;
  16074. };
  16075. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16076. {
  16077. const auto res = curl_easy_perform(curl.get());
  16078. ASSERT_EQ(res, CURLE_OK);
  16079. }
  16080. {
  16081. auto response_code = long{};
  16082. const auto res =
  16083. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16084. ASSERT_EQ(res, CURLE_OK);
  16085. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16086. }
  16087. {
  16088. auto dl = curl_off_t{};
  16089. const auto res =
  16090. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16091. ASSERT_EQ(res, CURLE_OK);
  16092. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16093. }
  16094. {
  16095. buffer.push_back('\0');
  16096. ASSERT_STRCASEEQ(buffer.data(), reject);
  16097. }
  16098. }
  16099. }
  16100. #endif
  16101. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16102. // Regression test for #2458.
  16103. //
  16104. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16105. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16106. // ticket can make the client socket spuriously readable during the
  16107. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16108. // the client withholds the body and then blocks reading a response that never
  16109. // comes, failing with `Failed to read connection`.
  16110. //
  16111. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16112. // within the timeout. This raw OpenSSL server deliberately never sends
  16113. // `100 Continue`; the client must still deliver the body and receive 200.
  16114. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16115. signal(SIGPIPE, SIG_IGN);
  16116. const auto port = PORT + 4;
  16117. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16118. ASSERT_NE(srv, INVALID_SOCKET);
  16119. int opt = 1;
  16120. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16121. sockaddr_in addr{};
  16122. addr.sin_family = AF_INET;
  16123. addr.sin_port = htons(static_cast<uint16_t>(port));
  16124. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16125. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16126. ASSERT_EQ(0, ::listen(srv, 1));
  16127. std::atomic<size_t> server_body_bytes{0};
  16128. auto server_thread = std::thread([&] {
  16129. sockaddr_in cli_addr{};
  16130. socklen_t cli_len = sizeof(cli_addr);
  16131. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16132. if (cli == INVALID_SOCKET) { return; }
  16133. // Bound the lifetime of the server side so a buggy client (which never
  16134. // sends the body) cannot make this thread block forever on join.
  16135. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16136. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16137. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16138. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16139. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16140. SSL *ssl = SSL_new(ctx);
  16141. SSL_set_fd(ssl, static_cast<int>(cli));
  16142. if (SSL_accept(ssl) > 0) {
  16143. // Read the request headers. Reading here also flushes the TLS 1.3
  16144. // session tickets to the client. Deliberately do NOT send
  16145. // `100 Continue`.
  16146. std::string buf;
  16147. char tmp[1024];
  16148. while (buf.find("\r\n\r\n") == std::string::npos) {
  16149. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16150. if (n <= 0) { break; }
  16151. buf.append(tmp, static_cast<size_t>(n));
  16152. }
  16153. // A correct client sends the body now; count what arrives.
  16154. auto pos = buf.find("\r\n\r\n");
  16155. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16156. while (body < 4096) {
  16157. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16158. if (n <= 0) { break; }
  16159. body += static_cast<size_t>(n);
  16160. }
  16161. server_body_bytes = body;
  16162. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16163. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16164. SSL_shutdown(ssl);
  16165. }
  16166. SSL_free(ssl);
  16167. detail::close_socket(cli);
  16168. SSL_CTX_free(ctx);
  16169. });
  16170. auto se = detail::scope_exit([&] {
  16171. server_thread.join();
  16172. detail::close_socket(srv);
  16173. });
  16174. SSLClient cli("127.0.0.1", port);
  16175. cli.enable_server_certificate_verification(false);
  16176. cli.set_connection_timeout(5, 0);
  16177. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16178. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16179. std::string body(4096, 'A');
  16180. auto res = cli.Put("/api/test", body, "application/json");
  16181. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16182. EXPECT_EQ(StatusCode::OK_200, res->status);
  16183. EXPECT_EQ(body.size(), server_body_bytes.load());
  16184. }
  16185. #endif
  16186. template <typename S, typename C>
  16187. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16188. svr.Get("/stream", [&](const Request &, Response &res) {
  16189. auto data = new std::string("01234567890123456789");
  16190. res.set_content_provider(
  16191. data->size(), "text/plain",
  16192. [&, data](size_t offset, size_t length, DataSink &sink) {
  16193. const size_t DATA_CHUNK_SIZE = 4;
  16194. const auto &d = *data;
  16195. std::this_thread::sleep_for(std::chrono::seconds(1));
  16196. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16197. return true;
  16198. },
  16199. [data](bool success) {
  16200. EXPECT_FALSE(success);
  16201. delete data;
  16202. });
  16203. });
  16204. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16205. auto i = new size_t(0);
  16206. res.set_content_provider(
  16207. "text/plain",
  16208. [i](size_t, DataSink &sink) {
  16209. if (*i < 5) {
  16210. std::this_thread::sleep_for(std::chrono::seconds(1));
  16211. sink.write("abcd", 4);
  16212. (*i)++;
  16213. } else {
  16214. sink.done();
  16215. }
  16216. return true;
  16217. },
  16218. [i](bool success) {
  16219. EXPECT_FALSE(success);
  16220. delete i;
  16221. });
  16222. });
  16223. svr.Get("/chunked", [&](const Request &, Response &res) {
  16224. auto i = new size_t(0);
  16225. res.set_chunked_content_provider(
  16226. "text/plain",
  16227. [i](size_t, DataSink &sink) {
  16228. if (*i < 5) {
  16229. std::this_thread::sleep_for(std::chrono::seconds(1));
  16230. sink.os << "abcd";
  16231. (*i)++;
  16232. } else {
  16233. sink.done();
  16234. }
  16235. return true;
  16236. },
  16237. [i](bool success) {
  16238. EXPECT_FALSE(success);
  16239. delete i;
  16240. });
  16241. });
  16242. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16243. auto se = detail::scope_exit([&] {
  16244. svr.stop();
  16245. listen_thread.join();
  16246. ASSERT_FALSE(svr.is_running());
  16247. });
  16248. svr.wait_until_ready();
  16249. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16250. {
  16251. auto start = std::chrono::steady_clock::now();
  16252. auto res = cli.Get("/stream");
  16253. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16254. std::chrono::steady_clock::now() - start)
  16255. .count();
  16256. ASSERT_FALSE(res);
  16257. EXPECT_EQ(Error::Read, res.error());
  16258. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16259. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16260. }
  16261. {
  16262. auto start = std::chrono::steady_clock::now();
  16263. auto res = cli.Get("/stream_without_length");
  16264. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16265. std::chrono::steady_clock::now() - start)
  16266. .count();
  16267. ASSERT_FALSE(res);
  16268. EXPECT_EQ(Error::Read, res.error());
  16269. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16270. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16271. }
  16272. {
  16273. auto start = std::chrono::steady_clock::now();
  16274. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16275. EXPECT_EQ("abcd", string(data, data_length));
  16276. return true;
  16277. });
  16278. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16279. std::chrono::steady_clock::now() - start)
  16280. .count();
  16281. ASSERT_FALSE(res);
  16282. EXPECT_EQ(Error::Read, res.error());
  16283. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16284. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16285. }
  16286. }
  16287. TEST(MaxTimeoutTest, ContentStream) {
  16288. time_t timeout = 2000;
  16289. time_t threshold = 200;
  16290. Server svr;
  16291. Client cli("localhost", PORT);
  16292. max_timeout_test(svr, cli, timeout, threshold);
  16293. }
  16294. #ifdef CPPHTTPLIB_SSL_ENABLED
  16295. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16296. time_t timeout = 2000;
  16297. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16298. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16299. SSLClient cli("localhost", PORT);
  16300. cli.enable_server_certificate_verification(false);
  16301. max_timeout_test(svr, cli, timeout, threshold);
  16302. }
  16303. #endif
  16304. class EventDispatcher {
  16305. public:
  16306. EventDispatcher() {}
  16307. bool wait_event(DataSink *sink) {
  16308. unique_lock<mutex> lk(m_);
  16309. int id = id_;
  16310. // Wait with timeout to prevent hanging if client disconnects
  16311. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16312. [&] { return cid_ == id; })) {
  16313. return false; // Timeout occurred
  16314. }
  16315. sink->write(message_.data(), message_.size());
  16316. return true;
  16317. }
  16318. void send_event(const string &message) {
  16319. lock_guard<mutex> lk(m_);
  16320. cid_ = id_++;
  16321. message_ = message;
  16322. cv_.notify_all();
  16323. }
  16324. private:
  16325. mutex m_;
  16326. condition_variable cv_;
  16327. atomic_int id_{0};
  16328. atomic_int cid_{-1};
  16329. string message_;
  16330. };
  16331. TEST(ClientInThreadTest, Issue2068) {
  16332. EventDispatcher ed;
  16333. Server svr;
  16334. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16335. res.set_chunked_content_provider("text/event-stream",
  16336. [&](size_t /*offset*/, DataSink &sink) {
  16337. return ed.wait_event(&sink);
  16338. });
  16339. });
  16340. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16341. svr.wait_until_ready();
  16342. thread event_thread([&] {
  16343. int id = 0;
  16344. while (svr.is_running()) {
  16345. this_thread::sleep_for(chrono::milliseconds(500));
  16346. std::stringstream ss;
  16347. ss << "data: " << id << "\n\n";
  16348. ed.send_event(ss.str());
  16349. id++;
  16350. }
  16351. });
  16352. auto se = detail::scope_exit([&] {
  16353. svr.stop();
  16354. listen_thread.join();
  16355. event_thread.join();
  16356. ASSERT_FALSE(svr.is_running());
  16357. });
  16358. {
  16359. auto client = detail::make_unique<Client>(HOST, PORT);
  16360. client->set_read_timeout(std::chrono::minutes(10));
  16361. std::atomic<bool> stop{false};
  16362. std::thread t([&] {
  16363. client->Get("/event1",
  16364. [&](const char *, size_t) -> bool { return !stop; });
  16365. });
  16366. std::this_thread::sleep_for(std::chrono::seconds(2));
  16367. stop = true;
  16368. client->stop();
  16369. t.join();
  16370. // Reset client after thread has finished
  16371. client.reset();
  16372. }
  16373. }
  16374. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16375. auto handled = false;
  16376. Server svr;
  16377. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16378. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16379. auto se = detail::scope_exit([&] {
  16380. svr.stop();
  16381. t.join();
  16382. ASSERT_FALSE(svr.is_running());
  16383. ASSERT_FALSE(handled);
  16384. });
  16385. svr.wait_until_ready();
  16386. // Two Content-Length headers with different values — must be rejected
  16387. auto req = "POST /test HTTP/1.1\r\n"
  16388. "Content-Length: 5\r\n"
  16389. "Content-Length: 10\r\n"
  16390. "\r\n"
  16391. "hello";
  16392. std::string response;
  16393. ASSERT_TRUE(send_request(1, req, &response));
  16394. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16395. response.substr(0, response.find("\r\n")));
  16396. }
  16397. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16398. auto handled = false;
  16399. Server svr;
  16400. svr.Post("/test", [&](const Request &, Response &res) {
  16401. handled = true;
  16402. res.set_content("ok", "text/plain");
  16403. });
  16404. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16405. auto se = detail::scope_exit([&] {
  16406. svr.stop();
  16407. t.join();
  16408. ASSERT_FALSE(svr.is_running());
  16409. ASSERT_TRUE(handled);
  16410. });
  16411. svr.wait_until_ready();
  16412. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16413. auto req = "POST /test HTTP/1.1\r\n"
  16414. "Content-Length: 5\r\n"
  16415. "Content-Length: 5\r\n"
  16416. "\r\n"
  16417. "hello";
  16418. std::string response;
  16419. ASSERT_TRUE(send_request(1, req, &response));
  16420. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16421. }
  16422. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16423. Server svr;
  16424. svr.Get("/", [](const Request &req, Response &res) {
  16425. EXPECT_EQ(2U, req.trailers.size());
  16426. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16427. // Denied
  16428. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16429. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16430. // Accepted
  16431. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16432. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16433. EXPECT_TRUE(req.has_trailer("X-World"));
  16434. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16435. res.set_content("ok", "text/plain");
  16436. });
  16437. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16438. auto se = detail::scope_exit([&] {
  16439. svr.stop();
  16440. t.join();
  16441. ASSERT_FALSE(svr.is_running());
  16442. });
  16443. svr.wait_until_ready();
  16444. const std::string req = "GET / HTTP/1.1\r\n"
  16445. "Transfer-Encoding: chunked\r\n"
  16446. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16447. "\r\n"
  16448. "0\r\n"
  16449. "Content-Length: 10\r\n"
  16450. "Host: internal.local\r\n"
  16451. "Content-Type: malicious/content\r\n"
  16452. "Cookie: any\r\n"
  16453. "Set-Cookie: any\r\n"
  16454. "X-Forwarded-For: attacker.com\r\n"
  16455. "X-Real-Ip: 1.1.1.1\r\n"
  16456. "X-Hello: hello\r\n"
  16457. "X-World: world\r\n"
  16458. "\r\n";
  16459. std::string res;
  16460. ASSERT_TRUE(send_request(1, req, &res));
  16461. }
  16462. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16463. // several field lines, and the combined value is what has to be parsed. A
  16464. // Trailer field split across lines therefore declares every name it lists;
  16465. // reading only the first line silently drops the trailers the later lines
  16466. // declare. The prohibited-trailer filter still applies to every line.
  16467. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16468. Server svr;
  16469. size_t observed_trailer_count = 0;
  16470. std::string observed_hello;
  16471. std::string observed_world;
  16472. bool observed_content_length = true;
  16473. svr.Get("/", [&](const Request &req, Response &res) {
  16474. observed_trailer_count = req.trailers.size();
  16475. observed_hello = req.get_trailer_value("X-Hello");
  16476. observed_world = req.get_trailer_value("X-World");
  16477. observed_content_length = req.has_trailer("Content-Length");
  16478. res.set_content("ok", "text/plain");
  16479. });
  16480. auto port = svr.bind_to_any_port(HOST);
  16481. thread t = thread([&]() { svr.listen_after_bind(); });
  16482. auto se = detail::scope_exit([&] {
  16483. svr.stop();
  16484. t.join();
  16485. ASSERT_FALSE(svr.is_running());
  16486. });
  16487. svr.wait_until_ready();
  16488. const std::string req = "GET / HTTP/1.1\r\n"
  16489. "Transfer-Encoding: chunked\r\n"
  16490. "Trailer: X-Hello\r\n"
  16491. "Trailer: X-World, Content-Length\r\n"
  16492. "\r\n"
  16493. "0\r\n"
  16494. "X-Hello: hello\r\n"
  16495. "X-World: world\r\n"
  16496. "Content-Length: 10\r\n"
  16497. "\r\n";
  16498. std::string res;
  16499. ASSERT_TRUE(send_request(1, req, &res, port));
  16500. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16501. // Accepted: both field lines contribute to the declared set
  16502. EXPECT_EQ(2U, observed_trailer_count);
  16503. EXPECT_EQ(observed_hello, "hello");
  16504. EXPECT_EQ(observed_world, "world");
  16505. // Denied: a prohibited name stays prohibited on a later field line
  16506. EXPECT_FALSE(observed_content_length);
  16507. }
  16508. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16509. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16510. // unbounded run of fields that are never declared, because the counter would
  16511. // only advance for declared fields.
  16512. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16513. Server svr;
  16514. bool handler_called = false;
  16515. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16516. handler_called = true;
  16517. res.set_content("ok", "text/plain");
  16518. });
  16519. auto port = svr.bind_to_any_port(HOST);
  16520. thread t = thread([&]() { svr.listen_after_bind(); });
  16521. auto se = detail::scope_exit([&] {
  16522. svr.stop();
  16523. t.join();
  16524. ASSERT_FALSE(svr.is_running());
  16525. });
  16526. svr.wait_until_ready();
  16527. // Declare nothing, then send far more undeclared trailer fields than the
  16528. // header-count limit. Parsing must stop and reject the request rather than
  16529. // read every line.
  16530. std::string req = "GET / HTTP/1.1\r\n"
  16531. "Transfer-Encoding: chunked\r\n"
  16532. "\r\n"
  16533. "0\r\n";
  16534. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16535. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16536. }
  16537. req += "\r\n";
  16538. std::string res;
  16539. ASSERT_TRUE(send_request(1, req, &res, port));
  16540. // The request is rejected before the handler runs.
  16541. EXPECT_FALSE(handler_called);
  16542. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16543. }
  16544. // The set of declared trailer names is capped so a peer cannot grow it without
  16545. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16546. // declared past the cap is not honored, even if the field is actually sent.
  16547. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16548. Server svr;
  16549. // One name inside the cap and one past it, so the test tracks the cap rather
  16550. // than a fixed count.
  16551. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16552. const std::string within_cap_name = "X-T-0";
  16553. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16554. bool observed_within_cap = false;
  16555. bool observed_past_cap = false;
  16556. svr.Get("/", [&](const Request &req, Response &res) {
  16557. observed_within_cap = req.has_trailer(within_cap_name);
  16558. observed_past_cap = req.has_trailer(past_cap_name);
  16559. res.set_content("ok", "text/plain");
  16560. });
  16561. auto port = svr.bind_to_any_port(HOST);
  16562. thread t = thread([&]() { svr.listen_after_bind(); });
  16563. auto se = detail::scope_exit([&] {
  16564. svr.stop();
  16565. t.join();
  16566. ASSERT_FALSE(svr.is_running());
  16567. });
  16568. svr.wait_until_ready();
  16569. // Declare more trailer names than the cap in a single Trailer field, then
  16570. // actually send the first (within the cap) and the last (past it).
  16571. std::string trailer_decl = "Trailer: ";
  16572. for (int i = 0; i < declared_count; i++) {
  16573. if (i != 0) { trailer_decl += ", "; }
  16574. trailer_decl += "X-T-" + std::to_string(i);
  16575. }
  16576. trailer_decl += "\r\n";
  16577. const std::string req = "GET / HTTP/1.1\r\n"
  16578. "Transfer-Encoding: chunked\r\n" +
  16579. trailer_decl +
  16580. "\r\n"
  16581. "0\r\n" +
  16582. within_cap_name + ": a\r\n" + past_cap_name +
  16583. ": b\r\n"
  16584. "\r\n";
  16585. std::string res;
  16586. ASSERT_TRUE(send_request(1, req, &res, port));
  16587. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16588. // A name within the cap is honored; one declared past the cap is dropped.
  16589. EXPECT_TRUE(observed_within_cap);
  16590. EXPECT_FALSE(observed_past_cap);
  16591. }
  16592. // A direct client that is not listed in trusted_proxies must not be able to
  16593. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16594. // the peer address on the actual TCP connection determines whether the
  16595. // header is honored.
  16596. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16597. Server svr;
  16598. // Deliberately does NOT include the loopback address the test client
  16599. // actually connects from, so the direct connection is not a trusted proxy.
  16600. svr.set_trusted_proxies({"203.0.113.66"});
  16601. std::string observed_remote_addr;
  16602. svr.Get("/ip", [&](const Request &req, Response &res) {
  16603. observed_remote_addr = req.remote_addr;
  16604. res.set_content("ok", "text/plain");
  16605. });
  16606. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16607. auto se = detail::scope_exit([&] {
  16608. svr.stop();
  16609. t.join();
  16610. ASSERT_FALSE(svr.is_running());
  16611. });
  16612. svr.wait_until_ready();
  16613. Client cli(HOST, PORT);
  16614. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16616. EXPECT_EQ(StatusCode::OK_200, res->status);
  16617. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16618. // ignored entirely and the real connection-level address retained.
  16619. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16620. observed_remote_addr == "127.0.0.1");
  16621. }
  16622. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16623. Server svr;
  16624. std::string observed_remote_addr;
  16625. std::string observed_xff;
  16626. svr.Get("/ip", [&](const Request &req, Response &res) {
  16627. observed_remote_addr = req.remote_addr;
  16628. observed_xff = req.get_header_value("X-Forwarded-For");
  16629. res.set_content("ok", "text/plain");
  16630. });
  16631. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16632. auto se = detail::scope_exit([&] {
  16633. svr.stop();
  16634. t.join();
  16635. ASSERT_FALSE(svr.is_running());
  16636. });
  16637. svr.wait_until_ready();
  16638. Client cli(HOST, PORT);
  16639. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16641. EXPECT_EQ(StatusCode::OK_200, res->status);
  16642. EXPECT_EQ(observed_xff, "203.0.113.66");
  16643. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16644. observed_remote_addr == "127.0.0.1");
  16645. }
  16646. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16647. Server svr;
  16648. svr.set_trusted_proxies({"203.0.113.66"});
  16649. std::string observed_remote_addr;
  16650. std::string observed_xff;
  16651. svr.Get("/ip", [&](const Request &req, Response &res) {
  16652. observed_remote_addr = req.remote_addr;
  16653. observed_xff = req.get_header_value("X-Forwarded-For");
  16654. res.set_content("ok", "text/plain");
  16655. });
  16656. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16657. auto se = detail::scope_exit([&] {
  16658. svr.stop();
  16659. t.join();
  16660. ASSERT_FALSE(svr.is_running());
  16661. });
  16662. svr.wait_until_ready();
  16663. Client cli(HOST, PORT);
  16664. auto res = cli.Get("/ip");
  16665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16666. EXPECT_EQ(StatusCode::OK_200, res->status);
  16667. EXPECT_EQ(observed_xff, "");
  16668. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16669. observed_remote_addr == "127.0.0.1");
  16670. }
  16671. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16672. Server svr;
  16673. // Include the loopback address the test client actually connects from, so
  16674. // the direct connection itself is recognized as the trusted proxy hop.
  16675. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16676. std::string observed_remote_addr;
  16677. std::string observed_xff;
  16678. svr.Get("/ip", [&](const Request &req, Response &res) {
  16679. observed_remote_addr = req.remote_addr;
  16680. observed_xff = req.get_header_value("X-Forwarded-For");
  16681. res.set_content("ok", "text/plain");
  16682. });
  16683. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16684. auto se = detail::scope_exit([&] {
  16685. svr.stop();
  16686. t.join();
  16687. ASSERT_FALSE(svr.is_running());
  16688. });
  16689. svr.wait_until_ready();
  16690. Client cli(HOST, PORT);
  16691. auto res = cli.Get(
  16692. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16694. EXPECT_EQ(StatusCode::OK_200, res->status);
  16695. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16696. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16697. }
  16698. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16699. Server svr;
  16700. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16701. std::string observed_remote_addr;
  16702. std::string observed_xff;
  16703. svr.Get("/ip", [&](const Request &req, Response &res) {
  16704. observed_remote_addr = req.remote_addr;
  16705. observed_xff = req.get_header_value("X-Forwarded-For");
  16706. res.set_content("ok", "text/plain");
  16707. });
  16708. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16709. auto se = detail::scope_exit([&] {
  16710. svr.stop();
  16711. t.join();
  16712. ASSERT_FALSE(svr.is_running());
  16713. });
  16714. svr.wait_until_ready();
  16715. Client cli(HOST, PORT);
  16716. auto res = cli.Get(
  16717. "/ip",
  16718. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16720. EXPECT_EQ(StatusCode::OK_200, res->status);
  16721. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16722. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16723. }
  16724. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16725. Server svr;
  16726. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16727. std::string observed_remote_addr;
  16728. std::string observed_xff;
  16729. svr.Get("/ip", [&](const Request &req, Response &res) {
  16730. observed_remote_addr = req.remote_addr;
  16731. observed_xff = req.get_header_value("X-Forwarded-For");
  16732. res.set_content("ok", "text/plain");
  16733. });
  16734. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16735. auto se = detail::scope_exit([&] {
  16736. svr.stop();
  16737. t.join();
  16738. ASSERT_FALSE(svr.is_running());
  16739. });
  16740. svr.wait_until_ready();
  16741. Client cli(HOST, PORT);
  16742. auto res = cli.Get(
  16743. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16745. EXPECT_EQ(StatusCode::OK_200, res->status);
  16746. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16747. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16748. // and must not be selected.
  16749. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16750. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16751. }
  16752. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16753. Server svr;
  16754. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16755. std::string observed_remote_addr;
  16756. svr.Get("/ip", [&](const Request &req, Response &res) {
  16757. observed_remote_addr = req.remote_addr;
  16758. res.set_content("ok", "text/plain");
  16759. });
  16760. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16761. auto se = detail::scope_exit([&] {
  16762. svr.stop();
  16763. t.join();
  16764. ASSERT_FALSE(svr.is_running());
  16765. });
  16766. svr.wait_until_ready();
  16767. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16768. // a forged address and the trusted proxy's own address; the forged value must
  16769. // not win over the address the trusted proxy actually recorded.
  16770. Client cli(HOST, PORT);
  16771. auto res = cli.Get(
  16772. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16774. EXPECT_EQ(StatusCode::OK_200, res->status);
  16775. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16776. }
  16777. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16778. Server svr;
  16779. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16780. std::string observed_remote_addr;
  16781. std::string observed_xff;
  16782. svr.Get("/ip", [&](const Request &req, Response &res) {
  16783. observed_remote_addr = req.remote_addr;
  16784. observed_xff = req.get_header_value("X-Forwarded-For");
  16785. res.set_content("ok", "text/plain");
  16786. });
  16787. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16788. auto se = detail::scope_exit([&] {
  16789. svr.stop();
  16790. t.join();
  16791. ASSERT_FALSE(svr.is_running());
  16792. });
  16793. svr.wait_until_ready();
  16794. Client cli(HOST, PORT);
  16795. auto res = cli.Get(
  16796. "/ip",
  16797. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16799. EXPECT_EQ(StatusCode::OK_200, res->status);
  16800. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16801. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16802. }
  16803. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16804. Server svr;
  16805. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16806. std::string observed_remote_addr;
  16807. std::string observed_xff;
  16808. svr.Get("/ip", [&](const Request &req, Response &res) {
  16809. observed_remote_addr = req.remote_addr;
  16810. observed_xff = req.get_header_value("X-Forwarded-For");
  16811. res.set_content("ok", "text/plain");
  16812. });
  16813. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16814. auto se = detail::scope_exit([&] {
  16815. svr.stop();
  16816. t.join();
  16817. ASSERT_FALSE(svr.is_running());
  16818. });
  16819. svr.wait_until_ready();
  16820. std::string raw_req =
  16821. "GET /ip HTTP/1.1\r\n"
  16822. "Host: localhost\r\n"
  16823. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16824. "Connection: close\r\n"
  16825. "\r\n";
  16826. std::string out;
  16827. ASSERT_TRUE(send_request(5, raw_req, &out));
  16828. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16829. // Header parser trims surrounding whitespace of the header value
  16830. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16831. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16832. }
  16833. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16834. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16835. // their own X-Forwarded-For as a separate field line rather than extending the
  16836. // one the client sent, so every occurrence has to be taken into account.
  16837. // Reading only the first one hands back the address the client chose.
  16838. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16839. Server svr;
  16840. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16841. std::string observed_remote_addr;
  16842. size_t observed_xff_count = 0;
  16843. svr.Get("/ip", [&](const Request &req, Response &res) {
  16844. observed_remote_addr = req.remote_addr;
  16845. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16846. res.set_content("ok", "text/plain");
  16847. });
  16848. auto port = svr.bind_to_any_port(HOST);
  16849. thread t = thread([&]() { svr.listen_after_bind(); });
  16850. auto se = detail::scope_exit([&] {
  16851. svr.stop();
  16852. t.join();
  16853. ASSERT_FALSE(svr.is_running());
  16854. });
  16855. svr.wait_until_ready();
  16856. // The client supplies the first field line; the trusted proxy appends the
  16857. // address it observed as a second one.
  16858. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16859. "Host: localhost\r\n"
  16860. "X-Forwarded-For: 1.2.3.4\r\n"
  16861. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16862. "Connection: close\r\n"
  16863. "\r\n";
  16864. std::string out;
  16865. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16866. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16867. EXPECT_EQ(observed_xff_count, 2U);
  16868. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16869. // The same chain spread over one field line per hop derives the same client
  16870. // address, i.e. the split and the comma-joined representations agree.
  16871. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16872. "Host: localhost\r\n"
  16873. "X-Forwarded-For: 1.2.3.4\r\n"
  16874. "X-Forwarded-For: 198.51.100.23\r\n"
  16875. "X-Forwarded-For: 192.0.2.45\r\n"
  16876. "Connection: close\r\n"
  16877. "\r\n";
  16878. out.clear();
  16879. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16880. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16881. EXPECT_EQ(observed_xff_count, 3U);
  16882. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16883. }
  16884. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16885. // crash the server (it used to call front() on an empty vector inside
  16886. // get_client_ip). The connection-level remote address must be retained instead.
  16887. static void run_malformed_xff_test(const std::string &xff_value) {
  16888. Server svr;
  16889. svr.set_trusted_proxies({"192.0.2.45"});
  16890. std::string observed_remote_addr;
  16891. svr.Get("/ip", [&](const Request &req, Response &res) {
  16892. observed_remote_addr = req.remote_addr;
  16893. res.set_content("ok", "text/plain");
  16894. });
  16895. int port = 0;
  16896. thread t = thread([&]() {
  16897. port = svr.bind_to_any_port(HOST);
  16898. svr.listen_after_bind();
  16899. });
  16900. auto se = detail::scope_exit([&] {
  16901. svr.stop();
  16902. t.join();
  16903. ASSERT_FALSE(svr.is_running());
  16904. });
  16905. svr.wait_until_ready();
  16906. Client cli(HOST, port);
  16907. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16909. EXPECT_EQ(StatusCode::OK_200, res->status);
  16910. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16911. observed_remote_addr == "127.0.0.1");
  16912. }
  16913. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16914. run_malformed_xff_test("");
  16915. }
  16916. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16917. run_malformed_xff_test(",");
  16918. }
  16919. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16920. run_malformed_xff_test(", , ,");
  16921. }
  16922. // The same rule applies to Accept: a request whose acceptable types are spread
  16923. // over several field lines must be negotiated against all of them.
  16924. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16925. // case-insensitive connection options. Comparing the whole field value against
  16926. // one option misses a client that sends several of them, and misses every
  16927. // casing but the one written in the comparison.
  16928. //
  16929. // Sends req, reads the response, then reuses the same socket for a second
  16930. // request to find out whether the server kept the connection.
  16931. static void probe_connection_reuse(int port, const std::string &req,
  16932. bool *announced_close, bool *reusable) {
  16933. auto error = Error::Success;
  16934. auto sock = detail::create_client_socket(
  16935. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16936. /*connection_timeout_sec=*/5, 0,
  16937. /*read_timeout_sec=*/1, 0,
  16938. /*write_timeout_sec=*/5, 0, std::string(), error);
  16939. ASSERT_NE(sock, INVALID_SOCKET);
  16940. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16941. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16942. "Host: localhost\r\n"
  16943. "Connection: close\r\n"
  16944. "\r\n";
  16945. std::string first_response;
  16946. std::string second_response;
  16947. detail::process_client_socket(
  16948. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16949. [&](Stream &strm) {
  16950. if (strm.write(req.data(), req.size()) !=
  16951. static_cast<ssize_t>(req.size())) {
  16952. return false;
  16953. }
  16954. char buf[512];
  16955. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16956. // Headers plus the two-byte body of the handler below
  16957. while (reader.getline()) {
  16958. first_response += reader.ptr();
  16959. if (first_response.find("ok") != std::string::npos) { break; }
  16960. }
  16961. if (strm.write(second.data(), second.size()) !=
  16962. static_cast<ssize_t>(second.size())) {
  16963. return true;
  16964. }
  16965. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16966. while (reader2.getline()) {
  16967. second_response += reader2.ptr();
  16968. if (second_response.find("ok") != std::string::npos) { break; }
  16969. }
  16970. return true;
  16971. });
  16972. *announced_close =
  16973. first_response.find("Connection: close") != std::string::npos;
  16974. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16975. }
  16976. class ConnectionTokenTest : public ::testing::Test {
  16977. protected:
  16978. void SetUp() override {
  16979. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16980. res.set_content("ok", "text/plain");
  16981. });
  16982. port_ = svr_.bind_to_any_port(HOST);
  16983. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16984. svr_.wait_until_ready();
  16985. }
  16986. void TearDown() override {
  16987. svr_.stop();
  16988. if (thread_.joinable()) { thread_.join(); }
  16989. }
  16990. Server svr_;
  16991. int port_ = 0;
  16992. thread thread_;
  16993. };
  16994. // "close" alongside another option still closes the connection, and the
  16995. // response says so rather than leaving the peer to discover it.
  16996. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16997. bool announced_close = false;
  16998. bool reusable = true;
  16999. probe_connection_reuse(port_,
  17000. "GET /keepalive HTTP/1.1\r\n"
  17001. "Host: localhost\r\n"
  17002. "Connection: keep-alive, close\r\n"
  17003. "\r\n",
  17004. &announced_close, &reusable);
  17005. EXPECT_TRUE(announced_close);
  17006. EXPECT_FALSE(reusable);
  17007. }
  17008. // "close" split over two field lines is the same list, so it is honored too.
  17009. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17010. bool announced_close = false;
  17011. bool reusable = true;
  17012. probe_connection_reuse(port_,
  17013. "GET /keepalive HTTP/1.1\r\n"
  17014. "Host: localhost\r\n"
  17015. "Connection: keep-alive\r\n"
  17016. "Connection: close\r\n"
  17017. "\r\n",
  17018. &announced_close, &reusable);
  17019. EXPECT_TRUE(announced_close);
  17020. EXPECT_FALSE(reusable);
  17021. }
  17022. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17023. // keep-alive in the spelling everyone actually sends keeps its connection.
  17024. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17025. bool announced_close = false;
  17026. bool reusable = false;
  17027. probe_connection_reuse(port_,
  17028. "GET /keepalive HTTP/1.0\r\n"
  17029. "Host: localhost\r\n"
  17030. "Connection: keep-alive\r\n"
  17031. "\r\n",
  17032. &announced_close, &reusable);
  17033. EXPECT_FALSE(announced_close);
  17034. EXPECT_TRUE(reusable);
  17035. }
  17036. // A token the value merely contains is not the token itself.
  17037. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17038. bool announced_close = false;
  17039. bool reusable = false;
  17040. probe_connection_reuse(port_,
  17041. "GET /keepalive HTTP/1.1\r\n"
  17042. "Host: localhost\r\n"
  17043. "Connection: notclose\r\n"
  17044. "\r\n",
  17045. &announced_close, &reusable);
  17046. EXPECT_FALSE(announced_close);
  17047. EXPECT_TRUE(reusable);
  17048. }
  17049. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17050. Server svr;
  17051. std::vector<std::string> observed_types;
  17052. svr.Get("/", [&](const Request &req, Response &res) {
  17053. observed_types = req.accept_content_types;
  17054. res.set_content("ok", "text/plain");
  17055. });
  17056. auto port = svr.bind_to_any_port(HOST);
  17057. thread t = thread([&]() { svr.listen_after_bind(); });
  17058. auto se = detail::scope_exit([&] {
  17059. svr.stop();
  17060. t.join();
  17061. ASSERT_FALSE(svr.is_running());
  17062. });
  17063. svr.wait_until_ready();
  17064. Client cli(HOST, port);
  17065. Headers headers;
  17066. headers.emplace("Accept", "text/plain;q=0.5");
  17067. headers.emplace("Accept", "application/json");
  17068. auto res = cli.Get("/", headers);
  17069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17070. EXPECT_EQ(StatusCode::OK_200, res->status);
  17071. // Sorted by q-value, so the second field line's type comes first
  17072. ASSERT_EQ(2U, observed_types.size());
  17073. EXPECT_EQ("application/json", observed_types[0]);
  17074. EXPECT_EQ("text/plain", observed_types[1]);
  17075. }
  17076. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17077. // empty field line must not contribute a bare comma to the combined value.
  17078. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17079. Server svr;
  17080. std::vector<std::string> observed_types;
  17081. svr.Get("/", [&](const Request &req, Response &res) {
  17082. observed_types = req.accept_content_types;
  17083. res.set_content("ok", "text/plain");
  17084. });
  17085. auto port = svr.bind_to_any_port(HOST);
  17086. thread t = thread([&]() { svr.listen_after_bind(); });
  17087. auto se = detail::scope_exit([&] {
  17088. svr.stop();
  17089. t.join();
  17090. ASSERT_FALSE(svr.is_running());
  17091. });
  17092. svr.wait_until_ready();
  17093. // Empty first field line, then a real one
  17094. std::string raw_req = "GET / HTTP/1.1\r\n"
  17095. "Host: localhost\r\n"
  17096. "Accept:\r\n"
  17097. "Accept: application/json\r\n"
  17098. "Connection: close\r\n"
  17099. "\r\n";
  17100. std::string out;
  17101. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17102. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17103. ASSERT_EQ(1U, observed_types.size());
  17104. EXPECT_EQ("application/json", observed_types[0]);
  17105. }
  17106. // The skip in get_combined_header_value() is what keeps an empty field line
  17107. // from contributing a bare comma. Only a trailing empty field line exercises
  17108. // it: a leading one is already covered by the "combined is still empty" check,
  17109. // and parse_accept_header() now ignores the empty element either way, so the
  17110. // request-level test above can no longer tell the two apart.
  17111. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17112. Headers headers;
  17113. headers.emplace("Accept", "text/html");
  17114. headers.emplace("Accept", "");
  17115. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17116. headers.clear();
  17117. headers.emplace("Accept", "");
  17118. headers.emplace("Accept", "application/json");
  17119. EXPECT_EQ("application/json",
  17120. detail::get_combined_header_value(headers, "Accept"));
  17121. }
  17122. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17123. // An encoding offered on a later Accept-Encoding field line is still offered.
  17124. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17125. Server svr;
  17126. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17127. res.set_content(std::string(1024, 'x'), "text/plain");
  17128. });
  17129. auto port = svr.bind_to_any_port(HOST);
  17130. thread t = thread([&]() { svr.listen_after_bind(); });
  17131. auto se = detail::scope_exit([&] {
  17132. svr.stop();
  17133. t.join();
  17134. ASSERT_FALSE(svr.is_running());
  17135. });
  17136. svr.wait_until_ready();
  17137. Client cli(HOST, port);
  17138. cli.set_decompress(false);
  17139. Headers headers;
  17140. headers.emplace("Accept-Encoding", "identity");
  17141. headers.emplace("Accept-Encoding", "gzip");
  17142. auto res = cli.Get("/", headers);
  17143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17144. EXPECT_EQ(StatusCode::OK_200, res->status);
  17145. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17146. }
  17147. #endif
  17148. #ifndef _WIN32
  17149. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17150. Server svr;
  17151. svr.Post("/post", [&](const Request &req, Response &res) {
  17152. res.set_content(req.body, "text/plain");
  17153. });
  17154. svr.Put("/put", [&](const Request &req, Response &res) {
  17155. res.set_content(req.body, "text/plain");
  17156. });
  17157. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17158. res.set_content(req.body, "text/plain");
  17159. });
  17160. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17161. res.set_content(req.body, "text/plain");
  17162. });
  17163. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17164. auto se = detail::scope_exit([&] {
  17165. svr.stop();
  17166. t.join();
  17167. ASSERT_FALSE(svr.is_running());
  17168. });
  17169. svr.wait_until_ready();
  17170. std::string resp;
  17171. // POST without Content-Length
  17172. ASSERT_TRUE(send_request(5,
  17173. "POST /post HTTP/1.1\r\n"
  17174. "Host: localhost\r\n"
  17175. "Connection: close\r\n"
  17176. "\r\n",
  17177. &resp));
  17178. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17179. // PUT without Content-Length
  17180. resp.clear();
  17181. ASSERT_TRUE(send_request(5,
  17182. "PUT /put HTTP/1.1\r\n"
  17183. "Host: localhost\r\n"
  17184. "Connection: close\r\n"
  17185. "\r\n",
  17186. &resp));
  17187. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17188. // PATCH without Content-Length
  17189. resp.clear();
  17190. ASSERT_TRUE(send_request(5,
  17191. "PATCH /patch HTTP/1.1\r\n"
  17192. "Host: localhost\r\n"
  17193. "Connection: close\r\n"
  17194. "\r\n",
  17195. &resp));
  17196. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17197. // DELETE without Content-Length
  17198. resp.clear();
  17199. ASSERT_TRUE(send_request(5,
  17200. "DELETE /delete HTTP/1.1\r\n"
  17201. "Host: localhost\r\n"
  17202. "Connection: close\r\n"
  17203. "\r\n",
  17204. &resp));
  17205. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17206. }
  17207. #endif
  17208. //==============================================================================
  17209. // open_stream() Tests
  17210. //==============================================================================
  17211. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17212. std::string result;
  17213. char buf[8192];
  17214. ssize_t n;
  17215. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17216. result.append(buf, static_cast<size_t>(n));
  17217. }
  17218. return result;
  17219. }
  17220. // Mock stream for unit tests
  17221. class MockStream : public Stream {
  17222. public:
  17223. std::string data;
  17224. size_t pos = 0;
  17225. ssize_t error_after = -1; // -1 = no error
  17226. explicit MockStream(const std::string &d, ssize_t err = -1)
  17227. : data(d), error_after(err) {}
  17228. bool is_readable() const override { return true; }
  17229. bool wait_readable() const override { return true; }
  17230. bool wait_writable() const override { return true; }
  17231. ssize_t read(char *ptr, size_t size) override {
  17232. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17233. if (pos >= data.size()) return 0;
  17234. size_t limit =
  17235. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17236. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17237. std::memcpy(ptr, data.data() + pos, to_read);
  17238. pos += to_read;
  17239. return static_cast<ssize_t>(to_read);
  17240. }
  17241. ssize_t write(const char *, size_t) override { return -1; }
  17242. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17243. ip = "127.0.0.1";
  17244. port = 0;
  17245. }
  17246. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17247. ip = "127.0.0.1";
  17248. port = 0;
  17249. }
  17250. socket_t socket() const override { return INVALID_SOCKET; }
  17251. time_t duration() const override { return 0; }
  17252. };
  17253. TEST(StreamHandleTest, Basic) {
  17254. ClientImpl::StreamHandle handle;
  17255. EXPECT_FALSE(handle.is_valid());
  17256. handle.response = detail::make_unique<Response>();
  17257. handle.error = Error::Connection;
  17258. EXPECT_FALSE(handle.is_valid());
  17259. handle.error = Error::Success;
  17260. EXPECT_TRUE(handle.is_valid());
  17261. }
  17262. TEST(BodyReaderTest, Basic) {
  17263. MockStream stream("Hello, World!");
  17264. detail::BodyReader reader;
  17265. reader.stream = &stream;
  17266. reader.content_length = 13;
  17267. char buf[32];
  17268. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17269. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17270. EXPECT_TRUE(reader.eof);
  17271. }
  17272. TEST(BodyReaderTest, NoStream) {
  17273. detail::BodyReader reader;
  17274. char buf[32];
  17275. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17276. EXPECT_EQ(Error::Connection, reader.last_error);
  17277. }
  17278. TEST(BodyReaderTest, Error) {
  17279. MockStream stream("Hello, World!", 5);
  17280. detail::BodyReader reader;
  17281. reader.stream = &stream;
  17282. reader.content_length = 13;
  17283. char buf[32];
  17284. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17285. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17286. EXPECT_EQ(Error::Read, reader.last_error);
  17287. }
  17288. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17289. // Mock-based StreamHandle tests relying on private internals are removed.
  17290. class OpenStreamTest : public ::testing::Test {
  17291. protected:
  17292. void SetUp() override {
  17293. svr_.Get("/hello", [](const Request &, Response &res) {
  17294. res.set_content("Hello World!", "text/plain");
  17295. });
  17296. svr_.Get("/large", [](const Request &, Response &res) {
  17297. res.set_content(std::string(10000, 'X'), "text/plain");
  17298. });
  17299. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17300. res.set_content("Hello World!", "image/jpeg");
  17301. res.set_header("Content-Encoding", "UTF-8");
  17302. });
  17303. svr_.Get("/chunked", [](const Request &, Response &res) {
  17304. res.set_chunked_content_provider("text/plain",
  17305. [](size_t offset, DataSink &sink) {
  17306. if (offset < 15) {
  17307. sink.write("chunk", 5);
  17308. return true;
  17309. }
  17310. sink.done();
  17311. return true;
  17312. });
  17313. });
  17314. svr_.Get("/compressible", [](const Request &, Response &res) {
  17315. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17316. DataSink &sink) {
  17317. if (offset < 100 * 1024) {
  17318. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17319. sink.write(chunk.data(), chunk.size());
  17320. return true;
  17321. }
  17322. sink.done();
  17323. return true;
  17324. });
  17325. });
  17326. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17327. [](const Request & /*req*/, Response &res) {
  17328. auto i = new int(0);
  17329. res.set_header("Trailer", "Content-Length, X-Allowed");
  17330. res.set_chunked_content_provider(
  17331. "text/plain",
  17332. [i](size_t /*offset*/, DataSink &sink) {
  17333. switch (*i) {
  17334. case 0: sink.os << "123"; break;
  17335. case 1: sink.os << "456"; break;
  17336. case 2: sink.os << "789"; break;
  17337. case 3: {
  17338. sink.done_with_trailer(
  17339. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17340. } break;
  17341. }
  17342. (*i)++;
  17343. return true;
  17344. },
  17345. [i](bool success) {
  17346. EXPECT_TRUE(success);
  17347. delete i;
  17348. });
  17349. });
  17350. // Echo headers endpoint for header-related tests
  17351. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17352. std::string body;
  17353. for (const auto &h : req.headers) {
  17354. body.append(h.first);
  17355. body.push_back(':');
  17356. body.append(h.second);
  17357. body.push_back('\n');
  17358. }
  17359. res.set_content(body, "text/plain");
  17360. });
  17361. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17362. std::string body;
  17363. for (const auto &h : req.headers) {
  17364. body.append(h.first);
  17365. body.push_back(':');
  17366. body.append(h.second);
  17367. body.push_back('\n');
  17368. }
  17369. res.set_content(body, "text/plain");
  17370. });
  17371. port_ = svr_.bind_to_any_port("127.0.0.1");
  17372. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17373. svr_.wait_until_ready();
  17374. }
  17375. void TearDown() override {
  17376. svr_.stop();
  17377. if (thread_.joinable()) thread_.join();
  17378. }
  17379. Server svr_;
  17380. std::thread thread_;
  17381. int port_ = 0;
  17382. };
  17383. TEST_F(OpenStreamTest, Basic) {
  17384. Client cli("127.0.0.1", port_);
  17385. auto handle = cli.open_stream("GET", "/hello");
  17386. EXPECT_TRUE(handle.is_valid());
  17387. EXPECT_EQ("Hello World!", read_all(handle));
  17388. }
  17389. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17390. Client cli("127.0.0.1", port_);
  17391. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17392. ASSERT_TRUE(handle.is_valid());
  17393. EXPECT_EQ("Hello World!", read_all(handle));
  17394. }
  17395. TEST_F(OpenStreamTest, SmallBuffer) {
  17396. Client cli("127.0.0.1", port_);
  17397. auto handle = cli.open_stream("GET", "/hello");
  17398. std::string result;
  17399. char buf[4];
  17400. ssize_t n;
  17401. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17402. result.append(buf, static_cast<size_t>(n));
  17403. EXPECT_EQ("Hello World!", result);
  17404. }
  17405. TEST_F(OpenStreamTest, DefaultHeaders) {
  17406. Client cli("127.0.0.1", port_);
  17407. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17408. {
  17409. auto handle = cli.open_stream("GET", "/echo-headers");
  17410. ASSERT_TRUE(handle.is_valid());
  17411. auto body = read_all(handle);
  17412. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17413. std::string::npos);
  17414. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17415. std::string::npos);
  17416. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17417. }
  17418. // open_stream POST with body and no explicit content_type should NOT add
  17419. // text/plain Content-Type (behavior differs from non-streaming path), but
  17420. // should include Content-Length
  17421. {
  17422. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17423. ASSERT_TRUE(handle.is_valid());
  17424. auto body = read_all(handle);
  17425. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17426. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17427. }
  17428. // open_stream POST with explicit Content-Type should preserve it
  17429. {
  17430. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17431. {{"Content-Type", "application/custom"}},
  17432. "{}", "application/custom");
  17433. ASSERT_TRUE(handle.is_valid());
  17434. auto body = read_all(handle);
  17435. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17436. }
  17437. // User-specified User-Agent must not be overwritten for stream API
  17438. {
  17439. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17440. {{"User-Agent", "MyAgent/1.2"}});
  17441. ASSERT_TRUE(handle.is_valid());
  17442. auto body = read_all(handle);
  17443. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17444. }
  17445. }
  17446. TEST_F(OpenStreamTest, Large) {
  17447. Client cli("127.0.0.1", port_);
  17448. auto handle = cli.open_stream("GET", "/large");
  17449. EXPECT_EQ(10000u, read_all(handle).size());
  17450. }
  17451. TEST_F(OpenStreamTest, ConnectionError) {
  17452. Client cli("127.0.0.1", 9999);
  17453. auto handle = cli.open_stream("GET", "/hello");
  17454. EXPECT_FALSE(handle.is_valid());
  17455. }
  17456. TEST_F(OpenStreamTest, Chunked) {
  17457. Client cli("127.0.0.1", port_);
  17458. auto handle = cli.open_stream("GET", "/chunked");
  17459. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17460. "Transfer-Encoding") == "chunked");
  17461. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17462. }
  17463. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17464. Client cli("127.0.0.1", port_);
  17465. auto handle =
  17466. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17467. ASSERT_TRUE(handle.is_valid());
  17468. // Consume body to allow trailers to be received/parsed
  17469. auto body = read_all(handle);
  17470. // Explicitly parse trailers (ensure trailers are available for assertion)
  17471. handle.parse_trailers_if_needed();
  17472. EXPECT_EQ(std::string("123456789"), body);
  17473. // The response should include a Trailer header declaring both names
  17474. ASSERT_TRUE(handle.response);
  17475. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17476. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17477. handle.response->get_header_value("Trailer"));
  17478. // Prohibited trailer must not be present
  17479. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17480. // Allowed trailer should be present
  17481. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17482. EXPECT_EQ(std::string("yes"),
  17483. handle.response->get_trailer_value("X-Allowed"));
  17484. // Verify trailers are NOT present as regular headers
  17485. EXPECT_EQ(std::string(""),
  17486. handle.response->get_header_value("Content-Length"));
  17487. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17488. }
  17489. static std::thread serve_single_response(std::promise<int> &port_promise,
  17490. const std::string &response) {
  17491. return std::thread([&port_promise, response] {
  17492. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17493. default_socket_options(srv);
  17494. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17495. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17496. sockaddr_in addr{};
  17497. addr.sin_family = AF_INET;
  17498. addr.sin_port = htons(0); // Let OS assign a free port
  17499. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17500. int opt = 1;
  17501. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17502. #ifdef _WIN32
  17503. reinterpret_cast<const char *>(&opt),
  17504. #else
  17505. &opt,
  17506. #endif
  17507. sizeof(opt));
  17508. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17509. ::listen(srv, 1) != 0) {
  17510. port_promise.set_value(-1);
  17511. detail::close_socket(srv);
  17512. return;
  17513. }
  17514. socklen_t addr_len = sizeof(addr);
  17515. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17516. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17517. sockaddr_in cli_addr{};
  17518. socklen_t cli_len = sizeof(cli_addr);
  17519. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17520. if (cli != INVALID_SOCKET) {
  17521. // Read the complete HTTP request (until the blank line that terminates
  17522. // headers) before sending the response. If the server closes the socket
  17523. // while the client's request data is still unread in the kernel receive
  17524. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17525. // connection on both sides: it discards the client's receive buffer
  17526. // (which already holds our response) and causes any in-progress write on
  17527. // the client to fail with ECONNRESET. Reading all request data first
  17528. // ensures close() emits a graceful FIN.
  17529. {
  17530. char rbuf[256];
  17531. std::string req;
  17532. while (req.find("\r\n\r\n") == std::string::npos) {
  17533. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17534. if (n <= 0) { break; }
  17535. req.append(rbuf, static_cast<size_t>(n));
  17536. }
  17537. }
  17538. ::send(cli,
  17539. #ifdef _WIN32
  17540. static_cast<const char *>(response.c_str()),
  17541. static_cast<int>(response.size()),
  17542. #else
  17543. response.c_str(), response.size(),
  17544. #endif
  17545. 0);
  17546. detail::close_socket(cli);
  17547. }
  17548. detail::close_socket(srv);
  17549. });
  17550. }
  17551. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17552. #ifndef _WIN32
  17553. signal(SIGPIPE, SIG_IGN);
  17554. #endif
  17555. std::promise<int> port_promise;
  17556. auto port_future = port_promise.get_future();
  17557. auto server_thread =
  17558. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17559. "Content-Type: text/plain\r\n"
  17560. "Content-Length: not-a-number\r\n"
  17561. "Connection: close\r\n"
  17562. "\r\n"
  17563. "hello");
  17564. auto port = port_future.get();
  17565. ASSERT_GT(port, 0);
  17566. Client cli("127.0.0.1", port);
  17567. auto handle = cli.open_stream("GET", "/");
  17568. EXPECT_FALSE(handle.is_valid());
  17569. server_thread.join();
  17570. }
  17571. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17572. #ifndef _WIN32
  17573. signal(SIGPIPE, SIG_IGN);
  17574. #endif
  17575. std::promise<int> port_promise;
  17576. auto port_future = port_promise.get_future();
  17577. auto server_thread = serve_single_response(
  17578. port_promise, "HTTP/1.1 200 OK\r\n"
  17579. "Content-Type: text/plain\r\n"
  17580. "Content-Length: 99999999999999999999999999\r\n"
  17581. "Connection: close\r\n"
  17582. "\r\n"
  17583. "hello");
  17584. auto port = port_future.get();
  17585. ASSERT_GT(port, 0);
  17586. // Historically std::stoull would throw std::out_of_range here and crash
  17587. // the process, then parsing silently clamped to a bogus framing length and
  17588. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17589. // so the stream fails to open, matching the not-a-number case above. The
  17590. // process still must NOT terminate.
  17591. Client cli("127.0.0.1", port);
  17592. auto handle = cli.open_stream("GET", "/");
  17593. EXPECT_FALSE(handle.is_valid());
  17594. server_thread.join();
  17595. }
  17596. // Serves `response` to the single request `fn` makes with a fresh client.
  17597. template <typename Fn>
  17598. static void with_single_response(const std::string &response, Fn fn) {
  17599. #ifndef _WIN32
  17600. signal(SIGPIPE, SIG_IGN);
  17601. #endif
  17602. std::promise<int> port_promise;
  17603. auto port_future = port_promise.get_future();
  17604. auto server_thread = serve_single_response(port_promise, response);
  17605. auto se = detail::scope_exit([&] { server_thread.join(); });
  17606. auto port = port_future.get();
  17607. ASSERT_GT(port, 0);
  17608. Client cli("127.0.0.1", port);
  17609. fn(cli);
  17610. }
  17611. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17612. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17613. // the chunked coding and drop Content-Length, so a front-end that trusts
  17614. // Content-Length would disagree about where the body ends (response
  17615. // smuggling). The client must reject such a response.
  17616. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17617. for (const char *te : {"chunked", "gzip, chunked"}) {
  17618. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17619. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17620. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17621. "5\r\nhello\r\n0\r\n\r\n";
  17622. with_single_response(response, [&](Client &cli) {
  17623. auto res = cli.Get("/");
  17624. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17625. EXPECT_EQ(Error::Read, res.error()) << te;
  17626. });
  17627. with_single_response(response, [&](Client &cli) {
  17628. auto handle = cli.open_stream("GET", "/");
  17629. EXPECT_FALSE(handle.is_valid()) << te;
  17630. EXPECT_EQ(Error::Read, handle.error) << te;
  17631. });
  17632. }
  17633. }
  17634. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17635. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17636. // closing the connection (unlike a request, which must be rejected).
  17637. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17638. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17639. "Transfer-Encoding: chunked\r\n"
  17640. "Connection: close\r\n"
  17641. "\r\n"
  17642. "5\r\nhello\r\n0\r\n\r\n",
  17643. "HTTP/1.1 200 OK\r\n"
  17644. "Transfer-Encoding: gzip\r\n"
  17645. "Connection: close\r\n"
  17646. "\r\n"
  17647. "hello"}) {
  17648. with_single_response(response, [&](Client &cli) {
  17649. auto res = cli.Get("/");
  17650. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17651. EXPECT_EQ("hello", res->body);
  17652. });
  17653. with_single_response(response, [&](Client &cli) {
  17654. auto handle = cli.open_stream("GET", "/");
  17655. ASSERT_TRUE(handle.is_valid()) << response;
  17656. EXPECT_EQ("hello", read_all(handle));
  17657. });
  17658. }
  17659. }
  17660. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17661. // framing headers describe nothing to read and must not be rejected.
  17662. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17663. const std::string framing = "Content-Length: 5\r\n"
  17664. "Transfer-Encoding: chunked\r\n"
  17665. "Connection: close\r\n"
  17666. "\r\n";
  17667. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17668. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17669. });
  17670. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17671. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17672. });
  17673. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17674. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17675. with_single_response(response, [&](Client &cli) {
  17676. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17677. });
  17678. with_single_response(response, [&](Client &cli) {
  17679. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17680. });
  17681. }
  17682. }
  17683. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17684. TEST_F(OpenStreamTest, Gzip) {
  17685. Client cli("127.0.0.1", port_);
  17686. auto handle = cli.open_stream("GET", "/compressible", {},
  17687. {{"Accept-Encoding", "gzip"}});
  17688. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17689. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17690. }
  17691. #endif
  17692. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17693. TEST_F(OpenStreamTest, Brotli) {
  17694. Client cli("127.0.0.1", port_);
  17695. auto handle =
  17696. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17697. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17698. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17699. }
  17700. #endif
  17701. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17702. TEST_F(OpenStreamTest, Zstd) {
  17703. Client cli("127.0.0.1", port_);
  17704. auto handle = cli.open_stream("GET", "/compressible", {},
  17705. {{"Accept-Encoding", "zstd"}});
  17706. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17707. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17708. }
  17709. #endif
  17710. #ifdef CPPHTTPLIB_SSL_ENABLED
  17711. class SSLOpenStreamTest : public ::testing::Test {
  17712. protected:
  17713. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17714. void SetUp() override {
  17715. svr_.Get("/hello", [](const Request &, Response &res) {
  17716. res.set_content("Hello SSL World!", "text/plain");
  17717. });
  17718. svr_.Get("/chunked", [](const Request &, Response &res) {
  17719. res.set_chunked_content_provider("text/plain",
  17720. [](size_t offset, DataSink &sink) {
  17721. if (offset < 15) {
  17722. sink.write("chunk", 5);
  17723. return true;
  17724. }
  17725. sink.done();
  17726. return true;
  17727. });
  17728. });
  17729. svr_.Post("/echo", [](const Request &req, Response &res) {
  17730. res.set_content(req.body, req.get_header_value("Content-Type"));
  17731. });
  17732. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17733. std::string body = req.body;
  17734. res.set_chunked_content_provider(
  17735. "text/plain", [body](size_t offset, DataSink &sink) {
  17736. if (offset < body.size()) {
  17737. sink.write(body.data() + offset, body.size() - offset);
  17738. }
  17739. sink.done();
  17740. return true;
  17741. });
  17742. });
  17743. port_ = svr_.bind_to_any_port("127.0.0.1");
  17744. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17745. svr_.wait_until_ready();
  17746. }
  17747. void TearDown() override {
  17748. svr_.stop();
  17749. if (thread_.joinable()) thread_.join();
  17750. }
  17751. SSLServer svr_;
  17752. std::thread thread_;
  17753. int port_ = 0;
  17754. };
  17755. TEST_F(SSLOpenStreamTest, Basic) {
  17756. SSLClient cli("127.0.0.1", port_);
  17757. cli.enable_server_certificate_verification(false);
  17758. auto handle = cli.open_stream("GET", "/hello");
  17759. ASSERT_TRUE(handle.is_valid());
  17760. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17761. }
  17762. TEST_F(SSLOpenStreamTest, Chunked) {
  17763. SSLClient cli("127.0.0.1", port_);
  17764. cli.enable_server_certificate_verification(false);
  17765. auto handle = cli.open_stream("GET", "/chunked");
  17766. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17767. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17768. "Transfer-Encoding") == "chunked");
  17769. auto body = read_all(handle);
  17770. EXPECT_EQ("chunkchunkchunk", body);
  17771. }
  17772. TEST_F(SSLOpenStreamTest, Post) {
  17773. SSLClient cli("127.0.0.1", port_);
  17774. cli.enable_server_certificate_verification(false);
  17775. auto handle =
  17776. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17777. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17778. EXPECT_EQ(200, handle.response->status);
  17779. auto body = read_all(handle);
  17780. EXPECT_EQ("Hello SSL POST", body);
  17781. }
  17782. TEST_F(SSLOpenStreamTest, PostChunked) {
  17783. SSLClient cli("127.0.0.1", port_);
  17784. cli.enable_server_certificate_verification(false);
  17785. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17786. "Chunked SSL Data", "text/plain");
  17787. ASSERT_TRUE(handle.is_valid());
  17788. EXPECT_EQ(200, handle.response->status);
  17789. auto body = read_all(handle);
  17790. EXPECT_EQ("Chunked SSL Data", body);
  17791. }
  17792. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17793. // Content-Length is terminated by the server closing the connection. When the
  17794. // SSL peer sends a close_notify after the body, the client must treat it as a
  17795. // clean EOF and return a successful response rather than an error.
  17796. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17797. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17798. ASSERT_TRUE(svr.is_valid());
  17799. svr.set_keep_alive_max_count(1);
  17800. const std::string expected_body = "Hello from connection-close response!";
  17801. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17802. res.set_content_provider("text/plain",
  17803. [&](size_t offset, DataSink &sink) -> bool {
  17804. if (offset < expected_body.size()) {
  17805. sink.write(expected_body.data() + offset,
  17806. expected_body.size() - offset);
  17807. }
  17808. sink.done();
  17809. return true;
  17810. });
  17811. });
  17812. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17813. auto se = detail::scope_exit([&] {
  17814. svr.stop();
  17815. listen_thread.join();
  17816. ASSERT_FALSE(svr.is_running());
  17817. });
  17818. svr.wait_until_ready();
  17819. SSLClient cli(HOST, PORT);
  17820. cli.enable_server_certificate_verification(false);
  17821. auto res = cli.Get("/no-content-length");
  17822. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17823. EXPECT_EQ(StatusCode::OK_200, res->status);
  17824. EXPECT_EQ(expected_body, res->body);
  17825. }
  17826. #endif // CPPHTTPLIB_SSL_ENABLED
  17827. //==============================================================================
  17828. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17829. // results for various scenarios.
  17830. //==============================================================================
  17831. TEST(ParityTest, GetVsOpenStream) {
  17832. Server svr;
  17833. const std::string path = "/parity";
  17834. const std::string content = "Parity test content: hello world";
  17835. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17836. res.set_content(content, "text/plain");
  17837. });
  17838. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17839. auto se = detail::scope_exit([&] {
  17840. svr.stop();
  17841. t.join();
  17842. ASSERT_FALSE(svr.is_running());
  17843. });
  17844. svr.wait_until_ready();
  17845. Client cli(HOST, PORT);
  17846. // Non-stream path
  17847. auto r1 = cli.Get(path);
  17848. ASSERT_TRUE(r1);
  17849. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17850. // Stream path
  17851. auto h = cli.open_stream("GET", path);
  17852. ASSERT_TRUE(h.is_valid());
  17853. EXPECT_EQ(r1->body, read_all(h));
  17854. }
  17855. // Helper to compress data with provided compressor type T
  17856. template <typename Compressor>
  17857. static std::string compress_payload_for_parity(const std::string &in) {
  17858. std::string out;
  17859. Compressor compressor;
  17860. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17861. [&](const char *data, size_t n) {
  17862. out.append(data, n);
  17863. return true;
  17864. });
  17865. EXPECT_TRUE(ok);
  17866. return out;
  17867. }
  17868. // Helper function for compression parity tests
  17869. template <typename Compressor>
  17870. static void test_compression_parity(const std::string &original,
  17871. const std::string &path,
  17872. const std::string &encoding) {
  17873. const std::string compressed =
  17874. compress_payload_for_parity<Compressor>(original);
  17875. Server svr;
  17876. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17877. res.set_content(compressed, "application/octet-stream");
  17878. res.set_header("Content-Encoding", encoding);
  17879. });
  17880. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17881. auto se = detail::scope_exit([&] {
  17882. svr.stop();
  17883. t.join();
  17884. ASSERT_FALSE(svr.is_running());
  17885. });
  17886. svr.wait_until_ready();
  17887. Client cli(HOST, PORT);
  17888. // Non-streaming
  17889. {
  17890. auto res = cli.Get(path);
  17891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17892. EXPECT_EQ(StatusCode::OK_200, res->status);
  17893. EXPECT_EQ(original, res->body);
  17894. }
  17895. // Streaming
  17896. {
  17897. auto h = cli.open_stream("GET", path);
  17898. ASSERT_TRUE(h.is_valid());
  17899. EXPECT_EQ(original, read_all(h));
  17900. }
  17901. }
  17902. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17903. TEST(ParityTest, Gzip) {
  17904. test_compression_parity<detail::gzip_compressor>(
  17905. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17906. }
  17907. #endif
  17908. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17909. TEST(ParityTest, Brotli) {
  17910. test_compression_parity<detail::brotli_compressor>(
  17911. "Hello, brotli parity test payload", "/parity-br", "br");
  17912. }
  17913. #endif
  17914. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17915. TEST(ParityTest, Zstd) {
  17916. test_compression_parity<detail::zstd_compressor>(
  17917. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17918. }
  17919. #endif
  17920. //==============================================================================
  17921. // New Stream API Tests
  17922. //==============================================================================
  17923. inline std::string read_body(httplib::stream::Result &result) {
  17924. std::string body;
  17925. while (result.next()) {
  17926. body.append(result.data(), result.size());
  17927. }
  17928. return body;
  17929. }
  17930. TEST(ClientConnectionTest, Basic) {
  17931. httplib::ClientConnection conn;
  17932. EXPECT_FALSE(conn.is_open());
  17933. conn.sock = 1;
  17934. EXPECT_TRUE(conn.is_open());
  17935. httplib::ClientConnection conn2(std::move(conn));
  17936. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17937. conn2.sock = INVALID_SOCKET;
  17938. }
  17939. // Unified test server for all stream::* tests
  17940. class StreamApiTest : public ::testing::Test {
  17941. protected:
  17942. void SetUp() override {
  17943. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17944. res.set_content("Hello World!", "text/plain");
  17945. });
  17946. svr_.Get("/echo-params",
  17947. [](const httplib::Request &req, httplib::Response &res) {
  17948. std::string r;
  17949. for (const auto &p : req.params) {
  17950. if (!r.empty()) r += "&";
  17951. r += p.first + "=" + p.second;
  17952. }
  17953. res.set_content(r, "text/plain");
  17954. });
  17955. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17956. res.set_content(req.body, req.get_header_value("Content-Type"));
  17957. });
  17958. svr_.Post("/echo-headers",
  17959. [](const httplib::Request &req, httplib::Response &res) {
  17960. std::string r;
  17961. for (const auto &h : req.headers)
  17962. r += h.first + ": " + h.second + "\n";
  17963. res.set_content(r, "text/plain");
  17964. });
  17965. svr_.Post("/echo-params",
  17966. [](const httplib::Request &req, httplib::Response &res) {
  17967. std::string r = "params:";
  17968. for (const auto &p : req.params)
  17969. r += p.first + "=" + p.second + ";";
  17970. res.set_content(r + " body:" + req.body, "text/plain");
  17971. });
  17972. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17973. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17974. });
  17975. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17976. res.set_content("PUT:" + req.body, "text/plain");
  17977. });
  17978. svr_.Patch("/echo",
  17979. [](const httplib::Request &req, httplib::Response &res) {
  17980. res.set_content("PATCH:" + req.body, "text/plain");
  17981. });
  17982. svr_.Delete(
  17983. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17984. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17985. "text/plain");
  17986. });
  17987. svr_.Get("/head-test",
  17988. [](const httplib::Request &, httplib::Response &res) {
  17989. res.set_content("body for HEAD", "text/plain");
  17990. });
  17991. svr_.Options("/options",
  17992. [](const httplib::Request &, httplib::Response &res) {
  17993. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17994. });
  17995. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17996. svr_.wait_until_ready();
  17997. }
  17998. void TearDown() override {
  17999. svr_.stop();
  18000. if (thread_.joinable()) thread_.join();
  18001. }
  18002. httplib::Server svr_;
  18003. std::thread thread_;
  18004. };
  18005. // stream::Get tests
  18006. TEST_F(StreamApiTest, GetBasic) {
  18007. httplib::Client cli(HOST, PORT);
  18008. auto result = httplib::stream::Get(cli, "/hello");
  18009. ASSERT_TRUE(result.is_valid());
  18010. EXPECT_EQ(200, result.status());
  18011. EXPECT_EQ("Hello World!", read_body(result));
  18012. }
  18013. TEST_F(StreamApiTest, GetWithParams) {
  18014. httplib::Client cli(HOST, PORT);
  18015. httplib::Params params{{"foo", "bar"}};
  18016. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18017. ASSERT_TRUE(result.is_valid());
  18018. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18019. }
  18020. TEST_F(StreamApiTest, GetConnectionError) {
  18021. httplib::Client cli(HOST, 9999);
  18022. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18023. }
  18024. TEST_F(StreamApiTest, Get404) {
  18025. httplib::Client cli(HOST, PORT);
  18026. auto result = httplib::stream::Get(cli, "/nonexistent");
  18027. EXPECT_TRUE(result.is_valid());
  18028. EXPECT_EQ(404, result.status());
  18029. }
  18030. // stream::Post tests
  18031. TEST_F(StreamApiTest, PostBasic) {
  18032. httplib::Client cli(HOST, PORT);
  18033. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18034. "application/json");
  18035. ASSERT_TRUE(result.is_valid());
  18036. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18037. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18038. }
  18039. TEST_F(StreamApiTest, PostWithHeaders) {
  18040. httplib::Client cli(HOST, PORT);
  18041. httplib::Headers headers{{"X-Custom", "value"}};
  18042. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18043. "text/plain");
  18044. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18045. }
  18046. TEST_F(StreamApiTest, PostWithParams) {
  18047. httplib::Client cli(HOST, PORT);
  18048. httplib::Params params{{"k", "v"}};
  18049. auto result =
  18050. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18051. auto body = read_body(result);
  18052. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18053. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18054. }
  18055. TEST_F(StreamApiTest, PostLarge) {
  18056. httplib::Client cli(HOST, PORT);
  18057. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18058. size_t total = 0;
  18059. while (result.next()) {
  18060. total += result.size();
  18061. }
  18062. EXPECT_EQ(100u * 1024u, total);
  18063. }
  18064. // stream::Put/Patch tests
  18065. TEST_F(StreamApiTest, PutAndPatch) {
  18066. httplib::Client cli(HOST, PORT);
  18067. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18068. EXPECT_EQ("PUT:test", read_body(put));
  18069. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18070. EXPECT_EQ("PATCH:test", read_body(patch));
  18071. }
  18072. // stream::Delete tests
  18073. TEST_F(StreamApiTest, Delete) {
  18074. httplib::Client cli(HOST, PORT);
  18075. auto del1 = httplib::stream::Delete(cli, "/resource");
  18076. EXPECT_EQ("Deleted", read_body(del1));
  18077. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18078. EXPECT_EQ("Deleted:data", read_body(del2));
  18079. }
  18080. // stream::Head/Options tests
  18081. TEST_F(StreamApiTest, HeadAndOptions) {
  18082. httplib::Client cli(HOST, PORT);
  18083. auto head = httplib::stream::Head(cli, "/head-test");
  18084. EXPECT_TRUE(head.is_valid());
  18085. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18086. auto opts = httplib::stream::Options(cli, "/options");
  18087. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18088. }
  18089. // SSL stream::* tests
  18090. #ifdef CPPHTTPLIB_SSL_ENABLED
  18091. class SSLStreamApiTest : public ::testing::Test {
  18092. protected:
  18093. void SetUp() override {
  18094. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18095. res.set_content("Hello SSL!", "text/plain");
  18096. });
  18097. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18098. res.set_content(req.body, "text/plain");
  18099. });
  18100. port_ = svr_.bind_to_any_port("127.0.0.1");
  18101. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18102. svr_.wait_until_ready();
  18103. }
  18104. void TearDown() override {
  18105. svr_.stop();
  18106. if (thread_.joinable()) thread_.join();
  18107. }
  18108. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18109. std::thread thread_;
  18110. int port_ = 0;
  18111. };
  18112. TEST_F(SSLStreamApiTest, GetAndPost) {
  18113. httplib::SSLClient cli("127.0.0.1", port_);
  18114. cli.enable_server_certificate_verification(false);
  18115. auto get = httplib::stream::Get(cli, "/hello");
  18116. EXPECT_EQ("Hello SSL!", read_body(get));
  18117. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18118. EXPECT_EQ("test", read_body(post));
  18119. }
  18120. #endif
  18121. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18122. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18123. // BodyReader
  18124. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18125. // Test that read timeout during streaming is detected
  18126. // Use a large content-length response where server delays mid-stream
  18127. Server svr;
  18128. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18129. // Send a large response with delay in the middle
  18130. res.set_content_provider(
  18131. 1000, // content_length
  18132. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18133. if (offset < 100) {
  18134. // Send first 100 bytes immediately
  18135. std::string data(100, 'A');
  18136. sink.write(data.c_str(), data.size());
  18137. return true;
  18138. }
  18139. // Then delay longer than client timeout
  18140. std::this_thread::sleep_for(std::chrono::seconds(3));
  18141. std::string data(900, 'B');
  18142. sink.write(data.c_str(), data.size());
  18143. return true;
  18144. });
  18145. });
  18146. auto port = 8091;
  18147. std::thread t([&]() { svr.listen("localhost", port); });
  18148. svr.wait_until_ready();
  18149. Client cli("localhost", port);
  18150. cli.set_read_timeout(1, 0); // 1 second timeout
  18151. auto handle = cli.open_stream("GET", "/slow-stream");
  18152. ASSERT_TRUE(handle.is_valid());
  18153. char buf[256];
  18154. ssize_t total = 0;
  18155. ssize_t n;
  18156. bool got_error = false;
  18157. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18158. total += n;
  18159. }
  18160. if (n < 0) {
  18161. got_error = true;
  18162. // Should be timeout or read error
  18163. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18164. handle.get_read_error() == Error::Read)
  18165. << "Actual error: " << to_string(handle.get_read_error());
  18166. }
  18167. // Either we got an error, or we got less data than expected
  18168. EXPECT_TRUE(got_error || total < 1000)
  18169. << "Expected timeout but got all " << total << " bytes";
  18170. svr.stop();
  18171. t.join();
  18172. }
  18173. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18174. // Test connection closed detection via BodyReader
  18175. Server svr;
  18176. std::atomic<bool> close_now{false};
  18177. svr.Get("/will-close", [&](const Request &, Response &res) {
  18178. res.set_content_provider(
  18179. 10000, // Large content_length that we won't fully send
  18180. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18181. if (offset < 100) {
  18182. std::string data(100, 'X');
  18183. sink.write(data.c_str(), data.size());
  18184. return true;
  18185. }
  18186. // Wait for signal then abort
  18187. while (!close_now) {
  18188. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18189. }
  18190. return false; // Abort - server will close connection
  18191. });
  18192. });
  18193. auto port = 8092;
  18194. std::thread t([&]() { svr.listen("localhost", port); });
  18195. svr.wait_until_ready();
  18196. Client cli("localhost", port);
  18197. auto handle = cli.open_stream("GET", "/will-close");
  18198. ASSERT_TRUE(handle.is_valid());
  18199. char buf[256];
  18200. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18201. EXPECT_GT(n, 0) << "First read should succeed";
  18202. // Signal server to close
  18203. close_now = true;
  18204. // Keep reading until error or EOF
  18205. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18206. // Keep reading
  18207. }
  18208. // Should get an error since content_length wasn't satisfied
  18209. if (n < 0) {
  18210. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18211. handle.get_read_error() == Error::Read)
  18212. << "Actual error: " << to_string(handle.get_read_error());
  18213. }
  18214. svr.stop();
  18215. t.join();
  18216. }
  18217. #ifdef CPPHTTPLIB_SSL_ENABLED
  18218. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18219. // Test that read timeout during SSL streaming is detected
  18220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18221. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18222. res.set_content_provider(
  18223. 1000, "text/plain",
  18224. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18225. if (offset < 100) {
  18226. std::string data(100, 'A');
  18227. sink.write(data.c_str(), data.size());
  18228. return true;
  18229. }
  18230. std::this_thread::sleep_for(std::chrono::seconds(3));
  18231. std::string data(900, 'B');
  18232. sink.write(data.c_str(), data.size());
  18233. return true;
  18234. });
  18235. });
  18236. auto port = 8093;
  18237. std::thread t([&]() { svr.listen("localhost", port); });
  18238. svr.wait_until_ready();
  18239. SSLClient cli("localhost", port);
  18240. cli.enable_server_certificate_verification(false);
  18241. cli.set_read_timeout(1, 0); // 1 second timeout
  18242. auto handle = cli.open_stream("GET", "/slow-stream");
  18243. ASSERT_TRUE(handle.is_valid());
  18244. char buf[256];
  18245. ssize_t total = 0;
  18246. ssize_t n;
  18247. bool got_error = false;
  18248. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18249. total += n;
  18250. }
  18251. if (n < 0) {
  18252. got_error = true;
  18253. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18254. handle.get_read_error() == Error::Read)
  18255. << "Actual error: " << to_string(handle.get_read_error());
  18256. }
  18257. EXPECT_TRUE(got_error || total < 1000)
  18258. << "Expected timeout but got all " << total << " bytes";
  18259. svr.stop();
  18260. t.join();
  18261. }
  18262. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18263. // Test SSL connection closed detection
  18264. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18265. std::atomic<bool> close_now{false};
  18266. svr.Get("/will-close", [&](const Request &, Response &res) {
  18267. res.set_content_provider(
  18268. 10000, "text/plain",
  18269. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18270. if (offset < 100) {
  18271. std::string data(100, 'X');
  18272. sink.write(data.c_str(), data.size());
  18273. return true;
  18274. }
  18275. while (!close_now) {
  18276. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18277. }
  18278. return false;
  18279. });
  18280. });
  18281. auto port = 8094;
  18282. std::thread t([&]() { svr.listen("localhost", port); });
  18283. svr.wait_until_ready();
  18284. SSLClient cli("localhost", port);
  18285. cli.enable_server_certificate_verification(false);
  18286. auto handle = cli.open_stream("GET", "/will-close");
  18287. ASSERT_TRUE(handle.is_valid());
  18288. char buf[256];
  18289. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18290. EXPECT_GT(n, 0);
  18291. // Signal server to close
  18292. close_now = true;
  18293. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18294. // Keep reading
  18295. }
  18296. if (n < 0) {
  18297. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18298. handle.get_read_error() == Error::Read)
  18299. << "Actual error: " << to_string(handle.get_read_error());
  18300. }
  18301. svr.stop();
  18302. t.join();
  18303. }
  18304. #endif
  18305. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18306. using namespace httplib;
  18307. // Create a test file
  18308. const char *fname = "etag_testfile.txt";
  18309. const char *content = "etag-content";
  18310. {
  18311. std::ofstream ofs(fname);
  18312. ofs << content;
  18313. ASSERT_TRUE(ofs.good());
  18314. }
  18315. Server svr;
  18316. svr.set_mount_point("/static", ".");
  18317. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18318. svr.wait_until_ready();
  18319. Client cli(HOST, PORT);
  18320. // First request: should get 200 with ETag header
  18321. auto res1 = cli.Get("/static/etag_testfile.txt");
  18322. ASSERT_TRUE(res1);
  18323. ASSERT_EQ(200, res1->status);
  18324. ASSERT_TRUE(res1->has_header("ETag"));
  18325. std::string etag = res1->get_header_value("ETag");
  18326. EXPECT_FALSE(etag.empty());
  18327. // Verify ETag format: W/"hex-hex"
  18328. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18329. EXPECT_EQ('W', etag[0]);
  18330. EXPECT_EQ('/', etag[1]);
  18331. EXPECT_EQ('"', etag[2]);
  18332. EXPECT_EQ('"', etag.back());
  18333. // Exact match: expect 304 Not Modified
  18334. Headers h2 = {{"If-None-Match", etag}};
  18335. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18336. ASSERT_TRUE(res2);
  18337. EXPECT_EQ(304, res2->status);
  18338. // Wildcard match: expect 304 Not Modified
  18339. Headers h3 = {{"If-None-Match", "*"}};
  18340. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18341. ASSERT_TRUE(res3);
  18342. EXPECT_EQ(304, res3->status);
  18343. // Non-matching ETag: expect 200
  18344. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18345. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18346. ASSERT_TRUE(res4);
  18347. EXPECT_EQ(200, res4->status);
  18348. // Multiple ETags with one matching: expect 304
  18349. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18350. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18351. ASSERT_TRUE(res5);
  18352. EXPECT_EQ(304, res5->status);
  18353. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18354. // that equivalent to the single comma-separated list above, so the match on
  18355. // the second line must still be found.
  18356. Headers h6;
  18357. h6.emplace("If-None-Match", "W/\"other\"");
  18358. h6.emplace("If-None-Match", etag);
  18359. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18360. ASSERT_TRUE(res6);
  18361. EXPECT_EQ(304, res6->status);
  18362. svr.stop();
  18363. t.join();
  18364. std::remove(fname);
  18365. }
  18366. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18367. using namespace httplib;
  18368. Server svr;
  18369. svr.set_mount_point("/static", ".");
  18370. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18371. svr.wait_until_ready();
  18372. Client cli(HOST, PORT);
  18373. // Send If-None-Match: * to a non-existent file
  18374. Headers h = {{"If-None-Match", "*"}};
  18375. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18377. EXPECT_EQ(404, res->status);
  18378. svr.stop();
  18379. t.join();
  18380. }
  18381. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18382. using namespace httplib;
  18383. // Create a test file
  18384. const char *fname = "etag_boundary_testfile.txt";
  18385. const char *content = "boundary-test";
  18386. {
  18387. std::ofstream ofs(fname);
  18388. ofs << content;
  18389. ASSERT_TRUE(ofs.good());
  18390. }
  18391. Server svr;
  18392. svr.set_mount_point("/static", ".");
  18393. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18394. svr.wait_until_ready();
  18395. Client cli(HOST, PORT);
  18396. // Get the actual ETag
  18397. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18398. ASSERT_TRUE(res1);
  18399. ASSERT_EQ(200, res1->status);
  18400. ASSERT_TRUE(res1->has_header("ETag"));
  18401. std::string etag = res1->get_header_value("ETag");
  18402. // Test 1: Very long ETag value (longer than actual ETag)
  18403. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18404. Headers h1 = {{"If-None-Match", "W/"
  18405. "\"very-long-etag-value-that-is-much-longer-"
  18406. "than-the-actual-etag-value\""}};
  18407. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18408. ASSERT_TRUE(res2);
  18409. EXPECT_EQ(200, res2->status); // Should not match
  18410. // Test 2: Long string followed by wildcard
  18411. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18412. // string)
  18413. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18414. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18415. ASSERT_TRUE(res3);
  18416. EXPECT_EQ(304, res3->status); // Should match on "*"
  18417. // Test 3: Wildcard followed by long string
  18418. // Should match on "*" immediately and return 304
  18419. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18420. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18421. ASSERT_TRUE(res4);
  18422. EXPECT_EQ(304, res4->status); // Should match on "*"
  18423. // Test 4: Multiple long non-matching values
  18424. // Should NOT match and return 200 (test that all comparisons are safe)
  18425. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18426. "W/\"second-long-non-matching-value\", "
  18427. "W/\"third-long-non-matching-value\""}};
  18428. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18429. ASSERT_TRUE(res5);
  18430. EXPECT_EQ(200, res5->status); // Should not match
  18431. // Test 5: Single character that is not "*" (edge case)
  18432. Headers h5 = {{"If-None-Match", "X"}};
  18433. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18434. ASSERT_TRUE(res6);
  18435. EXPECT_EQ(200, res6->status); // Should not match
  18436. svr.stop();
  18437. t.join();
  18438. std::remove(fname);
  18439. }
  18440. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18441. using namespace httplib;
  18442. // Create a test file
  18443. const char *fname = "ims_testfile.txt";
  18444. const char *content = "if-modified-since-test";
  18445. {
  18446. std::ofstream ofs(fname);
  18447. ofs << content;
  18448. ASSERT_TRUE(ofs.good());
  18449. }
  18450. Server svr;
  18451. svr.set_mount_point("/static", ".");
  18452. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18453. svr.wait_until_ready();
  18454. Client cli(HOST, PORT);
  18455. // First request: should get 200 with Last-Modified header
  18456. auto res1 = cli.Get("/static/ims_testfile.txt");
  18457. ASSERT_TRUE(res1);
  18458. ASSERT_EQ(200, res1->status);
  18459. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18460. std::string last_modified = res1->get_header_value("Last-Modified");
  18461. EXPECT_FALSE(last_modified.empty());
  18462. // If-Modified-Since with same time: expect 304
  18463. Headers h2 = {{"If-Modified-Since", last_modified}};
  18464. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18465. ASSERT_TRUE(res2);
  18466. EXPECT_EQ(304, res2->status);
  18467. // If-Modified-Since with future time: expect 304
  18468. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18469. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18470. ASSERT_TRUE(res3);
  18471. EXPECT_EQ(304, res3->status);
  18472. // If-Modified-Since with past time: expect 200
  18473. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18474. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18475. ASSERT_TRUE(res4);
  18476. EXPECT_EQ(200, res4->status);
  18477. // If-None-Match takes precedence over If-Modified-Since
  18478. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18479. ASSERT_TRUE(res1->has_header("ETag"));
  18480. std::string etag = res1->get_header_value("ETag");
  18481. Headers h5 = {{"If-None-Match", etag},
  18482. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18483. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18484. ASSERT_TRUE(res5);
  18485. EXPECT_EQ(304, res5->status);
  18486. svr.stop();
  18487. t.join();
  18488. std::remove(fname);
  18489. }
  18490. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18491. using namespace httplib;
  18492. Server svr;
  18493. // Endpoint that returns compressible content
  18494. svr.Get("/compressible", [](const Request &, Response &res) {
  18495. // Return a large enough body to trigger compression
  18496. std::string body(1000, 'a');
  18497. res.set_content(body, "text/plain");
  18498. });
  18499. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18500. svr.wait_until_ready();
  18501. Client cli(HOST, PORT);
  18502. // Request with gzip support: should get Vary header when compressed
  18503. cli.set_compress(true);
  18504. auto res1 = cli.Get("/compressible");
  18505. ASSERT_TRUE(res1);
  18506. EXPECT_EQ(200, res1->status);
  18507. // If Content-Encoding is set, Vary should also be set
  18508. if (res1->has_header("Content-Encoding")) {
  18509. EXPECT_TRUE(res1->has_header("Vary"));
  18510. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18511. }
  18512. // Request without Accept-Encoding header: should not have compression
  18513. Headers h_no_compress;
  18514. auto res2 = cli.Get("/compressible", h_no_compress);
  18515. ASSERT_TRUE(res2);
  18516. EXPECT_EQ(200, res2->status);
  18517. // Verify Vary header is present when compression is applied
  18518. // (the exact behavior depends on server configuration)
  18519. svr.stop();
  18520. t.join();
  18521. }
  18522. TEST(ETagTest, IfRangeWithETag) {
  18523. using namespace httplib;
  18524. // Create a test file with known content
  18525. const char *fname = "if_range_testfile.txt";
  18526. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18527. {
  18528. std::ofstream ofs(fname);
  18529. ofs << content;
  18530. ASSERT_TRUE(ofs.good());
  18531. }
  18532. Server svr;
  18533. svr.set_mount_point("/static", ".");
  18534. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18535. svr.wait_until_ready();
  18536. Client cli(HOST, PORT);
  18537. // First request: get ETag
  18538. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18539. ASSERT_TRUE(res1);
  18540. ASSERT_EQ(200, res1->status);
  18541. ASSERT_TRUE(res1->has_header("ETag"));
  18542. std::string etag = res1->get_header_value("ETag");
  18543. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18544. // Since our server generates weak ETags (W/"..."), If-Range with our
  18545. // ETag should NOT result in partial content - it should return full content.
  18546. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18547. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18548. ASSERT_TRUE(res2);
  18549. // Weak ETag in If-Range -> full content (200), not partial (206)
  18550. EXPECT_EQ(200, res2->status);
  18551. EXPECT_EQ(content, res2->body);
  18552. EXPECT_FALSE(res2->has_header("Content-Range"));
  18553. // Range request with non-matching If-Range (ETag): should get 200 (full
  18554. // content)
  18555. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18556. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18557. ASSERT_TRUE(res3);
  18558. EXPECT_EQ(200, res3->status);
  18559. EXPECT_EQ(content, res3->body);
  18560. EXPECT_FALSE(res3->has_header("Content-Range"));
  18561. // Range request with strong ETag (hypothetical - our server doesn't generate
  18562. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18563. // should return full content)
  18564. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18565. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18566. ASSERT_TRUE(res4);
  18567. EXPECT_EQ(200, res4->status);
  18568. EXPECT_EQ(content, res4->body);
  18569. EXPECT_FALSE(res4->has_header("Content-Range"));
  18570. svr.stop();
  18571. t.join();
  18572. std::remove(fname);
  18573. }
  18574. TEST(ETagTest, IfRangeWithDate) {
  18575. using namespace httplib;
  18576. // Create a test file
  18577. const char *fname = "if_range_date_testfile.txt";
  18578. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18579. {
  18580. std::ofstream ofs(fname);
  18581. ofs << content;
  18582. ASSERT_TRUE(ofs.good());
  18583. }
  18584. Server svr;
  18585. svr.set_mount_point("/static", ".");
  18586. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18587. svr.wait_until_ready();
  18588. Client cli(HOST, PORT);
  18589. // First request: get Last-Modified
  18590. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18591. ASSERT_TRUE(res1);
  18592. ASSERT_EQ(200, res1->status);
  18593. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18594. std::string last_modified = res1->get_header_value("Last-Modified");
  18595. // Range request with matching If-Range (date): should get 206
  18596. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18597. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18598. ASSERT_TRUE(res2);
  18599. EXPECT_EQ(206, res2->status);
  18600. EXPECT_EQ("FGHIJ", res2->body);
  18601. // Range request with old If-Range date: should get 200 (full content)
  18602. Headers h3 = {{"Range", "bytes=5-9"},
  18603. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18604. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18605. ASSERT_TRUE(res3);
  18606. EXPECT_EQ(200, res3->status);
  18607. EXPECT_EQ(content, res3->body);
  18608. // Range request with future If-Range date: should get 206
  18609. Headers h4 = {{"Range", "bytes=0-4"},
  18610. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18611. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18612. ASSERT_TRUE(res4);
  18613. EXPECT_EQ(206, res4->status);
  18614. EXPECT_EQ("ABCDE", res4->body);
  18615. svr.stop();
  18616. t.join();
  18617. std::remove(fname);
  18618. }
  18619. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18620. using namespace httplib;
  18621. const char *fname = "etag_malformed.txt";
  18622. const char *content = "malformed-etag";
  18623. {
  18624. std::ofstream ofs(fname);
  18625. ofs << content;
  18626. ASSERT_TRUE(ofs.good());
  18627. }
  18628. Server svr;
  18629. svr.set_mount_point("/static", ".");
  18630. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18631. svr.wait_until_ready();
  18632. Client cli(HOST, PORT);
  18633. // baseline: should get 200 and an ETag
  18634. auto res1 = cli.Get("/static/etag_malformed.txt");
  18635. ASSERT_TRUE(res1);
  18636. ASSERT_EQ(200, res1->status);
  18637. ASSERT_TRUE(res1->has_header("ETag"));
  18638. // Malformed ETag value (missing quotes) should be treated as non-matching
  18639. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18640. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18641. ASSERT_TRUE(res_bad);
  18642. EXPECT_EQ(200, res_bad->status);
  18643. // Whitespace-only header value should be considered invalid / non-matching
  18644. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18645. "Host: localhost\r\n"
  18646. "If-None-Match: \r\n"
  18647. "Connection: close\r\n"
  18648. "\r\n";
  18649. std::string out;
  18650. ASSERT_TRUE(send_request(5, raw_req, &out));
  18651. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18652. svr.stop();
  18653. t.join();
  18654. std::remove(fname);
  18655. }
  18656. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18657. using namespace httplib;
  18658. const char *fname = "ims_invalid_format.txt";
  18659. const char *content = "ims-bad-format";
  18660. {
  18661. std::ofstream ofs(fname);
  18662. ofs << content;
  18663. ASSERT_TRUE(ofs.good());
  18664. }
  18665. Server svr;
  18666. svr.set_mount_point("/static", ".");
  18667. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18668. svr.wait_until_ready();
  18669. Client cli(HOST, PORT);
  18670. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18671. ASSERT_TRUE(res1);
  18672. ASSERT_EQ(200, res1->status);
  18673. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18674. // If-Modified-Since with invalid format should not result in 304
  18675. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18676. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18677. ASSERT_TRUE(res_bad);
  18678. EXPECT_EQ(200, res_bad->status);
  18679. // If-Range with invalid date format should be treated as mismatch -> full
  18680. // content (200)
  18681. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18682. {"If-Range", "invalid-date"}};
  18683. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18684. ASSERT_TRUE(res_ifrange);
  18685. EXPECT_EQ(200, res_ifrange->status);
  18686. svr.stop();
  18687. t.join();
  18688. std::remove(fname);
  18689. }
  18690. TEST(ETagTest, IfRangeWithMalformedETag) {
  18691. using namespace httplib;
  18692. const char *fname = "ifrange_malformed.txt";
  18693. const std::string content = "0123456789";
  18694. {
  18695. std::ofstream ofs(fname);
  18696. ofs << content;
  18697. ASSERT_TRUE(ofs.good());
  18698. }
  18699. Server svr;
  18700. svr.set_mount_point("/static", ".");
  18701. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18702. svr.wait_until_ready();
  18703. Client cli(HOST, PORT);
  18704. // First request: get ETag
  18705. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18706. ASSERT_TRUE(res1);
  18707. ASSERT_EQ(200, res1->status);
  18708. ASSERT_TRUE(res1->has_header("ETag"));
  18709. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18710. // full content (200)
  18711. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18712. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18713. ASSERT_TRUE(res2);
  18714. EXPECT_EQ(200, res2->status);
  18715. EXPECT_EQ(content, res2->body);
  18716. svr.stop();
  18717. t.join();
  18718. std::remove(fname);
  18719. }
  18720. TEST(ETagTest, ExtremeLargeDateValues) {
  18721. using namespace httplib;
  18722. const char *fname = "ims_extreme_date.txt";
  18723. const char *content = "ims-extreme-date";
  18724. {
  18725. std::ofstream ofs(fname);
  18726. ofs << content;
  18727. ASSERT_TRUE(ofs.good());
  18728. }
  18729. Server svr;
  18730. svr.set_mount_point("/static", ".");
  18731. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18732. svr.wait_until_ready();
  18733. Client cli(HOST, PORT);
  18734. auto res1 = cli.Get(std::string("/static/") + fname);
  18735. ASSERT_TRUE(res1);
  18736. ASSERT_EQ(200, res1->status);
  18737. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18738. // Extremely large year that may overflow date parsing routines.
  18739. Headers h_large_date = {
  18740. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18741. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18742. ASSERT_TRUE(res_bad);
  18743. // Expect server to treat this as invalid/mismatch and return full content
  18744. EXPECT_EQ(200, res_bad->status);
  18745. // If-Range with extremely large date should be treated as mismatch -> full
  18746. // content (200)
  18747. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18748. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18749. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18750. ASSERT_TRUE(res_ifrange);
  18751. EXPECT_EQ(200, res_ifrange->status);
  18752. svr.stop();
  18753. t.join();
  18754. std::remove(fname);
  18755. }
  18756. TEST(ETagTest, NegativeFileModificationTime) {
  18757. using namespace httplib;
  18758. const char *fname = "ims_negative_mtime.txt";
  18759. const std::string content = "negative-mtime";
  18760. {
  18761. std::ofstream ofs(fname);
  18762. ofs << content;
  18763. ASSERT_TRUE(ofs.good());
  18764. }
  18765. // Try to set file mtime to a negative value. This may fail on some
  18766. // platforms/filesystems; if it fails, the test will still verify server
  18767. // behaves safely by performing a regular conditional request.
  18768. #if defined(__APPLE__) || defined(__linux__)
  18769. bool set_negative = false;
  18770. do {
  18771. struct timeval times[2];
  18772. // access time: now
  18773. times[0].tv_sec = time(nullptr);
  18774. times[0].tv_usec = 0;
  18775. // modification time: negative (e.g., -1)
  18776. times[1].tv_sec = -1;
  18777. times[1].tv_usec = 0;
  18778. if (utimes(fname, times) == 0) { set_negative = true; }
  18779. } while (0);
  18780. #else
  18781. bool set_negative = false;
  18782. #endif
  18783. Server svr;
  18784. svr.set_mount_point("/static", ".");
  18785. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18786. svr.wait_until_ready();
  18787. Client cli(HOST, PORT);
  18788. auto res1 = cli.Get(std::string("/static/") + fname);
  18789. ASSERT_TRUE(res1);
  18790. ASSERT_EQ(200, res1->status);
  18791. bool has_last_modified = res1->has_header("Last-Modified");
  18792. std::string last_modified;
  18793. if (has_last_modified) {
  18794. last_modified = res1->get_header_value("Last-Modified");
  18795. }
  18796. if (set_negative) {
  18797. // If we successfully set a negative mtime, ensure server returns a
  18798. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18799. // with an old date and ensure server handles it without crash.
  18800. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18801. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18802. ASSERT_TRUE(res2);
  18803. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18804. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18805. } else {
  18806. // Could not set negative mtime on this platform; fall back to verifying
  18807. // that normal invalid/malformed dates are treated safely (non-304).
  18808. Headers h_bad_date = {
  18809. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18810. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18811. ASSERT_TRUE(res_bad);
  18812. EXPECT_EQ(200, res_bad->status);
  18813. }
  18814. svr.stop();
  18815. t.join();
  18816. std::remove(fname);
  18817. }
  18818. //==============================================================================
  18819. // Integration Tests with Server
  18820. //==============================================================================
  18821. class SSEIntegrationTest : public ::testing::Test {
  18822. protected:
  18823. void SetUp() override {
  18824. stop_server_.store(false);
  18825. events_.clear();
  18826. server_ = httplib::detail::make_unique<Server>();
  18827. setup_server();
  18828. start_server();
  18829. }
  18830. void TearDown() override {
  18831. stop_server_.store(true);
  18832. event_cv_.notify_all();
  18833. server_->stop();
  18834. if (server_thread_.joinable()) { server_thread_.join(); }
  18835. }
  18836. void setup_server() {
  18837. // Simple SSE endpoint
  18838. server_->Get("/events", [this](const Request &req, Response &res) {
  18839. auto last_id = req.get_header_value("Last-Event-ID");
  18840. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18841. res.set_chunked_content_provider(
  18842. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18843. std::unique_lock<std::mutex> lock(event_mutex_);
  18844. if (event_cv_.wait_for(
  18845. lock, std::chrono::milliseconds(200), [this] {
  18846. return !events_.empty() || stop_server_.load();
  18847. })) {
  18848. if (stop_server_.load()) { return false; }
  18849. if (!events_.empty()) {
  18850. std::string event = events_.front();
  18851. events_.erase(events_.begin());
  18852. sink.write(event.data(), event.size());
  18853. return true;
  18854. }
  18855. }
  18856. return !stop_server_.load();
  18857. });
  18858. });
  18859. // Endpoint that returns error
  18860. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18861. res.status = 500;
  18862. res.set_content("Internal Server Error", "text/plain");
  18863. });
  18864. // Endpoint for custom event types
  18865. server_->Get("/custom-events", [](const Request &, Response &res) {
  18866. res.set_chunked_content_provider(
  18867. "text/event-stream", [](size_t offset, DataSink &sink) {
  18868. if (offset == 0) {
  18869. std::string event = "event: update\ndata: updated\n\n"
  18870. "event: delete\ndata: deleted\n\n";
  18871. sink.write(event.data(), event.size());
  18872. }
  18873. return false; // End stream after sending
  18874. });
  18875. });
  18876. }
  18877. void start_server() {
  18878. port_ = server_->bind_to_any_port(HOST);
  18879. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18880. // Wait for server to start
  18881. while (!server_->is_running()) {
  18882. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18883. }
  18884. }
  18885. int get_port() const { return port_; }
  18886. void send_event(const std::string &event) {
  18887. std::lock_guard<std::mutex> lock(event_mutex_);
  18888. events_.push_back(event);
  18889. event_cv_.notify_all();
  18890. }
  18891. std::unique_ptr<Server> server_;
  18892. std::thread server_thread_;
  18893. std::mutex event_mutex_;
  18894. std::condition_variable event_cv_;
  18895. std::vector<std::string> events_;
  18896. std::atomic<bool> stop_server_{false};
  18897. std::string last_received_event_id_;
  18898. int port_ = 0;
  18899. };
  18900. //==============================================================================
  18901. // SSE Parsing Tests
  18902. //==============================================================================
  18903. class SSEParsingTest : public SSEIntegrationTest {
  18904. protected:
  18905. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  18906. // A trailing sentinel event tells when the whole stream has been parsed.
  18907. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  18908. auto body = stream + "event: end\ndata: end\n\n";
  18909. server_->Get("/parse", [body](const Request &, Response &res) {
  18910. res.set_content(body, "text/event-stream");
  18911. });
  18912. return collect("/parse");
  18913. }
  18914. // Runs SSEClient against path until an "end" event arrives and returns the
  18915. // messages dispatched before it
  18916. std::vector<sse::SSEMessage> collect(const std::string &path) {
  18917. Client client(HOST, get_port());
  18918. sse::SSEClient sse(client, path);
  18919. std::mutex mutex;
  18920. std::condition_variable cv;
  18921. std::vector<sse::SSEMessage> messages;
  18922. auto done = false;
  18923. sse.on_message([&](const sse::SSEMessage &msg) {
  18924. std::lock_guard<std::mutex> lock(mutex);
  18925. // Ignore a replay from a reconnect that races with stop()
  18926. if (!done) { messages.push_back(msg); }
  18927. });
  18928. sse.on_event("end", [&](const sse::SSEMessage &) {
  18929. std::lock_guard<std::mutex> lock(mutex);
  18930. done = true;
  18931. cv.notify_all();
  18932. });
  18933. sse.set_reconnect_interval(100);
  18934. sse.start_async();
  18935. {
  18936. std::unique_lock<std::mutex> lock(mutex);
  18937. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  18938. }
  18939. sse.stop();
  18940. EXPECT_TRUE(done);
  18941. return messages;
  18942. }
  18943. };
  18944. TEST_F(SSEParsingTest, SingleLineData) {
  18945. auto msgs = parse("data: hello\n\n");
  18946. ASSERT_EQ(msgs.size(), 1u);
  18947. EXPECT_EQ(msgs[0].data, "hello");
  18948. EXPECT_EQ(msgs[0].event, "message");
  18949. }
  18950. TEST_F(SSEParsingTest, MultiLineData) {
  18951. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  18952. ASSERT_EQ(msgs.size(), 1u);
  18953. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  18954. }
  18955. TEST_F(SSEParsingTest, CustomEventType) {
  18956. auto msgs = parse("event: update\ndata: payload\n\n");
  18957. ASSERT_EQ(msgs.size(), 1u);
  18958. EXPECT_EQ(msgs[0].event, "update");
  18959. EXPECT_EQ(msgs[0].data, "payload");
  18960. }
  18961. TEST_F(SSEParsingTest, EventIdHandling) {
  18962. auto msgs = parse("id: 12345\ndata: test\n\n");
  18963. ASSERT_EQ(msgs.size(), 1u);
  18964. EXPECT_EQ(msgs[0].id, "12345");
  18965. }
  18966. TEST_F(SSEParsingTest, EmptyEventId) {
  18967. auto msgs = parse("id:\ndata: test\n\n");
  18968. ASSERT_EQ(msgs.size(), 1u);
  18969. EXPECT_EQ(msgs[0].id, "");
  18970. }
  18971. TEST_F(SSEParsingTest, CommentsIgnored) {
  18972. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  18973. ASSERT_EQ(msgs.size(), 1u);
  18974. EXPECT_EQ(msgs[0].data, "hello");
  18975. EXPECT_EQ(msgs[0].event, "message");
  18976. }
  18977. TEST_F(SSEParsingTest, ColonInValue) {
  18978. auto msgs = parse("data: hello:world:test\n\n");
  18979. ASSERT_EQ(msgs.size(), 1u);
  18980. EXPECT_EQ(msgs[0].data, "hello:world:test");
  18981. }
  18982. TEST_F(SSEParsingTest, FieldNameOnly) {
  18983. // A line without a colon is a field name with an empty value
  18984. auto msgs = parse("data\n\n");
  18985. ASSERT_EQ(msgs.size(), 1u);
  18986. EXPECT_EQ(msgs[0].data, "");
  18987. }
  18988. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18989. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  18990. ASSERT_EQ(msgs.size(), 1u);
  18991. EXPECT_EQ(msgs[0].event, "update");
  18992. EXPECT_EQ(msgs[0].data, "hello");
  18993. }
  18994. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  18995. auto msgs = parse("data\r\n\r\n");
  18996. ASSERT_EQ(msgs.size(), 1u);
  18997. EXPECT_EQ(msgs[0].data, "");
  18998. }
  18999. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19000. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19001. ASSERT_EQ(msgs.size(), 1u);
  19002. EXPECT_EQ(msgs[0].data, "hello");
  19003. EXPECT_EQ(msgs[0].event, "message");
  19004. }
  19005. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19006. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19007. ASSERT_EQ(msgs.size(), 2u);
  19008. EXPECT_EQ(msgs[0].data, "hello");
  19009. EXPECT_EQ(msgs[1].data, "hello");
  19010. }
  19011. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19012. // An event without data is not dispatched, and its type must not leak
  19013. // into the next event
  19014. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19015. ASSERT_EQ(msgs.size(), 1u);
  19016. EXPECT_EQ(msgs[0].event, "message");
  19017. EXPECT_EQ(msgs[0].data, "hello");
  19018. }
  19019. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19020. // The first connection sends only an id; the second echoes back the
  19021. // Last-Event-ID it was reconnected with
  19022. std::atomic<int> connection_count{0};
  19023. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19024. if (connection_count++ == 0) {
  19025. res.set_content("id: 42\n\n", "text/event-stream");
  19026. } else {
  19027. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19028. "\n\nevent: end\ndata: end\n\n",
  19029. "text/event-stream");
  19030. }
  19031. });
  19032. auto msgs = collect("/id-only");
  19033. ASSERT_EQ(msgs.size(), 1u);
  19034. EXPECT_EQ(msgs[0].data, "42");
  19035. }
  19036. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19037. // The first connection sets an id and then clears it with an empty one; the
  19038. // second reports whether it was reconnected with a Last-Event-ID
  19039. std::atomic<int> connection_count{0};
  19040. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19041. if (connection_count++ == 0) {
  19042. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19043. "text/event-stream");
  19044. } else {
  19045. res.set_content(
  19046. std::string("data: ") +
  19047. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19048. "\n\nevent: end\ndata: end\n\n",
  19049. "text/event-stream");
  19050. }
  19051. });
  19052. auto msgs = collect("/id-clear");
  19053. ASSERT_EQ(msgs.size(), 3u);
  19054. EXPECT_EQ(msgs[0].id, "1");
  19055. EXPECT_EQ(msgs[1].id, "");
  19056. EXPECT_EQ(msgs[2].data, "not sent");
  19057. }
  19058. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19059. auto msgs = parse("event: notification\nid: evt-42\n"
  19060. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19061. ASSERT_EQ(msgs.size(), 1u);
  19062. EXPECT_EQ(msgs[0].event, "notification");
  19063. EXPECT_EQ(msgs[0].id, "evt-42");
  19064. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19065. }
  19066. TEST(SSEMessageTest, Clear) {
  19067. sse::SSEMessage msg;
  19068. msg.event = "custom";
  19069. msg.data = "some data";
  19070. msg.id = "123";
  19071. msg.clear();
  19072. EXPECT_EQ(msg.event, "message");
  19073. EXPECT_EQ(msg.data, "");
  19074. EXPECT_EQ(msg.id, "");
  19075. }
  19076. //==============================================================================
  19077. // SSE Integration Tests
  19078. //==============================================================================
  19079. // Test: Successful connection and on_open callback
  19080. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19081. // Add a simple endpoint that sends one event and closes
  19082. server_->Get("/simple-event", [](const Request &, Response &res) {
  19083. res.set_chunked_content_provider(
  19084. "text/event-stream", [](size_t offset, DataSink &sink) {
  19085. if (offset == 0) {
  19086. std::string event = "data: hello\n\n";
  19087. sink.write(event.data(), event.size());
  19088. }
  19089. return false; // Close stream after sending
  19090. });
  19091. });
  19092. Client client("localhost", get_port());
  19093. sse::SSEClient sse(client, "/simple-event");
  19094. std::atomic<bool> open_called{false};
  19095. std::atomic<bool> message_received{false};
  19096. sse.on_open([&open_called]() { open_called.store(true); });
  19097. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19098. if (msg.data == "hello") { message_received.store(true); }
  19099. });
  19100. sse.set_reconnect_interval(100);
  19101. sse.set_max_reconnect_attempts(1);
  19102. // Start async
  19103. sse.start_async();
  19104. // Wait for message to be processed
  19105. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19106. sse.stop();
  19107. EXPECT_TRUE(open_called.load());
  19108. EXPECT_TRUE(message_received.load());
  19109. }
  19110. // Test: on_message callback
  19111. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19112. // Endpoint that sends multiple events then closes
  19113. server_->Get("/multi-event", [](const Request &, Response &res) {
  19114. res.set_chunked_content_provider(
  19115. "text/event-stream", [](size_t offset, DataSink &sink) {
  19116. if (offset == 0) {
  19117. std::string events = "data: message1\n\ndata: message2\n\n";
  19118. sink.write(events.data(), events.size());
  19119. }
  19120. return false;
  19121. });
  19122. });
  19123. Client client("localhost", get_port());
  19124. sse::SSEClient sse(client, "/multi-event");
  19125. std::vector<std::string> received_messages;
  19126. std::mutex messages_mutex;
  19127. sse.on_message([&](const sse::SSEMessage &msg) {
  19128. std::lock_guard<std::mutex> lock(messages_mutex);
  19129. received_messages.push_back(msg.data);
  19130. });
  19131. sse.set_reconnect_interval(100);
  19132. sse.set_max_reconnect_attempts(1);
  19133. sse.start_async();
  19134. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19135. sse.stop();
  19136. std::lock_guard<std::mutex> lock(messages_mutex);
  19137. EXPECT_GE(received_messages.size(), 2u);
  19138. if (received_messages.size() >= 2) {
  19139. EXPECT_EQ(received_messages[0], "message1");
  19140. EXPECT_EQ(received_messages[1], "message2");
  19141. }
  19142. }
  19143. // Test: on_event for specific types
  19144. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19145. Client client("localhost", get_port());
  19146. sse::SSEClient sse(client, "/custom-events");
  19147. std::atomic<bool> update_received{false};
  19148. std::atomic<bool> delete_received{false};
  19149. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19150. if (msg.data == "updated") { update_received.store(true); }
  19151. });
  19152. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19153. if (msg.data == "deleted") { delete_received.store(true); }
  19154. });
  19155. sse.set_max_reconnect_attempts(1);
  19156. sse.start_async();
  19157. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19158. sse.stop();
  19159. EXPECT_TRUE(update_received.load());
  19160. EXPECT_TRUE(delete_received.load());
  19161. }
  19162. // Test: on_error callback on connection failure
  19163. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19164. // Connect to a non-existent port
  19165. Client client("localhost", 59999);
  19166. sse::SSEClient sse(client, "/events");
  19167. std::atomic<bool> error_called{false};
  19168. Error received_error = Error::Success;
  19169. sse.on_error([&](Error err) {
  19170. error_called.store(true);
  19171. received_error = err;
  19172. });
  19173. sse.set_reconnect_interval(50);
  19174. sse.set_max_reconnect_attempts(1);
  19175. sse.start_async();
  19176. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19177. sse.stop();
  19178. EXPECT_TRUE(error_called.load());
  19179. EXPECT_NE(received_error, Error::Success);
  19180. }
  19181. // Test: Last-Event-ID header sent on reconnect
  19182. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19183. // Endpoint that sends event with ID
  19184. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19185. res.set_chunked_content_provider(
  19186. "text/event-stream", [](size_t offset, DataSink &sink) {
  19187. if (offset == 0) {
  19188. std::string event = "id: evt-123\ndata: test\n\n";
  19189. sink.write(event.data(), event.size());
  19190. }
  19191. return false;
  19192. });
  19193. });
  19194. Client client("localhost", get_port());
  19195. sse::SSEClient sse(client, "/event-with-id");
  19196. std::atomic<bool> id_received{false};
  19197. sse.on_message([&](const sse::SSEMessage &msg) {
  19198. if (!msg.id.empty()) { id_received.store(true); }
  19199. });
  19200. sse.set_reconnect_interval(100);
  19201. sse.set_max_reconnect_attempts(1);
  19202. sse.start_async();
  19203. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19204. sse.stop();
  19205. EXPECT_TRUE(id_received.load());
  19206. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19207. }
  19208. // Test: Manual stop
  19209. TEST_F(SSEIntegrationTest, ManualStop) {
  19210. // Endpoint that sends one event and stays open briefly
  19211. std::atomic<bool> handler_running{true};
  19212. server_->Get("/stay-open", [&handler_running](const Request &,
  19213. Response &res) {
  19214. res.set_chunked_content_provider(
  19215. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19216. if (offset == 0) {
  19217. std::string event = "data: connected\n\n";
  19218. sink.write(event.data(), event.size());
  19219. }
  19220. // Keep connection open while handler_running is true
  19221. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19222. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19223. }
  19224. return false;
  19225. });
  19226. });
  19227. Client client("localhost", get_port());
  19228. sse::SSEClient sse(client, "/stay-open");
  19229. std::atomic<bool> connected{false};
  19230. sse.on_open([&connected]() { connected.store(true); });
  19231. sse.set_reconnect_interval(100);
  19232. sse.set_max_reconnect_attempts(1);
  19233. sse.start_async();
  19234. // Wait for connection to establish
  19235. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19236. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19237. }
  19238. EXPECT_TRUE(connected.load());
  19239. EXPECT_TRUE(sse.is_connected());
  19240. // Signal handler to stop
  19241. handler_running.store(false);
  19242. // Stop SSE client
  19243. sse.stop();
  19244. EXPECT_FALSE(sse.is_connected());
  19245. }
  19246. // Test: SSEClient with custom headers
  19247. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19248. // Setup a server endpoint that checks for custom header
  19249. std::atomic<bool> header_received{false};
  19250. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19251. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19252. header_received.store(true);
  19253. }
  19254. res.set_chunked_content_provider("text/event-stream",
  19255. [](size_t, DataSink &) { return false; });
  19256. });
  19257. Client client("localhost", get_port());
  19258. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19259. sse::SSEClient sse(client, "/header-check", headers);
  19260. sse.set_max_reconnect_attempts(1);
  19261. sse.start_async();
  19262. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19263. sse.stop();
  19264. EXPECT_TRUE(header_received.load());
  19265. }
  19266. // Test: Reconnect interval configuration
  19267. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19268. Client client("localhost", get_port());
  19269. sse::SSEClient sse(client, "/events");
  19270. auto &result = sse.set_reconnect_interval(500);
  19271. // Builder pattern should return reference to self
  19272. EXPECT_EQ(&result, &sse);
  19273. }
  19274. // Test: Max reconnect attempts
  19275. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19276. // Connect to non-existent port to force reconnects
  19277. Client client("localhost", 59998);
  19278. sse::SSEClient sse(client, "/events");
  19279. std::atomic<int> error_count{0};
  19280. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19281. sse.set_reconnect_interval(50);
  19282. sse.set_max_reconnect_attempts(2);
  19283. auto start = std::chrono::steady_clock::now();
  19284. sse.start(); // Blocking call
  19285. auto end = std::chrono::steady_clock::now();
  19286. // Should have stopped after 2 failed attempts
  19287. EXPECT_GE(error_count.load(), 2);
  19288. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19289. auto duration =
  19290. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19291. #ifdef _WIN32
  19292. // Windows is much slower for socket connection failures
  19293. EXPECT_LT(duration.count(), 7000);
  19294. #else
  19295. EXPECT_LT(duration.count(), 1000);
  19296. #endif
  19297. }
  19298. // Test: Multi-line data in integration
  19299. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19300. // Endpoint with multi-line data
  19301. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19302. res.set_chunked_content_provider(
  19303. "text/event-stream", [](size_t offset, DataSink &sink) {
  19304. if (offset == 0) {
  19305. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19306. sink.write(event.data(), event.size());
  19307. }
  19308. return false;
  19309. });
  19310. });
  19311. Client client("localhost", get_port());
  19312. sse::SSEClient sse(client, "/multiline-data");
  19313. std::string received_data;
  19314. std::mutex data_mutex;
  19315. sse.on_message([&](const sse::SSEMessage &msg) {
  19316. std::lock_guard<std::mutex> lock(data_mutex);
  19317. received_data = msg.data;
  19318. });
  19319. sse.set_reconnect_interval(100);
  19320. sse.set_max_reconnect_attempts(1);
  19321. sse.start_async();
  19322. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19323. sse.stop();
  19324. std::lock_guard<std::mutex> lock(data_mutex);
  19325. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19326. }
  19327. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19328. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19329. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19330. DataSink &sink) {
  19331. if (offset == 0) {
  19332. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19333. sink.write(events.data(), events.size());
  19334. }
  19335. return false;
  19336. });
  19337. });
  19338. Client client("localhost", get_port());
  19339. sse::SSEClient sse(client, "/empty-data-lines");
  19340. std::mutex mutex;
  19341. std::condition_variable cv;
  19342. std::vector<std::string> received;
  19343. sse.on_message([&](const sse::SSEMessage &msg) {
  19344. std::lock_guard<std::mutex> lock(mutex);
  19345. received.push_back(msg.data);
  19346. cv.notify_all();
  19347. });
  19348. sse.set_max_reconnect_attempts(1);
  19349. sse.start_async();
  19350. {
  19351. std::unique_lock<std::mutex> lock(mutex);
  19352. cv.wait_for(lock, std::chrono::seconds(2),
  19353. [&] { return received.size() >= 3; });
  19354. }
  19355. sse.stop();
  19356. ASSERT_GE(received.size(), 3u);
  19357. EXPECT_EQ(received[0], "");
  19358. EXPECT_EQ(received[1], "\nhello");
  19359. EXPECT_EQ(received[2], "");
  19360. }
  19361. // Test: Auto-reconnect after server disconnection
  19362. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19363. std::atomic<int> connection_count{0};
  19364. std::atomic<int> message_count{0};
  19365. // Endpoint that sends one event and closes, forcing reconnect
  19366. server_->Get("/reconnect-test",
  19367. [&connection_count](const Request &, Response &res) {
  19368. connection_count.fetch_add(1);
  19369. res.set_chunked_content_provider(
  19370. "text/event-stream", [](size_t offset, DataSink &sink) {
  19371. if (offset == 0) {
  19372. std::string event = "data: hello\n\n";
  19373. sink.write(event.data(), event.size());
  19374. }
  19375. return false; // Close connection after sending
  19376. });
  19377. });
  19378. Client client("localhost", get_port());
  19379. sse::SSEClient sse(client, "/reconnect-test");
  19380. sse.on_message([&message_count](const sse::SSEMessage &) {
  19381. message_count.fetch_add(1);
  19382. });
  19383. sse.set_reconnect_interval(100);
  19384. sse.set_max_reconnect_attempts(3);
  19385. sse.start_async();
  19386. // Wait long enough for multiple reconnects
  19387. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19388. sse.stop();
  19389. // Should have connected multiple times (initial + reconnects)
  19390. EXPECT_GE(connection_count.load(), 2);
  19391. // Should have received messages from multiple connections
  19392. EXPECT_GE(message_count.load(), 2);
  19393. }
  19394. // Test: A retry field that is not all ASCII digits is ignored
  19395. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19396. std::atomic<int> connection_count{0};
  19397. server_->Get("/bad-retry",
  19398. [&connection_count](const Request &, Response &res) {
  19399. connection_count.fetch_add(1);
  19400. res.set_chunked_content_provider(
  19401. "text/event-stream", [](size_t offset, DataSink &sink) {
  19402. if (offset == 0) {
  19403. std::string event = "retry: -1\ndata: hello\n\n";
  19404. sink.write(event.data(), event.size());
  19405. }
  19406. return false;
  19407. });
  19408. });
  19409. Client client("localhost", get_port());
  19410. sse::SSEClient sse(client, "/bad-retry");
  19411. sse.set_reconnect_interval(10000);
  19412. sse.start_async();
  19413. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19414. sse.stop();
  19415. EXPECT_EQ(connection_count.load(), 1);
  19416. }
  19417. // Test: A retry field of all ASCII digits sets the reconnection time
  19418. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19419. std::atomic<int> connection_count{0};
  19420. server_->Get("/zero-retry",
  19421. [&connection_count](const Request &, Response &res) {
  19422. connection_count.fetch_add(1);
  19423. res.set_chunked_content_provider(
  19424. "text/event-stream", [](size_t offset, DataSink &sink) {
  19425. if (offset == 0) {
  19426. std::string event = "retry: 0\ndata: hello\n\n";
  19427. sink.write(event.data(), event.size());
  19428. }
  19429. return false;
  19430. });
  19431. });
  19432. Client client("localhost", get_port());
  19433. sse::SSEClient sse(client, "/zero-retry");
  19434. sse.set_reconnect_interval(10000);
  19435. sse.start_async();
  19436. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19437. sse.stop();
  19438. // The server-supplied interval is applied, but never below 100ms, so
  19439. // "retry: 0" does not cause a busy reconnect loop
  19440. EXPECT_GE(connection_count.load(), 2);
  19441. EXPECT_LE(connection_count.load(), 10);
  19442. }
  19443. // Test: Last-Event-ID sent on reconnect
  19444. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19445. std::atomic<int> connection_count{0};
  19446. std::vector<std::string> received_last_event_ids;
  19447. std::mutex id_mutex;
  19448. // Endpoint that checks Last-Event-ID header and sends event with ID
  19449. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19450. int conn = connection_count.fetch_add(1);
  19451. // Capture the Last-Event-ID header from each connection
  19452. {
  19453. std::lock_guard<std::mutex> lock(id_mutex);
  19454. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19455. }
  19456. res.set_chunked_content_provider(
  19457. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19458. if (offset == 0) {
  19459. std::string event =
  19460. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19461. sink.write(event.data(), event.size());
  19462. }
  19463. return false;
  19464. });
  19465. });
  19466. Client client("localhost", get_port());
  19467. sse::SSEClient sse(client, "/reconnect-with-id");
  19468. sse.set_reconnect_interval(100);
  19469. sse.set_max_reconnect_attempts(3);
  19470. sse.start_async();
  19471. // Wait for at least 2 connections
  19472. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19473. sse.stop();
  19474. // Verify behavior
  19475. std::lock_guard<std::mutex> lock(id_mutex);
  19476. EXPECT_GE(received_last_event_ids.size(), 2u);
  19477. // First connection should have no Last-Event-ID
  19478. if (!received_last_event_ids.empty()) {
  19479. EXPECT_EQ(received_last_event_ids[0], "");
  19480. }
  19481. // Second connection should have Last-Event-ID from first connection
  19482. if (received_last_event_ids.size() >= 2) {
  19483. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19484. }
  19485. }
  19486. // Test: set_headers updates headers used on reconnect
  19487. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19488. std::vector<std::string> received_tokens;
  19489. std::mutex token_mutex;
  19490. // Endpoint that captures Authorization header
  19491. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19492. {
  19493. std::lock_guard<std::mutex> lock(token_mutex);
  19494. received_tokens.push_back(req.get_header_value("Authorization"));
  19495. }
  19496. res.set_chunked_content_provider(
  19497. "text/event-stream", [](size_t offset, DataSink &sink) {
  19498. if (offset == 0) {
  19499. std::string event = "data: hello\n\n";
  19500. sink.write(event.data(), event.size());
  19501. }
  19502. return false; // Close connection to trigger reconnect
  19503. });
  19504. });
  19505. Client client("localhost", get_port());
  19506. Headers headers = {{"Authorization", "Bearer old-token"}};
  19507. sse::SSEClient sse(client, "/auth-check", headers);
  19508. // Update headers on each successful connection
  19509. sse.on_open(
  19510. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19511. sse.set_reconnect_interval(100);
  19512. sse.set_max_reconnect_attempts(3);
  19513. sse.start_async();
  19514. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19515. sse.stop();
  19516. std::lock_guard<std::mutex> lock(token_mutex);
  19517. ASSERT_GE(received_tokens.size(), 2u);
  19518. // First connection uses original header
  19519. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19520. // Second connection uses updated header from set_headers
  19521. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19522. }
  19523. // Test: 401 allows reconnection (so on_error can refresh headers)
  19524. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19525. std::atomic<int> connection_count{0};
  19526. // Endpoint: returns 401 on first attempt, 200 on second
  19527. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19528. int conn = connection_count.fetch_add(1);
  19529. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19530. res.status = StatusCode::Unauthorized_401;
  19531. res.set_content("Unauthorized", "text/plain");
  19532. return;
  19533. }
  19534. res.set_chunked_content_provider(
  19535. "text/event-stream", [](size_t offset, DataSink &sink) {
  19536. if (offset == 0) {
  19537. std::string event = "data: authenticated\n\n";
  19538. sink.write(event.data(), event.size());
  19539. }
  19540. return false;
  19541. });
  19542. });
  19543. Client client("localhost", get_port());
  19544. Headers headers = {{"Authorization", "Bearer expired"}};
  19545. sse::SSEClient sse(client, "/auth-retry", headers);
  19546. std::atomic<bool> message_received{false};
  19547. // Refresh token on error
  19548. sse.on_error(
  19549. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19550. sse.on_message([&](const sse::SSEMessage &msg) {
  19551. if (msg.data == "authenticated") { message_received.store(true); }
  19552. });
  19553. sse.set_reconnect_interval(100);
  19554. sse.set_max_reconnect_attempts(3);
  19555. sse.start_async();
  19556. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19557. sse.stop();
  19558. // Should have reconnected after 401 and succeeded with new token
  19559. EXPECT_GE(connection_count.load(), 2);
  19560. EXPECT_TRUE(message_received.load());
  19561. }
  19562. TEST(Issue2318Test, EmptyHostString) {
  19563. {
  19564. httplib::Client cli_empty("", PORT);
  19565. auto res = cli_empty.Get("/");
  19566. ASSERT_FALSE(res);
  19567. EXPECT_EQ(httplib::Error::Connection, res.error());
  19568. }
  19569. {
  19570. httplib::Client cli(" ", PORT);
  19571. auto res = cli.Get("/");
  19572. ASSERT_FALSE(res);
  19573. EXPECT_EQ(httplib::Error::Connection, res.error());
  19574. }
  19575. }
  19576. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19577. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19578. Server svr;
  19579. // Set a small payload limit (1KB)
  19580. svr.set_payload_max_length(1024);
  19581. svr.Post("/test", [&](const Request &req, Response &res) {
  19582. res.set_content("Body size: " + std::to_string(req.body.size()),
  19583. "text/plain");
  19584. });
  19585. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19586. auto se = detail::scope_exit([&] {
  19587. svr.stop();
  19588. listen_thread.join();
  19589. });
  19590. svr.wait_until_ready();
  19591. // Create data that compresses well but exceeds limit when decompressed
  19592. // 8KB of repeated null bytes compresses to a very small size
  19593. std::string original_data(8 * 1024, '\0');
  19594. // Compress the data using gzip
  19595. std::string compressed_data;
  19596. detail::gzip_compressor compressor;
  19597. compressor.compress(original_data.data(), original_data.size(), true,
  19598. [&](const char *data, size_t size) {
  19599. compressed_data.append(data, size);
  19600. return true;
  19601. });
  19602. // Verify compression worked (compressed should be much smaller)
  19603. ASSERT_LT(compressed_data.size(), original_data.size());
  19604. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19605. // Send compressed data with Content-Encoding: gzip
  19606. Client cli(HOST, PORT);
  19607. Headers headers = {{"Content-Encoding", "gzip"}};
  19608. auto res =
  19609. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19610. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19612. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19613. }
  19614. #endif
  19615. // ============================================================================
  19616. // OpenSSL-Specific Tests
  19617. // ============================================================================
  19618. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19619. X509 *readCertificate(const std::string &strFileName) {
  19620. std::ifstream inStream(strFileName);
  19621. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19622. std::istreambuf_iterator<char>());
  19623. if (strCertPEM.empty()) return (nullptr);
  19624. BIO *pbCert = BIO_new(BIO_s_mem());
  19625. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19626. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19627. BIO_free(pbCert);
  19628. return (pCert);
  19629. }
  19630. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19631. std::ifstream inStream(strFileName);
  19632. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19633. std::istreambuf_iterator<char>());
  19634. if (strPrivateKeyPEM.empty()) return (nullptr);
  19635. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19636. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19637. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19638. BIO_free(pbPrivKey);
  19639. return (pPrivateKey);
  19640. }
  19641. TEST(BindServerTest, UpdateCerts) {
  19642. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19643. int port = svr.bind_to_any_port("0.0.0.0");
  19644. ASSERT_TRUE(svr.is_valid());
  19645. ASSERT_TRUE(port > 0);
  19646. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19647. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19648. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19649. ASSERT_TRUE(cert != nullptr);
  19650. ASSERT_TRUE(ca_cert != nullptr);
  19651. ASSERT_TRUE(key != nullptr);
  19652. X509_STORE *cert_store = X509_STORE_new();
  19653. X509_STORE_add_cert(cert_store, ca_cert);
  19654. // svr.update_certs(cert, key, cert_store); // deprecated
  19655. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19656. CLIENT_CA_CERT_FILE);
  19657. ASSERT_TRUE(svr.is_valid());
  19658. svr.stop();
  19659. X509_STORE_free(cert_store);
  19660. X509_free(cert);
  19661. X509_free(ca_cert);
  19662. EVP_PKEY_free(key);
  19663. }
  19664. // Test that update_certs() updates client CA list correctly
  19665. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19666. // Start with file-based constructor
  19667. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19668. ASSERT_TRUE(svr.is_valid());
  19669. // Initially no client CA list should be set
  19670. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19671. ASSERT_TRUE(ssl_ctx != nullptr);
  19672. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19673. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19674. EXPECT_EQ(0, count_before);
  19675. // Now update with client CA (PEM string)
  19676. std::string cert_pem, key_pem, ca_pem;
  19677. read_file(SERVER_CERT_FILE, cert_pem);
  19678. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19679. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19680. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19681. ASSERT_TRUE(svr.is_valid());
  19682. // Now client CA list should be set
  19683. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19684. ASSERT_TRUE(ca_list_after != nullptr);
  19685. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19686. }
  19687. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19688. // Test that the file-path SSLServer constructor properly sets the client CA
  19689. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19691. ASSERT_TRUE(svr.is_valid());
  19692. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19693. ASSERT_TRUE(ssl_ctx != nullptr);
  19694. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19695. ASSERT_TRUE(ca_list != nullptr);
  19696. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19697. }
  19698. #endif
  19699. // ============================================================================
  19700. // MbedTLS-Specific Tests
  19701. // ============================================================================
  19702. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19703. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19704. using namespace httplib::tls;
  19705. // Track if callback was invoked
  19706. bool callback_invoked = false;
  19707. // The callback receives void* ctx which is actually MbedTlsContext*
  19708. // We can access the mbedtls_ssl_config via the context
  19709. auto setup_callback = [&callback_invoked](void *ctx) {
  19710. callback_invoked = true;
  19711. // Cast to MbedTlsContext* to access the ssl config
  19712. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19713. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19714. // Use static variables to hold certificate data (simplified for test)
  19715. static mbedtls_x509_crt own_cert;
  19716. static mbedtls_pk_context own_key;
  19717. static mbedtls_x509_crt ca_chain;
  19718. static bool initialized = false;
  19719. if (!initialized) {
  19720. mbedtls_x509_crt_init(&own_cert);
  19721. mbedtls_pk_init(&own_key);
  19722. mbedtls_x509_crt_init(&ca_chain);
  19723. // Load server certificate
  19724. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19725. return false;
  19726. }
  19727. // Load server private key.
  19728. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19729. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19730. #if MBEDTLS_VERSION_MAJOR == 3
  19731. ,
  19732. mbedtls_ctr_drbg_random, nullptr
  19733. #endif
  19734. ) != 0) {
  19735. return false;
  19736. }
  19737. // Load CA chain for client verification
  19738. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19739. return false;
  19740. }
  19741. initialized = true;
  19742. }
  19743. // Configure the SSL config
  19744. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19745. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19746. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19747. // Set minimum TLS version using mbedTLS native API
  19748. #if MBEDTLS_VERSION_MAJOR >= 3
  19749. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19750. #else
  19751. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19752. MBEDTLS_SSL_MINOR_VERSION_3);
  19753. #endif
  19754. return true;
  19755. };
  19756. SSLServer svr(setup_callback);
  19757. ASSERT_TRUE(svr.is_valid());
  19758. ASSERT_TRUE(callback_invoked);
  19759. svr.Get("/test", [&](const Request &req, Response &res) {
  19760. res.set_content("test", "text/plain");
  19761. auto cert = req.peer_cert();
  19762. ASSERT_TRUE(static_cast<bool>(cert));
  19763. auto common_name = cert.subject_cn();
  19764. EXPECT_EQ("Common Name", common_name);
  19765. });
  19766. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19767. auto se = detail::scope_exit([&] {
  19768. svr.stop();
  19769. t.join();
  19770. ASSERT_FALSE(svr.is_running());
  19771. });
  19772. svr.wait_until_ready();
  19773. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19774. cli.enable_server_certificate_verification(false);
  19775. cli.set_connection_timeout(30);
  19776. auto res = cli.Get("/test");
  19777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19778. ASSERT_EQ(StatusCode::OK_200, res->status);
  19779. }
  19780. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19781. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19782. // keep-alive SSL session, which reads through that config in
  19783. // mbedtls_ssl_close_notify.
  19784. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19786. ASSERT_TRUE(svr.is_valid());
  19787. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19788. res.set_content("test", "text/plain");
  19789. });
  19790. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19791. auto se = detail::scope_exit([&] {
  19792. svr.stop();
  19793. t.join();
  19794. ASSERT_FALSE(svr.is_running());
  19795. });
  19796. svr.wait_until_ready();
  19797. {
  19798. SSLClient cli(HOST, PORT);
  19799. cli.enable_server_certificate_verification(false);
  19800. cli.set_keep_alive(true);
  19801. auto res = cli.Get("/test");
  19802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19803. ASSERT_EQ(StatusCode::OK_200, res->status);
  19804. // cli is destructed here with the keep-alive SSL session still open.
  19805. }
  19806. }
  19807. #endif
  19808. // WebSocket Tests
  19809. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19810. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19811. // defining the meaning of these bits has been negotiated.
  19812. auto make_frame = [](uint8_t first_byte) {
  19813. std::string frame;
  19814. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19815. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19816. frame += "Hello";
  19817. return frame;
  19818. };
  19819. // RSV1 set (0x40)
  19820. {
  19821. detail::BufferStream strm;
  19822. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19823. ws::Opcode opcode;
  19824. std::string payload;
  19825. bool fin;
  19826. EXPECT_EQ(
  19827. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19828. ws::impl::FrameRead::Fail);
  19829. }
  19830. // RSV2 set (0x20)
  19831. {
  19832. detail::BufferStream strm;
  19833. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19834. ws::Opcode opcode;
  19835. std::string payload;
  19836. bool fin;
  19837. EXPECT_EQ(
  19838. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19839. ws::impl::FrameRead::Fail);
  19840. }
  19841. // RSV3 set (0x10)
  19842. {
  19843. detail::BufferStream strm;
  19844. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19845. ws::Opcode opcode;
  19846. std::string payload;
  19847. bool fin;
  19848. EXPECT_EQ(
  19849. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19850. ws::impl::FrameRead::Fail);
  19851. }
  19852. // No RSV bits set - should succeed
  19853. {
  19854. detail::BufferStream strm;
  19855. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19856. ws::Opcode opcode;
  19857. std::string payload;
  19858. bool fin;
  19859. EXPECT_EQ(
  19860. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19861. ws::impl::FrameRead::Ok);
  19862. EXPECT_EQ(ws::Opcode::Text, opcode);
  19863. EXPECT_EQ("Hello", payload);
  19864. EXPECT_TRUE(fin);
  19865. }
  19866. }
  19867. TEST(WebSocketTest, ControlFrameValidation) {
  19868. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19869. // payload length <= 125.
  19870. // Ping with FIN=0 - must be rejected
  19871. {
  19872. detail::BufferStream strm;
  19873. std::string frame;
  19874. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19875. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19876. strm.write(frame.data(), frame.size());
  19877. ws::Opcode opcode;
  19878. std::string payload;
  19879. bool fin;
  19880. EXPECT_EQ(
  19881. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19882. ws::impl::FrameRead::Fail);
  19883. }
  19884. // Close with FIN=0 - must be rejected
  19885. {
  19886. detail::BufferStream strm;
  19887. std::string frame;
  19888. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19889. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19890. strm.write(frame.data(), frame.size());
  19891. ws::Opcode opcode;
  19892. std::string payload;
  19893. bool fin;
  19894. EXPECT_EQ(
  19895. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19896. ws::impl::FrameRead::Fail);
  19897. }
  19898. // Ping with payload_len=126 (extended length) - must be rejected
  19899. {
  19900. detail::BufferStream strm;
  19901. std::string frame;
  19902. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19903. frame += static_cast<char>(126); // payload_len=126 (>125)
  19904. frame += static_cast<char>(0x00); // extended length high byte
  19905. frame += static_cast<char>(126); // extended length low byte
  19906. frame += std::string(126, 'x');
  19907. strm.write(frame.data(), frame.size());
  19908. ws::Opcode opcode;
  19909. std::string payload;
  19910. bool fin;
  19911. EXPECT_EQ(
  19912. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19913. ws::impl::FrameRead::Fail);
  19914. }
  19915. // Ping with FIN=1 and payload_len=125 - should succeed
  19916. {
  19917. detail::BufferStream strm;
  19918. std::string frame;
  19919. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19920. frame += static_cast<char>(125); // payload_len=125
  19921. frame += std::string(125, 'x');
  19922. strm.write(frame.data(), frame.size());
  19923. ws::Opcode opcode;
  19924. std::string payload;
  19925. bool fin;
  19926. EXPECT_EQ(
  19927. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19928. ws::impl::FrameRead::Ok);
  19929. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19930. EXPECT_EQ(125u, payload.size());
  19931. EXPECT_TRUE(fin);
  19932. }
  19933. }
  19934. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19935. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19936. // length MUST be 0.
  19937. // MSB set - must be rejected
  19938. {
  19939. detail::BufferStream strm;
  19940. std::string frame;
  19941. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19942. frame += static_cast<char>(127); // 64-bit extended length
  19943. frame += static_cast<char>(0x80); // MSB set (invalid)
  19944. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19945. strm.write(frame.data(), frame.size());
  19946. ws::Opcode opcode;
  19947. std::string payload;
  19948. bool fin;
  19949. EXPECT_EQ(
  19950. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19951. ws::impl::FrameRead::Fail);
  19952. }
  19953. // MSB clear - should pass length parsing (will be rejected by max_len,
  19954. // but that's a different check; use a small length to verify)
  19955. {
  19956. detail::BufferStream strm;
  19957. std::string frame;
  19958. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19959. frame += static_cast<char>(127); // 64-bit extended length
  19960. frame += std::string(7, '\0'); // high bytes = 0
  19961. frame += static_cast<char>(0x03); // length = 3
  19962. frame += "abc";
  19963. strm.write(frame.data(), frame.size());
  19964. ws::Opcode opcode;
  19965. std::string payload;
  19966. bool fin;
  19967. EXPECT_EQ(
  19968. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19969. ws::impl::FrameRead::Ok);
  19970. EXPECT_EQ(ws::Opcode::Text, opcode);
  19971. EXPECT_EQ("abc", payload);
  19972. }
  19973. }
  19974. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19975. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19976. // Valid UTF-8
  19977. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19978. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19979. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19980. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19981. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19982. // Invalid UTF-8
  19983. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19984. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19985. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19986. EXPECT_FALSE(
  19987. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19988. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19989. }
  19990. TEST(WebSocketTest, ConnectAndDisconnect) {
  19991. Server svr;
  19992. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19993. std::string msg;
  19994. while (ws.read(msg)) {}
  19995. });
  19996. auto port = svr.bind_to_any_port(HOST);
  19997. std::thread t([&]() { svr.listen_after_bind(); });
  19998. svr.wait_until_ready();
  19999. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20000. auto res = client.connect();
  20001. ASSERT_TRUE(res);
  20002. EXPECT_EQ(Error::Success, res.error());
  20003. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20004. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20005. EXPECT_TRUE(client.is_open());
  20006. client.close();
  20007. EXPECT_FALSE(client.is_open());
  20008. svr.stop();
  20009. t.join();
  20010. }
  20011. TEST(WebSocketTest, ValidURL) {
  20012. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20013. EXPECT_TRUE(ws1.is_valid());
  20014. ws::WebSocketClient ws2("ws://example.com/path");
  20015. EXPECT_TRUE(ws2.is_valid());
  20016. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20017. EXPECT_TRUE(ws3.is_valid());
  20018. #ifdef CPPHTTPLIB_SSL_ENABLED
  20019. ws::WebSocketClient wss1("wss://example.com/path");
  20020. EXPECT_TRUE(wss1.is_valid());
  20021. ws::WebSocketClient wss2("wss://example.com:443/path");
  20022. EXPECT_TRUE(wss2.is_valid());
  20023. #endif
  20024. }
  20025. TEST(WebSocketTest, InvalidURL) {
  20026. // No scheme
  20027. ws::WebSocketClient ws1("localhost:8080/path");
  20028. EXPECT_FALSE(ws1.is_valid());
  20029. // No path
  20030. ws::WebSocketClient ws2("ws://localhost:8080");
  20031. EXPECT_FALSE(ws2.is_valid());
  20032. // Empty string
  20033. ws::WebSocketClient ws3("");
  20034. EXPECT_FALSE(ws3.is_valid());
  20035. // Missing host
  20036. ws::WebSocketClient ws4("ws://:8080/path");
  20037. EXPECT_FALSE(ws4.is_valid());
  20038. // Port number overflow — should not crash
  20039. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20040. EXPECT_FALSE(ws5.is_valid());
  20041. // Port out of range
  20042. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20043. EXPECT_FALSE(ws6.is_valid());
  20044. }
  20045. TEST(WebSocketTest, UnsupportedScheme) {
  20046. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20047. ws::WebSocketClient ws1("http://localhost:8080/path");
  20048. EXPECT_FALSE(ws1.is_valid());
  20049. ws::WebSocketClient ws2("https://localhost:8080/path");
  20050. EXPECT_FALSE(ws2.is_valid());
  20051. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20052. EXPECT_FALSE(ws3.is_valid());
  20053. #else
  20054. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20055. std::invalid_argument);
  20056. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20057. std::invalid_argument);
  20058. #endif
  20059. }
  20060. TEST(WebSocketTest, ConnectWhenInvalid) {
  20061. ws::WebSocketClient ws("not a valid url");
  20062. EXPECT_FALSE(ws.is_valid());
  20063. auto res = ws.connect();
  20064. EXPECT_FALSE(res);
  20065. EXPECT_EQ(Error::Connection, res.error());
  20066. EXPECT_EQ(-1, res.status());
  20067. }
  20068. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20069. // Grab a port that is free, then close it again so nothing listens there
  20070. Server svr;
  20071. auto port = svr.bind_to_any_port(HOST);
  20072. svr.stop();
  20073. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20074. auto res = client.connect();
  20075. ASSERT_FALSE(res);
  20076. EXPECT_EQ(Error::Connection, res.error());
  20077. EXPECT_EQ(-1, res.status());
  20078. }
  20079. TEST(WebSocketTest, DefaultPort) {
  20080. ws::WebSocketClient ws1("ws://example.com/path");
  20081. EXPECT_TRUE(ws1.is_valid());
  20082. // ws:// defaults to port 80 (verified by successful parse)
  20083. #ifdef CPPHTTPLIB_SSL_ENABLED
  20084. ws::WebSocketClient ws2("wss://example.com/path");
  20085. EXPECT_TRUE(ws2.is_valid());
  20086. // wss:// defaults to port 443 (verified by successful parse)
  20087. #endif
  20088. }
  20089. TEST(WebSocketTest, IPv6LiteralAddress) {
  20090. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20091. EXPECT_TRUE(ws1.is_valid());
  20092. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20093. EXPECT_TRUE(ws2.is_valid());
  20094. }
  20095. TEST(WebSocketTest, ComplexPath) {
  20096. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20097. EXPECT_TRUE(ws1.is_valid());
  20098. ws::WebSocketClient ws2("ws://localhost:8080/");
  20099. EXPECT_TRUE(ws2.is_valid());
  20100. }
  20101. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20102. Server svr;
  20103. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20104. std::string msg;
  20105. while (ws.read(msg)) {}
  20106. });
  20107. auto port = svr.bind_to_any_port(HOST);
  20108. std::thread t([&]() { svr.listen_after_bind(); });
  20109. svr.wait_until_ready();
  20110. auto another_host = "example.com";
  20111. auto wrong_ip = "192.0.2.1";
  20112. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20113. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20114. ASSERT_TRUE(client.connect());
  20115. EXPECT_TRUE(client.is_open());
  20116. client.close();
  20117. svr.stop();
  20118. t.join();
  20119. }
  20120. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20121. Server svr;
  20122. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20123. std::string msg;
  20124. while (ws.read(msg)) {}
  20125. });
  20126. auto port = svr.bind_to_any_port(HOST);
  20127. std::thread t([&]() { svr.listen_after_bind(); });
  20128. svr.wait_until_ready();
  20129. auto wrong_ip = "192.0.2.1";
  20130. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20131. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20132. client.set_connection_timeout(1);
  20133. client.set_read_timeout(1);
  20134. client.set_write_timeout(1);
  20135. EXPECT_FALSE(client.connect());
  20136. EXPECT_FALSE(client.is_open());
  20137. svr.stop();
  20138. t.join();
  20139. }
  20140. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20141. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20142. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20143. // (RFC 6761) is only a map key and the Host header value.
  20144. auto host = "target.invalid";
  20145. Server svr;
  20146. std::string received_host;
  20147. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20148. received_host = req.get_header_value("Host");
  20149. std::string msg;
  20150. while (ws.read(msg)) {}
  20151. });
  20152. auto port = svr.bind_to_any_port(HOST);
  20153. std::thread t([&]() { svr.listen_after_bind(); });
  20154. // ASSERT_* below returns from the test body, which would leave t joinable
  20155. // and make ~thread call std::terminate.
  20156. auto se = detail::scope_exit([&] {
  20157. svr.stop();
  20158. if (t.joinable()) { t.join(); }
  20159. });
  20160. svr.wait_until_ready();
  20161. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20162. std::to_string(port) + "/ws");
  20163. client.set_hostname_addr_map({{host, HOST}});
  20164. ASSERT_TRUE(client.connect());
  20165. EXPECT_TRUE(client.is_open());
  20166. client.close();
  20167. svr.stop();
  20168. t.join();
  20169. // The mapping only redirects the connection; the identity stays host_.
  20170. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20171. }
  20172. class WebSocketIntegrationTest : public ::testing::Test {
  20173. protected:
  20174. void SetUp() override {
  20175. server_ = httplib::detail::make_unique<Server>();
  20176. setup_server();
  20177. start_server();
  20178. }
  20179. void TearDown() override {
  20180. server_->stop();
  20181. if (server_thread_.joinable()) { server_thread_.join(); }
  20182. }
  20183. void setup_server() {
  20184. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20185. std::string msg;
  20186. ws::ReadResult ret;
  20187. while ((ret = ws.read(msg))) {
  20188. if (ret == ws::Binary) {
  20189. ws.send(msg.data(), msg.size());
  20190. } else {
  20191. ws.send(msg);
  20192. }
  20193. }
  20194. });
  20195. server_->WebSocket("/ws-echo-string",
  20196. [](const Request &, ws::WebSocket &ws) {
  20197. std::string msg;
  20198. while (ws.read(msg)) {
  20199. ws.send("echo: " + msg);
  20200. }
  20201. });
  20202. server_->WebSocket(
  20203. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20204. // Echo back request metadata
  20205. ws.send("path:" + req.path);
  20206. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20207. std::string msg;
  20208. while (ws.read(msg)) {}
  20209. });
  20210. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20211. std::string msg;
  20212. ws.read(msg); // wait for a message
  20213. ws.close();
  20214. });
  20215. server_->WebSocket("/ws-close-status",
  20216. [](const Request &, ws::WebSocket &ws) {
  20217. std::string msg;
  20218. ws.read(msg); // wait for a message
  20219. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20220. });
  20221. server_->WebSocket(
  20222. "/ws-subprotocol",
  20223. [](const Request &, ws::WebSocket &ws) {
  20224. std::string msg;
  20225. while (ws.read(msg)) {
  20226. ws.send(msg);
  20227. }
  20228. },
  20229. [](const std::vector<std::string> &protocols) -> std::string {
  20230. for (const auto &p : protocols) {
  20231. if (p == "graphql-ws") { return p; }
  20232. }
  20233. return "";
  20234. });
  20235. server_->WebSocket(
  20236. "/ws-subprotocol-unoffered",
  20237. [](const Request &, ws::WebSocket &ws) {
  20238. std::string msg;
  20239. while (ws.read(msg)) {
  20240. ws.send(msg);
  20241. }
  20242. },
  20243. [](const std::vector<std::string> &) -> std::string {
  20244. return "admin";
  20245. });
  20246. }
  20247. void start_server() {
  20248. port_ = server_->bind_to_any_port(HOST);
  20249. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20250. server_->wait_until_ready();
  20251. }
  20252. std::unique_ptr<Server> server_;
  20253. std::thread server_thread_;
  20254. int port_ = 0;
  20255. };
  20256. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20257. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20258. "/ws-echo");
  20259. ASSERT_TRUE(client.connect());
  20260. ASSERT_TRUE(client.is_open());
  20261. ASSERT_TRUE(client.send("Hello WebSocket"));
  20262. std::string msg;
  20263. EXPECT_EQ(ws::Text, client.read(msg));
  20264. EXPECT_EQ("Hello WebSocket", msg);
  20265. client.close();
  20266. }
  20267. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20268. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20269. "/ws-echo");
  20270. ASSERT_TRUE(client.connect());
  20271. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20272. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20273. std::string msg;
  20274. EXPECT_EQ(ws::Binary, client.read(msg));
  20275. EXPECT_EQ(binary_data, msg);
  20276. client.close();
  20277. }
  20278. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20279. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20280. "/ws-echo");
  20281. ASSERT_TRUE(client.connect());
  20282. for (int i = 0; i < 10; i++) {
  20283. auto text = "message " + std::to_string(i);
  20284. ASSERT_TRUE(client.send(text));
  20285. std::string msg;
  20286. ASSERT_TRUE(client.read(msg));
  20287. EXPECT_EQ(text, msg);
  20288. }
  20289. client.close();
  20290. }
  20291. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20292. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20293. "/ws-close");
  20294. ASSERT_TRUE(client.connect());
  20295. // Send a message to trigger the server to close
  20296. ASSERT_TRUE(client.send("trigger close"));
  20297. // The server will close, so read should return false
  20298. std::string msg;
  20299. EXPECT_FALSE(client.read(msg));
  20300. EXPECT_FALSE(client.is_open());
  20301. }
  20302. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20303. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20304. "/ws-echo");
  20305. ASSERT_TRUE(client.connect());
  20306. // 128KB message
  20307. std::string large_data(128 * 1024, 'X');
  20308. ASSERT_TRUE(client.send(large_data));
  20309. std::string msg;
  20310. ASSERT_TRUE(client.read(msg));
  20311. EXPECT_EQ(large_data, msg);
  20312. client.close();
  20313. }
  20314. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20315. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20316. "/ws-echo");
  20317. ASSERT_TRUE(client.connect());
  20318. const int num_threads = 4;
  20319. std::vector<std::thread> threads;
  20320. std::atomic<int> send_count{0};
  20321. for (int t = 0; t < num_threads; t++) {
  20322. threads.emplace_back([&client, &send_count, t]() {
  20323. for (int i = 0; i < 5; i++) {
  20324. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20325. if (client.send(text)) { send_count++; }
  20326. }
  20327. });
  20328. }
  20329. for (auto &th : threads) {
  20330. th.join();
  20331. }
  20332. int received = 0;
  20333. std::string msg;
  20334. while (received < send_count.load()) {
  20335. if (!client.read(msg)) { break; }
  20336. received++;
  20337. }
  20338. EXPECT_EQ(send_count.load(), received);
  20339. client.close();
  20340. }
  20341. TEST_F(WebSocketIntegrationTest, ReadString) {
  20342. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20343. "/ws-echo-string");
  20344. ASSERT_TRUE(client.connect());
  20345. ASSERT_TRUE(client.send("hello"));
  20346. std::string msg;
  20347. ASSERT_TRUE(client.read(msg));
  20348. EXPECT_EQ("echo: hello", msg);
  20349. ASSERT_TRUE(client.send("world"));
  20350. ASSERT_TRUE(client.read(msg));
  20351. EXPECT_EQ("echo: world", msg);
  20352. client.close();
  20353. }
  20354. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20355. Headers headers = {{"X-Test-Header", "test-value"}};
  20356. ws::WebSocketClient client(
  20357. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20358. ASSERT_TRUE(client.connect());
  20359. std::string msg;
  20360. ASSERT_TRUE(client.read(msg));
  20361. EXPECT_EQ("path:/ws-request-info", msg);
  20362. ASSERT_TRUE(client.read(msg));
  20363. EXPECT_EQ("header:test-value", msg);
  20364. client.close();
  20365. }
  20366. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20367. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20368. "/ws-echo");
  20369. client.set_read_timeout(1, 0); // 1 second
  20370. ASSERT_TRUE(client.connect());
  20371. // Don't send anything — server echo handler waits for a message, so read()
  20372. // should time out. The connection survives it: nothing was consumed.
  20373. std::string msg;
  20374. EXPECT_EQ(client.read(msg), ws::Timeout);
  20375. EXPECT_TRUE(client.is_open());
  20376. // And it is still usable afterwards.
  20377. EXPECT_TRUE(client.send("after timeout"));
  20378. EXPECT_EQ(client.read(msg), ws::Text);
  20379. EXPECT_EQ(msg, "after timeout");
  20380. }
  20381. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20382. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20383. "/ws-echo");
  20384. client.set_read_timeout(1, 0);
  20385. ASSERT_TRUE(client.connect());
  20386. ASSERT_TRUE(client.send("first"));
  20387. std::string msg;
  20388. ASSERT_EQ(client.read(msg), ws::Text);
  20389. ASSERT_EQ(msg, "first");
  20390. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20391. // not be used with a read timeout: it would reprocess the previous message.
  20392. EXPECT_EQ(client.read(msg), ws::Timeout);
  20393. EXPECT_EQ(msg, "first");
  20394. }
  20395. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20396. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20397. "/ws-echo");
  20398. ASSERT_TRUE(client.connect());
  20399. // Setting it once the connection is open reaches the live stream, not just
  20400. // the seed for the next connect().
  20401. client.set_read_timeout(1, 0);
  20402. std::string msg;
  20403. EXPECT_EQ(client.read(msg), ws::Timeout);
  20404. EXPECT_TRUE(client.is_open());
  20405. }
  20406. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20407. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20408. "/ws-echo");
  20409. client.set_read_timeout(5, 0);
  20410. ASSERT_TRUE(client.connect());
  20411. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20412. // The server should reject it and close the connection.
  20413. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20414. client.send(oversized);
  20415. // The server's read() should have failed due to payload limit,
  20416. // so our read() should return false (connection closed).
  20417. std::string msg;
  20418. EXPECT_FALSE(client.read(msg));
  20419. }
  20420. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20421. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20422. "/ws-echo");
  20423. client.set_read_timeout(10, 0);
  20424. ASSERT_TRUE(client.connect());
  20425. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20426. // This should succeed.
  20427. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20428. ASSERT_TRUE(client.send(at_limit));
  20429. std::string msg;
  20430. ASSERT_TRUE(client.read(msg));
  20431. EXPECT_EQ(at_limit.size(), msg.size());
  20432. client.close();
  20433. }
  20434. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20435. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20436. "/nonexistent");
  20437. auto res = client.connect();
  20438. EXPECT_FALSE(res);
  20439. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20440. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20441. EXPECT_FALSE(client.is_open());
  20442. }
  20443. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20444. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20445. "/ws-echo");
  20446. ASSERT_TRUE(client.connect());
  20447. ASSERT_TRUE(client.send(""));
  20448. std::string msg;
  20449. EXPECT_EQ(ws::Text, client.read(msg));
  20450. EXPECT_EQ("", msg);
  20451. client.close();
  20452. }
  20453. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20454. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20455. "/ws-echo");
  20456. // First connection
  20457. ASSERT_TRUE(client.connect());
  20458. ASSERT_TRUE(client.send("first"));
  20459. std::string msg;
  20460. ASSERT_TRUE(client.read(msg));
  20461. EXPECT_EQ("first", msg);
  20462. client.close();
  20463. EXPECT_FALSE(client.is_open());
  20464. // Reconnect using the same client object
  20465. ASSERT_TRUE(client.connect());
  20466. ASSERT_TRUE(client.is_open());
  20467. ASSERT_TRUE(client.send("second"));
  20468. ASSERT_TRUE(client.read(msg));
  20469. EXPECT_EQ("second", msg);
  20470. client.close();
  20471. }
  20472. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20473. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20474. "/ws-close-status");
  20475. ASSERT_TRUE(client.connect());
  20476. // Trigger the server to close with GoingAway status
  20477. ASSERT_TRUE(client.send("trigger"));
  20478. // read() should return false after receiving the close frame
  20479. std::string msg;
  20480. EXPECT_FALSE(client.read(msg));
  20481. EXPECT_FALSE(client.is_open());
  20482. }
  20483. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20484. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20485. "/ws-echo");
  20486. ASSERT_TRUE(client.connect());
  20487. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20488. EXPECT_FALSE(client.is_open());
  20489. }
  20490. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20491. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20492. ws::WebSocketClient client(
  20493. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20494. ASSERT_TRUE(client.connect());
  20495. // Server should have selected graphql-ws
  20496. EXPECT_EQ("graphql-ws", client.subprotocol());
  20497. client.close();
  20498. }
  20499. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20500. Headers headers;
  20501. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20502. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20503. ws::WebSocketClient client(
  20504. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20505. ASSERT_TRUE(client.connect());
  20506. // The offer on the second field line counts too, so graphql-ws is selected
  20507. EXPECT_EQ("graphql-ws", client.subprotocol());
  20508. client.close();
  20509. }
  20510. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20511. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20512. ws::WebSocketClient client(
  20513. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20514. ASSERT_TRUE(client.connect());
  20515. // Server should not have selected any subprotocol
  20516. EXPECT_TRUE(client.subprotocol().empty());
  20517. client.close();
  20518. }
  20519. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  20520. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  20521. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20522. "/ws-subprotocol-unoffered",
  20523. headers);
  20524. ASSERT_TRUE(client.connect());
  20525. EXPECT_TRUE(client.subprotocol().empty());
  20526. client.close();
  20527. }
  20528. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20529. // Connect without requesting any subprotocol
  20530. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20531. "/ws-subprotocol");
  20532. ASSERT_TRUE(client.connect());
  20533. EXPECT_TRUE(client.subprotocol().empty());
  20534. client.close();
  20535. }
  20536. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20537. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20538. "/ws-echo");
  20539. client.set_tcp_nodelay(true);
  20540. client.set_connection_timeout(3, 0);
  20541. bool socket_options_called = false;
  20542. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20543. ASSERT_TRUE(client.connect());
  20544. ASSERT_TRUE(client.is_open());
  20545. EXPECT_TRUE(socket_options_called);
  20546. ASSERT_TRUE(client.send("hello"));
  20547. std::string msg;
  20548. auto result = client.read(msg);
  20549. EXPECT_EQ(result, ws::ReadResult::Text);
  20550. EXPECT_EQ(msg, "hello");
  20551. client.close();
  20552. }
  20553. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20554. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20555. "/ws-echo");
  20556. client.set_connection_timeout(std::chrono::seconds(3));
  20557. client.set_write_timeout(std::chrono::seconds(3));
  20558. // A sub-second remainder exercises the seconds/microseconds split.
  20559. client.set_read_timeout(std::chrono::milliseconds(1500));
  20560. ASSERT_TRUE(client.connect());
  20561. auto start = std::chrono::steady_clock::now();
  20562. std::string msg;
  20563. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20564. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20565. std::chrono::steady_clock::now() - start)
  20566. .count();
  20567. // Above 1s so that dropping the microseconds half of the split fails here.
  20568. // Ignoring the setter altogether would not reach this line at all: a client
  20569. // waits forever by default.
  20570. EXPECT_GE(elapsed, 1400);
  20571. EXPECT_LT(elapsed, 30000);
  20572. }
  20573. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20574. Server svr;
  20575. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20576. if (!req.has_header("Authorization")) {
  20577. res.status = StatusCode::Unauthorized_401;
  20578. res.set_content("Unauthorized", "text/plain");
  20579. return Server::HandlerResponse::Handled;
  20580. }
  20581. return Server::HandlerResponse::Unhandled;
  20582. });
  20583. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20584. std::string msg;
  20585. while (ws.read(msg)) {
  20586. ws.send(msg);
  20587. }
  20588. });
  20589. auto port = svr.bind_to_any_port("localhost");
  20590. std::thread t([&]() { svr.listen_after_bind(); });
  20591. svr.wait_until_ready();
  20592. // Without Authorization header - should be rejected before upgrade
  20593. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20594. EXPECT_FALSE(client1.connect());
  20595. // The rejection is framed like any other HTTP response
  20596. {
  20597. Client cli("localhost", port);
  20598. Headers headers = {{"Upgrade", "websocket"},
  20599. {"Connection", "Upgrade"},
  20600. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20601. {"Sec-WebSocket-Version", "13"}};
  20602. auto res = cli.Get("/ws", headers);
  20603. ASSERT_TRUE(res);
  20604. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20605. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20606. EXPECT_EQ("Unauthorized", res->body);
  20607. }
  20608. // With Authorization header - should succeed
  20609. Headers headers = {{"Authorization", "Bearer token123"}};
  20610. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20611. headers);
  20612. ASSERT_TRUE(client2.connect());
  20613. ASSERT_TRUE(client2.send("hello"));
  20614. std::string msg;
  20615. ASSERT_TRUE(client2.read(msg));
  20616. EXPECT_EQ("hello", msg);
  20617. client2.close();
  20618. svr.stop();
  20619. t.join();
  20620. }
  20621. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20622. Server svr;
  20623. std::atomic<int> pre_request_calls{0};
  20624. std::atomic<bool> route_matched{false};
  20625. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20626. pre_request_calls++;
  20627. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20628. if (req.get_header_value("Authorization") != "Bearer token123") {
  20629. res.status = StatusCode::Unauthorized_401;
  20630. res.set_content("Unauthorized", "text/plain");
  20631. return Server::HandlerResponse::Handled;
  20632. }
  20633. return Server::HandlerResponse::Unhandled;
  20634. });
  20635. std::atomic<bool> handler_called{false};
  20636. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20637. handler_called = true;
  20638. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20639. });
  20640. auto port = svr.bind_to_any_port("localhost");
  20641. std::thread t([&]() { svr.listen_after_bind(); });
  20642. svr.wait_until_ready();
  20643. // Without Authorization header - should be rejected before upgrade
  20644. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20645. "/ws/1");
  20646. EXPECT_FALSE(client1.connect());
  20647. EXPECT_FALSE(handler_called);
  20648. EXPECT_EQ(1, pre_request_calls);
  20649. EXPECT_TRUE(route_matched);
  20650. // The rejection is an ordinary HTTP response, not a protocol switch
  20651. {
  20652. Client cli("localhost", port);
  20653. Headers headers = {{"Upgrade", "websocket"},
  20654. {"Connection", "Upgrade"},
  20655. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20656. {"Sec-WebSocket-Version", "13"}};
  20657. auto res = cli.Get("/ws/1", headers);
  20658. ASSERT_TRUE(res);
  20659. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20660. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20661. EXPECT_EQ("Unauthorized", res->body);
  20662. }
  20663. EXPECT_FALSE(handler_called);
  20664. // With Authorization header - should succeed
  20665. Headers headers = {{"Authorization", "Bearer token123"}};
  20666. ws::WebSocketClient client2(
  20667. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20668. ASSERT_TRUE(client2.connect());
  20669. std::string msg;
  20670. ASSERT_TRUE(client2.read(msg));
  20671. EXPECT_EQ("/ws/:id 2", msg);
  20672. EXPECT_TRUE(handler_called);
  20673. client2.close();
  20674. svr.stop();
  20675. t.join();
  20676. }
  20677. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20678. Server svr;
  20679. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20680. // A read timeout is how a handler gets control back. Without it, a handler
  20681. // parked in read() can never write on the connection it is reading.
  20682. ws.set_read_timeout(std::chrono::milliseconds(100));
  20683. std::string msg;
  20684. while (ws.is_open()) {
  20685. auto r = ws.read(msg);
  20686. if (r == httplib::ws::Timeout) {
  20687. ws.send("tick");
  20688. continue;
  20689. }
  20690. if (r == httplib::ws::Fail) { break; }
  20691. ws.send(msg);
  20692. }
  20693. });
  20694. auto port = svr.bind_to_any_port("localhost");
  20695. std::thread t([&]() { svr.listen_after_bind(); });
  20696. svr.wait_until_ready();
  20697. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20698. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20699. ASSERT_TRUE(client.connect());
  20700. // The client sends nothing, so anything it receives came out of the
  20701. // handler's timeout path.
  20702. std::string msg;
  20703. ASSERT_EQ(client.read(msg), ws::Text);
  20704. EXPECT_EQ("tick", msg);
  20705. client.close();
  20706. svr.stop();
  20707. t.join();
  20708. }
  20709. // Stream::read may return fewer bytes than asked for. This is that contract at
  20710. // its worst -- one byte per call -- which is what a frame header straddling a
  20711. // read buffer's boundary looks like to the frame parser.
  20712. class WsByteAtATimeStream : public Stream {
  20713. public:
  20714. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20715. bool is_readable() const override { return true; }
  20716. bool wait_readable() const override { return true; }
  20717. bool wait_writable() const override { return true; }
  20718. ssize_t read(char *ptr, size_t size) override {
  20719. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20720. *ptr = data_[pos_++];
  20721. return 1;
  20722. }
  20723. ssize_t write(const char *, size_t size) override {
  20724. return static_cast<ssize_t>(size);
  20725. }
  20726. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20727. ip = "127.0.0.1";
  20728. port = 0;
  20729. }
  20730. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20731. ip = "127.0.0.1";
  20732. port = 0;
  20733. }
  20734. socket_t socket() const override { return INVALID_SOCKET; }
  20735. time_t duration() const override { return 0; }
  20736. private:
  20737. std::string data_;
  20738. size_t pos_ = 0;
  20739. };
  20740. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20741. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20742. // length and the mask key are all multi-byte fields here. Each used to be
  20743. // read with a single read() call, which fails as soon as one is split.
  20744. std::string body(200, 'x');
  20745. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20746. std::string frame;
  20747. frame += static_cast<char>(0x81); // FIN + Text
  20748. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20749. frame += static_cast<char>(body.size() >> 8);
  20750. frame += static_cast<char>(body.size() & 0xff);
  20751. for (size_t i = 0; i < 4; i++) {
  20752. frame += static_cast<char>(mask[i]);
  20753. }
  20754. for (size_t i = 0; i < body.size(); i++) {
  20755. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20756. }
  20757. WsByteAtATimeStream strm(frame);
  20758. ws::Opcode opcode;
  20759. std::string payload;
  20760. bool fin = false;
  20761. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20762. /*expect_masked=*/true, 1024),
  20763. ws::impl::FrameRead::Ok);
  20764. EXPECT_TRUE(fin);
  20765. EXPECT_EQ(opcode, ws::Opcode::Text);
  20766. EXPECT_EQ(payload, body);
  20767. }
  20768. TEST(WebSocketTest, QueryStringInHandshake) {
  20769. Server svr;
  20770. std::mutex mtx;
  20771. std::string received_target;
  20772. std::string received_token;
  20773. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20774. {
  20775. std::lock_guard<std::mutex> lock(mtx);
  20776. received_target = req.target;
  20777. if (req.has_param("token")) {
  20778. received_token = req.get_param_value("token");
  20779. }
  20780. }
  20781. std::string msg;
  20782. while (ws.read(msg)) {
  20783. ws.send(msg);
  20784. }
  20785. });
  20786. auto port = svr.bind_to_any_port("localhost");
  20787. std::thread t([&]() { svr.listen_after_bind(); });
  20788. svr.wait_until_ready();
  20789. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20790. "/ws?token=ABC&session=123");
  20791. ASSERT_TRUE(client.connect());
  20792. // Round-trip ensures the handler has run and captured the request.
  20793. ASSERT_TRUE(client.send("hello"));
  20794. std::string msg;
  20795. ASSERT_TRUE(client.read(msg));
  20796. EXPECT_EQ("hello", msg);
  20797. client.close();
  20798. {
  20799. std::lock_guard<std::mutex> lock(mtx);
  20800. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20801. EXPECT_EQ("ABC", received_token);
  20802. }
  20803. svr.stop();
  20804. t.join();
  20805. }
  20806. // Run a handshake against a throwaway server and hand the request the server
  20807. // received back to the caller, so tests can assert on the headers the client
  20808. // actually put on the wire.
  20809. static void capture_websocket_handshake_request(
  20810. const Headers &client_headers,
  20811. std::function<void(const Request &, int port)> verify) {
  20812. Server svr;
  20813. std::mutex mtx;
  20814. Request received;
  20815. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20816. {
  20817. std::lock_guard<std::mutex> lock(mtx);
  20818. received = req;
  20819. }
  20820. std::string msg;
  20821. while (ws.read(msg)) {
  20822. ws.send(msg);
  20823. }
  20824. });
  20825. auto port = svr.bind_to_any_port("localhost");
  20826. std::thread t([&]() { svr.listen_after_bind(); });
  20827. auto se = detail::scope_exit([&] {
  20828. svr.stop();
  20829. t.join();
  20830. });
  20831. svr.wait_until_ready();
  20832. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20833. client_headers);
  20834. ASSERT_TRUE(client.connect());
  20835. ASSERT_TRUE(client.send("hello"));
  20836. std::string msg;
  20837. ASSERT_TRUE(client.read(msg));
  20838. client.close();
  20839. {
  20840. std::lock_guard<std::mutex> lock(mtx);
  20841. verify(received, port);
  20842. }
  20843. }
  20844. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20845. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20846. // Non-default port must be present in the Host header. Default ports
  20847. // (80/443) are omitted; that logic is covered by
  20848. // MakeHostAndPortStringTest.
  20849. EXPECT_EQ("localhost:" + std::to_string(port),
  20850. req.get_header_value("Host"));
  20851. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20852. req.get_header_value("User-Agent"));
  20853. EXPECT_FALSE(req.has_header("Accept"));
  20854. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20855. EXPECT_FALSE(req.has_header("Content-Length"));
  20856. });
  20857. }
  20858. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20859. capture_websocket_handshake_request(
  20860. {{"Host", "example.com"},
  20861. {"User-Agent", "custom-agent"},
  20862. {"X-Custom", "value"}},
  20863. [](const Request &req, int) {
  20864. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20865. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20866. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20867. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20868. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20869. });
  20870. }
  20871. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20872. capture_websocket_handshake_request(
  20873. {{"Upgrade", "bogus"},
  20874. {"Connection", "close"},
  20875. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20876. {"Sec-WebSocket-Version", "8"}},
  20877. [](const Request &req, int) {
  20878. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20879. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20880. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20881. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20882. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20883. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20884. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20885. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20886. req.get_header_value("Sec-WebSocket-Key"));
  20887. });
  20888. }
  20889. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20890. // A header the client refuses to send must abort the handshake before any
  20891. // part of it reaches the wire; a lone request line would otherwise sit in
  20892. // the peer's buffer as a truncated request.
  20893. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20894. ASSERT_NE(INVALID_SOCKET, srv);
  20895. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20896. sockaddr_in addr{};
  20897. addr.sin_family = AF_INET;
  20898. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20899. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20900. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20901. ASSERT_EQ(0, ::listen(srv, 1));
  20902. sockaddr_in bound{};
  20903. socklen_t bound_len = sizeof(bound);
  20904. ASSERT_EQ(
  20905. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20906. auto port = ntohs(bound.sin_port);
  20907. ssize_t received = -1;
  20908. std::thread t([&] {
  20909. // Bound every blocking call so a regression fails the test with a bad
  20910. // value instead of hanging the suite.
  20911. fd_set rfds;
  20912. FD_ZERO(&rfds);
  20913. FD_SET(srv, &rfds);
  20914. timeval tv{5, 0};
  20915. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20916. 0) {
  20917. return;
  20918. }
  20919. sockaddr_in cli_addr{};
  20920. socklen_t cli_len = sizeof(cli_addr);
  20921. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20922. if (cli == INVALID_SOCKET) { return; }
  20923. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20924. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20925. char buf[4096];
  20926. received = ::recv(cli, buf, sizeof(buf), 0);
  20927. });
  20928. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20929. // connect() has already shut the socket down by the time it returns false,
  20930. // so the peer sees EOF without waiting for the client to be destroyed.
  20931. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20932. {{"X-Bad", "a\r\nInjected: 1"}});
  20933. EXPECT_FALSE(client.connect());
  20934. t.join();
  20935. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20936. EXPECT_EQ(0, received);
  20937. }
  20938. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20939. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20940. // contains "upgrade" as a substring is a different token and must not
  20941. // start a WebSocket handshake.
  20942. auto make_request = [](const std::vector<std::string> &connection_values) {
  20943. Request req;
  20944. req.method = "GET";
  20945. req.headers.emplace("Upgrade", "websocket");
  20946. for (const auto &value : connection_values) {
  20947. req.headers.emplace("Connection", value);
  20948. }
  20949. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20950. req.headers.emplace("Sec-WebSocket-Version", "13");
  20951. return req;
  20952. };
  20953. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20954. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20955. EXPECT_TRUE(
  20956. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20957. EXPECT_TRUE(
  20958. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20959. EXPECT_TRUE(
  20960. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20961. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20962. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20963. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20964. EXPECT_FALSE(
  20965. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20966. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20967. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20968. }
  20969. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20970. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20971. // asks recipients to match each protocol-name case-insensitively, and RFC
  20972. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20973. // client naming websocket alongside another protocol, or on a second field
  20974. // line, is offering websocket; a value that merely contains "websocket" as a
  20975. // substring is a different protocol name and is not.
  20976. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20977. Request req;
  20978. req.method = "GET";
  20979. for (const auto &value : upgrade_values) {
  20980. req.headers.emplace("Upgrade", value);
  20981. }
  20982. req.headers.emplace("Connection", "Upgrade");
  20983. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20984. req.headers.emplace("Sec-WebSocket-Version", "13");
  20985. return req;
  20986. };
  20987. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20988. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20989. EXPECT_TRUE(
  20990. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20991. EXPECT_TRUE(
  20992. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20993. EXPECT_TRUE(
  20994. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20995. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20996. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20997. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20998. EXPECT_FALSE(
  20999. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21000. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21001. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21002. }
  21003. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21004. Server svr;
  21005. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21006. auto port = svr.bind_to_any_port("localhost");
  21007. std::thread t([&]() { svr.listen_after_bind(); });
  21008. auto se = detail::scope_exit([&] {
  21009. svr.stop();
  21010. t.join();
  21011. });
  21012. svr.wait_until_ready();
  21013. Headers headers = {{"Upgrade", "websocket"},
  21014. {"Connection", "notupgrade"},
  21015. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21016. {"Sec-WebSocket-Version", "13"}};
  21017. Client cli("localhost", port);
  21018. auto res = cli.Get("/ws", headers);
  21019. // The route exists only as a WebSocket route, so a request that fails the
  21020. // handshake check falls through to ordinary routing.
  21021. ASSERT_TRUE(res);
  21022. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21023. }
  21024. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21025. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21026. // Connection value is the only thing left for the client to reject.
  21027. Server svr;
  21028. svr.Get("/ws", [](const Request &req, Response &res) {
  21029. res.status = StatusCode::SwitchingProtocol_101;
  21030. res.set_header("Upgrade", "websocket");
  21031. res.set_header("Connection", "notupgrade");
  21032. res.set_header("Sec-WebSocket-Accept",
  21033. detail::websocket_accept_key(
  21034. req.get_header_value("Sec-WebSocket-Key")));
  21035. });
  21036. auto port = svr.bind_to_any_port("localhost");
  21037. std::thread t([&]() { svr.listen_after_bind(); });
  21038. auto se = detail::scope_exit([&] {
  21039. svr.stop();
  21040. t.join();
  21041. });
  21042. svr.wait_until_ready();
  21043. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21044. auto res = client.connect();
  21045. EXPECT_FALSE(res);
  21046. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21047. EXPECT_FALSE(client.is_open());
  21048. }
  21049. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21050. Server svr;
  21051. svr.Get("/ws", [](const Request &req, Response &res) {
  21052. res.status = StatusCode::SwitchingProtocol_101;
  21053. res.set_header("Upgrade", "websocket");
  21054. res.set_header("Connection", "Upgrade");
  21055. res.set_header("Sec-WebSocket-Accept",
  21056. detail::websocket_accept_key(
  21057. req.get_header_value("Sec-WebSocket-Key")));
  21058. res.set_header("Sec-WebSocket-Protocol", "admin");
  21059. });
  21060. auto port = svr.bind_to_any_port("localhost");
  21061. std::thread t([&]() { svr.listen_after_bind(); });
  21062. auto se = detail::scope_exit([&] {
  21063. svr.stop();
  21064. t.join();
  21065. });
  21066. svr.wait_until_ready();
  21067. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21068. // Server selects a subprotocol the client never offered
  21069. {
  21070. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21071. ws::WebSocketClient client(url, headers);
  21072. auto res = client.connect();
  21073. EXPECT_FALSE(res);
  21074. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21075. EXPECT_FALSE(client.is_open());
  21076. EXPECT_TRUE(client.subprotocol().empty());
  21077. }
  21078. // Client offered none but the server named one anyway
  21079. {
  21080. ws::WebSocketClient client(url);
  21081. auto res = client.connect();
  21082. EXPECT_FALSE(res);
  21083. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21084. EXPECT_FALSE(client.is_open());
  21085. EXPECT_TRUE(client.subprotocol().empty());
  21086. }
  21087. }
  21088. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21089. // The socket path doubles as the URL host, so it must not contain '/'.
  21090. const char *shard = getenv("GTEST_SHARD_INDEX");
  21091. const std::string sock_path =
  21092. shard ? std::string("httplib-ws-") + shard + ".sock"
  21093. : std::string("httplib-ws.sock");
  21094. std::remove(sock_path.c_str());
  21095. Server svr;
  21096. std::mutex mtx;
  21097. std::string received_host;
  21098. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21099. {
  21100. std::lock_guard<std::mutex> lock(mtx);
  21101. received_host = req.get_header_value("Host");
  21102. }
  21103. std::string msg;
  21104. while (ws.read(msg)) {
  21105. ws.send(msg);
  21106. }
  21107. });
  21108. svr.set_address_family(AF_UNIX);
  21109. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21110. auto se = detail::scope_exit([&] {
  21111. svr.stop();
  21112. t.join();
  21113. std::remove(sock_path.c_str());
  21114. });
  21115. svr.wait_until_ready();
  21116. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21117. client.set_address_family(AF_UNIX);
  21118. ASSERT_TRUE(client.connect());
  21119. ASSERT_TRUE(client.send("hello"));
  21120. std::string msg;
  21121. ASSERT_TRUE(client.read(msg));
  21122. client.close();
  21123. {
  21124. std::lock_guard<std::mutex> lock(mtx);
  21125. // There is no host:port for a Unix socket, so the same "localhost"
  21126. // placeholder the HTTP client uses is expected.
  21127. EXPECT_EQ("localhost", received_host);
  21128. }
  21129. }
  21130. // Two threads must never parse WebSocket frames from the same stream.
  21131. // close() used to read the peer's Close reply with its own frame read, so it
  21132. // raced a reader thread that was in the middle of a payload: the payload loop
  21133. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21134. // so bytes taken by close() were replaced with bytes from further along the
  21135. // stream. The message kept its length and silently changed content.
  21136. //
  21137. // The raw peer below sends a frame header plus part of the payload, waits for
  21138. // the handler to call close(), and only then sends the rest. Whichever thread
  21139. // would win the race for those bytes, the message must arrive intact, because
  21140. // close() must not touch the stream while read() owns it.
  21141. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21142. #ifndef _WIN32
  21143. signal(SIGPIPE, SIG_IGN);
  21144. #endif
  21145. const size_t payload_len = 120; // fits the 7-bit length field
  21146. const size_t prefix_len = 8;
  21147. const int attempts = 8;
  21148. std::string expected(payload_len, '\0');
  21149. for (size_t i = 0; i < payload_len; i++) {
  21150. expected[i] = static_cast<char>('a' + i % 26);
  21151. }
  21152. std::atomic<bool> peer_stalled{false};
  21153. std::atomic<bool> handler_done{false};
  21154. std::mutex received_mutex;
  21155. std::vector<std::string> received;
  21156. // Bound every wait, so a regression fails the test instead of hanging the
  21157. // suite.
  21158. auto wait_for = [](const std::atomic<bool> &flag) {
  21159. for (int i = 0; i < 500 && !flag; i++) {
  21160. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21161. }
  21162. };
  21163. Server svr;
  21164. svr.set_websocket_ping_interval(0);
  21165. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21166. std::thread reader([&]() {
  21167. std::string msg;
  21168. while (ws.read(msg)) {
  21169. std::lock_guard<std::mutex> guard(received_mutex);
  21170. received.push_back(msg);
  21171. }
  21172. });
  21173. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21174. // inside read_websocket_frame() when close() runs.
  21175. wait_for(peer_stalled);
  21176. ws.close();
  21177. reader.join();
  21178. handler_done = true;
  21179. });
  21180. auto port = svr.bind_to_any_port("127.0.0.1");
  21181. std::thread t([&]() { svr.listen_after_bind(); });
  21182. auto se = detail::scope_exit([&] {
  21183. svr.stop();
  21184. t.join();
  21185. });
  21186. svr.wait_until_ready();
  21187. auto send_bytes = [](socket_t s, const std::string &data) {
  21188. #ifdef _WIN32
  21189. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21190. #else
  21191. auto n = ::send(s, data.data(), data.size(), 0);
  21192. #endif
  21193. return n == static_cast<decltype(n)>(data.size());
  21194. };
  21195. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21196. // Every length used here fits the 7-bit length field.
  21197. auto masked_header = [](uint8_t first_byte, size_t len) {
  21198. std::string h;
  21199. h += static_cast<char>(first_byte);
  21200. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21201. h.append(4, '\0'); // mask key
  21202. return h;
  21203. };
  21204. for (int attempt = 0; attempt < attempts; attempt++) {
  21205. peer_stalled = false;
  21206. handler_done = false;
  21207. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21208. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21209. auto se_sock = detail::scope_exit([&] {
  21210. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21211. });
  21212. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21213. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21214. sockaddr_in addr{};
  21215. addr.sin_family = AF_INET;
  21216. addr.sin_port = htons(static_cast<uint16_t>(port));
  21217. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21218. ASSERT_EQ(
  21219. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21220. << "attempt " << attempt;
  21221. ASSERT_TRUE(send_bytes(sock,
  21222. "GET /ws HTTP/1.1\r\n"
  21223. "Host: 127.0.0.1\r\n"
  21224. "Upgrade: websocket\r\n"
  21225. "Connection: Upgrade\r\n"
  21226. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21227. "Sec-WebSocket-Version: 13\r\n"
  21228. "\r\n"))
  21229. << "attempt " << attempt;
  21230. std::string response;
  21231. while (response.find("\r\n\r\n") == std::string::npos) {
  21232. char buf[512];
  21233. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21234. if (n <= 0) { break; }
  21235. response.append(buf, static_cast<size_t>(n));
  21236. }
  21237. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21238. << "attempt " << attempt;
  21239. // Send the header of a Binary message but only the first prefix_len bytes
  21240. // of its payload, leaving the reader thread stalled inside the payload.
  21241. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21242. expected.substr(0, prefix_len)))
  21243. << "attempt " << attempt;
  21244. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21245. peer_stalled = true;
  21246. // Let close() send its Close frame and park in its own read before the
  21247. // rest of the payload arrives, so both threads are waiting for it.
  21248. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21249. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21250. close_frame += static_cast<char>(0x03); // status 1000
  21251. close_frame += static_cast<char>(0xE8);
  21252. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21253. << "attempt " << attempt;
  21254. // Closing the peer releases the reader thread even on the buggy path,
  21255. // where it waits for bytes another thread already consumed.
  21256. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21257. detail::close_socket(sock);
  21258. sock = INVALID_SOCKET;
  21259. wait_for(handler_done);
  21260. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21261. }
  21262. std::lock_guard<std::mutex> guard(received_mutex);
  21263. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21264. << "a message in flight when close() ran was dropped";
  21265. for (size_t i = 0; i < received.size(); i++) {
  21266. EXPECT_EQ(expected, received[i]) << "message " << i;
  21267. }
  21268. }
  21269. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21270. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21271. protected:
  21272. void SetUp() override {
  21273. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21274. SERVER_PRIVATE_KEY_FILE);
  21275. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21276. std::string msg;
  21277. ws::ReadResult ret;
  21278. while ((ret = ws.read(msg))) {
  21279. if (ret == ws::Binary) {
  21280. ws.send(msg.data(), msg.size());
  21281. } else {
  21282. ws.send(msg);
  21283. }
  21284. }
  21285. });
  21286. port_ = server_->bind_to_any_port(HOST);
  21287. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21288. server_->wait_until_ready();
  21289. }
  21290. void TearDown() override {
  21291. server_->stop();
  21292. if (server_thread_.joinable()) { server_thread_.join(); }
  21293. }
  21294. std::unique_ptr<SSLServer> server_;
  21295. std::thread server_thread_;
  21296. int port_ = 0;
  21297. };
  21298. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21299. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21300. "/ws-echo");
  21301. client.enable_server_certificate_verification(false);
  21302. ASSERT_TRUE(client.connect());
  21303. ASSERT_TRUE(client.is_open());
  21304. ASSERT_TRUE(client.send("Hello WSS"));
  21305. std::string msg;
  21306. EXPECT_EQ(ws::Text, client.read(msg));
  21307. EXPECT_EQ("Hello WSS", msg);
  21308. client.close();
  21309. }
  21310. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21311. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21312. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21313. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21314. // client (without calling close() first) is the only path that runs
  21315. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21316. // bug exactly.
  21317. //
  21318. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21319. // when linked against an instrumented libssl; run under Valgrind to catch it
  21320. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21321. // suite (the freed session otherwise stalls on the close handshake) — this test
  21322. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21323. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21324. {
  21325. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21326. "/ws-echo");
  21327. client.enable_server_certificate_verification(false);
  21328. client.set_read_timeout(2, 0);
  21329. client.set_write_timeout(2, 0);
  21330. ASSERT_TRUE(client.connect());
  21331. ASSERT_TRUE(client.is_open());
  21332. ASSERT_TRUE(client.send("still open"));
  21333. // Intentionally do NOT call client.close(): leaving scope runs
  21334. // shutdown_and_close() with the WebSocket still open, which must send the
  21335. // close frame while the TLS session is still alive.
  21336. }
  21337. }
  21338. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21339. // shutdown_and_close() at the start of connect(), reproducing the same
  21340. // use-after-free within the test body rather than at scope exit. The second
  21341. // connect must succeed and echo, proving the close handshake ran over a live
  21342. // session. See the note above about memory-tool requirements.
  21343. TEST_F(WebSocketSSLIntegrationTest,
  21344. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21345. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21346. "/ws-echo");
  21347. client.enable_server_certificate_verification(false);
  21348. client.set_read_timeout(2, 0);
  21349. client.set_write_timeout(2, 0);
  21350. ASSERT_TRUE(client.connect());
  21351. ASSERT_TRUE(client.is_open());
  21352. ASSERT_TRUE(client.send("still open"));
  21353. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21354. // the still-open connection, which must not touch a freed TLS session.
  21355. ASSERT_TRUE(client.connect());
  21356. ASSERT_TRUE(client.is_open());
  21357. ASSERT_TRUE(client.send("after reconnect"));
  21358. std::string msg;
  21359. EXPECT_EQ(ws::Text, client.read(msg));
  21360. EXPECT_EQ("after reconnect", msg);
  21361. client.close();
  21362. }
  21363. #endif
  21364. #ifdef CPPHTTPLIB_SSL_ENABLED
  21365. class WebSocketSSLCATest : public ::testing::Test {
  21366. protected:
  21367. void SetUp() override {
  21368. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21369. SERVER_PRIVATE_KEY_FILE);
  21370. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21371. std::string msg;
  21372. while (ws.read(msg)) {
  21373. ws.send(msg);
  21374. }
  21375. });
  21376. port_ = server_->bind_to_any_port("127.0.0.1");
  21377. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21378. server_->wait_until_ready();
  21379. }
  21380. void TearDown() override {
  21381. server_->stop();
  21382. if (server_thread_.joinable()) { server_thread_.join(); }
  21383. }
  21384. std::string url() const {
  21385. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21386. }
  21387. std::unique_ptr<SSLServer> server_;
  21388. std::thread server_thread_;
  21389. int port_ = 0;
  21390. };
  21391. // A custom CA loaded as PEM verifies the server with full certificate
  21392. // verification enabled
  21393. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21394. ws::WebSocketClient client(url());
  21395. std::string cert;
  21396. read_file(SERVER_CERT2_FILE, cert);
  21397. client.load_ca_cert_store(cert.c_str(), cert.size());
  21398. ASSERT_TRUE(client.connect());
  21399. ASSERT_TRUE(client.send("hello"));
  21400. std::string msg;
  21401. EXPECT_EQ(ws::Text, client.read(msg));
  21402. EXPECT_EQ("hello", msg);
  21403. client.close();
  21404. }
  21405. // A custom CA that does not cover the server must fail verification (the
  21406. // custom CA is exclusive; system certs are not loaded alongside it)
  21407. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21408. ws::WebSocketClient client(url());
  21409. std::string cert;
  21410. read_file(CLIENT_CA_CERT_FILE, cert);
  21411. client.load_ca_cert_store(cert.c_str(), cert.size());
  21412. auto res = client.connect();
  21413. ASSERT_FALSE(res);
  21414. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21415. EXPECT_EQ(-1, res.status());
  21416. EXPECT_NE(0u, res.ssl_backend_error());
  21417. }
  21418. // The same CA as a file path rather than PEM in memory
  21419. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21420. ws::WebSocketClient client(url());
  21421. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21422. ASSERT_TRUE(client.connect());
  21423. ASSERT_TRUE(client.send("hello"));
  21424. std::string msg;
  21425. EXPECT_EQ(ws::Text, client.read(msg));
  21426. EXPECT_EQ("hello", msg);
  21427. client.close();
  21428. }
  21429. // ...and a CA file that does not cover the server still fails, so it is the
  21430. // path above that decides the outcome
  21431. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21432. ws::WebSocketClient client(url());
  21433. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21434. ASSERT_FALSE(client.connect());
  21435. }
  21436. // Regression test: reconnecting with a native custom CA store used to reuse
  21437. // a store handle the previous TLS context had already freed (use-after-free
  21438. // under the OpenSSL backend). The context now lives as long as the client.
  21439. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21440. ws::WebSocketClient client(url());
  21441. std::string cert;
  21442. read_file(SERVER_CERT2_FILE, cert);
  21443. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21444. ASSERT_TRUE(client.connect());
  21445. client.close();
  21446. ASSERT_TRUE(client.connect());
  21447. ASSERT_TRUE(client.send("again"));
  21448. std::string msg;
  21449. EXPECT_EQ(ws::Text, client.read(msg));
  21450. EXPECT_EQ("again", msg);
  21451. client.close();
  21452. }
  21453. // Regression test: a certificate with a trusted chain but no identity match
  21454. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21455. // verification entirely for IP hosts, so this connection succeeded there.
  21456. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21457. // chain verification while the identity check must still fail.
  21458. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21459. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21460. ASSERT_TRUE(svr.is_valid());
  21461. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21462. std::string msg;
  21463. while (ws.read(msg)) {
  21464. ws.send(msg);
  21465. }
  21466. });
  21467. auto port = svr.bind_to_any_port("127.0.0.1");
  21468. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21469. auto se = detail::scope_exit([&] {
  21470. svr.stop();
  21471. t.join();
  21472. });
  21473. svr.wait_until_ready();
  21474. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21475. "/echo");
  21476. std::string cert;
  21477. read_file(SERVER_CERT_FILE, cert);
  21478. client.load_ca_cert_store(cert.c_str(), cert.size());
  21479. ASSERT_FALSE(client.connect());
  21480. }
  21481. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21482. // SNI, so nothing binds the host name to the TLS session. These bind the
  21483. // server to "localhost" instead, the only shape that exercises the SNI and
  21484. // hostname-verification path with certificate verification left enabled.
  21485. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21486. protected:
  21487. void Start(const char *cert_file) {
  21488. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21489. SERVER_PRIVATE_KEY_FILE);
  21490. ASSERT_TRUE(server_->is_valid());
  21491. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21492. std::string msg;
  21493. while (ws.read(msg)) {
  21494. ws.send(msg);
  21495. }
  21496. });
  21497. port_ = server_->bind_to_any_port("localhost");
  21498. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21499. server_->wait_until_ready();
  21500. }
  21501. void TearDown() override {
  21502. if (server_) { server_->stop(); }
  21503. if (server_thread_.joinable()) { server_thread_.join(); }
  21504. }
  21505. std::string url() const {
  21506. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21507. }
  21508. std::unique_ptr<SSLServer> server_;
  21509. std::thread server_thread_;
  21510. int port_ = 0;
  21511. };
  21512. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21513. // out and the connection is usable
  21514. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21515. Start(SERVER_CERT2_FILE);
  21516. ws::WebSocketClient client(url());
  21517. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21518. ASSERT_TRUE(client.connect());
  21519. ASSERT_TRUE(client.send("hello"));
  21520. std::string msg;
  21521. EXPECT_EQ(ws::Text, client.read(msg));
  21522. EXPECT_EQ("hello", msg);
  21523. client.close();
  21524. }
  21525. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21526. // while the identity check must still reject "localhost"
  21527. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21528. Start(SERVER_CERT_FILE);
  21529. ws::WebSocketClient client(url());
  21530. client.set_ca_cert_path(SERVER_CERT_FILE);
  21531. auto res = client.connect();
  21532. ASSERT_FALSE(res);
  21533. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21534. EXPECT_EQ(-1, res.status());
  21535. }
  21536. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21537. // disabled: the chain is still checked, only the identity check is skipped
  21538. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21539. Start(SERVER_CERT_FILE);
  21540. ws::WebSocketClient client(url());
  21541. client.set_ca_cert_path(SERVER_CERT_FILE);
  21542. client.enable_server_hostname_verification(false);
  21543. ASSERT_TRUE(client.connect());
  21544. ASSERT_TRUE(client.send("hello"));
  21545. std::string msg;
  21546. EXPECT_EQ(ws::Text, client.read(msg));
  21547. EXPECT_EQ("hello", msg);
  21548. client.close();
  21549. }
  21550. // A CA that did not sign the server certificate fails the chain, even though
  21551. // the name would match
  21552. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21553. Start(SERVER_CERT2_FILE);
  21554. ws::WebSocketClient client(url());
  21555. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21556. ASSERT_FALSE(client.connect());
  21557. }
  21558. // With verification disabled, neither the chain nor the name is checked
  21559. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21560. Start(SERVER_CERT_FILE);
  21561. ws::WebSocketClient client(url());
  21562. client.enable_server_certificate_verification(false);
  21563. ASSERT_TRUE(client.connect());
  21564. ASSERT_TRUE(client.send("hello"));
  21565. std::string msg;
  21566. EXPECT_EQ(ws::Text, client.read(msg));
  21567. EXPECT_EQ("hello", msg);
  21568. client.close();
  21569. }
  21570. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21571. protected:
  21572. void SetUp() override {
  21573. server_ = httplib::detail::make_unique<SSLServer>(
  21574. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21575. ASSERT_TRUE(server_->is_valid());
  21576. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21577. std::string msg;
  21578. while (ws.read(msg)) {
  21579. ws.send(msg);
  21580. }
  21581. });
  21582. port_ = server_->bind_to_any_port("localhost");
  21583. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21584. server_->wait_until_ready();
  21585. }
  21586. void TearDown() override {
  21587. server_->stop();
  21588. if (server_thread_.joinable()) { server_thread_.join(); }
  21589. }
  21590. std::string url() const {
  21591. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21592. }
  21593. void ConnectWithClientCert(const std::string &client_cert_file,
  21594. const std::string &client_private_key_file,
  21595. const char *private_key_password) {
  21596. std::string cert_pem, key_pem;
  21597. read_file(client_cert_file, cert_pem);
  21598. read_file(client_private_key_file, key_pem);
  21599. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21600. key_pem.c_str(), key_pem.size(),
  21601. private_key_password};
  21602. ws::WebSocketClient client(url(), pem);
  21603. ASSERT_TRUE(client.is_valid());
  21604. client.enable_server_certificate_verification(false);
  21605. ASSERT_TRUE(client.connect());
  21606. ASSERT_TRUE(client.send("hello"));
  21607. std::string msg;
  21608. EXPECT_EQ(ws::Text, client.read(msg));
  21609. EXPECT_EQ("hello", msg);
  21610. client.close();
  21611. }
  21612. std::unique_ptr<SSLServer> server_;
  21613. std::thread server_thread_;
  21614. int port_ = 0;
  21615. };
  21616. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21617. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21618. }
  21619. // Control for the tests above: the fixture's server really does require a
  21620. // client certificate, so it is the PEM the constructor installed that decides
  21621. // the outcome.
  21622. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21623. ws::WebSocketClient client(url());
  21624. ASSERT_TRUE(client.is_valid());
  21625. client.enable_server_certificate_verification(false);
  21626. EXPECT_FALSE(client.connect());
  21627. }
  21628. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21629. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21630. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21631. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21632. }
  21633. #endif
  21634. #if !defined(_WIN32)
  21635. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21636. auto secret_dir = std::string("./symlink_test_secret");
  21637. auto served_dir = std::string("./symlink_test_served");
  21638. auto secret_file = secret_dir + "/secret.txt";
  21639. auto symlink_path = served_dir + "/escape";
  21640. // Setup: create directories and files
  21641. mkdir(secret_dir.c_str(), 0755);
  21642. mkdir(served_dir.c_str(), 0755);
  21643. {
  21644. std::ofstream ofs(secret_file);
  21645. ofs << "SECRET_DATA";
  21646. }
  21647. // Create symlink using absolute path so it resolves correctly
  21648. #ifdef PATH_MAX
  21649. char abs_secret[PATH_MAX];
  21650. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21651. #else
  21652. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21653. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21654. ASSERT_NE(nullptr, abs_secret);
  21655. #endif
  21656. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21657. auto se = detail::scope_exit([&] {
  21658. unlink(symlink_path.c_str());
  21659. unlink(secret_file.c_str());
  21660. rmdir(served_dir.c_str());
  21661. rmdir(secret_dir.c_str());
  21662. });
  21663. Server svr;
  21664. svr.set_mount_point("/", served_dir);
  21665. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21666. auto se2 = detail::scope_exit([&] {
  21667. svr.stop();
  21668. listen_thread.join();
  21669. });
  21670. svr.wait_until_ready();
  21671. Client cli("localhost", PORT);
  21672. // Symlink pointing outside base dir should be blocked
  21673. auto res = cli.Get("/escape/secret.txt");
  21674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21675. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21676. }
  21677. #endif
  21678. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  21679. // "GET /smuggled" request), reads the first response, and only then sends the
  21680. // embedded request as the body. Returns how many times /smuggled ran.
  21681. //
  21682. // The body is sent AFTER receiving the first response (as in the original
  21683. // PoC) so that the stream_line_reader cannot buffer it together with the
  21684. // headers of the first request.
  21685. static int count_smuggled_requests(const std::string &outer_head,
  21686. std::string &first_response) {
  21687. Server svr;
  21688. svr.set_mount_point("/", "./www");
  21689. std::atomic<int> smuggled_count(0);
  21690. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21691. smuggled_count++;
  21692. res.set_content("oops", "text/plain");
  21693. });
  21694. svr.Post("/post", [&](const Request &req, Response &res) {
  21695. res.set_content(req.body, "text/plain");
  21696. });
  21697. auto port = svr.bind_to_any_port("localhost");
  21698. thread t = thread([&] { svr.listen_after_bind(); });
  21699. auto se = detail::scope_exit([&] {
  21700. svr.stop();
  21701. t.join();
  21702. });
  21703. svr.wait_until_ready();
  21704. auto error = Error::Success;
  21705. auto sock = detail::create_client_socket(
  21706. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21707. /*connection_timeout_sec=*/2, 0,
  21708. /*read_timeout_sec=*/2, 0,
  21709. /*write_timeout_sec=*/2, 0, std::string(), error);
  21710. EXPECT_NE(INVALID_SOCKET, sock);
  21711. if (sock == INVALID_SOCKET) { return -1; }
  21712. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21713. // The "smuggled" request will be sent as the body of the outer request
  21714. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21715. "Host: localhost\r\n"
  21716. "Connection: close\r\n"
  21717. "\r\n";
  21718. auto head = outer_head;
  21719. auto len = std::to_string(smuggled.size());
  21720. for (auto pos = head.find("{len}"); pos != std::string::npos;
  21721. pos = head.find("{len}", pos + len.size())) {
  21722. head.replace(pos, 5, len);
  21723. }
  21724. // Step 1: Send only the outer request headers (no body yet)
  21725. auto sent = send(sock, head.data(), head.size(), 0);
  21726. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  21727. // Step 2: Read the first response
  21728. char buf[4096];
  21729. for (;;) {
  21730. auto n = recv(sock, buf, sizeof(buf), 0);
  21731. if (n <= 0) break;
  21732. first_response.append(buf, static_cast<size_t>(n));
  21733. // Stop once we have a complete response (headers + body)
  21734. auto hdr_end = first_response.find("\r\n\r\n");
  21735. if (hdr_end != std::string::npos) {
  21736. // Check for Content-Length to know when the body is complete
  21737. auto cl_pos = first_response.find("Content-Length:");
  21738. if (cl_pos != std::string::npos) {
  21739. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21740. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21741. auto cl = std::stoul(
  21742. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21743. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21744. } else {
  21745. break; // No Content-Length, assume headers-only response
  21746. }
  21747. }
  21748. }
  21749. // Step 3: Now send the body, which looks like a new HTTP request. On a
  21750. // vulnerable server the keep-alive loop reads this as a second request. The
  21751. // server may already have closed the connection, so the result is ignored.
  21752. send(sock, smuggled.data(), smuggled.size(), 0);
  21753. // Half-close so that a server which drained the body sees EOF and closes,
  21754. // instead of the read below waiting for the read timeout.
  21755. #ifdef _WIN32
  21756. ::shutdown(sock, SD_SEND);
  21757. #else
  21758. ::shutdown(sock, SHUT_WR);
  21759. #endif
  21760. // Step 4: Read until the server closes the connection
  21761. for (;;) {
  21762. auto n = recv(sock, buf, sizeof(buf), 0);
  21763. if (n <= 0) break;
  21764. }
  21765. return smuggled_count.load();
  21766. }
  21767. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21768. // A GET request with Content-Length to a static file handler must have its
  21769. // body drained before the keep-alive connection is reused. Otherwise the
  21770. // unread body bytes are interpreted as the next HTTP request.
  21771. std::string first_response;
  21772. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21773. "Host: localhost\r\n"
  21774. "Content-Length: {len}\r\n"
  21775. "\r\n",
  21776. first_response));
  21777. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  21778. }
  21779. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  21780. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  21781. // be answered with 400 and the connection closed. Treating it as "no body"
  21782. // leaves the body to be parsed as the next request.
  21783. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  21784. const char *targets[] = {
  21785. "GET /file", // handler that never reads the body
  21786. "GET /not-found", // no handler matches (404)
  21787. "POST /post", // handler that reads the body
  21788. };
  21789. for (auto target : targets) {
  21790. for (auto value : values) {
  21791. std::string first_response;
  21792. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  21793. " HTTP/1.1\r\n"
  21794. "Host: localhost\r\n"
  21795. "Content-Length: " +
  21796. value + "\r\n\r\n",
  21797. first_response))
  21798. << target << " with Content-Length: " << value;
  21799. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  21800. << target << " with Content-Length: " << value;
  21801. }
  21802. }
  21803. }
  21804. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  21805. // A 400 for an unparseable request line leaves the rest of the message
  21806. // unread, so the connection must be closed rather than reused.
  21807. std::string first_response;
  21808. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  21809. "Host: localhost\r\n"
  21810. "Content-Length: {len}\r\n"
  21811. "\r\n",
  21812. first_response));
  21813. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21814. }
  21815. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  21816. // Same as above for a header block that fails to parse.
  21817. std::string first_response;
  21818. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21819. "Host: localhost\r\n"
  21820. "Bad Header\r\n"
  21821. "Content-Length: {len}\r\n"
  21822. "\r\n",
  21823. first_response));
  21824. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21825. }
  21826. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  21827. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  21828. // server must not read another request on that connection, even when the
  21829. // request had no body to drain.
  21830. std::string first_response;
  21831. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  21832. "Host: localhost\r\n"
  21833. "\r\n",
  21834. first_response));
  21835. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  21836. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  21837. }
  21838. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21839. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21840. // must be rejected with 400 Bad Request.
  21841. Server svr;
  21842. svr.Post("/test", [&](const Request &, Response &res) {
  21843. res.set_content("ok", "text/plain");
  21844. });
  21845. thread t = thread([&] { svr.listen(HOST, PORT); });
  21846. auto se = detail::scope_exit([&] {
  21847. svr.stop();
  21848. t.join();
  21849. ASSERT_FALSE(svr.is_running());
  21850. });
  21851. svr.wait_until_ready();
  21852. // Exact "chunked"
  21853. {
  21854. auto req = "POST /test HTTP/1.1\r\n"
  21855. "Host: localhost\r\n"
  21856. "Content-Length: 5\r\n"
  21857. "Transfer-Encoding: chunked\r\n"
  21858. "Connection: close\r\n"
  21859. "\r\n"
  21860. "hello";
  21861. std::string response;
  21862. ASSERT_TRUE(send_request(1, req, &response));
  21863. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21864. response.substr(0, response.find("\r\n")));
  21865. }
  21866. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21867. {
  21868. auto req = "POST /test HTTP/1.1\r\n"
  21869. "Host: localhost\r\n"
  21870. "Content-Length: 5\r\n"
  21871. "Transfer-Encoding: gzip, chunked\r\n"
  21872. "Connection: close\r\n"
  21873. "\r\n"
  21874. "hello";
  21875. std::string response;
  21876. ASSERT_TRUE(send_request(1, req, &response));
  21877. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21878. response.substr(0, response.find("\r\n")));
  21879. }
  21880. }
  21881. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21882. Server svr;
  21883. svr.Post("/test", [&](const Request &, Response &res) {
  21884. res.set_content("ok", "text/plain");
  21885. });
  21886. thread t = thread([&] { svr.listen(HOST, PORT); });
  21887. auto se = detail::scope_exit([&] {
  21888. svr.stop();
  21889. t.join();
  21890. ASSERT_FALSE(svr.is_running());
  21891. });
  21892. svr.wait_until_ready();
  21893. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21894. // length cannot be determined, so the server must answer 400 and close
  21895. // rather than treat the request as bodyless and leave the body in the
  21896. // socket for the next request to pick up.
  21897. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21898. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21899. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21900. std::string response;
  21901. ASSERT_TRUE(send_request(1, req, &response));
  21902. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21903. response.substr(0, response.find("\r\n")))
  21904. << transfer_encoding;
  21905. }
  21906. // RFC 9110 5.3: the codings may also be split across several
  21907. // Transfer-Encoding lines, which combine in the order they were received.
  21908. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21909. // just like the single-line "chunked, gzip" above.
  21910. {
  21911. auto req = "POST /test HTTP/1.1\r\n"
  21912. "Host: localhost\r\n"
  21913. "Transfer-Encoding: chunked\r\n"
  21914. "Transfer-Encoding: gzip\r\n"
  21915. "\r\n"
  21916. "0\r\n\r\n";
  21917. std::string response;
  21918. ASSERT_TRUE(send_request(1, req, &response));
  21919. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21920. response.substr(0, response.find("\r\n")));
  21921. }
  21922. // A sequence ending in chunked stays valid.
  21923. auto req = "POST /test HTTP/1.1\r\n"
  21924. "Host: localhost\r\n"
  21925. "Transfer-Encoding: gzip, chunked\r\n"
  21926. "Connection: close\r\n"
  21927. "\r\n"
  21928. "0\r\n\r\n";
  21929. std::string response;
  21930. ASSERT_TRUE(send_request(1, req, &response));
  21931. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21932. // ...including when it is spread over several lines.
  21933. auto split_req = "POST /test HTTP/1.1\r\n"
  21934. "Host: localhost\r\n"
  21935. "Transfer-Encoding: gzip\r\n"
  21936. "Transfer-Encoding: chunked\r\n"
  21937. "Connection: close\r\n"
  21938. "\r\n"
  21939. "0\r\n\r\n";
  21940. std::string split_response;
  21941. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21942. EXPECT_EQ("HTTP/1.1 200 OK",
  21943. split_response.substr(0, split_response.find("\r\n")));
  21944. }
  21945. // Regression for issue #2450: a DELETE without Content-Length on a
  21946. // keep-alive connection must not let the post-response drain consume the
  21947. // next request's bytes.
  21948. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21949. Server svr;
  21950. std::atomic<int> delete_count(0);
  21951. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21952. delete_count++;
  21953. res.status = StatusCode::NoContent_204;
  21954. });
  21955. auto port = svr.bind_to_any_port(HOST);
  21956. thread t = thread([&] { svr.listen_after_bind(); });
  21957. auto se = detail::scope_exit([&] {
  21958. svr.stop();
  21959. t.join();
  21960. });
  21961. svr.wait_until_ready();
  21962. auto error = Error::Success;
  21963. auto sock = detail::create_client_socket(
  21964. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21965. /*connection_timeout_sec=*/2, 0,
  21966. /*read_timeout_sec=*/2, 0,
  21967. /*write_timeout_sec=*/2, 0, std::string(), error);
  21968. ASSERT_NE(INVALID_SOCKET, sock);
  21969. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21970. auto send_request_and_read_response = [&](const std::string &req,
  21971. std::string &out) -> bool {
  21972. auto sent = send(sock, req.data(), req.size(), 0);
  21973. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21974. char buf[4096];
  21975. for (;;) {
  21976. auto n = recv(sock, buf, sizeof(buf), 0);
  21977. if (n <= 0) { return !out.empty(); }
  21978. out.append(buf, static_cast<size_t>(n));
  21979. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21980. }
  21981. };
  21982. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21983. "Host: localhost\r\n"
  21984. "\r\n";
  21985. std::string resp1;
  21986. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21987. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21988. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21989. "Host: localhost\r\n"
  21990. "Connection: close\r\n"
  21991. "\r\n";
  21992. std::string resp2;
  21993. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21994. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21995. EXPECT_EQ(2, delete_count.load());
  21996. }
  21997. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21998. Server svr;
  21999. svr.Post("/ingest", [&](const Request &, Response &res,
  22000. const ContentReader &content_reader) {
  22001. auto consumed = content_reader([](const char *, size_t) { return false; });
  22002. EXPECT_FALSE(consumed);
  22003. res.status = StatusCode::Conflict_409;
  22004. res.set_header("Connection", "close");
  22005. });
  22006. auto port = svr.bind_to_any_port(HOST);
  22007. thread t = thread([&] { svr.listen_after_bind(); });
  22008. auto se = detail::scope_exit([&] {
  22009. svr.stop();
  22010. t.join();
  22011. });
  22012. svr.wait_until_ready();
  22013. auto error = Error::Success;
  22014. auto sock = detail::create_client_socket(
  22015. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22016. /*connection_timeout_sec=*/2, 0,
  22017. /*read_timeout_sec=*/1, 0,
  22018. /*write_timeout_sec=*/2, 0, std::string(), error);
  22019. ASSERT_NE(INVALID_SOCKET, sock);
  22020. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22021. std::string request = "POST /ingest HTTP/1.1\r\n"
  22022. "Host: localhost\r\n"
  22023. "Transfer-Encoding: chunked\r\n"
  22024. "\r\n"
  22025. "4\r\n"
  22026. "data\r\n";
  22027. auto sent = send(sock, request.data(), request.size(), 0);
  22028. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22029. std::string response;
  22030. ssize_t received = 0;
  22031. do {
  22032. char buf[4096];
  22033. received = recv(sock, buf, sizeof(buf), 0);
  22034. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22035. } while (received > 0);
  22036. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22037. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22038. EXPECT_EQ(0, received);
  22039. }
  22040. namespace no_proxy_test {
  22041. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22042. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22043. // calling listen().
  22044. class ScopedServer {
  22045. public:
  22046. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22047. ~ScopedServer() {
  22048. svr_.stop();
  22049. if (th_.joinable()) { th_.join(); }
  22050. }
  22051. Server &svr() { return svr_; }
  22052. int port() const { return port_; }
  22053. void listen() {
  22054. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22055. svr_.wait_until_ready();
  22056. }
  22057. private:
  22058. Server svr_;
  22059. std::thread th_;
  22060. int port_ = 0;
  22061. };
  22062. class ProxyAndTargetServers {
  22063. public:
  22064. ProxyAndTargetServers() {
  22065. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22066. proxy_hits_++;
  22067. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22068. res.set_content("via-proxy", "text/plain");
  22069. });
  22070. target_.Get(".*", [this](const Request &req, Response &res) {
  22071. target_hits_++;
  22072. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22073. res.set_content("direct", "text/plain");
  22074. });
  22075. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22076. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22077. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22078. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22079. proxy_mock_.wait_until_ready();
  22080. target_.wait_until_ready();
  22081. }
  22082. ~ProxyAndTargetServers() {
  22083. proxy_mock_.stop();
  22084. target_.stop();
  22085. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22086. if (target_thread_.joinable()) { target_thread_.join(); }
  22087. }
  22088. Server &proxy_mock() { return proxy_mock_; }
  22089. Server &target() { return target_; }
  22090. int proxy_port() const { return proxy_port_; }
  22091. int target_port() const { return target_port_; }
  22092. int proxy_hits() const { return proxy_hits_.load(); }
  22093. int target_hits() const { return target_hits_.load(); }
  22094. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22095. void reset_counters() {
  22096. proxy_hits_ = 0;
  22097. target_hits_ = 0;
  22098. last_had_proxy_authz_ = false;
  22099. }
  22100. private:
  22101. Server proxy_mock_;
  22102. Server target_;
  22103. std::thread proxy_thread_;
  22104. std::thread target_thread_;
  22105. int proxy_port_ = 0;
  22106. int target_port_ = 0;
  22107. std::atomic<int> proxy_hits_{0};
  22108. std::atomic<int> target_hits_{0};
  22109. std::atomic<bool> last_had_proxy_authz_{false};
  22110. };
  22111. inline std::unique_ptr<Client> make_client(const std::string &host,
  22112. ProxyAndTargetServers &s) {
  22113. auto cli = detail::make_unique<Client>(host, s.target_port());
  22114. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22115. cli->set_proxy("127.0.0.1", s.proxy_port());
  22116. return cli;
  22117. }
  22118. } // namespace no_proxy_test
  22119. using no_proxy_test::make_client;
  22120. using no_proxy_test::ProxyAndTargetServers;
  22121. TEST(NoProxyTest, ExactHostnameBypasses) {
  22122. ProxyAndTargetServers s;
  22123. auto cli = make_client("example.com", s);
  22124. cli->set_no_proxy({"example.com"});
  22125. auto res = cli->Get("/");
  22126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22127. EXPECT_EQ(0, s.proxy_hits());
  22128. EXPECT_EQ(1, s.target_hits());
  22129. }
  22130. TEST(NoProxyTest, SubdomainBypasses) {
  22131. ProxyAndTargetServers s;
  22132. auto cli = make_client("foo.example.com", s);
  22133. cli->set_no_proxy({"example.com"});
  22134. auto res = cli->Get("/");
  22135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22136. EXPECT_EQ(0, s.proxy_hits());
  22137. EXPECT_EQ(1, s.target_hits());
  22138. }
  22139. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22140. // Regression guard: "evilexample.com" must not be considered a subdomain
  22141. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22142. // check would let traffic bypass the proxy and leak credentials direct
  22143. // to the attacker host.
  22144. ProxyAndTargetServers s;
  22145. auto cli = make_client("evilexample.com", s);
  22146. cli->set_no_proxy({"example.com"});
  22147. auto res = cli->Get("/");
  22148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22149. EXPECT_GE(s.proxy_hits(), 1);
  22150. EXPECT_EQ(0, s.target_hits());
  22151. }
  22152. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22153. ProxyAndTargetServers s;
  22154. auto cli = make_client("example.com.evil.com", s);
  22155. cli->set_no_proxy({"example.com"});
  22156. auto res = cli->Get("/");
  22157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22158. EXPECT_GE(s.proxy_hits(), 1);
  22159. EXPECT_EQ(0, s.target_hits());
  22160. }
  22161. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22162. ProxyAndTargetServers s;
  22163. auto cli = make_client("example.com", s);
  22164. cli->set_no_proxy({".example.com"});
  22165. auto res = cli->Get("/");
  22166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22167. EXPECT_EQ(0, s.proxy_hits());
  22168. EXPECT_EQ(1, s.target_hits());
  22169. }
  22170. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22171. ProxyAndTargetServers s;
  22172. auto cli = make_client("Example.COM", s);
  22173. cli->set_no_proxy({"EXAMPLE.com"});
  22174. auto res = cli->Get("/");
  22175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22176. EXPECT_EQ(0, s.proxy_hits());
  22177. EXPECT_EQ(1, s.target_hits());
  22178. }
  22179. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22180. ProxyAndTargetServers s;
  22181. auto cli = make_client("example.com.", s);
  22182. cli->set_no_proxy({"example.com"});
  22183. auto res = cli->Get("/");
  22184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22185. EXPECT_EQ(0, s.proxy_hits());
  22186. EXPECT_EQ(1, s.target_hits());
  22187. }
  22188. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22189. // Trailing dots must be normalized on BOTH sides — host and entry.
  22190. // An implementation that only strips the host-side trailing dot would
  22191. // fail to match host "example.com" against entry "example.com." because
  22192. // a literal substring search would compare 11 chars against 12.
  22193. ProxyAndTargetServers s;
  22194. auto cli = make_client("example.com", s);
  22195. cli->set_no_proxy({"example.com."});
  22196. auto res = cli->Get("/");
  22197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22198. EXPECT_EQ(0, s.proxy_hits());
  22199. EXPECT_EQ(1, s.target_hits());
  22200. }
  22201. TEST(NoProxyTest, WildcardBypassesEverything) {
  22202. ProxyAndTargetServers s;
  22203. auto cli = make_client("anything.invalid.test", s);
  22204. cli->set_no_proxy({"*"});
  22205. auto res = cli->Get("/");
  22206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22207. EXPECT_EQ(0, s.proxy_hits());
  22208. EXPECT_EQ(1, s.target_hits());
  22209. }
  22210. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22211. ProxyAndTargetServers s;
  22212. Client cli("127.0.0.1", s.target_port());
  22213. cli.set_proxy("127.0.0.1", s.proxy_port());
  22214. cli.set_no_proxy({"127.0.0.1"});
  22215. auto res = cli.Get("/");
  22216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22217. EXPECT_EQ(0, s.proxy_hits());
  22218. EXPECT_EQ(1, s.target_hits());
  22219. }
  22220. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22221. ProxyAndTargetServers s;
  22222. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22223. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22224. cli.set_proxy("127.0.0.1", s.proxy_port());
  22225. cli.set_no_proxy({"::1"});
  22226. auto res = cli.Get("/");
  22227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22228. EXPECT_EQ(0, s.proxy_hits());
  22229. EXPECT_EQ(1, s.target_hits());
  22230. }
  22231. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22232. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22233. // must still be recognized as IPv6 for CIDR matching. Implementations
  22234. // that detect IPv6 only when the host begins with '[' would parse the
  22235. // host as a hostname and miss the match.
  22236. ProxyAndTargetServers s;
  22237. Client cli("fe80::1", s.target_port());
  22238. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22239. cli.set_proxy("127.0.0.1", s.proxy_port());
  22240. cli.set_no_proxy({"fe80::/10"});
  22241. auto res = cli.Get("/");
  22242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22243. EXPECT_EQ(0, s.proxy_hits());
  22244. EXPECT_EQ(1, s.target_hits());
  22245. }
  22246. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22247. ProxyAndTargetServers s;
  22248. Client cli("::1", s.target_port());
  22249. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22250. cli.set_proxy("127.0.0.1", s.proxy_port());
  22251. cli.set_no_proxy({"[::1]"});
  22252. auto res = cli.Get("/");
  22253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22254. EXPECT_EQ(0, s.proxy_hits());
  22255. EXPECT_EQ(1, s.target_hits());
  22256. }
  22257. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22258. ProxyAndTargetServers s;
  22259. Client cli("fe80::1", s.target_port());
  22260. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22261. cli.set_proxy("127.0.0.1", s.proxy_port());
  22262. cli.set_no_proxy({"[fe80::]/10"});
  22263. auto res = cli.Get("/");
  22264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22265. EXPECT_EQ(0, s.proxy_hits());
  22266. EXPECT_EQ(1, s.target_hits());
  22267. }
  22268. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22269. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22270. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22271. // tricks via address-family conversion.
  22272. ProxyAndTargetServers s;
  22273. Client cli("::ffff:127.0.0.1", s.target_port());
  22274. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22275. cli.set_proxy("127.0.0.1", s.proxy_port());
  22276. cli.set_no_proxy({"127.0.0.1"});
  22277. auto res = cli.Get("/");
  22278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22279. EXPECT_GE(s.proxy_hits(), 1);
  22280. EXPECT_EQ(0, s.target_hits());
  22281. }
  22282. TEST(NoProxyTest, IPv4CidrMatch) {
  22283. ProxyAndTargetServers s;
  22284. Client cli("127.0.0.1", s.target_port());
  22285. cli.set_proxy("127.0.0.1", s.proxy_port());
  22286. cli.set_no_proxy({"127.0.0.0/8"});
  22287. auto res = cli.Get("/");
  22288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22289. EXPECT_EQ(0, s.proxy_hits());
  22290. EXPECT_EQ(1, s.target_hits());
  22291. }
  22292. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22293. ProxyAndTargetServers s;
  22294. Client cli("127.0.0.1", s.target_port());
  22295. cli.set_proxy("127.0.0.1", s.proxy_port());
  22296. cli.set_no_proxy({"10.0.0.0/8"});
  22297. auto res = cli.Get("/");
  22298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22299. EXPECT_GE(s.proxy_hits(), 1);
  22300. EXPECT_EQ(0, s.target_hits());
  22301. }
  22302. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22303. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22304. // IPv4 target matches.
  22305. ProxyAndTargetServers s;
  22306. Client cli("127.0.0.1", s.target_port());
  22307. cli.set_proxy("127.0.0.1", s.proxy_port());
  22308. cli.set_no_proxy({"0.0.0.0/0"});
  22309. auto res = cli.Get("/");
  22310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22311. EXPECT_EQ(0, s.proxy_hits());
  22312. EXPECT_EQ(1, s.target_hits());
  22313. }
  22314. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22315. ProxyAndTargetServers s;
  22316. Client cli("127.0.0.1", s.target_port());
  22317. cli.set_proxy("127.0.0.1", s.proxy_port());
  22318. cli.set_no_proxy({"127.0.0.1"});
  22319. auto res = cli.Get("/");
  22320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22321. EXPECT_EQ(0, s.proxy_hits());
  22322. EXPECT_EQ(1, s.target_hits());
  22323. }
  22324. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22325. ProxyAndTargetServers s;
  22326. Client cli("127.0.0.1", s.target_port());
  22327. cli.set_proxy("127.0.0.1", s.proxy_port());
  22328. cli.set_no_proxy({"127.0.0.0/33"});
  22329. auto res = cli.Get("/");
  22330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22331. EXPECT_GE(s.proxy_hits(), 1);
  22332. EXPECT_EQ(0, s.target_hits());
  22333. }
  22334. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22335. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22336. ProxyAndTargetServers s;
  22337. Client cli("127.0.0.1", s.target_port());
  22338. cli.set_proxy("127.0.0.1", s.proxy_port());
  22339. cli.set_no_proxy({"127.0.0.1/"});
  22340. auto res = cli.Get("/");
  22341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22342. EXPECT_GE(s.proxy_hits(), 1);
  22343. EXPECT_EQ(0, s.target_hits());
  22344. }
  22345. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22346. ProxyAndTargetServers s;
  22347. auto cli = make_client("internal.corp", s);
  22348. cli->set_proxy_basic_auth("u", "p");
  22349. cli->set_no_proxy({"internal.corp"});
  22350. auto res = cli->Get("/");
  22351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22352. EXPECT_EQ(1, s.target_hits());
  22353. EXPECT_EQ(0, s.proxy_hits());
  22354. EXPECT_FALSE(s.last_had_proxy_authz())
  22355. << "Proxy-Authorization must not be sent direct to the target";
  22356. }
  22357. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22358. ProxyAndTargetServers s;
  22359. auto cli = make_client("public.example", s);
  22360. cli->set_proxy_basic_auth("u", "p");
  22361. cli->set_no_proxy({"internal.corp"}); // does not match
  22362. auto res = cli->Get("/");
  22363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22364. EXPECT_GE(s.proxy_hits(), 1);
  22365. EXPECT_TRUE(s.last_had_proxy_authz());
  22366. }
  22367. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22368. ProxyAndTargetServers s;
  22369. auto cli = make_client("anything.test", s);
  22370. auto res = cli->Get("/");
  22371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22372. EXPECT_GE(s.proxy_hits(), 1);
  22373. EXPECT_EQ(0, s.target_hits());
  22374. }
  22375. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22376. ProxyAndTargetServers s;
  22377. auto cli = make_client("example.com", s);
  22378. cli->set_no_proxy({"example.com:8080"});
  22379. auto res = cli->Get("/");
  22380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22381. EXPECT_GE(s.proxy_hits(), 1);
  22382. EXPECT_EQ(0, s.target_hits());
  22383. }
  22384. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22385. ProxyAndTargetServers s;
  22386. auto cli = make_client("anything.test", s);
  22387. cli->set_no_proxy({"", " ", "\t"});
  22388. auto res = cli->Get("/");
  22389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22390. EXPECT_GE(s.proxy_hits(), 1);
  22391. EXPECT_EQ(0, s.target_hits());
  22392. }
  22393. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22394. // An entry with leading/trailing whitespace must still match — env-style
  22395. // values are commonly pasted with stray spaces and an implementation
  22396. // that feeds the raw token directly to inet_pton would fail to match
  22397. // valid CIDRs because of the spaces.
  22398. ProxyAndTargetServers s;
  22399. Client cli("127.0.0.1", s.target_port());
  22400. cli.set_proxy("127.0.0.1", s.proxy_port());
  22401. cli.set_no_proxy({" 127.0.0.0/8 "});
  22402. auto res = cli.Get("/");
  22403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22404. EXPECT_EQ(0, s.proxy_hits());
  22405. EXPECT_EQ(1, s.target_hits());
  22406. }
  22407. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22408. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22409. // go direct and must NOT carry Proxy-Authorization.
  22410. std::atomic<int> proxy_hits{0};
  22411. std::atomic<int> target_hits{0};
  22412. std::atomic<bool> target_saw_authz{false};
  22413. no_proxy_test::ScopedServer proxy_mock, target;
  22414. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22415. proxy_hits++;
  22416. res.status = 302;
  22417. res.set_header("Location", "http://127.0.0.1:" +
  22418. std::to_string(target.port()) + "/landed");
  22419. });
  22420. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22421. target_hits++;
  22422. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22423. res.set_content("direct", "text/plain");
  22424. });
  22425. proxy_mock.listen();
  22426. target.listen();
  22427. Client cli("public.example", target.port());
  22428. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22429. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22430. cli.set_proxy_basic_auth("u", "p");
  22431. cli.set_no_proxy({"127.0.0.1"});
  22432. cli.set_follow_location(true);
  22433. auto res = cli.Get("/redir");
  22434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22435. EXPECT_GE(proxy_hits.load(), 1);
  22436. EXPECT_GE(target_hits.load(), 1);
  22437. EXPECT_FALSE(target_saw_authz.load());
  22438. }
  22439. #ifdef CPPHTTPLIB_SSL_ENABLED
  22440. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  22441. // Direct origin replying 407 must not trigger the digest retry; otherwise
  22442. // proxy creds would be sent to the (possibly hostile) origin.
  22443. std::atomic<int> target_hits{0};
  22444. std::atomic<bool> target_saw_proxy_authz{false};
  22445. no_proxy_test::ScopedServer target;
  22446. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22447. target_hits++;
  22448. if (req.has_header("Proxy-Authorization")) {
  22449. target_saw_proxy_authz = true;
  22450. }
  22451. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22452. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22453. "nonce=\"abc\", algorithm=MD5");
  22454. });
  22455. target.listen();
  22456. // The proxy address is set to the target's port: the bypass MUST kick in;
  22457. // if it doesn't, the test still routes "via proxy" to the same server and
  22458. // the Proxy-Authorization assertion below catches the leak.
  22459. Client cli("evil.example", target.port());
  22460. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22461. cli.set_proxy("127.0.0.1", target.port());
  22462. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22463. cli.set_no_proxy({"evil.example"});
  22464. auto res = cli.Get("/x");
  22465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22466. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22467. EXPECT_EQ(1, target_hits.load());
  22468. EXPECT_FALSE(target_saw_proxy_authz.load());
  22469. }
  22470. #endif
  22471. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  22472. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  22473. std::atomic<int> proxy_hits{0};
  22474. std::atomic<int> bypass_hits{0};
  22475. std::atomic<bool> proxy_saw_c_url{false};
  22476. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  22477. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22478. proxy_hits++;
  22479. if (req.path.find("/start") != std::string::npos) {
  22480. res.status = 302;
  22481. res.set_header("Location", "http://127.0.0.1:" +
  22482. std::to_string(bypass_server.port()) +
  22483. "/middle");
  22484. return;
  22485. }
  22486. if (req.path.find("/end") != std::string::npos) {
  22487. proxy_saw_c_url = true;
  22488. res.set_content("c-via-proxy", "text/plain");
  22489. return;
  22490. }
  22491. res.set_content("unexpected", "text/plain");
  22492. });
  22493. // public.example's "advertised" port is arbitrary (the request never lands
  22494. // there — it goes through the proxy), but use a dynamic value to stay
  22495. // friendly with sharded parallel runs.
  22496. int public_port = bypass_server.port();
  22497. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  22498. bypass_hits++;
  22499. res.status = 302;
  22500. res.set_header("Location", "http://public.example:" +
  22501. std::to_string(public_port) + "/end");
  22502. });
  22503. proxy_mock.listen();
  22504. bypass_server.listen();
  22505. Client cli("public.example", public_port);
  22506. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22507. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22508. cli.set_no_proxy({"127.0.0.1"});
  22509. cli.set_follow_location(true);
  22510. auto res = cli.Get("/start");
  22511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22512. EXPECT_EQ(StatusCode::OK_200, res->status);
  22513. EXPECT_EQ("c-via-proxy", res->body);
  22514. EXPECT_GE(proxy_hits.load(), 2);
  22515. EXPECT_GE(bypass_hits.load(), 1);
  22516. EXPECT_TRUE(proxy_saw_c_url.load());
  22517. }
  22518. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  22519. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  22520. // request reconnects to the correct endpoint.
  22521. std::atomic<int> proxy_hits{0};
  22522. std::atomic<int> target_hits{0};
  22523. no_proxy_test::ScopedServer proxy_mock, target;
  22524. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22525. proxy_hits++;
  22526. res.set_content("via-proxy", "text/plain");
  22527. });
  22528. target.svr().Get(".*", [&](const Request &, Response &res) {
  22529. target_hits++;
  22530. res.set_content("direct", "text/plain");
  22531. });
  22532. proxy_mock.listen();
  22533. target.listen();
  22534. Client cli("public.example", target.port());
  22535. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22536. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22537. cli.set_keep_alive(true);
  22538. auto res1 = cli.Get("/a");
  22539. ASSERT_TRUE(res1);
  22540. EXPECT_EQ("via-proxy", res1->body);
  22541. EXPECT_EQ(1, proxy_hits.load());
  22542. EXPECT_EQ(0, target_hits.load());
  22543. cli.set_no_proxy({"public.example"});
  22544. auto res2 = cli.Get("/b");
  22545. ASSERT_TRUE(res2);
  22546. EXPECT_EQ("direct", res2->body);
  22547. EXPECT_EQ(1, proxy_hits.load());
  22548. EXPECT_EQ(1, target_hits.load());
  22549. }
  22550. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  22551. namespace proxy_tunnel_test {
  22552. // SSLServer counterpart to no_proxy_test::ScopedServer.
  22553. class ScopedSSLServer {
  22554. public:
  22555. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  22556. port_ = svr_.bind_to_any_port("127.0.0.1");
  22557. }
  22558. ~ScopedSSLServer() {
  22559. svr_.stop();
  22560. if (th_.joinable()) { th_.join(); }
  22561. }
  22562. SSLServer &svr() { return svr_; }
  22563. int port() const { return port_; }
  22564. void listen() {
  22565. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22566. svr_.wait_until_ready();
  22567. }
  22568. private:
  22569. SSLServer svr_;
  22570. std::thread th_;
  22571. int port_ = 0;
  22572. };
  22573. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  22574. class ScopedConnectProxy {
  22575. public:
  22576. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  22577. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  22578. if (listen_fd_ < 0) { return; }
  22579. int yes = 1;
  22580. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  22581. sockaddr_in a{};
  22582. a.sin_family = AF_INET;
  22583. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22584. a.sin_port = 0;
  22585. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  22586. return;
  22587. }
  22588. socklen_t alen = sizeof(a);
  22589. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22590. 0) {
  22591. return;
  22592. }
  22593. port_ = ntohs(a.sin_port);
  22594. if (::listen(listen_fd_, 1) != 0) { return; }
  22595. th_ = std::thread([this] { run(); });
  22596. }
  22597. ~ScopedConnectProxy() {
  22598. stop_ = true;
  22599. if (listen_fd_ >= 0) {
  22600. ::shutdown(listen_fd_, SHUT_RDWR);
  22601. ::close(listen_fd_);
  22602. }
  22603. if (th_.joinable()) { th_.join(); }
  22604. }
  22605. int port() const { return port_; }
  22606. int connect_hits() const { return connect_hits_.load(); }
  22607. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22608. std::string connect_request() const {
  22609. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22610. return connect_request_;
  22611. }
  22612. private:
  22613. void run() {
  22614. while (!stop_.load()) {
  22615. fd_set rfds;
  22616. FD_ZERO(&rfds);
  22617. FD_SET(listen_fd_, &rfds);
  22618. timeval tv{0, 100 * 1000};
  22619. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22620. if (sel <= 0) { continue; }
  22621. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22622. if (client_fd < 0) { continue; }
  22623. std::string req;
  22624. char buf[2048];
  22625. while (req.find("\r\n\r\n") == std::string::npos) {
  22626. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22627. if (n <= 0) { break; }
  22628. req.append(buf, static_cast<size_t>(n));
  22629. }
  22630. if (req.compare(0, 7, "CONNECT") != 0) {
  22631. ::close(client_fd);
  22632. continue;
  22633. }
  22634. connect_hits_++;
  22635. {
  22636. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22637. connect_request_ = req;
  22638. }
  22639. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22640. ::send(client_fd, ok, std::strlen(ok), 0);
  22641. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22642. sockaddr_in o{};
  22643. o.sin_family = AF_INET;
  22644. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22645. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22646. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22647. 0) {
  22648. ::close(client_fd);
  22649. ::close(origin_fd);
  22650. continue;
  22651. }
  22652. auto forward = [](int from, int to) {
  22653. char b[8192];
  22654. for (;;) {
  22655. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22656. if (n <= 0) { break; }
  22657. ssize_t off = 0;
  22658. while (off < n) {
  22659. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22660. if (s <= 0) {
  22661. off = n;
  22662. break;
  22663. }
  22664. off += s;
  22665. }
  22666. }
  22667. ::shutdown(to, SHUT_WR);
  22668. };
  22669. std::thread t1([&] { forward(client_fd, origin_fd); });
  22670. std::thread t2([&] { forward(origin_fd, client_fd); });
  22671. t1.join();
  22672. t2.join();
  22673. ::close(client_fd);
  22674. ::close(origin_fd);
  22675. }
  22676. }
  22677. int forward_port_ = -1;
  22678. int listen_fd_ = -1;
  22679. int port_ = 0;
  22680. std::thread th_;
  22681. std::atomic<bool> stop_{false};
  22682. std::atomic<int> connect_hits_{0};
  22683. mutable std::mutex connect_request_mutex_;
  22684. std::string connect_request_;
  22685. };
  22686. // Sends one request through the CONNECT proxy to the TLS origin with a
  22687. // credential configured for each hop, and checks that each credential reaches
  22688. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22689. // origin's (every header in origin_headers) on the tunnelled request.
  22690. void CredentialsStayWithTheirHop(
  22691. const std::function<void(SSLClient &)> &set_credentials,
  22692. const std::string &scheme,
  22693. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22694. std::atomic<int> origin_hits{0};
  22695. std::atomic<bool> origin_saw_proxy_authz{false};
  22696. std::atomic<bool> origin_saw_headers{false};
  22697. ScopedSSLServer origin;
  22698. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22699. origin_hits++;
  22700. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22701. origin_saw_headers =
  22702. std::all_of(origin_headers.begin(), origin_headers.end(),
  22703. [&](const std::string &h) { return req.has_header(h); });
  22704. res.set_content("ok", "text/plain");
  22705. });
  22706. origin.listen();
  22707. ScopedConnectProxy proxy(origin.port());
  22708. ASSERT_NE(0, proxy.port());
  22709. // Pinned to 127.0.0.1 for the same reason as the test below.
  22710. SSLClient cli("127.0.0.1", origin.port());
  22711. cli.enable_server_certificate_verification(false);
  22712. cli.set_proxy("127.0.0.1", proxy.port());
  22713. set_credentials(cli);
  22714. auto res = cli.Get("/x");
  22715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22716. EXPECT_EQ(StatusCode::OK_200, res->status);
  22717. EXPECT_EQ(1, origin_hits.load());
  22718. EXPECT_EQ(1, proxy.connect_hits());
  22719. EXPECT_TRUE(origin_saw_headers.load());
  22720. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22721. << "Proxy-Authorization must not be sent inside the tunnel";
  22722. auto connect_req = proxy.connect_request();
  22723. EXPECT_NE(std::string::npos,
  22724. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22725. for (const auto &h : origin_headers) {
  22726. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22727. << h << " must not be sent to the proxy on CONNECT";
  22728. }
  22729. }
  22730. } // namespace proxy_tunnel_test
  22731. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22732. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22733. [](SSLClient &cli) {
  22734. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22735. cli.set_basic_auth("origin-user", "origin-pass");
  22736. },
  22737. "Basic");
  22738. }
  22739. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22740. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22741. [](SSLClient &cli) {
  22742. cli.set_proxy_bearer_token_auth("proxy-token");
  22743. cli.set_bearer_token_auth("origin-token");
  22744. },
  22745. "Bearer");
  22746. }
  22747. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22748. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22749. [](SSLClient &cli) {
  22750. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22751. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22752. {"Cookie", "sid=origin-session"},
  22753. {"X-Api-Key", "origin-key"}});
  22754. },
  22755. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22756. }
  22757. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22758. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22759. // retry; otherwise proxy creds would be sent to the origin.
  22760. std::atomic<int> origin_hits{0};
  22761. std::atomic<bool> origin_saw_proxy_authz{false};
  22762. proxy_tunnel_test::ScopedSSLServer origin;
  22763. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22764. origin_hits++;
  22765. if (req.has_header("Proxy-Authorization")) {
  22766. origin_saw_proxy_authz = true;
  22767. }
  22768. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22769. res.set_header("Proxy-Authenticate",
  22770. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22771. "algorithm=MD5");
  22772. });
  22773. origin.listen();
  22774. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22775. ASSERT_NE(0, proxy.port());
  22776. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22777. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22778. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22779. // and answer with its own status, making this test flaky.
  22780. SSLClient cli("127.0.0.1", origin.port());
  22781. cli.enable_server_certificate_verification(false);
  22782. cli.set_proxy("127.0.0.1", proxy.port());
  22783. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22784. auto res = cli.Get("/x");
  22785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22786. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22787. EXPECT_EQ(1, origin_hits.load());
  22788. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22789. EXPECT_EQ(1, proxy.connect_hits());
  22790. }
  22791. #endif