test.cc 775 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139
  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_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // Empty quality value
  892. EXPECT_FALSE(
  893. detail::parse_accept_header("text/html;q=,application/json", result));
  894. // Invalid media type format (no slash and not wildcard)
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("invalidtype,application/json", result));
  897. // Empty media type
  898. result.clear();
  899. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  900. // Only commas
  901. result.clear();
  902. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  903. // Valid cases should still work
  904. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*/*");
  907. EXPECT_TRUE(detail::parse_accept_header("*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "*");
  910. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  911. EXPECT_EQ(result.size(), 1U);
  912. EXPECT_EQ(result[0], "text/*");
  913. }
  914. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  915. Server svr;
  916. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  917. EXPECT_EQ(req.accept_content_types.size(), 3U);
  918. EXPECT_EQ(req.accept_content_types[0], "application/json");
  919. EXPECT_EQ(req.accept_content_types[1], "text/html");
  920. EXPECT_EQ(req.accept_content_types[2], "*/*");
  921. res.set_content("ok", "text/plain");
  922. });
  923. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  924. EXPECT_TRUE(false);
  925. res.set_content("bad request", "text/plain");
  926. });
  927. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  928. auto se = detail::scope_exit([&] {
  929. svr.stop();
  930. listen_thread.join();
  931. ASSERT_FALSE(svr.is_running());
  932. });
  933. svr.wait_until_ready();
  934. Client cli("localhost", PORT);
  935. {
  936. auto res = cli.Get(
  937. "/accept_ok",
  938. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  940. EXPECT_EQ(StatusCode::OK_200, res->status);
  941. }
  942. {
  943. auto res = cli.Get("/accept_bad_request",
  944. Headers{{"Accept", "text/html;q=abc,application/json"}});
  945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  946. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  947. }
  948. }
  949. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  950. Server svr;
  951. svr.Get("/", [](const Request & /*req*/, Response &res) {
  952. res.set_content("ok", "text/plain");
  953. });
  954. std::atomic<int> start_count{0};
  955. std::atomic<bool> running_when_called{false};
  956. svr.set_start_handler([&]() {
  957. running_when_called = svr.is_running();
  958. start_count++;
  959. });
  960. auto port = svr.bind_to_any_port(HOST);
  961. std::thread t([&]() { svr.listen_after_bind(); });
  962. auto se = detail::scope_exit([&] {
  963. svr.stop();
  964. t.join();
  965. ASSERT_FALSE(svr.is_running());
  966. });
  967. svr.wait_until_ready();
  968. // A successful request proves the accept loop is running, which the start
  969. // handler precedes; so by now the handler must have run exactly once.
  970. Client cli(HOST, port);
  971. cli.set_connection_timeout(std::chrono::seconds(5));
  972. auto res = cli.Get("/");
  973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  974. EXPECT_EQ(StatusCode::OK_200, res->status);
  975. EXPECT_EQ(1, start_count.load());
  976. EXPECT_TRUE(running_when_called.load());
  977. }
  978. TEST(DivideTest, DivideStringTests) {
  979. auto divide = [](const std::string &str, char d) {
  980. std::string lhs;
  981. std::string rhs;
  982. detail::divide(str, d,
  983. [&](const char *lhs_data, std::size_t lhs_size,
  984. const char *rhs_data, std::size_t rhs_size) {
  985. lhs.assign(lhs_data, lhs_size);
  986. rhs.assign(rhs_data, rhs_size);
  987. });
  988. return std::make_pair(std::move(lhs), std::move(rhs));
  989. };
  990. {
  991. const auto res = divide("", '=');
  992. EXPECT_EQ(res.first, "");
  993. EXPECT_EQ(res.second, "");
  994. }
  995. {
  996. const auto res = divide("=", '=');
  997. EXPECT_EQ(res.first, "");
  998. EXPECT_EQ(res.second, "");
  999. }
  1000. {
  1001. const auto res = divide(" ", '=');
  1002. EXPECT_EQ(res.first, " ");
  1003. EXPECT_EQ(res.second, "");
  1004. }
  1005. {
  1006. const auto res = divide("a", '=');
  1007. EXPECT_EQ(res.first, "a");
  1008. EXPECT_EQ(res.second, "");
  1009. }
  1010. {
  1011. const auto res = divide("a=", '=');
  1012. EXPECT_EQ(res.first, "a");
  1013. EXPECT_EQ(res.second, "");
  1014. }
  1015. {
  1016. const auto res = divide("=b", '=');
  1017. EXPECT_EQ(res.first, "");
  1018. EXPECT_EQ(res.second, "b");
  1019. }
  1020. {
  1021. const auto res = divide("a=b", '=');
  1022. EXPECT_EQ(res.first, "a");
  1023. EXPECT_EQ(res.second, "b");
  1024. }
  1025. {
  1026. const auto res = divide("a=b=", '=');
  1027. EXPECT_EQ(res.first, "a");
  1028. EXPECT_EQ(res.second, "b=");
  1029. }
  1030. {
  1031. const auto res = divide("a=b=c", '=');
  1032. EXPECT_EQ(res.first, "a");
  1033. EXPECT_EQ(res.second, "b=c");
  1034. }
  1035. }
  1036. TEST(SplitTest, ParseQueryString) {
  1037. string s = "key1=val1&key2=val2&key3=val3";
  1038. Params dic;
  1039. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1040. [&](const char *b, const char *e) {
  1041. string key, val;
  1042. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1043. if (key.empty()) {
  1044. key.assign(b2, e2);
  1045. } else {
  1046. val.assign(b2, e2);
  1047. }
  1048. });
  1049. dic.emplace(key, val);
  1050. });
  1051. EXPECT_EQ("val1", dic.find("key1")->second);
  1052. EXPECT_EQ("val2", dic.find("key2")->second);
  1053. EXPECT_EQ("val3", dic.find("key3")->second);
  1054. }
  1055. TEST(SplitTest, ParseInvalidQueryTests) {
  1056. {
  1057. string s = " ";
  1058. Params dict;
  1059. detail::parse_query_text(s, dict);
  1060. EXPECT_TRUE(dict.empty());
  1061. }
  1062. {
  1063. string s = " = =";
  1064. Params dict;
  1065. detail::parse_query_text(s, dict);
  1066. EXPECT_TRUE(dict.empty());
  1067. }
  1068. }
  1069. TEST(ParseQueryTest, ParseQueryString) {
  1070. {
  1071. std::string s = "key1=val1&key2=val2&key3=val3";
  1072. Params dic;
  1073. detail::parse_query_text(s, dic);
  1074. EXPECT_EQ("val1", dic.find("key1")->second);
  1075. EXPECT_EQ("val2", dic.find("key2")->second);
  1076. EXPECT_EQ("val3", dic.find("key3")->second);
  1077. }
  1078. {
  1079. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1080. Params dic;
  1081. detail::parse_query_text(s, dic);
  1082. EXPECT_EQ("", dic.find("key1")->second);
  1083. EXPECT_EQ("val1", dic.find("key2")->second);
  1084. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1085. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1086. }
  1087. }
  1088. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1089. Params dic;
  1090. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1091. dic.emplace("key1", "val1");
  1092. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1093. dic.emplace("key2", "val2");
  1094. dic.emplace("key3", "val3");
  1095. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1096. }
  1097. // Joins every entry of a Headers or Params into "key=value " so a whole
  1098. // traversal can be compared in one assertion. Both are instantiations of the
  1099. // same insertion-ordered container, so one helper serves both.
  1100. template <typename Map> static std::string entries_to_string(const Map &m) {
  1101. std::string s;
  1102. for (const auto &entry : m) {
  1103. s += entry.first + "=" + entry.second + " ";
  1104. }
  1105. return s;
  1106. }
  1107. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1108. // Params used to be a std::multimap, which sorted by name and handed the
  1109. // caller's query back alphabetised. A client signing its query string could
  1110. // not reproduce the order it asked for.
  1111. Params dic;
  1112. dic.emplace("zulu", "1");
  1113. dic.emplace("alpha", "2");
  1114. dic.emplace("mike", "3");
  1115. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1116. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1117. }
  1118. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1119. Params dic;
  1120. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1121. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1122. }
  1123. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1124. Request req;
  1125. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1126. req.params);
  1127. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1128. EXPECT_EQ("first", req.get_param_value("tag"));
  1129. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1130. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1131. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1132. EXPECT_EQ("", req.get_param_value("tag", 3));
  1133. }
  1134. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1135. // Params shares its container with Headers, which matches field names
  1136. // case-insensitively. Parameter names must not pick that up.
  1137. Params dic;
  1138. dic.emplace("Key", "upper");
  1139. dic.emplace("key", "lower");
  1140. EXPECT_EQ(2U, dic.size());
  1141. EXPECT_EQ(1U, dic.count("Key"));
  1142. EXPECT_EQ(1U, dic.count("key"));
  1143. EXPECT_EQ("upper", dic.find("Key")->second);
  1144. EXPECT_EQ("lower", dic.find("key")->second);
  1145. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1146. }
  1147. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1148. Server svr;
  1149. std::string order;
  1150. svr.Get("/order", [&](const Request &req, Response &res) {
  1151. order = entries_to_string(req.params);
  1152. res.set_content("ok", "text/plain");
  1153. });
  1154. auto port = svr.bind_to_any_port(HOST);
  1155. thread t = thread([&] { svr.listen_after_bind(); });
  1156. auto se = detail::scope_exit([&] {
  1157. svr.stop();
  1158. t.join();
  1159. ASSERT_FALSE(svr.is_running());
  1160. });
  1161. svr.wait_until_ready();
  1162. Client cli(HOST, port);
  1163. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1164. ASSERT_TRUE(res);
  1165. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1166. }
  1167. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1168. Server svr;
  1169. std::string field_order, file_order;
  1170. svr.Post("/order", [&](const Request &req, Response &res) {
  1171. for (const auto &field : req.form.fields) {
  1172. field_order += field.first + "=" + field.second.content + " ";
  1173. }
  1174. for (const auto &file : req.form.files) {
  1175. file_order += file.first + "=" + file.second.filename + " ";
  1176. }
  1177. res.set_content("ok", "text/plain");
  1178. });
  1179. auto port = svr.bind_to_any_port(HOST);
  1180. thread t = thread([&] { svr.listen_after_bind(); });
  1181. auto se = detail::scope_exit([&] {
  1182. svr.stop();
  1183. t.join();
  1184. ASSERT_FALSE(svr.is_running());
  1185. });
  1186. svr.wait_until_ready();
  1187. UploadFormDataItems items = {
  1188. {"zulu", "1", "", ""},
  1189. {"alpha", "2", "", ""},
  1190. {"mike", "3", "", ""},
  1191. {"zebra", "z", "z.txt", "text/plain"},
  1192. {"apple", "a", "a.txt", "text/plain"},
  1193. };
  1194. Client cli(HOST, port);
  1195. auto res = cli.Post("/order", items);
  1196. ASSERT_TRUE(res);
  1197. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1198. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1199. }
  1200. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1201. Server svr;
  1202. std::vector<std::string> values;
  1203. std::string first, second, out_of_range, order;
  1204. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1205. values = req.form.get_fields("tag");
  1206. first = req.form.get_field("tag", 0);
  1207. second = req.form.get_field("tag", 1);
  1208. out_of_range = req.form.get_field("tag", 2);
  1209. for (const auto &field : req.form.fields) {
  1210. order += field.first + "=" + field.second.content + " ";
  1211. }
  1212. res.set_content("ok", "text/plain");
  1213. });
  1214. auto port = svr.bind_to_any_port(HOST);
  1215. thread t = thread([&] { svr.listen_after_bind(); });
  1216. auto se = detail::scope_exit([&] {
  1217. svr.stop();
  1218. t.join();
  1219. ASSERT_FALSE(svr.is_running());
  1220. });
  1221. svr.wait_until_ready();
  1222. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1223. // not adjacent in the container.
  1224. UploadFormDataItems items = {
  1225. {"tag", "first", "", ""},
  1226. {"other", "x", "", ""},
  1227. {"tag", "second", "", ""},
  1228. };
  1229. Client cli(HOST, port);
  1230. auto res = cli.Post("/repeated", items);
  1231. ASSERT_TRUE(res);
  1232. ASSERT_EQ(2U, values.size());
  1233. EXPECT_EQ("first", values[0]);
  1234. EXPECT_EQ("second", values[1]);
  1235. EXPECT_EQ("first", first);
  1236. EXPECT_EQ("second", second);
  1237. // std::multimap already kept entries sharing a name in insertion order, so
  1238. // everything above passes without this change too. The whole traversal is
  1239. // what tells the two apart: sorting by name would hoist "other" to the front
  1240. // and the two "tag" parts would end up adjacent.
  1241. EXPECT_EQ("tag=first other=x tag=second ", order);
  1242. // Advancing past the last entry of a name used to run off the container;
  1243. // the container's saturating increment makes it return the default instead.
  1244. EXPECT_EQ("", out_of_range);
  1245. }
  1246. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1247. // Server::read_content() keeps a FormFields::iterator alive across the
  1248. // content callbacks that fill the part it points at. The container is
  1249. // vector-backed, so a later emplace can reallocate and invalidate an older
  1250. // iterator; 64 parts grow the vector through seven reallocations, which
  1251. // checks that every part's content still lands in its own entry.
  1252. const size_t part_count = 64;
  1253. // One formula for both the parts sent and the values expected back, so the
  1254. // two cannot drift apart.
  1255. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1256. auto content_of = [](size_t i) {
  1257. return std::string(64, static_cast<char>('a' + (i % 26)));
  1258. };
  1259. Server svr;
  1260. std::vector<std::pair<std::string, std::string>> received;
  1261. svr.Post("/many", [&](const Request &req, Response &res) {
  1262. for (const auto &field : req.form.fields) {
  1263. received.emplace_back(field.first, field.second.content);
  1264. }
  1265. res.set_content("ok", "text/plain");
  1266. });
  1267. auto port = svr.bind_to_any_port(HOST);
  1268. thread t = thread([&] { svr.listen_after_bind(); });
  1269. auto se = detail::scope_exit([&] {
  1270. svr.stop();
  1271. t.join();
  1272. ASSERT_FALSE(svr.is_running());
  1273. });
  1274. svr.wait_until_ready();
  1275. UploadFormDataItems items;
  1276. for (size_t i = 0; i < part_count; i++) {
  1277. items.push_back({name_of(i), content_of(i), "", ""});
  1278. }
  1279. Client cli(HOST, port);
  1280. auto res = cli.Post("/many", items);
  1281. ASSERT_TRUE(res);
  1282. ASSERT_EQ(part_count, received.size());
  1283. for (size_t i = 0; i < part_count; i++) {
  1284. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1285. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1286. }
  1287. }
  1288. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1289. string content_type = "multipart/form-data; boundary=something";
  1290. string boundary;
  1291. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1292. EXPECT_TRUE(ret);
  1293. EXPECT_EQ(boundary, "something");
  1294. }
  1295. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1296. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1297. string boundary;
  1298. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1299. EXPECT_TRUE(ret);
  1300. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1301. }
  1302. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1303. string content_type =
  1304. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1305. string boundary;
  1306. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1307. EXPECT_TRUE(ret);
  1308. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1309. }
  1310. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1311. string content_type =
  1312. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1313. string boundary;
  1314. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1315. EXPECT_TRUE(ret);
  1316. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1317. }
  1318. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1319. const string boundary(70, 'a');
  1320. string content_type = "multipart/form-data; boundary=" + boundary;
  1321. string parsed;
  1322. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1323. EXPECT_TRUE(ret);
  1324. EXPECT_EQ(parsed, boundary);
  1325. }
  1326. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1327. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1328. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1329. string parsed;
  1330. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1331. EXPECT_FALSE(ret);
  1332. }
  1333. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1334. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1335. // is 72 characters on the wire and still valid.
  1336. const string boundary(70, 'a');
  1337. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1338. string parsed;
  1339. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1340. EXPECT_EQ(parsed, boundary);
  1341. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1342. parsed.clear();
  1343. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1344. }
  1345. TEST(GetHeaderValueTest, DefaultValue) {
  1346. Headers headers = {{"Dummy", "Dummy"}};
  1347. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1348. EXPECT_STREQ("text/plain", val);
  1349. }
  1350. TEST(GetHeaderValueTest, DefaultValueInt) {
  1351. Headers headers = {{"Dummy", "Dummy"}};
  1352. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1353. EXPECT_EQ(100ull, val);
  1354. }
  1355. TEST(GetHeaderValueTest, RegularValue) {
  1356. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1357. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1358. EXPECT_STREQ("text/html", val);
  1359. }
  1360. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1361. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1362. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1363. EXPECT_STREQ("text/html", val);
  1364. }
  1365. TEST(GetHeaderValueTest, SetContent) {
  1366. Response res;
  1367. res.set_content("html", "text/html");
  1368. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1369. res.set_content("text", "text/plain");
  1370. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1371. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1372. }
  1373. TEST(GetHeaderValueTest, RegularValueInt) {
  1374. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1375. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1376. EXPECT_EQ(100ull, val);
  1377. }
  1378. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1379. Headers headers = {{"Content-Length", "x"}};
  1380. auto is_invalid_value = false;
  1381. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1382. is_invalid_value);
  1383. EXPECT_EQ(0ull, val);
  1384. EXPECT_TRUE(is_invalid_value);
  1385. }
  1386. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1387. // An all-digit value that overflows size_t must be reported as invalid, not
  1388. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1389. // a large length to a small one on 32-bit builds, leaving the framing length
  1390. // wrong while is_invalid_value stayed false.
  1391. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1392. auto is_invalid_value = false;
  1393. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1394. is_invalid_value);
  1395. EXPECT_TRUE(is_invalid_value);
  1396. // A well-formed length is unaffected.
  1397. Headers ok = {{"Content-Length", "1234"}};
  1398. is_invalid_value = false;
  1399. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1400. is_invalid_value);
  1401. EXPECT_EQ(1234ull, val);
  1402. EXPECT_FALSE(is_invalid_value);
  1403. }
  1404. TEST(GetHeaderValueTest, Range) {
  1405. {
  1406. Headers headers = {make_range_header({{1, -1}})};
  1407. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1408. EXPECT_STREQ("bytes=1-", val);
  1409. }
  1410. {
  1411. Headers headers = {make_range_header({{-1, 1}})};
  1412. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1413. EXPECT_STREQ("bytes=-1", val);
  1414. }
  1415. {
  1416. Headers headers = {make_range_header({{1, 10}})};
  1417. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1418. EXPECT_STREQ("bytes=1-10", val);
  1419. }
  1420. {
  1421. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1422. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1423. EXPECT_STREQ("bytes=1-10, 100-", val);
  1424. }
  1425. {
  1426. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1427. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1428. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1429. }
  1430. {
  1431. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1432. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1433. EXPECT_STREQ("bytes=0-0, -1", val);
  1434. }
  1435. }
  1436. TEST(BearerTokenAuthTest, SchemeValidation) {
  1437. // A value shorter than "Bearer " must not throw from the fixed-length
  1438. // substr, and a non-Bearer scheme must not be reported as a token.
  1439. struct {
  1440. const char *value;
  1441. const char *expected;
  1442. } cases[] = {
  1443. {"x", ""},
  1444. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1445. {"Bearer abc123", "abc123"},
  1446. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1447. };
  1448. for (const auto &c : cases) {
  1449. Request req;
  1450. req.set_header("Authorization", c.value);
  1451. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1452. }
  1453. }
  1454. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1455. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1456. // to depend on the standard library (libstdc++ handed back duplicates in
  1457. // reverse insertion order, libc++ in insertion order).
  1458. Request req;
  1459. req.set_header("Accept-Encoding", "gzip");
  1460. req.set_header("Accept-Encoding", "deflate");
  1461. req.set_header("Accept-Encoding", "br");
  1462. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1463. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1464. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1465. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1466. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1467. }
  1468. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1469. Request req;
  1470. req.set_header("X-Test", "only");
  1471. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1472. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1473. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1474. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1475. }
  1476. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1477. Headers headers;
  1478. headers.emplace("Host", "example.com");
  1479. headers.emplace("Accept-Encoding", "gzip");
  1480. headers.emplace("User-Agent", "test");
  1481. headers.emplace("Accept-Encoding", "deflate");
  1482. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1483. "Accept-Encoding=deflate ",
  1484. entries_to_string(headers));
  1485. }
  1486. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1487. Headers headers = {{"Content-Type", "text/html"},
  1488. {"CONTENT-TYPE", "text/xml"}};
  1489. EXPECT_EQ(2U, headers.count("content-type"));
  1490. auto it = headers.find("content-type");
  1491. ASSERT_TRUE(it != headers.end());
  1492. EXPECT_EQ("text/html", it->second);
  1493. }
  1494. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1495. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1496. // drop only those fields and leave everything positioned between them.
  1497. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1498. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1499. auto rng = headers.equal_range("a");
  1500. headers.erase(rng.first, rng.second);
  1501. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1502. }
  1503. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1504. Headers headers = {
  1505. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1506. EXPECT_EQ(3U, headers.erase("A"));
  1507. EXPECT_EQ(0U, headers.count("A"));
  1508. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1509. }
  1510. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1511. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1512. headers.emplace_front("Host", "example.com");
  1513. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1514. entries_to_string(headers));
  1515. }
  1516. TEST(ParseHeaderValueTest, Range) {
  1517. {
  1518. Ranges ranges;
  1519. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1520. EXPECT_TRUE(ret);
  1521. EXPECT_EQ(1u, ranges.size());
  1522. EXPECT_EQ(1u, ranges[0].first);
  1523. EXPECT_EQ(-1, ranges[0].second);
  1524. }
  1525. {
  1526. Ranges ranges;
  1527. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1528. EXPECT_TRUE(ret);
  1529. EXPECT_EQ(1u, ranges.size());
  1530. EXPECT_EQ(-1, ranges[0].first);
  1531. EXPECT_EQ(1u, ranges[0].second);
  1532. }
  1533. {
  1534. Ranges ranges;
  1535. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1536. EXPECT_TRUE(ret);
  1537. EXPECT_EQ(1u, ranges.size());
  1538. EXPECT_EQ(1u, ranges[0].first);
  1539. EXPECT_EQ(10u, ranges[0].second);
  1540. }
  1541. {
  1542. Ranges ranges;
  1543. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1544. EXPECT_FALSE(ret);
  1545. }
  1546. {
  1547. Ranges ranges;
  1548. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1549. EXPECT_TRUE(ret);
  1550. EXPECT_EQ(2u, ranges.size());
  1551. EXPECT_EQ(1u, ranges[0].first);
  1552. EXPECT_EQ(10u, ranges[0].second);
  1553. EXPECT_EQ(100u, ranges[1].first);
  1554. EXPECT_EQ(-1, ranges[1].second);
  1555. }
  1556. {
  1557. Ranges ranges;
  1558. auto ret =
  1559. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(3u, ranges.size());
  1562. EXPECT_EQ(1u, ranges[0].first);
  1563. EXPECT_EQ(10u, ranges[0].second);
  1564. EXPECT_EQ(100u, ranges[1].first);
  1565. EXPECT_EQ(200u, ranges[1].second);
  1566. EXPECT_EQ(300u, ranges[2].first);
  1567. EXPECT_EQ(400u, ranges[2].second);
  1568. }
  1569. {
  1570. Ranges ranges;
  1571. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1572. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1573. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1574. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1575. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1576. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1577. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1578. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1579. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1580. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1581. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1582. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1583. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1584. EXPECT_TRUE(ranges.empty());
  1585. }
  1586. }
  1587. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1588. Request req;
  1589. req.set_header("Accept-Encoding", "gzip");
  1590. Response res;
  1591. res.set_header("Content-Type", "text/plain");
  1592. auto ret = detail::encoding_type(req, res);
  1593. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1594. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1595. #else
  1596. EXPECT_TRUE(ret == detail::EncodingType::None);
  1597. #endif
  1598. }
  1599. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1600. Request req;
  1601. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1602. Response res;
  1603. res.set_header("Content-Type", "text/plain");
  1604. auto ret = detail::encoding_type(req, res);
  1605. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1606. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1607. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1608. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1609. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1610. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1611. #else
  1612. EXPECT_TRUE(ret == detail::EncodingType::None);
  1613. #endif
  1614. }
  1615. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1616. Request req;
  1617. req.set_header("Accept-Encoding",
  1618. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1619. Response res;
  1620. res.set_header("Content-Type", "text/plain");
  1621. auto ret = detail::encoding_type(req, res);
  1622. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1623. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1624. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1625. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1626. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1627. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1628. #else
  1629. EXPECT_TRUE(ret == detail::EncodingType::None);
  1630. #endif
  1631. }
  1632. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1633. // All supported encodings rejected with q=0 should return None
  1634. Request req;
  1635. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1636. Response res;
  1637. res.set_header("Content-Type", "text/plain");
  1638. auto ret = detail::encoding_type(req, res);
  1639. EXPECT_TRUE(ret == detail::EncodingType::None);
  1640. }
  1641. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1642. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1643. Request req;
  1644. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1645. Response res;
  1646. res.set_header("Content-Type", "text/plain");
  1647. auto ret = detail::encoding_type(req, res);
  1648. EXPECT_TRUE(ret == detail::EncodingType::None);
  1649. }
  1650. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1651. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1652. Request req;
  1653. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1654. Response res;
  1655. res.set_header("Content-Type", "text/plain");
  1656. auto ret = detail::encoding_type(req, res);
  1657. EXPECT_TRUE(ret == detail::EncodingType::None);
  1658. }
  1659. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1660. // RFC 7231: Accept-Encoding values are case-insensitive
  1661. Request req;
  1662. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1663. Response res;
  1664. res.set_header("Content-Type", "text/plain");
  1665. auto ret = detail::encoding_type(req, res);
  1666. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1667. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1668. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1669. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1670. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1671. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1672. #else
  1673. EXPECT_TRUE(ret == detail::EncodingType::None);
  1674. #endif
  1675. }
  1676. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1677. // q value should determine priority, not hardcoded order
  1678. Request req;
  1679. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1680. Response res;
  1681. res.set_header("Content-Type", "text/plain");
  1682. auto ret = detail::encoding_type(req, res);
  1683. // gzip has highest q=1.0, so it should be selected even though
  1684. // br and zstd are also supported
  1685. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1686. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1687. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1688. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1689. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1690. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1691. #else
  1692. EXPECT_TRUE(ret == detail::EncodingType::None);
  1693. #endif
  1694. }
  1695. TEST(BufferStreamTest, read) {
  1696. detail::BufferStream strm1;
  1697. Stream &strm = strm1;
  1698. EXPECT_EQ(5, strm.write("hello"));
  1699. char buf[512];
  1700. EXPECT_EQ(2, strm.read(buf, 2));
  1701. EXPECT_EQ('h', buf[0]);
  1702. EXPECT_EQ('e', buf[1]);
  1703. EXPECT_EQ(2, strm.read(buf, 2));
  1704. EXPECT_EQ('l', buf[0]);
  1705. EXPECT_EQ('l', buf[1]);
  1706. EXPECT_EQ(1, strm.read(buf, 1));
  1707. EXPECT_EQ('o', buf[0]);
  1708. EXPECT_EQ(0, strm.read(buf, 1));
  1709. }
  1710. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1711. auto host = "www.httpwatch.com";
  1712. auto ip = hosted_at(host);
  1713. EXPECT_EQ("23.96.13.243", ip);
  1714. std::vector<std::string> addrs;
  1715. hosted_at(host, addrs);
  1716. EXPECT_EQ(1u, addrs.size());
  1717. }
  1718. #if 0 // It depends on each test environment...
  1719. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1720. auto host = "www.youtube.com";
  1721. std::vector<std::string> addrs;
  1722. hosted_at(host, addrs);
  1723. EXPECT_EQ(20u, addrs.size());
  1724. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1725. EXPECT_TRUE(it != addrs.end());
  1726. }
  1727. #endif
  1728. class ChunkedEncodingTest : public ::testing::Test {
  1729. protected:
  1730. ChunkedEncodingTest()
  1731. : cli_(HOST, PORT)
  1732. #ifdef CPPHTTPLIB_SSL_ENABLED
  1733. ,
  1734. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1735. #endif
  1736. {
  1737. cli_.set_connection_timeout(2);
  1738. #ifdef CPPHTTPLIB_SSL_ENABLED
  1739. cli_.enable_server_certificate_verification(false);
  1740. #endif
  1741. }
  1742. virtual void SetUp() {
  1743. read_file("./image.jpg", image_data_);
  1744. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1745. res.set_content("Hello World!", "text/plain");
  1746. });
  1747. svr_.Get(
  1748. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1749. res.set_chunked_content_provider(
  1750. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1751. size_t remaining = image_data_.size() - offset;
  1752. if (remaining == 0) {
  1753. sink.done();
  1754. } else {
  1755. constexpr size_t CHUNK_SIZE = 1024;
  1756. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1757. sink.write(&image_data_[offset], send_size);
  1758. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1759. }
  1760. return true;
  1761. });
  1762. });
  1763. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1764. svr_.wait_until_ready();
  1765. }
  1766. virtual void TearDown() {
  1767. svr_.stop();
  1768. if (!request_threads_.empty()) {
  1769. std::this_thread::sleep_for(std::chrono::seconds(1));
  1770. for (auto &t : request_threads_) {
  1771. t.join();
  1772. }
  1773. }
  1774. t_.join();
  1775. }
  1776. #ifdef CPPHTTPLIB_SSL_ENABLED
  1777. SSLClient cli_;
  1778. SSLServer svr_;
  1779. #else
  1780. Client cli_;
  1781. Server svr_;
  1782. #endif
  1783. thread t_;
  1784. std::vector<thread> request_threads_;
  1785. std::string image_data_;
  1786. };
  1787. TEST_F(ChunkedEncodingTest, NormalGet) {
  1788. auto res = cli_.Get("/chunked");
  1789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1790. std::string out;
  1791. read_file("./image.jpg", out);
  1792. EXPECT_EQ(StatusCode::OK_200, res->status);
  1793. EXPECT_EQ(out, res->body);
  1794. }
  1795. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1796. std::string body;
  1797. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1798. body.append(data, data_length);
  1799. return true;
  1800. });
  1801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1802. std::string out;
  1803. read_file("./image.jpg", out);
  1804. EXPECT_EQ(StatusCode::OK_200, res->status);
  1805. EXPECT_EQ(out, body);
  1806. }
  1807. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1808. std::string body;
  1809. auto res = cli_.Get(
  1810. "/chunked",
  1811. [&](const Response &response) {
  1812. EXPECT_EQ(StatusCode::OK_200, response.status);
  1813. return true;
  1814. },
  1815. [&](const char *data, size_t data_length) {
  1816. body.append(data, data_length);
  1817. return true;
  1818. });
  1819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1820. std::string out;
  1821. read_file("./image.jpg", out);
  1822. EXPECT_EQ(StatusCode::OK_200, res->status);
  1823. EXPECT_EQ(out, body);
  1824. }
  1825. TEST(RangeTest, FromHTTPBin_Online) {
  1826. auto host = "httpbingo.org";
  1827. auto path = std::string{"/range/32"};
  1828. #ifdef CPPHTTPLIB_SSL_ENABLED
  1829. auto port = 443;
  1830. SSLClient cli(host, port);
  1831. #else
  1832. auto port = 80;
  1833. Client cli(host, port);
  1834. #endif
  1835. cli.set_connection_timeout(5);
  1836. {
  1837. auto res = cli.Get(path);
  1838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1839. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1840. EXPECT_EQ(StatusCode::OK_200, res->status);
  1841. }
  1842. {
  1843. Headers headers = {make_range_header({{1, -1}})};
  1844. auto res = cli.Get(path, headers);
  1845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1846. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1847. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1848. }
  1849. {
  1850. Headers headers = {make_range_header({{1, 10}})};
  1851. auto res = cli.Get(path, headers);
  1852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1853. EXPECT_EQ("bcdefghijk", res->body);
  1854. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1855. }
  1856. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1857. // entire resource, while the original httpbin returned 200. Both are
  1858. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1859. {
  1860. Headers headers = {make_range_header({{0, 31}})};
  1861. auto res = cli.Get(path, headers);
  1862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1863. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1864. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1865. res->status == StatusCode::PartialContent_206);
  1866. }
  1867. {
  1868. Headers headers = {make_range_header({{0, -1}})};
  1869. auto res = cli.Get(path, headers);
  1870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1871. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1872. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1873. res->status == StatusCode::PartialContent_206);
  1874. }
  1875. // go-httpbin returns 206 with clamped range for over-range requests,
  1876. // while the original httpbin returned 416. Both behaviors are observed
  1877. // in real servers, so we only verify the request succeeds.
  1878. {
  1879. Headers headers = {make_range_header({{0, 32}})};
  1880. auto res = cli.Get(path, headers);
  1881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1882. }
  1883. }
  1884. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1885. auto host = "unresolvableaddress.local";
  1886. auto path = std::string{"/"};
  1887. #ifdef CPPHTTPLIB_SSL_ENABLED
  1888. auto port = 443;
  1889. SSLClient cli(host, port);
  1890. #else
  1891. auto port = 80;
  1892. Client cli(host, port);
  1893. #endif
  1894. cli.set_connection_timeout(1);
  1895. {
  1896. auto res = cli.Get(path);
  1897. ASSERT_FALSE(res);
  1898. }
  1899. std::this_thread::sleep_for(std::chrono::seconds(8));
  1900. }
  1901. #if defined(__linux__) && defined(__GLIBC__) && \
  1902. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1903. // Forward declaration: in split builds split.py strips `inline` and moves the
  1904. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1905. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1906. // against the symbol in both header-only and split builds.
  1907. namespace httplib {
  1908. namespace detail {
  1909. int getaddrinfo_with_timeout(const char *node, const char *service,
  1910. const struct addrinfo *hints,
  1911. struct addrinfo **res, time_t timeout_sec);
  1912. } // namespace detail
  1913. } // namespace httplib
  1914. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1915. //
  1916. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1917. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1918. // gai_suspend() call hits the connection timeout the function calls
  1919. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1920. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1921. // still alive and still references the now-destroyed stack frame.
  1922. //
  1923. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1924. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1925. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1926. // and runs them in a container.
  1927. namespace {
  1928. bool should_run_issue_2431_tests() {
  1929. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1930. return v && *v && std::string(v) != "0";
  1931. }
  1932. std::string unique_unresolvable_host(int n) {
  1933. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1934. // glibc still asks the configured nameserver — which is exactly the path
  1935. // we want to exercise. A unique label per call avoids the resolver cache.
  1936. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1937. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1938. std::to_string(n) + ".invalid";
  1939. }
  1940. } // namespace
  1941. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1942. if (!should_run_issue_2431_tests()) {
  1943. GTEST_SKIP()
  1944. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1945. }
  1946. for (int i = 0; i < 8; ++i) {
  1947. struct addrinfo hints;
  1948. memset(&hints, 0, sizeof(hints));
  1949. hints.ai_family = AF_UNSPEC;
  1950. hints.ai_socktype = SOCK_STREAM;
  1951. auto host = unique_unresolvable_host(i);
  1952. struct addrinfo *result = nullptr;
  1953. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1954. &result, /*timeout_sec=*/1);
  1955. if (rc == 0 && result) { freeaddrinfo(result); }
  1956. }
  1957. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1958. // stack region they still believe holds their gaicb.
  1959. std::this_thread::sleep_for(std::chrono::seconds(3));
  1960. }
  1961. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1962. if (!should_run_issue_2431_tests()) {
  1963. GTEST_SKIP()
  1964. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1965. }
  1966. std::atomic<bool> stop{false};
  1967. std::vector<std::thread> threads;
  1968. for (int t = 0; t < 8; ++t) {
  1969. threads.emplace_back([t, &stop] {
  1970. int i = 0;
  1971. while (!stop.load(std::memory_order_relaxed)) {
  1972. struct addrinfo hints;
  1973. memset(&hints, 0, sizeof(hints));
  1974. hints.ai_family = AF_UNSPEC;
  1975. hints.ai_socktype = SOCK_STREAM;
  1976. auto host = unique_unresolvable_host(t * 100000 + i++);
  1977. struct addrinfo *result = nullptr;
  1978. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1979. &result, /*timeout_sec=*/1);
  1980. if (rc == 0 && result) { freeaddrinfo(result); }
  1981. }
  1982. });
  1983. }
  1984. std::this_thread::sleep_for(std::chrono::seconds(8));
  1985. stop.store(true, std::memory_order_relaxed);
  1986. for (auto &th : threads) {
  1987. th.join();
  1988. }
  1989. std::this_thread::sleep_for(std::chrono::seconds(3));
  1990. }
  1991. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1992. if (!should_run_issue_2431_tests()) {
  1993. GTEST_SKIP()
  1994. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1995. }
  1996. std::atomic<bool> stop{false};
  1997. std::vector<std::thread> threads;
  1998. for (int t = 0; t < 8; ++t) {
  1999. threads.emplace_back([t, &stop] {
  2000. int i = 0;
  2001. while (!stop.load(std::memory_order_relaxed)) {
  2002. auto host = unique_unresolvable_host(t * 100000 + i++);
  2003. Client cli(host, 80);
  2004. cli.set_connection_timeout(1, 0);
  2005. cli.set_read_timeout(1, 0);
  2006. cli.set_write_timeout(1, 0);
  2007. (void)cli.Get("/");
  2008. }
  2009. });
  2010. }
  2011. std::this_thread::sleep_for(std::chrono::seconds(8));
  2012. stop.store(true, std::memory_order_relaxed);
  2013. for (auto &th : threads) {
  2014. th.join();
  2015. }
  2016. std::this_thread::sleep_for(std::chrono::seconds(3));
  2017. }
  2018. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2019. TEST(ConnectionErrorTest, InvalidHost) {
  2020. auto host = "-abcde.com";
  2021. #ifdef CPPHTTPLIB_SSL_ENABLED
  2022. auto port = 443;
  2023. SSLClient cli(host, port);
  2024. #else
  2025. auto port = 80;
  2026. Client cli(host, port);
  2027. #endif
  2028. cli.set_connection_timeout(std::chrono::seconds(2));
  2029. auto res = cli.Get("/");
  2030. ASSERT_TRUE(!res);
  2031. EXPECT_EQ(Error::Connection, res.error());
  2032. }
  2033. TEST(ConnectionErrorTest, InvalidHost2) {
  2034. auto host = "httpcan.org/";
  2035. #ifdef CPPHTTPLIB_SSL_ENABLED
  2036. SSLClient cli(host);
  2037. #else
  2038. Client cli(host);
  2039. #endif
  2040. cli.set_connection_timeout(std::chrono::seconds(2));
  2041. auto res = cli.Get("/");
  2042. ASSERT_TRUE(!res);
  2043. EXPECT_EQ(Error::Connection, res.error());
  2044. }
  2045. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2046. auto host = "httpcan.org/";
  2047. #ifdef CPPHTTPLIB_SSL_ENABLED
  2048. SSLClient cli(host);
  2049. #else
  2050. Client cli(host);
  2051. #endif
  2052. cli.set_connection_timeout(std::chrono::seconds(2));
  2053. auto res = cli.Get("/");
  2054. ASSERT_TRUE(!res);
  2055. stringstream s;
  2056. s << "error code: " << res.error();
  2057. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2058. }
  2059. TEST(ConnectionErrorTest, InvalidPort) {
  2060. auto host = "localhost";
  2061. auto port = 44380;
  2062. #ifdef CPPHTTPLIB_SSL_ENABLED
  2063. SSLClient cli(host, port);
  2064. #else
  2065. Client cli(host, port);
  2066. #endif
  2067. cli.set_connection_timeout(std::chrono::seconds(2));
  2068. auto res = cli.Get("/");
  2069. ASSERT_TRUE(!res);
  2070. EXPECT_TRUE(Error::Connection == res.error() ||
  2071. Error::ConnectionTimeout == res.error());
  2072. }
  2073. TEST(ConnectionErrorTest, Timeout_Online) {
  2074. auto host = "google.com";
  2075. #ifdef CPPHTTPLIB_SSL_ENABLED
  2076. auto port = 44380;
  2077. SSLClient cli(host, port);
  2078. #else
  2079. auto port = 8080;
  2080. Client cli(host, port);
  2081. #endif
  2082. cli.set_connection_timeout(std::chrono::seconds(2));
  2083. // only probe one address type so that the error reason
  2084. // correlates to the timed-out IPv4, not the unsupported
  2085. // IPv6 connection attempt
  2086. cli.set_address_family(AF_INET);
  2087. auto res = cli.Get("/");
  2088. ASSERT_TRUE(!res);
  2089. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2090. }
  2091. TEST(CancelTest, NoCancel_Online) {
  2092. auto host = "httpbingo.org";
  2093. auto path = std::string{"/range/32"};
  2094. #ifdef CPPHTTPLIB_SSL_ENABLED
  2095. auto port = 443;
  2096. SSLClient cli(host, port);
  2097. #else
  2098. auto port = 80;
  2099. Client cli(host, port);
  2100. #endif
  2101. cli.set_connection_timeout(std::chrono::seconds(5));
  2102. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2104. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2105. EXPECT_EQ(StatusCode::OK_200, res->status);
  2106. }
  2107. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2108. // Use /bytes with a large payload so that the DownloadProgress callback
  2109. // (which only fires for Content-Length responses) is invoked before the
  2110. // entire body is received, giving cancellation a chance to fire.
  2111. auto host = "httpbingo.org";
  2112. auto path = std::string{"/bytes/524288"};
  2113. #ifdef CPPHTTPLIB_SSL_ENABLED
  2114. auto port = 443;
  2115. SSLClient cli(host, port);
  2116. #else
  2117. auto port = 80;
  2118. Client cli(host, port);
  2119. #endif
  2120. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2121. cli.set_connection_timeout(std::chrono::seconds(5));
  2122. ASSERT_TRUE(!res);
  2123. EXPECT_EQ(Error::Canceled, res.error());
  2124. }
  2125. TEST(CancelTest, WithCancelLargePayload_Online) {
  2126. auto host = "httpbingo.org";
  2127. auto path = std::string{"/bytes/524288"};
  2128. #ifdef CPPHTTPLIB_SSL_ENABLED
  2129. auto port = 443;
  2130. SSLClient cli(host, port);
  2131. #else
  2132. auto port = 80;
  2133. Client cli(host, port);
  2134. #endif
  2135. cli.set_connection_timeout(std::chrono::seconds(5));
  2136. uint32_t count = 0;
  2137. auto res =
  2138. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2139. ASSERT_TRUE(!res);
  2140. EXPECT_EQ(Error::Canceled, res.error());
  2141. }
  2142. TEST(CancelTest, NoCancelPost) {
  2143. Server svr;
  2144. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2145. res.set_content("Hello World!", "text/plain");
  2146. });
  2147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2148. auto se = detail::scope_exit([&] {
  2149. svr.stop();
  2150. thread.join();
  2151. ASSERT_FALSE(svr.is_running());
  2152. });
  2153. svr.wait_until_ready();
  2154. Client cli(HOST, PORT);
  2155. cli.set_connection_timeout(std::chrono::seconds(5));
  2156. auto res =
  2157. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2158. "application/json", [](uint64_t, uint64_t) { return true; });
  2159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2160. EXPECT_EQ("Hello World!", res->body);
  2161. EXPECT_EQ(StatusCode::OK_200, res->status);
  2162. }
  2163. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2164. Server svr;
  2165. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2166. res.set_content("Hello World!", "text/plain");
  2167. });
  2168. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2169. auto se = detail::scope_exit([&] {
  2170. svr.stop();
  2171. thread.join();
  2172. ASSERT_FALSE(svr.is_running());
  2173. });
  2174. svr.wait_until_ready();
  2175. Client cli(HOST, PORT);
  2176. cli.set_connection_timeout(std::chrono::seconds(5));
  2177. auto res =
  2178. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2179. "application/json", [](uint64_t, uint64_t) { return false; });
  2180. ASSERT_TRUE(!res);
  2181. EXPECT_EQ(Error::Canceled, res.error());
  2182. }
  2183. TEST(CancelTest, WithCancelLargePayloadPost) {
  2184. Server svr;
  2185. svr.set_payload_max_length(200 * 1024 * 1024);
  2186. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2187. res.set_content(LARGE_DATA, "text/plain");
  2188. });
  2189. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2190. auto se = detail::scope_exit([&] {
  2191. svr.stop();
  2192. thread.join();
  2193. ASSERT_FALSE(svr.is_running());
  2194. });
  2195. svr.wait_until_ready();
  2196. Client cli(HOST, PORT);
  2197. cli.set_payload_max_length(200 * 1024 * 1024);
  2198. cli.set_connection_timeout(std::chrono::seconds(5));
  2199. auto res =
  2200. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2201. "application/json", [](uint64_t, uint64_t) { return false; });
  2202. ASSERT_TRUE(!res);
  2203. EXPECT_EQ(Error::Canceled, res.error());
  2204. }
  2205. TEST(CancelTest, NoCancelPut) {
  2206. Server svr;
  2207. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2208. res.set_content("Hello World!", "text/plain");
  2209. });
  2210. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2211. auto se = detail::scope_exit([&] {
  2212. svr.stop();
  2213. thread.join();
  2214. ASSERT_FALSE(svr.is_running());
  2215. });
  2216. svr.wait_until_ready();
  2217. Client cli(HOST, PORT);
  2218. cli.set_connection_timeout(std::chrono::seconds(5));
  2219. auto res =
  2220. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2221. "application/json", [](uint64_t, uint64_t) { return true; });
  2222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2223. EXPECT_EQ("Hello World!", res->body);
  2224. EXPECT_EQ(StatusCode::OK_200, res->status);
  2225. }
  2226. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2227. Server svr;
  2228. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2229. res.set_content("Hello World!", "text/plain");
  2230. });
  2231. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2232. auto se = detail::scope_exit([&] {
  2233. svr.stop();
  2234. thread.join();
  2235. ASSERT_FALSE(svr.is_running());
  2236. });
  2237. svr.wait_until_ready();
  2238. Client cli(HOST, PORT);
  2239. cli.set_connection_timeout(std::chrono::seconds(5));
  2240. auto res =
  2241. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2242. "application/json", [](uint64_t, uint64_t) { return false; });
  2243. ASSERT_TRUE(!res);
  2244. EXPECT_EQ(Error::Canceled, res.error());
  2245. }
  2246. TEST(CancelTest, WithCancelLargePayloadPut) {
  2247. Server svr;
  2248. svr.set_payload_max_length(200 * 1024 * 1024);
  2249. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2250. res.set_content(LARGE_DATA, "text/plain");
  2251. });
  2252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2253. auto se = detail::scope_exit([&] {
  2254. svr.stop();
  2255. thread.join();
  2256. ASSERT_FALSE(svr.is_running());
  2257. });
  2258. svr.wait_until_ready();
  2259. Client cli(HOST, PORT);
  2260. cli.set_payload_max_length(200 * 1024 * 1024);
  2261. cli.set_connection_timeout(std::chrono::seconds(5));
  2262. auto res =
  2263. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2264. "application/json", [](uint64_t, uint64_t) { return false; });
  2265. ASSERT_TRUE(!res);
  2266. EXPECT_EQ(Error::Canceled, res.error());
  2267. }
  2268. TEST(CancelTest, NoCancelPatch) {
  2269. Server svr;
  2270. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2271. res.set_content("Hello World!", "text/plain");
  2272. });
  2273. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2274. auto se = detail::scope_exit([&] {
  2275. svr.stop();
  2276. thread.join();
  2277. ASSERT_FALSE(svr.is_running());
  2278. });
  2279. svr.wait_until_ready();
  2280. Client cli(HOST, PORT);
  2281. cli.set_connection_timeout(std::chrono::seconds(5));
  2282. auto res =
  2283. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2284. "application/json", [](uint64_t, uint64_t) { return true; });
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("Hello World!", res->body);
  2287. EXPECT_EQ(StatusCode::OK_200, res->status);
  2288. }
  2289. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2290. Server svr;
  2291. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2292. res.set_content("Hello World!", "text/plain");
  2293. });
  2294. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2295. auto se = detail::scope_exit([&] {
  2296. svr.stop();
  2297. thread.join();
  2298. ASSERT_FALSE(svr.is_running());
  2299. });
  2300. svr.wait_until_ready();
  2301. Client cli(HOST, PORT);
  2302. cli.set_connection_timeout(std::chrono::seconds(5));
  2303. auto res =
  2304. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2305. "application/json", [](uint64_t, uint64_t) { return false; });
  2306. ASSERT_TRUE(!res);
  2307. EXPECT_EQ(Error::Canceled, res.error());
  2308. }
  2309. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2310. Server svr;
  2311. svr.set_payload_max_length(200 * 1024 * 1024);
  2312. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2313. res.set_content(LARGE_DATA, "text/plain");
  2314. });
  2315. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2316. auto se = detail::scope_exit([&] {
  2317. svr.stop();
  2318. thread.join();
  2319. ASSERT_FALSE(svr.is_running());
  2320. });
  2321. svr.wait_until_ready();
  2322. Client cli(HOST, PORT);
  2323. cli.set_payload_max_length(200 * 1024 * 1024);
  2324. cli.set_connection_timeout(std::chrono::seconds(5));
  2325. auto res =
  2326. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2327. "application/json", [](uint64_t, uint64_t) { return false; });
  2328. ASSERT_TRUE(!res);
  2329. EXPECT_EQ(Error::Canceled, res.error());
  2330. }
  2331. TEST(CancelTest, NoCancelDelete) {
  2332. Server svr;
  2333. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2334. res.set_content("Hello World!", "text/plain");
  2335. });
  2336. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2337. auto se = detail::scope_exit([&] {
  2338. svr.stop();
  2339. thread.join();
  2340. ASSERT_FALSE(svr.is_running());
  2341. });
  2342. svr.wait_until_ready();
  2343. Client cli(HOST, PORT);
  2344. cli.set_connection_timeout(std::chrono::seconds(5));
  2345. auto res =
  2346. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2347. "application/json", [](uint64_t, uint64_t) { return true; });
  2348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2349. EXPECT_EQ("Hello World!", res->body);
  2350. EXPECT_EQ(StatusCode::OK_200, res->status);
  2351. }
  2352. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2353. Server svr;
  2354. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2355. res.set_content("Hello World!", "text/plain");
  2356. });
  2357. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2358. auto se = detail::scope_exit([&] {
  2359. svr.stop();
  2360. thread.join();
  2361. ASSERT_FALSE(svr.is_running());
  2362. });
  2363. svr.wait_until_ready();
  2364. Client cli(HOST, PORT);
  2365. cli.set_connection_timeout(std::chrono::seconds(5));
  2366. auto res =
  2367. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2368. "application/json", [](uint64_t, uint64_t) { return false; });
  2369. ASSERT_TRUE(!res);
  2370. EXPECT_EQ(Error::Canceled, res.error());
  2371. }
  2372. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2373. Server svr;
  2374. svr.set_payload_max_length(200 * 1024 * 1024);
  2375. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2376. res.set_content(LARGE_DATA, "text/plain");
  2377. });
  2378. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2379. auto se = detail::scope_exit([&] {
  2380. svr.stop();
  2381. thread.join();
  2382. ASSERT_FALSE(svr.is_running());
  2383. });
  2384. svr.wait_until_ready();
  2385. Client cli(HOST, PORT);
  2386. cli.set_payload_max_length(200 * 1024 * 1024);
  2387. cli.set_connection_timeout(std::chrono::seconds(5));
  2388. auto res =
  2389. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2390. "application/json", [](uint64_t, uint64_t) { return false; });
  2391. ASSERT_TRUE(!res);
  2392. EXPECT_EQ(Error::Canceled, res.error());
  2393. }
  2394. static std::string remove_whitespace(const std::string &input) {
  2395. std::string output;
  2396. output.reserve(input.size());
  2397. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2398. [](unsigned char c) { return !std::isspace(c); });
  2399. return output;
  2400. }
  2401. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2402. auto host = "httpbingo.org";
  2403. auto path = std::string{"/basic-auth/hello/world"};
  2404. #ifdef CPPHTTPLIB_SSL_ENABLED
  2405. auto port = 443;
  2406. SSLClient cli(host, port);
  2407. #else
  2408. auto port = 80;
  2409. Client cli(host, port);
  2410. #endif
  2411. {
  2412. auto res = cli.Get(path);
  2413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2414. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2415. }
  2416. {
  2417. auto res = cli.Get(
  2418. path, Headers{make_basic_authentication_header("hello", "world")});
  2419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2420. auto body = remove_whitespace(res->body);
  2421. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2422. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2423. EXPECT_EQ(StatusCode::OK_200, res->status);
  2424. }
  2425. {
  2426. cli.set_basic_auth("hello", "world");
  2427. auto res = cli.Get(path);
  2428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2429. auto body = remove_whitespace(res->body);
  2430. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2431. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2432. EXPECT_EQ(StatusCode::OK_200, res->status);
  2433. }
  2434. {
  2435. cli.set_basic_auth("hello", "bad");
  2436. auto res = cli.Get(path);
  2437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2438. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2439. }
  2440. {
  2441. cli.set_basic_auth("bad", "world");
  2442. auto res = cli.Get(path);
  2443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2444. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2445. }
  2446. }
  2447. #ifdef CPPHTTPLIB_SSL_ENABLED
  2448. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2449. auto host = "httpbingo.org";
  2450. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2451. auto paths = std::vector<std::string>{
  2452. "/digest-auth/auth/hello/world/MD5",
  2453. "/digest-auth/auth/hello/world/SHA-256",
  2454. };
  2455. auto port = 443;
  2456. SSLClient cli(host, port);
  2457. {
  2458. auto res = cli.Get(unauth_path);
  2459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2460. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2461. }
  2462. {
  2463. cli.set_digest_auth("hello", "world");
  2464. for (const auto &path : paths) {
  2465. auto res = cli.Get(path.c_str());
  2466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2467. auto body = remove_whitespace(res->body);
  2468. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2469. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2470. EXPECT_EQ(StatusCode::OK_200, res->status);
  2471. }
  2472. cli.set_digest_auth("hello", "bad");
  2473. for (const auto &path : paths) {
  2474. auto res = cli.Get(path.c_str());
  2475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2476. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2477. }
  2478. }
  2479. }
  2480. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2481. // comma-separated list of challenges, and each challenge may itself carry a
  2482. // comma-separated auth-param list, so a server can legally offer Basic
  2483. // before Digest, either as two field lines or packed into one. Runs one 401
  2484. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2485. // value() joins them in receipt order) and checks that the retry carries a
  2486. // well-formed Digest Authorization header naming expected_realm.
  2487. static void
  2488. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2489. const std::string &expected_realm) {
  2490. std::atomic<int> hits{0};
  2491. Server svr;
  2492. svr.Get("/x", [&](const Request &req, Response &res) {
  2493. if (++hits == 1) {
  2494. res.status = StatusCode::Unauthorized_401;
  2495. for (const auto &challenge : challenges) {
  2496. res.set_header("WWW-Authenticate", challenge);
  2497. }
  2498. } else {
  2499. auto authorization = req.get_header_value("Authorization");
  2500. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2501. EXPECT_NE(std::string::npos,
  2502. authorization.find("realm=\"" + expected_realm + "\""));
  2503. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2504. res.set_content("ok", "text/plain");
  2505. }
  2506. });
  2507. auto port = svr.bind_to_any_port(HOST);
  2508. std::thread t([&]() { svr.listen_after_bind(); });
  2509. auto se = detail::scope_exit([&] {
  2510. svr.stop();
  2511. t.join();
  2512. });
  2513. svr.wait_until_ready();
  2514. Client cli(HOST, port);
  2515. cli.set_digest_auth("hello", "world");
  2516. auto res = cli.Get("/x");
  2517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2518. EXPECT_EQ(2, hits.load());
  2519. }
  2520. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2521. static const char *kDigestChallenge =
  2522. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2523. "algorithm=MD5";
  2524. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2525. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2526. "testrealm");
  2527. }
  2528. // Same challenge list with the schemes in the opposite order, to make sure
  2529. // the fix above didn't just special-case "Basic first".
  2530. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2531. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2532. "testrealm");
  2533. }
  2534. // A comma inside a quoted auth-param value must not be mistaken for the
  2535. // separator between two challenges (or two auth-params).
  2536. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2537. run_digest_challenge_list_test(
  2538. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2539. "algorithm=MD5"},
  2540. "test,realm");
  2541. }
  2542. #endif
  2543. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2544. auto host = "google.com";
  2545. auto another_host = "example.com";
  2546. auto wrong_ip = "0.0.0.0";
  2547. #ifdef CPPHTTPLIB_SSL_ENABLED
  2548. SSLClient cli(host);
  2549. #else
  2550. Client cli(host);
  2551. #endif
  2552. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2553. auto res = cli.Get("/");
  2554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2555. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2556. }
  2557. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2558. auto host = "google.com";
  2559. auto wrong_ip = "0.0.0.0";
  2560. #ifdef CPPHTTPLIB_SSL_ENABLED
  2561. SSLClient cli(host);
  2562. #else
  2563. Client cli(host);
  2564. #endif
  2565. cli.set_hostname_addr_map({{host, wrong_ip}});
  2566. auto res = cli.Get("/");
  2567. ASSERT_TRUE(!res);
  2568. EXPECT_EQ(Error::Connection, res.error());
  2569. }
  2570. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2571. // A mapped value that is not an IP literal must be resolved. "localhost"
  2572. // resolves from the hosts file, so this test needs no external DNS.
  2573. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2574. auto host = "target.invalid";
  2575. Server svr;
  2576. std::string received_host;
  2577. svr.Get("/hi", [&](const Request &req, Response &res) {
  2578. received_host = req.get_header_value("Host");
  2579. res.set_content("Hello World!", "text/plain");
  2580. });
  2581. auto port = svr.bind_to_any_port(HOST);
  2582. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2583. auto se = detail::scope_exit([&] {
  2584. svr.stop();
  2585. thread.join();
  2586. ASSERT_FALSE(svr.is_running());
  2587. });
  2588. svr.wait_until_ready();
  2589. Client cli(host, port);
  2590. cli.set_hostname_addr_map({{host, HOST}});
  2591. auto res = cli.Get("/hi");
  2592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2593. EXPECT_EQ(StatusCode::OK_200, res->status);
  2594. // The mapping only redirects the connection; the identity stays host_.
  2595. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2596. }
  2597. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2598. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2599. auto host = "target.invalid";
  2600. Server svr;
  2601. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2602. res.set_content("Hello World!", "text/plain");
  2603. });
  2604. auto port = svr.bind_to_any_port("127.0.0.1");
  2605. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2606. auto se = detail::scope_exit([&] {
  2607. svr.stop();
  2608. thread.join();
  2609. ASSERT_FALSE(svr.is_running());
  2610. });
  2611. svr.wait_until_ready();
  2612. Client cli(host, port);
  2613. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2614. auto res = cli.Get("/hi");
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::OK_200, res->status);
  2617. }
  2618. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2619. // An empty mapped value must leave host_ as the connection target. Without
  2620. // that guard the empty value would become the host argument, getaddrinfo
  2621. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2622. // loopback - silently connecting somewhere the caller never asked for.
  2623. // The server listens on loopback, so such a fallback would succeed and is
  2624. // therefore observable as a failure of this test.
  2625. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2626. Server svr;
  2627. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2628. res.set_content("Hello World!", "text/plain");
  2629. });
  2630. auto port = svr.bind_to_any_port(HOST);
  2631. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2632. auto se = detail::scope_exit([&] {
  2633. svr.stop();
  2634. thread.join();
  2635. ASSERT_FALSE(svr.is_running());
  2636. });
  2637. svr.wait_until_ready();
  2638. Client cli(blackhole, port);
  2639. cli.set_hostname_addr_map({{blackhole, ""}});
  2640. cli.set_connection_timeout(1);
  2641. auto res = cli.Get("/hi");
  2642. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2643. }
  2644. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2645. auto host = "httpbingo.org";
  2646. auto path = std::string{"/absolute-redirect/3"};
  2647. #ifdef CPPHTTPLIB_SSL_ENABLED
  2648. SSLClient cli(host);
  2649. #else
  2650. Client cli(host);
  2651. #endif
  2652. cli.set_follow_location(true);
  2653. auto res = cli.Get(path);
  2654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. }
  2657. TEST(RedirectTest, Redirect_Online) {
  2658. auto host = "httpbingo.org";
  2659. auto path = std::string{"/redirect/3"};
  2660. #ifdef CPPHTTPLIB_SSL_ENABLED
  2661. SSLClient cli(host);
  2662. #else
  2663. Client cli(host);
  2664. #endif
  2665. cli.set_follow_location(true);
  2666. auto res = cli.Get(path);
  2667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2668. EXPECT_EQ(StatusCode::OK_200, res->status);
  2669. }
  2670. TEST(RelativeRedirectTest, Redirect_Online) {
  2671. auto host = "httpbingo.org";
  2672. auto path = std::string{"/relative-redirect/3"};
  2673. #ifdef CPPHTTPLIB_SSL_ENABLED
  2674. SSLClient cli(host);
  2675. #else
  2676. Client cli(host);
  2677. #endif
  2678. cli.set_follow_location(true);
  2679. auto res = cli.Get(path);
  2680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2681. EXPECT_EQ(StatusCode::OK_200, res->status);
  2682. }
  2683. TEST(TooManyRedirectTest, Redirect_Online) {
  2684. auto host = "httpbingo.org";
  2685. auto path = std::string{"/redirect/21"};
  2686. #ifdef CPPHTTPLIB_SSL_ENABLED
  2687. SSLClient cli(host);
  2688. #else
  2689. Client cli(host);
  2690. #endif
  2691. cli.set_follow_location(true);
  2692. auto res = cli.Get(path);
  2693. ASSERT_TRUE(!res);
  2694. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2695. }
  2696. #ifdef CPPHTTPLIB_SSL_ENABLED
  2697. TEST(YahooRedirectTest, Redirect_Online) {
  2698. Client cli("yahoo.com");
  2699. auto res = cli.Get("/");
  2700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2701. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2702. cli.set_follow_location(true);
  2703. res = cli.Get("/");
  2704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2705. EXPECT_EQ(StatusCode::OK_200, res->status);
  2706. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2707. }
  2708. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2709. #define REDIR_HOST "httpbingo.org"
  2710. #define REDIR_PATH "/redirect-to"
  2711. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2712. SSLClient cli(REDIR_HOST);
  2713. cli.set_follow_location(true);
  2714. auto res =
  2715. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2717. EXPECT_EQ(StatusCode::OK_200, res->status);
  2718. }
  2719. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2720. SSLClient cli(REDIR_HOST);
  2721. cli.set_follow_location(true);
  2722. Params params;
  2723. params.emplace("url", "http://example.com");
  2724. params.emplace("status_code", "302");
  2725. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2727. EXPECT_EQ(StatusCode::OK_200, res->status);
  2728. }
  2729. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2730. SSLClient cli(REDIR_HOST);
  2731. cli.set_follow_location(true);
  2732. Params params;
  2733. params.emplace("url", "http://example.com");
  2734. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2736. EXPECT_EQ(StatusCode::OK_200, res->status);
  2737. }
  2738. TEST(UrlWithSpace, Redirect_Online) {
  2739. SSLClient cli("edge.forgecdn.net");
  2740. cli.set_follow_location(true);
  2741. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2743. EXPECT_EQ(StatusCode::OK_200, res->status);
  2744. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2745. }
  2746. #endif
  2747. #if !defined(_WIN32) && !defined(_WIN64)
  2748. TEST(ReceiveSignals, Signal) {
  2749. auto setupSignalHandlers = []() {
  2750. struct sigaction act;
  2751. sigemptyset(&act.sa_mask);
  2752. act.sa_flags = SA_SIGINFO;
  2753. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2754. switch (sig) {
  2755. case SIGINT:
  2756. default: break;
  2757. }
  2758. };
  2759. ::sigaction(SIGINT, &act, nullptr);
  2760. };
  2761. Server svr;
  2762. int port = 0;
  2763. auto thread = std::thread([&]() {
  2764. setupSignalHandlers();
  2765. port = svr.bind_to_any_port(HOST);
  2766. svr.listen_after_bind();
  2767. });
  2768. auto se = detail::scope_exit([&] {
  2769. svr.stop();
  2770. thread.join();
  2771. ASSERT_FALSE(svr.is_running());
  2772. });
  2773. svr.wait_until_ready();
  2774. ASSERT_TRUE(svr.is_running());
  2775. pthread_kill(thread.native_handle(), SIGINT);
  2776. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2777. ASSERT_TRUE(svr.is_running());
  2778. }
  2779. #endif
  2780. TEST(RedirectToDifferentPort, Redirect) {
  2781. Server svr1;
  2782. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2783. res.set_content("Hello World!", "text/plain");
  2784. });
  2785. int svr1_port = 0;
  2786. auto thread1 = std::thread([&]() {
  2787. svr1_port = svr1.bind_to_any_port(HOST);
  2788. svr1.listen_after_bind();
  2789. });
  2790. Server svr2;
  2791. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2792. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2793. });
  2794. int svr2_port = 0;
  2795. auto thread2 = std::thread([&]() {
  2796. svr2_port = svr2.bind_to_any_port(HOST);
  2797. svr2.listen_after_bind();
  2798. });
  2799. auto se = detail::scope_exit([&] {
  2800. svr2.stop();
  2801. thread2.join();
  2802. svr1.stop();
  2803. thread1.join();
  2804. ASSERT_FALSE(svr2.is_running());
  2805. ASSERT_FALSE(svr1.is_running());
  2806. });
  2807. svr1.wait_until_ready();
  2808. svr2.wait_until_ready();
  2809. Client cli("localhost", svr2_port);
  2810. cli.set_follow_location(true);
  2811. auto res = cli.Get("/2");
  2812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2813. EXPECT_EQ(StatusCode::OK_200, res->status);
  2814. EXPECT_EQ("Hello World!", res->body);
  2815. }
  2816. static void
  2817. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2818. Server svr1;
  2819. std::string captured_authorization;
  2820. svr1.Get("/target", [&](const Request &req, Response &res) {
  2821. captured_authorization = req.get_header_value("Authorization");
  2822. res.set_content("OK", "text/plain");
  2823. });
  2824. int svr1_port = 0;
  2825. auto thread1 = std::thread([&]() {
  2826. svr1_port = svr1.bind_to_any_port(HOST);
  2827. svr1.listen_after_bind();
  2828. });
  2829. Server svr2;
  2830. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2831. res.set_redirect(
  2832. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2833. });
  2834. int svr2_port = 0;
  2835. auto thread2 = std::thread([&]() {
  2836. svr2_port = svr2.bind_to_any_port(HOST);
  2837. svr2.listen_after_bind();
  2838. });
  2839. auto se = detail::scope_exit([&] {
  2840. svr2.stop();
  2841. thread2.join();
  2842. svr1.stop();
  2843. thread1.join();
  2844. ASSERT_FALSE(svr2.is_running());
  2845. ASSERT_FALSE(svr1.is_running());
  2846. });
  2847. svr1.wait_until_ready();
  2848. svr2.wait_until_ready();
  2849. Client cli("localhost", svr2_port);
  2850. cli.set_follow_location(true);
  2851. set_auth(cli);
  2852. auto res = cli.Get("/redir");
  2853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2854. EXPECT_EQ(StatusCode::OK_200, res->status);
  2855. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2856. EXPECT_TRUE(captured_authorization.empty());
  2857. }
  2858. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2859. TestDoNotForwardCredentialsOnRedirect(
  2860. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2861. }
  2862. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2863. TestDoNotForwardCredentialsOnRedirect(
  2864. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2865. }
  2866. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2867. Server svr1;
  2868. std::string captured_cookie;
  2869. bool target_hit = false;
  2870. svr1.Get("/target", [&](const Request &req, Response &res) {
  2871. captured_cookie = req.get_header_value("Cookie");
  2872. target_hit = true;
  2873. res.set_content("OK", "text/plain");
  2874. });
  2875. int svr1_port = 0;
  2876. auto thread1 = std::thread([&]() {
  2877. svr1_port = svr1.bind_to_any_port(HOST);
  2878. svr1.listen_after_bind();
  2879. });
  2880. Server svr2;
  2881. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2882. res.set_redirect(
  2883. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2884. });
  2885. int svr2_port = 0;
  2886. auto thread2 = std::thread([&]() {
  2887. svr2_port = svr2.bind_to_any_port(HOST);
  2888. svr2.listen_after_bind();
  2889. });
  2890. auto se = detail::scope_exit([&] {
  2891. svr2.stop();
  2892. thread2.join();
  2893. svr1.stop();
  2894. thread1.join();
  2895. ASSERT_FALSE(svr2.is_running());
  2896. ASSERT_FALSE(svr1.is_running());
  2897. });
  2898. svr1.wait_until_ready();
  2899. svr2.wait_until_ready();
  2900. Client cli("localhost", svr2_port);
  2901. cli.set_follow_location(true);
  2902. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2903. auto res = cli.Get("/redir", headers);
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::OK_200, res->status);
  2906. EXPECT_TRUE(target_hit);
  2907. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2908. EXPECT_TRUE(captured_cookie.empty());
  2909. }
  2910. TEST(RedirectToSamePort, ForwardCookie) {
  2911. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2912. // header so that ordinary session flows keep working.
  2913. Server svr;
  2914. std::string captured_cookie;
  2915. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2916. res.set_redirect("/target", 302);
  2917. });
  2918. svr.Get("/target", [&](const Request &req, Response &res) {
  2919. captured_cookie = req.get_header_value("Cookie");
  2920. res.set_content("OK", "text/plain");
  2921. });
  2922. auto port = svr.bind_to_any_port(HOST);
  2923. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2924. auto se = detail::scope_exit([&] {
  2925. svr.stop();
  2926. thread.join();
  2927. ASSERT_FALSE(svr.is_running());
  2928. });
  2929. svr.wait_until_ready();
  2930. Client cli(HOST, port);
  2931. cli.set_follow_location(true);
  2932. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2933. auto res = cli.Get("/redir", headers);
  2934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2935. EXPECT_EQ(StatusCode::OK_200, res->status);
  2936. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2937. }
  2938. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2939. Server svr;
  2940. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2941. // Port number that overflows int — should not crash
  2942. res.set_redirect("http://localhost:99999999999999999999/target");
  2943. });
  2944. auto port = svr.bind_to_any_port(HOST);
  2945. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2946. auto se = detail::scope_exit([&] {
  2947. svr.stop();
  2948. thread.join();
  2949. ASSERT_FALSE(svr.is_running());
  2950. });
  2951. svr.wait_until_ready();
  2952. Client cli(HOST, port);
  2953. cli.set_follow_location(true);
  2954. auto res = cli.Get("/redir");
  2955. // Should fail gracefully, not crash (no valid response due to bad port)
  2956. EXPECT_FALSE(res);
  2957. }
  2958. TEST(RedirectFromPageWithContent, Redirect) {
  2959. Server svr;
  2960. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2961. res.set_content("___", "text/plain");
  2962. res.set_redirect("/2");
  2963. });
  2964. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2965. res.set_content("Hello World!", "text/plain");
  2966. });
  2967. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2968. auto se = detail::scope_exit([&] {
  2969. svr.stop();
  2970. th.join();
  2971. ASSERT_FALSE(svr.is_running());
  2972. });
  2973. svr.wait_until_ready();
  2974. {
  2975. Client cli("localhost", PORT);
  2976. cli.set_follow_location(true);
  2977. std::string body;
  2978. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2979. body.append(data, data_length);
  2980. return true;
  2981. });
  2982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2983. EXPECT_EQ(StatusCode::OK_200, res->status);
  2984. EXPECT_EQ("Hello World!", body);
  2985. }
  2986. {
  2987. Client cli("localhost", PORT);
  2988. std::string body;
  2989. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2990. body.append(data, data_length);
  2991. return true;
  2992. });
  2993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2994. EXPECT_EQ(StatusCode::Found_302, res->status);
  2995. EXPECT_EQ("___", body);
  2996. }
  2997. }
  2998. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2999. Server svr;
  3000. auto port_str = std::to_string(PORT);
  3001. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3002. auto expected_host = "[::1]:" + port_str;
  3003. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3004. res.set_content("___", "text/plain");
  3005. // res.set_redirect("/2");
  3006. res.set_redirect(redirect_url);
  3007. });
  3008. svr.Get("/2", [&](const Request &req, Response &res) {
  3009. auto host_header = req.headers.find("Host");
  3010. ASSERT_TRUE(host_header != req.headers.end());
  3011. EXPECT_EQ(expected_host, host_header->second);
  3012. res.set_content("Hello World!", "text/plain");
  3013. });
  3014. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3015. auto se = detail::scope_exit([&] {
  3016. svr.stop();
  3017. th.join();
  3018. ASSERT_FALSE(svr.is_running());
  3019. });
  3020. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3021. // actually starts anything, so the condition !svr.is_running() will
  3022. // always remain true, and the loop never stops.
  3023. // This basically counts how many milliseconds have passed since the
  3024. // call to svr.listen(), and if after 5 seconds nothing started yet
  3025. // aborts the test.
  3026. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3027. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3028. ASSERT_LT(milliseconds, 5000U);
  3029. }
  3030. {
  3031. Client cli("::1", PORT);
  3032. cli.set_follow_location(true);
  3033. std::string body;
  3034. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3035. body.append(data, data_length);
  3036. return true;
  3037. });
  3038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3039. EXPECT_EQ(StatusCode::OK_200, res->status);
  3040. EXPECT_EQ("Hello World!", body);
  3041. }
  3042. {
  3043. Client cli("::1", PORT);
  3044. std::string body;
  3045. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3046. body.append(data, data_length);
  3047. return true;
  3048. });
  3049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3050. EXPECT_EQ(StatusCode::Found_302, res->status);
  3051. EXPECT_EQ("___", body);
  3052. }
  3053. }
  3054. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3055. Server svr;
  3056. svr.Get("/foo", [](const Request &req, Response &res) {
  3057. auto a = req.params.find("a");
  3058. if (a != req.params.end()) {
  3059. res.set_content((*a).second, "text/plain");
  3060. res.status = StatusCode::OK_200;
  3061. } else {
  3062. res.status = StatusCode::BadRequest_400;
  3063. }
  3064. });
  3065. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3066. auto se = detail::scope_exit([&] {
  3067. svr.stop();
  3068. thread.join();
  3069. ASSERT_FALSE(svr.is_running());
  3070. });
  3071. svr.wait_until_ready();
  3072. {
  3073. Client cli(HOST, PORT);
  3074. cli.set_path_encode(false);
  3075. auto res = cli.Get("/foo?a=explicitly+encoded");
  3076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3077. EXPECT_EQ(StatusCode::OK_200, res->status);
  3078. // This expects it back with a space, as the `+` won't have been
  3079. // url-encoded, and server-side the params get decoded turning `+`
  3080. // into spaces.
  3081. EXPECT_EQ("explicitly encoded", res->body);
  3082. }
  3083. }
  3084. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3085. // When path encoding is disabled the client must transmit the supplied
  3086. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3087. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3088. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3089. // than a space (0x20). Assert on the raw wire target to catch this.
  3090. Server svr;
  3091. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3092. svr.Get("/foo", [&](const Request &req, Response &res) {
  3093. EXPECT_EQ(expected_target, req.target);
  3094. res.status = StatusCode::OK_200;
  3095. });
  3096. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3097. auto se = detail::scope_exit([&] {
  3098. svr.stop();
  3099. thread.join();
  3100. ASSERT_FALSE(svr.is_running());
  3101. });
  3102. svr.wait_until_ready();
  3103. {
  3104. Client cli(HOST, PORT);
  3105. cli.set_path_encode(false);
  3106. auto res = cli.Get(expected_target.c_str());
  3107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3108. EXPECT_EQ(StatusCode::OK_200, res->status);
  3109. }
  3110. }
  3111. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3112. // `open_stream()` used to skip the path encoding that the buffered send
  3113. // path applies, so the same `path` produced different bytes in the request
  3114. // line depending on which API was used. Assert the two agree.
  3115. Server svr;
  3116. std::string target;
  3117. svr.Get(".*", [&](const Request &req, Response &res) {
  3118. target = req.target;
  3119. res.status = StatusCode::OK_200;
  3120. });
  3121. auto port = svr.bind_to_any_port(HOST);
  3122. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3123. auto se = detail::scope_exit([&] {
  3124. svr.stop();
  3125. thread.join();
  3126. ASSERT_FALSE(svr.is_running());
  3127. });
  3128. svr.wait_until_ready();
  3129. struct {
  3130. const char *path;
  3131. const char *expected;
  3132. } cases[] = {
  3133. {"/a b?x=1", "/a%20b?x=1"},
  3134. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3135. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3136. };
  3137. for (const auto &c : cases) {
  3138. Client cli(HOST, port);
  3139. target.clear();
  3140. auto res = cli.Get(c.path);
  3141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3142. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3143. auto buffered_target = target;
  3144. target.clear();
  3145. auto handle = cli.open_stream("GET", c.path);
  3146. EXPECT_TRUE(handle.is_valid())
  3147. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3148. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3149. }
  3150. }
  3151. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3152. // The `set_path_encode(false)` contract — transmit the supplied target
  3153. // verbatim — must hold for the streaming API too.
  3154. Server svr;
  3155. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3156. std::string target;
  3157. svr.Get("/foo", [&](const Request &req, Response &res) {
  3158. target = req.target;
  3159. res.status = StatusCode::OK_200;
  3160. });
  3161. auto port = svr.bind_to_any_port(HOST);
  3162. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3163. auto se = detail::scope_exit([&] {
  3164. svr.stop();
  3165. thread.join();
  3166. ASSERT_FALSE(svr.is_running());
  3167. });
  3168. svr.wait_until_ready();
  3169. {
  3170. Client cli(HOST, port);
  3171. cli.set_path_encode(false);
  3172. auto handle = cli.open_stream("GET", expected_target);
  3173. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3174. EXPECT_EQ(expected_target, target);
  3175. }
  3176. }
  3177. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3178. // With path encoding enabled a CR/LF in the target is percent-encoded
  3179. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3180. // write_request_line still backstops `set_path_encode(false)`, which is
  3181. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3182. Server svr;
  3183. // Captured before routing: the decoded path contains a newline, which a
  3184. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3185. std::string target;
  3186. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3187. target = req.target;
  3188. res.status = StatusCode::OK_200;
  3189. return Server::HandlerResponse::Handled;
  3190. });
  3191. auto port = svr.bind_to_any_port(HOST);
  3192. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3193. auto se = detail::scope_exit([&] {
  3194. svr.stop();
  3195. thread.join();
  3196. ASSERT_FALSE(svr.is_running());
  3197. });
  3198. svr.wait_until_ready();
  3199. {
  3200. Client cli(HOST, port);
  3201. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3202. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3203. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3204. }
  3205. }
  3206. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3207. // Nothing may reach the wire: a raw CR/LF target would split the request
  3208. // line and inject headers.
  3209. Server svr;
  3210. // Pre-routing so that "not called" means nothing reached the server at all,
  3211. // rather than merely failing to match a handler pattern.
  3212. auto handler_called = false;
  3213. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3214. handler_called = true;
  3215. res.status = StatusCode::OK_200;
  3216. return Server::HandlerResponse::Handled;
  3217. });
  3218. auto port = svr.bind_to_any_port(HOST);
  3219. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3220. auto se = detail::scope_exit([&] {
  3221. svr.stop();
  3222. thread.join();
  3223. ASSERT_FALSE(svr.is_running());
  3224. });
  3225. svr.wait_until_ready();
  3226. {
  3227. Client cli(HOST, port);
  3228. cli.set_path_encode(false);
  3229. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3230. EXPECT_FALSE(handle.is_valid());
  3231. EXPECT_EQ(Error::Write, handle.error);
  3232. EXPECT_FALSE(handler_called);
  3233. }
  3234. }
  3235. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3236. // Which of the two branches runs is decided by whether the query component
  3237. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3238. // an empty query and must still fall back to building one from
  3239. // `req.params`, while a non-empty query must win over `req.params`.
  3240. Server svr;
  3241. std::string target;
  3242. svr.Get("/foo", [&](const Request &req, Response &res) {
  3243. target = req.target;
  3244. res.status = StatusCode::OK_200;
  3245. });
  3246. auto port = svr.bind_to_any_port(HOST);
  3247. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3248. auto se = detail::scope_exit([&] {
  3249. svr.stop();
  3250. thread.join();
  3251. ASSERT_FALSE(svr.is_running());
  3252. });
  3253. svr.wait_until_ready();
  3254. {
  3255. // Trailing `?` -> empty query component -> `req.params` is used.
  3256. Client cli(HOST, port);
  3257. Request req;
  3258. req.method = "GET";
  3259. req.path = "/foo?";
  3260. req.params.emplace("a", "1");
  3261. target.clear();
  3262. auto res = cli.send(req);
  3263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3264. EXPECT_EQ("/foo?a=1", target);
  3265. }
  3266. {
  3267. // Non-empty query in `req.path` -> `req.params` is not appended.
  3268. Client cli(HOST, port);
  3269. Request req;
  3270. req.method = "GET";
  3271. req.path = "/foo?b=2";
  3272. req.params.emplace("a", "1");
  3273. target.clear();
  3274. auto res = cli.send(req);
  3275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3276. EXPECT_EQ("/foo?b=2", target);
  3277. }
  3278. }
  3279. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3280. Server svr;
  3281. svr.Get("/", [](const Request &req, Response &) {
  3282. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3283. });
  3284. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3285. auto se = detail::scope_exit([&] {
  3286. svr.stop();
  3287. thread.join();
  3288. ASSERT_FALSE(svr.is_running());
  3289. });
  3290. svr.wait_until_ready();
  3291. {
  3292. Client cli(HOST, PORT);
  3293. cli.set_path_encode(false);
  3294. auto res = cli.Get("/?something=%0A");
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. }
  3298. }
  3299. TEST(BindServerTest, BindDualStack) {
  3300. Server svr;
  3301. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3302. res.set_content("Hello World!", "text/plain");
  3303. });
  3304. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3305. auto se = detail::scope_exit([&] {
  3306. svr.stop();
  3307. thread.join();
  3308. ASSERT_FALSE(svr.is_running());
  3309. });
  3310. svr.wait_until_ready();
  3311. {
  3312. Client cli("127.0.0.1", PORT);
  3313. auto res = cli.Get("/1");
  3314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3315. EXPECT_EQ(StatusCode::OK_200, res->status);
  3316. EXPECT_EQ("Hello World!", res->body);
  3317. }
  3318. {
  3319. Client cli("::1", PORT);
  3320. auto res = cli.Get("/1");
  3321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3322. EXPECT_EQ(StatusCode::OK_200, res->status);
  3323. EXPECT_EQ("Hello World!", res->body);
  3324. }
  3325. }
  3326. TEST(BindServerTest, BindAndListenSeparately) {
  3327. Server svr;
  3328. int port = svr.bind_to_any_port("0.0.0.0");
  3329. ASSERT_TRUE(svr.is_valid());
  3330. ASSERT_TRUE(port > 0);
  3331. svr.stop();
  3332. }
  3333. // Reports whether anything is still listening on a loopback port. A plain
  3334. // connect() is used instead of a Client request because a socket left bound by
  3335. // mistake accepts the connection into its backlog and never answers, which
  3336. // would hang the test instead of failing it.
  3337. static bool is_loopback_port_accepting(int port) {
  3338. sockaddr_in addr{};
  3339. addr.sin_family = AF_INET;
  3340. addr.sin_port = htons(static_cast<uint16_t>(port));
  3341. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3342. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3343. EXPECT_NE(sock, INVALID_SOCKET);
  3344. if (sock == INVALID_SOCKET) { return false; }
  3345. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3346. static_cast<socklen_t>(sizeof(addr)));
  3347. detail::close_socket(sock);
  3348. return ret == 0;
  3349. }
  3350. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3351. Server svr;
  3352. auto port = svr.bind_to_any_port("127.0.0.1");
  3353. ASSERT_TRUE(port > 0);
  3354. svr.stop();
  3355. // bind_to_any_port() already called listen(2), so until stop() closed the
  3356. // descriptor the port kept accepting connections into the backlog. ASSERT
  3357. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3358. // below blocks forever in the accept loop.
  3359. ASSERT_FALSE(is_loopback_port_accepting(port));
  3360. // Nothing is left to accept on, so listen_after_bind() must report failure
  3361. // instead of returning success without ever serving.
  3362. EXPECT_FALSE(svr.listen_after_bind());
  3363. // The failed listen marks the server decommissioned, so a waiter returns
  3364. // instead of spinning forever.
  3365. svr.wait_until_ready();
  3366. }
  3367. #ifdef CPPHTTPLIB_SSL_ENABLED
  3368. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3370. CLIENT_CA_CERT_DIR);
  3371. int port = svr.bind_to_any_port("0.0.0.0");
  3372. ASSERT_TRUE(svr.is_valid());
  3373. ASSERT_TRUE(port > 0);
  3374. svr.stop();
  3375. }
  3376. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3377. // or a rejected CustomRoute() registration would not stop the server binding.
  3378. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3380. CLIENT_CA_CERT_DIR);
  3381. ASSERT_TRUE(svr.is_valid());
  3382. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3383. EXPECT_FALSE(svr.is_valid());
  3384. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3385. }
  3386. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3387. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3388. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3389. int port = svr.bind_to_any_port("0.0.0.0");
  3390. ASSERT_TRUE(svr.is_valid());
  3391. ASSERT_TRUE(port > 0);
  3392. svr.stop();
  3393. }
  3394. TEST(BindServerTest, UpdateCertsPem) {
  3395. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3396. int port = svr.bind_to_any_port("0.0.0.0");
  3397. ASSERT_TRUE(svr.is_valid());
  3398. ASSERT_TRUE(port > 0);
  3399. // Read PEM files
  3400. std::string cert_pem, key_pem, ca_pem;
  3401. read_file(SERVER_CERT_FILE, cert_pem);
  3402. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3403. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3404. // Update server certificates using PEM API
  3405. ASSERT_TRUE(
  3406. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3407. ASSERT_TRUE(svr.is_valid());
  3408. svr.stop();
  3409. }
  3410. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3411. // Start server with client CA (enables client auth)
  3412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3413. ASSERT_TRUE(svr.is_valid());
  3414. bool handler_called = false;
  3415. svr.Get("/test", [&](const Request &req, Response &res) {
  3416. handler_called = true;
  3417. // Verify client certificate is present
  3418. auto cert = req.peer_cert();
  3419. EXPECT_TRUE(static_cast<bool>(cert));
  3420. res.set_content("ok", "text/plain");
  3421. });
  3422. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3423. auto se = detail::scope_exit([&] {
  3424. svr.stop();
  3425. t.join();
  3426. ASSERT_FALSE(svr.is_running());
  3427. });
  3428. svr.wait_until_ready();
  3429. // Read PEM files
  3430. std::string cert_pem, key_pem, ca_pem;
  3431. read_file(SERVER_CERT_FILE, cert_pem);
  3432. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3433. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3434. // Update server certificates and client CA using PEM API while server running
  3435. ASSERT_TRUE(
  3436. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3437. // Connect with client certificate
  3438. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3439. cli.enable_server_certificate_verification(false);
  3440. cli.set_connection_timeout(30);
  3441. auto res = cli.Get("/test");
  3442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3443. ASSERT_EQ(StatusCode::OK_200, res->status);
  3444. ASSERT_TRUE(handler_called);
  3445. EXPECT_EQ("ok", res->body);
  3446. }
  3447. #endif
  3448. TEST(ErrorHandlerTest, ContentLength) {
  3449. Server svr;
  3450. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3451. res.status = StatusCode::OK_200;
  3452. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3453. "text/html"); // <= Content-Length still 13
  3454. });
  3455. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3456. res.set_content("Hello World!\n", "text/plain");
  3457. res.status = 524;
  3458. });
  3459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3460. auto se = detail::scope_exit([&] {
  3461. svr.stop();
  3462. thread.join();
  3463. ASSERT_FALSE(svr.is_running());
  3464. });
  3465. svr.wait_until_ready();
  3466. {
  3467. Client cli(HOST, PORT);
  3468. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3470. EXPECT_EQ(StatusCode::OK_200, res->status);
  3471. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3472. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3473. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3474. }
  3475. }
  3476. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3477. TEST(ExceptionTest, WithoutExceptionHandler) {
  3478. Server svr;
  3479. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3480. throw std::runtime_error("exception...");
  3481. });
  3482. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3483. throw std::runtime_error("exception\r\n...");
  3484. });
  3485. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3486. auto se = detail::scope_exit([&] {
  3487. svr.stop();
  3488. listen_thread.join();
  3489. ASSERT_FALSE(svr.is_running());
  3490. });
  3491. svr.wait_until_ready();
  3492. Client cli("localhost", PORT);
  3493. {
  3494. auto res = cli.Get("/exception");
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3497. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3498. }
  3499. {
  3500. auto res = cli.Get("/unknown");
  3501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3502. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3503. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3504. }
  3505. }
  3506. TEST(ExceptionTest, WithExceptionHandler) {
  3507. Server svr;
  3508. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3509. std::exception_ptr ep) {
  3510. EXPECT_FALSE(ep == nullptr);
  3511. try {
  3512. std::rethrow_exception(ep);
  3513. } catch (std::exception &e) {
  3514. EXPECT_EQ("abc", std::string(e.what()));
  3515. } catch (...) {}
  3516. res.status = StatusCode::InternalServerError_500;
  3517. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3518. "text/html"); // <= Content-Length still 13 at this point
  3519. });
  3520. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3521. res.set_content("Hello World!\n", "text/plain");
  3522. throw std::runtime_error("abc");
  3523. });
  3524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3525. auto se = detail::scope_exit([&] {
  3526. svr.stop();
  3527. thread.join();
  3528. ASSERT_FALSE(svr.is_running());
  3529. });
  3530. svr.wait_until_ready();
  3531. for (size_t i = 0; i < 10; i++) {
  3532. Client cli(HOST, PORT);
  3533. for (size_t j = 0; j < 100; j++) {
  3534. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3536. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3537. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3538. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3539. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3540. }
  3541. cli.set_keep_alive(true);
  3542. for (size_t j = 0; j < 100; j++) {
  3543. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3545. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3546. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3547. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3548. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3549. }
  3550. }
  3551. }
  3552. TEST(ExceptionTest, AndErrorHandler) {
  3553. Server svr;
  3554. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3555. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3556. });
  3557. svr.set_exception_handler(
  3558. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3559. EXPECT_FALSE(ep == nullptr);
  3560. try {
  3561. std::rethrow_exception(ep);
  3562. } catch (std::exception &e) {
  3563. res.set_content(e.what(), "text/html");
  3564. } catch (...) {}
  3565. res.status = StatusCode::InternalServerError_500;
  3566. });
  3567. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3568. throw std::runtime_error("EXCEPTION");
  3569. });
  3570. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3571. res.set_content("ERROR", "text/html");
  3572. res.status = StatusCode::InternalServerError_500;
  3573. });
  3574. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3575. auto se = detail::scope_exit([&] {
  3576. svr.stop();
  3577. thread.join();
  3578. ASSERT_FALSE(svr.is_running());
  3579. });
  3580. svr.wait_until_ready();
  3581. Client cli(HOST, PORT);
  3582. {
  3583. auto res = cli.Get("/exception");
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3586. EXPECT_EQ("EXCEPTION", res->body);
  3587. }
  3588. {
  3589. auto res = cli.Get("/error");
  3590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3591. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3592. EXPECT_EQ("ERROR", res->body);
  3593. }
  3594. {
  3595. auto res = cli.Get("/invalid");
  3596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3597. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3598. EXPECT_EQ("NOT_FOUND", res->body);
  3599. }
  3600. }
  3601. #endif
  3602. TEST(NoContentTest, ContentLength) {
  3603. Server svr;
  3604. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3605. res.status = StatusCode::NoContent_204;
  3606. });
  3607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3608. auto se = detail::scope_exit([&] {
  3609. svr.stop();
  3610. thread.join();
  3611. ASSERT_FALSE(svr.is_running());
  3612. });
  3613. svr.wait_until_ready();
  3614. {
  3615. Client cli(HOST, PORT);
  3616. auto res = cli.Get("/hi");
  3617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3618. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3619. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3620. }
  3621. }
  3622. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3623. #ifdef CPPHTTPLIB_SSL_ENABLED
  3624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3625. ASSERT_TRUE(svr.is_valid());
  3626. #else
  3627. Server svr;
  3628. #endif
  3629. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3630. if (req.path == "/routing_handler") {
  3631. res.set_header("PRE_ROUTING", "on");
  3632. res.set_content("Routing Handler", "text/plain");
  3633. return httplib::Server::HandlerResponse::Handled;
  3634. }
  3635. return httplib::Server::HandlerResponse::Unhandled;
  3636. });
  3637. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3638. res.set_content("Error", "text/html");
  3639. });
  3640. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3641. if (req.path == "/routing_handler") {
  3642. res.set_header("POST_ROUTING", "on");
  3643. }
  3644. });
  3645. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3646. res.set_content("Hello World!\n", "text/plain");
  3647. });
  3648. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3649. auto se = detail::scope_exit([&] {
  3650. svr.stop();
  3651. thread.join();
  3652. ASSERT_FALSE(svr.is_running());
  3653. });
  3654. svr.wait_until_ready();
  3655. {
  3656. #ifdef CPPHTTPLIB_SSL_ENABLED
  3657. SSLClient cli(HOST, PORT);
  3658. cli.enable_server_certificate_verification(false);
  3659. #else
  3660. Client cli(HOST, PORT);
  3661. #endif
  3662. auto res = cli.Get("/routing_handler");
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::OK_200, res->status);
  3665. EXPECT_EQ("Routing Handler", res->body);
  3666. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3667. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3668. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3669. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3670. }
  3671. {
  3672. #ifdef CPPHTTPLIB_SSL_ENABLED
  3673. SSLClient cli(HOST, PORT);
  3674. cli.enable_server_certificate_verification(false);
  3675. #else
  3676. Client cli(HOST, PORT);
  3677. #endif
  3678. auto res = cli.Get("/hi");
  3679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3680. EXPECT_EQ(StatusCode::OK_200, res->status);
  3681. EXPECT_EQ("Hello World!\n", res->body);
  3682. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3683. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3684. }
  3685. {
  3686. #ifdef CPPHTTPLIB_SSL_ENABLED
  3687. SSLClient cli(HOST, PORT);
  3688. cli.enable_server_certificate_verification(false);
  3689. #else
  3690. Client cli(HOST, PORT);
  3691. #endif
  3692. auto res = cli.Get("/aaa");
  3693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3694. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3695. EXPECT_EQ("Error", res->body);
  3696. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3697. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3698. }
  3699. }
  3700. TEST(RequestHandlerTest, PreRequestHandler) {
  3701. auto route_path = "/user/:user";
  3702. Server svr;
  3703. svr.Get("/hi", [](const Request &, Response &res) {
  3704. res.set_content("hi", "text/plain");
  3705. });
  3706. svr.Get(route_path, [](const Request &req, Response &res) {
  3707. res.set_content(req.path_params.at("user"), "text/plain");
  3708. });
  3709. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3710. if (req.matched_route == route_path) {
  3711. auto user = req.path_params.at("user");
  3712. if (user != "john") {
  3713. res.status = StatusCode::Forbidden_403;
  3714. res.set_content("error", "text/html");
  3715. return Server::HandlerResponse::Handled;
  3716. }
  3717. }
  3718. return Server::HandlerResponse::Unhandled;
  3719. });
  3720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3721. auto se = detail::scope_exit([&] {
  3722. svr.stop();
  3723. thread.join();
  3724. ASSERT_FALSE(svr.is_running());
  3725. });
  3726. svr.wait_until_ready();
  3727. Client cli(HOST, PORT);
  3728. {
  3729. auto res = cli.Get("/hi");
  3730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3731. EXPECT_EQ(StatusCode::OK_200, res->status);
  3732. EXPECT_EQ("hi", res->body);
  3733. }
  3734. {
  3735. auto res = cli.Get("/user/john");
  3736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3737. EXPECT_EQ(StatusCode::OK_200, res->status);
  3738. EXPECT_EQ("john", res->body);
  3739. }
  3740. {
  3741. auto res = cli.Get("/user/invalid-user");
  3742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3743. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3744. EXPECT_EQ("error", res->body);
  3745. }
  3746. }
  3747. // The pre-request handler must run before the request body is read, so a
  3748. // rejected request never forces the server to buffer a (potentially large)
  3749. // body. Here the posted body is larger than the payload limit: if the body
  3750. // were read first the server would answer 413, but because the pre-request
  3751. // handler runs first it answers 403 and the body is never read.
  3752. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3753. Server svr;
  3754. svr.set_payload_max_length(8);
  3755. auto handler_ran = false;
  3756. svr.Post("/reject", [&](const Request &req, Response &res) {
  3757. handler_ran = true;
  3758. res.set_content(req.body, "text/plain");
  3759. });
  3760. svr.Post("/accept", [](const Request &req, Response &res) {
  3761. res.set_content(req.body, "text/plain");
  3762. });
  3763. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3764. if (req.matched_route == "/reject") {
  3765. res.status = StatusCode::Forbidden_403;
  3766. res.set_content("denied", "text/plain");
  3767. return Server::HandlerResponse::Handled;
  3768. }
  3769. return Server::HandlerResponse::Unhandled;
  3770. });
  3771. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3772. auto se = detail::scope_exit([&] {
  3773. svr.stop();
  3774. thread.join();
  3775. ASSERT_FALSE(svr.is_running());
  3776. });
  3777. svr.wait_until_ready();
  3778. Client cli(HOST, PORT);
  3779. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3780. // rejects with 403 before the body is read, so 413 is never reached.
  3781. {
  3782. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3784. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3785. EXPECT_EQ("denied", res->body);
  3786. EXPECT_FALSE(handler_ran);
  3787. }
  3788. // An approved route still reads the body and enforces the payload limit.
  3789. {
  3790. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3792. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3793. }
  3794. }
  3795. TEST(UserDataTest, BasicOperations) {
  3796. httplib::UserData ud;
  3797. // Initially empty
  3798. EXPECT_FALSE(ud.has("key"));
  3799. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3800. // set and get
  3801. ud.set("key", 42);
  3802. EXPECT_TRUE(ud.has("key"));
  3803. auto *p = ud.get<int>("key");
  3804. ASSERT_NE(nullptr, p);
  3805. EXPECT_EQ(42, *p);
  3806. // Type mismatch → nullptr
  3807. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3808. // Overwrite with different type
  3809. ud.set("key", std::string("hello"));
  3810. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3811. auto *s = ud.get<std::string>("key");
  3812. ASSERT_NE(nullptr, s);
  3813. EXPECT_EQ("hello", *s);
  3814. // erase
  3815. ud.erase("key");
  3816. EXPECT_FALSE(ud.has("key"));
  3817. // clear
  3818. ud.set("a", 1);
  3819. ud.set("b", 2);
  3820. ud.clear();
  3821. EXPECT_FALSE(ud.has("a"));
  3822. EXPECT_FALSE(ud.has("b"));
  3823. }
  3824. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3825. struct AuthCtx {
  3826. std::string user_id;
  3827. };
  3828. Server svr;
  3829. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3830. res.user_data.set("auth", AuthCtx{"alice"});
  3831. return Server::HandlerResponse::Unhandled;
  3832. });
  3833. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3834. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3835. ASSERT_NE(nullptr, ctx);
  3836. res.set_content("Hello " + ctx->user_id, "text/plain");
  3837. });
  3838. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3839. auto se = detail::scope_exit([&] {
  3840. svr.stop();
  3841. thread.join();
  3842. ASSERT_FALSE(svr.is_running());
  3843. });
  3844. svr.wait_until_ready();
  3845. Client cli(HOST, PORT);
  3846. auto res = cli.Get("/me");
  3847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3848. EXPECT_EQ(StatusCode::OK_200, res->status);
  3849. EXPECT_EQ("Hello alice", res->body);
  3850. }
  3851. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3852. struct RoleCtx {
  3853. std::string role;
  3854. };
  3855. Server svr;
  3856. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3857. res.user_data.set("role", RoleCtx{"admin"});
  3858. return Server::HandlerResponse::Unhandled;
  3859. });
  3860. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3861. auto *ctx = res.user_data.get<RoleCtx>("role");
  3862. ASSERT_NE(nullptr, ctx);
  3863. res.set_content(ctx->role, "text/plain");
  3864. });
  3865. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3866. auto se = detail::scope_exit([&] {
  3867. svr.stop();
  3868. thread.join();
  3869. ASSERT_FALSE(svr.is_running());
  3870. });
  3871. svr.wait_until_ready();
  3872. Client cli(HOST, PORT);
  3873. auto res = cli.Get("/role");
  3874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3875. EXPECT_EQ(StatusCode::OK_200, res->status);
  3876. EXPECT_EQ("admin", res->body);
  3877. }
  3878. TEST(InvalidFormatTest, StatusCode) {
  3879. Server svr;
  3880. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3881. res.set_content("Hello World!\n", "text/plain");
  3882. res.status = 9999; // Status should be a three-digit code...
  3883. });
  3884. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3885. auto se = detail::scope_exit([&] {
  3886. svr.stop();
  3887. thread.join();
  3888. ASSERT_FALSE(svr.is_running());
  3889. });
  3890. svr.wait_until_ready();
  3891. {
  3892. Client cli(HOST, PORT);
  3893. auto res = cli.Get("/hi");
  3894. ASSERT_FALSE(res);
  3895. }
  3896. }
  3897. TEST(URLFragmentTest, WithFragment) {
  3898. Server svr;
  3899. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3900. EXPECT_TRUE(req.target == "/hi");
  3901. });
  3902. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3903. auto se = detail::scope_exit([&] {
  3904. svr.stop();
  3905. thread.join();
  3906. ASSERT_FALSE(svr.is_running());
  3907. });
  3908. svr.wait_until_ready();
  3909. {
  3910. Client cli(HOST, PORT);
  3911. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3912. EXPECT_TRUE(res);
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. res = cli.Get("/hi%23key1=val1=key2=val2");
  3915. EXPECT_TRUE(res);
  3916. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3917. }
  3918. }
  3919. TEST(HeaderWriter, SetHeaderWriter) {
  3920. Server svr;
  3921. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3922. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3923. return detail::write_headers(strm, hdrs);
  3924. });
  3925. svr.Get("/hi", [](const Request &req, Response &res) {
  3926. auto it = req.headers.find("CustomClientHeader");
  3927. EXPECT_TRUE(it != req.headers.end());
  3928. EXPECT_EQ(it->second, "CustomClientValue");
  3929. res.set_content("Hello World!\n", "text/plain");
  3930. });
  3931. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3932. auto se = detail::scope_exit([&] {
  3933. svr.stop();
  3934. thread.join();
  3935. ASSERT_FALSE(svr.is_running());
  3936. });
  3937. svr.wait_until_ready();
  3938. {
  3939. Client cli(HOST, PORT);
  3940. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3941. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3942. return detail::write_headers(strm, hdrs);
  3943. });
  3944. auto res = cli.Get("/hi");
  3945. EXPECT_TRUE(res);
  3946. EXPECT_EQ(StatusCode::OK_200, res->status);
  3947. auto it = res->headers.find("CustomServerHeader");
  3948. EXPECT_TRUE(it != res->headers.end());
  3949. EXPECT_EQ(it->second, "CustomServerValue");
  3950. }
  3951. }
  3952. class ServerTest : public ::testing::Test {
  3953. protected:
  3954. ServerTest()
  3955. : cli_(HOST, PORT)
  3956. #ifdef CPPHTTPLIB_SSL_ENABLED
  3957. ,
  3958. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3959. #endif
  3960. {
  3961. #ifdef CPPHTTPLIB_SSL_ENABLED
  3962. cli_.enable_server_certificate_verification(false);
  3963. #endif
  3964. // Allow LARGE_DATA (100MB) responses
  3965. cli_.set_payload_max_length(200 * 1024 * 1024);
  3966. }
  3967. virtual void SetUp() {
  3968. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3969. svr_.set_payload_max_length(200 * 1024 * 1024);
  3970. svr_.set_mount_point("/", "./www");
  3971. svr_.set_mount_point("/mount", "./www2");
  3972. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3973. svr_.Get("/hi",
  3974. [&](const Request & /*req*/, Response &res) {
  3975. res.set_content("Hello World!", "text/plain");
  3976. })
  3977. .Get("/file_content",
  3978. [&](const Request & /*req*/, Response &res) {
  3979. res.set_file_content("./www/dir/test.html");
  3980. })
  3981. .Get("/file_content_with_content_type",
  3982. [&](const Request & /*req*/, Response &res) {
  3983. res.set_file_content("./www/file", "text/plain");
  3984. })
  3985. .Get("/invalid_file_content",
  3986. [&](const Request & /*req*/, Response &res) {
  3987. res.set_file_content("./www/dir/invalid_file_path");
  3988. })
  3989. .Get("/http_response_splitting",
  3990. [&](const Request & /*req*/, Response &res) {
  3991. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3992. EXPECT_EQ(0U, res.headers.size());
  3993. EXPECT_FALSE(res.has_header("a"));
  3994. res.set_header("a", "1\nSet-Cookie: a=1");
  3995. EXPECT_EQ(0U, res.headers.size());
  3996. EXPECT_FALSE(res.has_header("a"));
  3997. res.set_header("a", "1\rSet-Cookie: a=1");
  3998. EXPECT_EQ(0U, res.headers.size());
  3999. EXPECT_FALSE(res.has_header("a"));
  4000. res.set_header("a\r\nb", "0");
  4001. EXPECT_EQ(0U, res.headers.size());
  4002. EXPECT_FALSE(res.has_header("a"));
  4003. res.set_header("a\rb", "0");
  4004. EXPECT_EQ(0U, res.headers.size());
  4005. EXPECT_FALSE(res.has_header("a"));
  4006. res.set_header("a\nb", "0");
  4007. EXPECT_EQ(0U, res.headers.size());
  4008. EXPECT_FALSE(res.has_header("a"));
  4009. res.set_redirect("1\r\nSet-Cookie: a=1");
  4010. EXPECT_EQ(0U, res.headers.size());
  4011. EXPECT_FALSE(res.has_header("Location"));
  4012. })
  4013. .Get("/slow",
  4014. [&](const Request & /*req*/, Response &res) {
  4015. std::this_thread::sleep_for(std::chrono::seconds(4));
  4016. res.set_content("slow", "text/plain");
  4017. })
  4018. #if 0
  4019. .Post("/slowpost",
  4020. [&](const Request & /*req*/, Response &res) {
  4021. std::this_thread::sleep_for(std::chrono::seconds(2));
  4022. res.set_content("slow", "text/plain");
  4023. })
  4024. #endif
  4025. .Get("/remote_addr",
  4026. [&](const Request &req, Response &res) {
  4027. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4028. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4029. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4030. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4031. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4032. #endif
  4033. res.set_content(req.remote_addr, "text/plain");
  4034. })
  4035. .Get("/local_addr",
  4036. [&](const Request &req, Response &res) {
  4037. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4038. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4039. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4040. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4041. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4042. #endif
  4043. auto local_addr = req.local_addr;
  4044. auto local_port = std::to_string(req.local_port);
  4045. res.set_content(local_addr.append(":").append(local_port),
  4046. "text/plain");
  4047. })
  4048. .Get("/endwith%",
  4049. [&](const Request & /*req*/, Response &res) {
  4050. res.set_content("Hello World!", "text/plain");
  4051. })
  4052. .Get("/a\\+\\+b",
  4053. [&](const Request &req, Response &res) {
  4054. ASSERT_TRUE(req.has_param("a +b"));
  4055. auto val = req.get_param_value("a +b");
  4056. res.set_content(val, "text/plain");
  4057. })
  4058. .Get("/", [&](const Request & /*req*/,
  4059. Response &res) { res.set_redirect("/hi"); })
  4060. .Post("/1",
  4061. [](const Request & /*req*/, Response &res) {
  4062. res.set_redirect("/2", StatusCode::SeeOther_303);
  4063. })
  4064. .Get("/2",
  4065. [](const Request & /*req*/, Response &res) {
  4066. res.set_content("redirected.", "text/plain");
  4067. res.status = StatusCode::OK_200;
  4068. })
  4069. .Post("/person",
  4070. [&](const Request &req, Response &res) {
  4071. if (req.has_param("name") && req.has_param("note")) {
  4072. persons_[req.get_param_value("name")] =
  4073. req.get_param_value("note");
  4074. } else {
  4075. res.status = StatusCode::BadRequest_400;
  4076. }
  4077. })
  4078. .Put("/person",
  4079. [&](const Request &req, Response &res) {
  4080. if (req.has_param("name") && req.has_param("note")) {
  4081. persons_[req.get_param_value("name")] =
  4082. req.get_param_value("note");
  4083. } else {
  4084. res.status = StatusCode::BadRequest_400;
  4085. }
  4086. })
  4087. .Get("/person/(.*)",
  4088. [&](const Request &req, Response &res) {
  4089. string name = req.matches[1];
  4090. if (persons_.find(name) != persons_.end()) {
  4091. auto note = persons_[name];
  4092. res.set_content(note, "text/plain");
  4093. } else {
  4094. res.status = StatusCode::NotFound_404;
  4095. }
  4096. })
  4097. .Delete("/person",
  4098. [&](const Request &req, Response &res) {
  4099. if (req.has_param("name")) {
  4100. string name = req.get_param_value("name");
  4101. if (persons_.find(name) != persons_.end()) {
  4102. persons_.erase(name);
  4103. res.set_content("DELETED", "text/plain");
  4104. } else {
  4105. res.status = StatusCode::NotFound_404;
  4106. }
  4107. } else {
  4108. res.status = StatusCode::BadRequest_400;
  4109. }
  4110. })
  4111. .Post("/x-www-form-urlencoded-json",
  4112. [&](const Request &req, Response &res) {
  4113. auto json = req.get_param_value("json");
  4114. ASSERT_EQ(JSON_DATA, json);
  4115. res.set_content(json, "appliation/json");
  4116. res.status = StatusCode::OK_200;
  4117. })
  4118. .Get("/streamed-chunked",
  4119. [&](const Request & /*req*/, Response &res) {
  4120. res.set_chunked_content_provider(
  4121. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4122. sink.os << "123";
  4123. sink.os << "456";
  4124. sink.os << "789";
  4125. sink.done();
  4126. return true;
  4127. });
  4128. })
  4129. .Get("/streamed-chunked-with-prohibited-trailer",
  4130. [&](const Request & /*req*/, Response &res) {
  4131. auto i = new int(0);
  4132. // Declare both a prohibited trailer (Content-Length) and an
  4133. // allowed one
  4134. res.set_header("Trailer", "Content-Length, X-Allowed");
  4135. res.set_chunked_content_provider(
  4136. "text/plain",
  4137. [i](size_t /*offset*/, DataSink &sink) {
  4138. switch (*i) {
  4139. case 0: sink.os << "123"; break;
  4140. case 1: sink.os << "456"; break;
  4141. case 2: sink.os << "789"; break;
  4142. case 3: {
  4143. sink.done_with_trailer(
  4144. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4145. } break;
  4146. }
  4147. (*i)++;
  4148. return true;
  4149. },
  4150. [i](bool success) {
  4151. EXPECT_TRUE(success);
  4152. delete i;
  4153. });
  4154. })
  4155. .Get("/streamed-chunked2",
  4156. [&](const Request & /*req*/, Response &res) {
  4157. auto i = new int(0);
  4158. res.set_chunked_content_provider(
  4159. "text/plain",
  4160. [i](size_t /*offset*/, DataSink &sink) {
  4161. switch (*i) {
  4162. case 0: sink.os << "123"; break;
  4163. case 1: sink.os << "456"; break;
  4164. case 2: sink.os << "789"; break;
  4165. case 3: sink.done(); break;
  4166. }
  4167. (*i)++;
  4168. return true;
  4169. },
  4170. [i](bool success) {
  4171. EXPECT_TRUE(success);
  4172. delete i;
  4173. });
  4174. })
  4175. .Get("/streamed-chunked-with-trailer",
  4176. [&](const Request & /*req*/, Response &res) {
  4177. auto i = new int(0);
  4178. res.set_header("Trailer", "Dummy1, Dummy2");
  4179. res.set_chunked_content_provider(
  4180. "text/plain",
  4181. [i](size_t /*offset*/, DataSink &sink) {
  4182. switch (*i) {
  4183. case 0: sink.os << "123"; break;
  4184. case 1: sink.os << "456"; break;
  4185. case 2: sink.os << "789"; break;
  4186. case 3: {
  4187. sink.done_with_trailer(
  4188. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4189. } break;
  4190. }
  4191. (*i)++;
  4192. return true;
  4193. },
  4194. [i](bool success) {
  4195. EXPECT_TRUE(success);
  4196. delete i;
  4197. });
  4198. })
  4199. .Get("/streamed",
  4200. [&](const Request & /*req*/, Response &res) {
  4201. res.set_content_provider(
  4202. 6, "text/plain",
  4203. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4204. sink.os << (offset < 3 ? "a" : "b");
  4205. return true;
  4206. });
  4207. })
  4208. .Get("/streamed-without-length",
  4209. [&](const Request & /*req*/, Response &res) {
  4210. auto data = new std::string("abcdefg");
  4211. res.set_content_provider(
  4212. "text/plain",
  4213. [data](size_t offset, DataSink &sink) {
  4214. if (offset < data->size()) {
  4215. sink.os << data->substr(offset);
  4216. }
  4217. sink.done();
  4218. return true;
  4219. },
  4220. [data](bool success) {
  4221. EXPECT_TRUE(success);
  4222. delete data;
  4223. });
  4224. })
  4225. .Get("/streamed-with-range",
  4226. [&](const Request &req, Response &res) {
  4227. auto data = new std::string("abcdefg");
  4228. // An explicit status keeps the server from picking the 206 it
  4229. // would otherwise choose for a ranged request, so the response
  4230. // is not a partial representation.
  4231. auto status = req.get_param_value("status");
  4232. if (status == "200") {
  4233. res.status = StatusCode::OK_200;
  4234. } else if (status == "403") {
  4235. res.status = StatusCode::Forbidden_403;
  4236. }
  4237. res.set_content_provider(
  4238. data->size(), "text/plain",
  4239. [data](size_t offset, size_t length, DataSink &sink) {
  4240. size_t DATA_CHUNK_SIZE = 4;
  4241. const auto &d = *data;
  4242. auto out_len =
  4243. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4244. auto ret =
  4245. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4246. EXPECT_TRUE(ret);
  4247. return true;
  4248. },
  4249. [data, &req](bool success) {
  4250. EXPECT_EQ(success, !req.has_param("error"));
  4251. delete data;
  4252. });
  4253. })
  4254. .Get("/streamed-cancel",
  4255. [&](const Request & /*req*/, Response &res) {
  4256. res.set_content_provider(
  4257. size_t(-1), "text/plain",
  4258. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4259. sink.os << "data_chunk";
  4260. return true;
  4261. });
  4262. })
  4263. .Get("/regex-with-delimiter",
  4264. [&](const Request &req, Response & /*res*/) {
  4265. ASSERT_TRUE(req.has_param("key"));
  4266. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4267. })
  4268. .Get("/with-range",
  4269. [&](const Request & /*req*/, Response &res) {
  4270. res.set_content("abcdefg", "text/plain");
  4271. })
  4272. .Get("/test-start-time",
  4273. [&](const Request &req, Response & /*res*/) {
  4274. EXPECT_NE(req.start_time_,
  4275. std::chrono::steady_clock::time_point::min());
  4276. })
  4277. .Get("/with-range-customized-response",
  4278. [&](const Request & /*req*/, Response &res) {
  4279. res.status = StatusCode::BadRequest_400;
  4280. res.set_content(JSON_DATA, "application/json");
  4281. })
  4282. .Post("/chunked",
  4283. [&](const Request &req, Response & /*res*/) {
  4284. EXPECT_EQ(req.body, "dechunked post body");
  4285. })
  4286. .Post("/large-chunked",
  4287. [&](const Request &req, Response & /*res*/) {
  4288. std::string expected(6 * 30 * 1024u, 'a');
  4289. EXPECT_EQ(req.body, expected);
  4290. })
  4291. .Post("/multipart",
  4292. [&](const Request &req, Response & /*res*/) {
  4293. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4294. req.form.get_field_count("text2") +
  4295. req.form.get_field_count("file3") +
  4296. req.form.get_field_count("file4"));
  4297. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4298. req.form.get_file_count("file2"));
  4299. ASSERT_TRUE(!req.form.has_file("???"));
  4300. ASSERT_TRUE(!req.form.has_field("???"));
  4301. ASSERT_TRUE(req.body.empty());
  4302. {
  4303. const auto &text = req.form.get_field("text1");
  4304. EXPECT_EQ("text default", text);
  4305. }
  4306. {
  4307. const auto &text = req.form.get_field("text2");
  4308. EXPECT_EQ("aωb", text);
  4309. }
  4310. {
  4311. const auto &file = req.form.get_file("file1");
  4312. EXPECT_EQ("hello.txt", file.filename);
  4313. EXPECT_EQ("text/plain", file.content_type);
  4314. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4315. }
  4316. {
  4317. const auto &file = req.form.get_file("file2");
  4318. EXPECT_EQ("world.json", file.filename);
  4319. EXPECT_EQ("application/json", file.content_type);
  4320. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4321. }
  4322. {
  4323. const auto &text = req.form.get_field("file3");
  4324. EXPECT_EQ(0u, text.size());
  4325. }
  4326. {
  4327. const auto &text = req.form.get_field("file4");
  4328. EXPECT_EQ(0u, text.size());
  4329. }
  4330. })
  4331. .Post("/multipart/multi_file_values",
  4332. [&](const Request &req, Response & /*res*/) {
  4333. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4334. req.form.get_field_count("multi_text1"));
  4335. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4336. ASSERT_TRUE(!req.form.has_file("???"));
  4337. ASSERT_TRUE(!req.form.has_field("???"));
  4338. ASSERT_TRUE(req.body.empty());
  4339. {
  4340. const auto &text = req.form.get_field("text");
  4341. EXPECT_EQ("default text", text);
  4342. }
  4343. {
  4344. const auto &text1_values = req.form.get_fields("multi_text1");
  4345. EXPECT_EQ(2u, text1_values.size());
  4346. EXPECT_EQ("aaaaa", text1_values[0]);
  4347. EXPECT_EQ("bbbbb", text1_values[1]);
  4348. }
  4349. {
  4350. const auto &file1_values = req.form.get_files("multi_file1");
  4351. EXPECT_EQ(2u, file1_values.size());
  4352. auto file1 = file1_values[0];
  4353. EXPECT_EQ(file1.filename, "hello.txt");
  4354. EXPECT_EQ(file1.content_type, "text/plain");
  4355. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4356. auto file2 = file1_values[1];
  4357. EXPECT_EQ(file2.filename, "world.json");
  4358. EXPECT_EQ(file2.content_type, "application/json");
  4359. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4360. }
  4361. })
  4362. .Post("/empty",
  4363. [&](const Request &req, Response &res) {
  4364. EXPECT_EQ(req.body, "");
  4365. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4366. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4367. res.set_content("empty", "text/plain");
  4368. })
  4369. .Post("/empty-no-content-type",
  4370. [&](const Request &req, Response &res) {
  4371. EXPECT_EQ(req.body, "");
  4372. EXPECT_FALSE(req.has_header("Content-Type"));
  4373. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4374. res.set_content("empty-no-content-type", "text/plain");
  4375. })
  4376. .Post("/path-only",
  4377. [&](const Request &req, Response &res) {
  4378. EXPECT_EQ(req.body, "");
  4379. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4380. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4381. res.set_content("path-only", "text/plain");
  4382. })
  4383. .Post("/path-headers-only",
  4384. [&](const Request &req, Response &res) {
  4385. EXPECT_EQ(req.body, "");
  4386. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4387. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4388. EXPECT_EQ("world", req.get_header_value("hello"));
  4389. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4390. res.set_content("path-headers-only", "text/plain");
  4391. })
  4392. .Post("/post-large",
  4393. [&](const Request &req, Response &res) {
  4394. EXPECT_EQ(req.body, LARGE_DATA);
  4395. res.set_content(req.body, "text/plain");
  4396. })
  4397. .Post("/post-loopback",
  4398. [&](const Request &, Response &res,
  4399. ContentReader const &content_reader) {
  4400. std::string body;
  4401. content_reader([&](const char *data, size_t data_length) {
  4402. body.append(data, data_length);
  4403. return true;
  4404. });
  4405. res.set_content(body, "text/plain");
  4406. })
  4407. .Put("/put-loopback",
  4408. [&](const Request &, Response &res,
  4409. ContentReader const &content_reader) {
  4410. std::string body;
  4411. content_reader([&](const char *data, size_t data_length) {
  4412. body.append(data, data_length);
  4413. return true;
  4414. });
  4415. res.set_content(body, "text/plain");
  4416. })
  4417. .Patch("/patch-loopback",
  4418. [&](const Request &, Response &res,
  4419. ContentReader const &content_reader) {
  4420. std::string body;
  4421. content_reader([&](const char *data, size_t data_length) {
  4422. body.append(data, data_length);
  4423. return true;
  4424. });
  4425. res.set_content(body, "text/plain");
  4426. })
  4427. .Put("/empty-no-content-type",
  4428. [&](const Request &req, Response &res) {
  4429. EXPECT_EQ(req.body, "");
  4430. EXPECT_FALSE(req.has_header("Content-Type"));
  4431. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4432. res.set_content("empty-no-content-type", "text/plain");
  4433. })
  4434. .Put("/put",
  4435. [&](const Request &req, Response &res) {
  4436. EXPECT_EQ(req.body, "PUT");
  4437. res.set_content(req.body, "text/plain");
  4438. })
  4439. .Put("/put-large",
  4440. [&](const Request &req, Response &res) {
  4441. EXPECT_EQ(req.body, LARGE_DATA);
  4442. res.set_content(req.body, "text/plain");
  4443. })
  4444. .Patch("/patch",
  4445. [&](const Request &req, Response &res) {
  4446. EXPECT_EQ(req.body, "PATCH");
  4447. res.set_content(req.body, "text/plain");
  4448. })
  4449. .Delete("/delete",
  4450. [&](const Request & /*req*/, Response &res) {
  4451. res.set_content("DELETE", "text/plain");
  4452. })
  4453. .Delete("/delete-body",
  4454. [&](const Request &req, Response &res) {
  4455. EXPECT_EQ(req.body, "content");
  4456. res.set_content(req.body, "text/plain");
  4457. })
  4458. .Options(R"(\*)",
  4459. [&](const Request & /*req*/, Response &res) {
  4460. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4461. })
  4462. .CustomRoute("PROPFIND", "/dav/:id",
  4463. [&](const Request &req, Response &res) {
  4464. res.set_header("x-body-size",
  4465. std::to_string(req.body.size()));
  4466. res.set_header("x-matched-route", req.matched_route);
  4467. res.set_header("x-dav-id", req.path_params.at("id"));
  4468. res.status = StatusCode::MultiStatus_207;
  4469. res.set_content(req.body, "application/xml");
  4470. })
  4471. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4472. [&](const Request &req, Response &res) {
  4473. res.set_header("x-dav-match", req.matches[1]);
  4474. res.status = StatusCode::MultiStatus_207;
  4475. })
  4476. .CustomRoute("MKCOL", "/dav-mkcol",
  4477. [&](const Request &req, Response &res) {
  4478. EXPECT_TRUE(req.body.empty());
  4479. res.status = StatusCode::Created_201;
  4480. })
  4481. .CustomRoute(
  4482. "REPORT", "/dav-report",
  4483. [&](const Request & /*req*/, Response &res,
  4484. const ContentReader &content_reader) {
  4485. std::string body;
  4486. content_reader([&](const char *data, size_t data_length) {
  4487. body.append(data, data_length);
  4488. return true;
  4489. });
  4490. res.set_header("x-body-size", std::to_string(body.size()));
  4491. res.status = StatusCode::MultiStatus_207;
  4492. res.set_content(body, "application/xml");
  4493. })
  4494. .Get("/request-target",
  4495. [&](const Request &req, Response & /*res*/) {
  4496. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4497. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4498. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4499. })
  4500. .Get("/long-query-value",
  4501. [&](const Request &req, Response & /*res*/) {
  4502. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4503. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4504. })
  4505. .Get("/too-long-query-value",
  4506. [&](const Request &req, Response & /*res*/) {
  4507. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4508. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4509. })
  4510. .Get("/array-param",
  4511. [&](const Request &req, Response & /*res*/) {
  4512. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4513. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4514. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4515. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4516. })
  4517. .Get("/array-param-values",
  4518. [&](const Request &req, Response & /*res*/) {
  4519. auto values = req.get_param_values("array");
  4520. EXPECT_EQ(3u, values.size());
  4521. EXPECT_EQ("value1", values[0]);
  4522. EXPECT_EQ("value2", values[1]);
  4523. EXPECT_EQ("value3", values[2]);
  4524. auto empty = req.get_param_values("nonexistent");
  4525. EXPECT_TRUE(empty.empty());
  4526. })
  4527. .Post("/validate-no-multiple-headers",
  4528. [&](const Request &req, Response & /*res*/) {
  4529. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4530. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4531. })
  4532. .Post("/content_receiver",
  4533. [&](const Request &req, Response &res,
  4534. const ContentReader &content_reader) {
  4535. if (req.is_multipart_form_data()) {
  4536. std::vector<FormData> items;
  4537. content_reader(
  4538. [&](const FormData &file) {
  4539. items.push_back(file);
  4540. return true;
  4541. },
  4542. [&](const char *data, size_t data_length) {
  4543. items.back().content.append(data, data_length);
  4544. return true;
  4545. });
  4546. EXPECT_EQ(5u, items.size());
  4547. {
  4548. const auto &file = get_file_value(items, "text1");
  4549. EXPECT_TRUE(file.filename.empty());
  4550. EXPECT_EQ("text default", file.content);
  4551. }
  4552. {
  4553. const auto &file = get_file_value(items, "text2");
  4554. EXPECT_TRUE(file.filename.empty());
  4555. EXPECT_EQ("aωb", file.content);
  4556. }
  4557. {
  4558. const auto &file = get_file_value(items, "file1");
  4559. EXPECT_EQ("hello.txt", file.filename);
  4560. EXPECT_EQ("text/plain", file.content_type);
  4561. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4562. }
  4563. {
  4564. const auto &file = get_file_value(items, "file2");
  4565. EXPECT_EQ("world.json", file.filename);
  4566. EXPECT_EQ("application/json", file.content_type);
  4567. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4568. }
  4569. {
  4570. const auto &file = get_file_value(items, "file3");
  4571. EXPECT_TRUE(file.filename.empty());
  4572. EXPECT_EQ("application/octet-stream", file.content_type);
  4573. EXPECT_EQ(0u, file.content.size());
  4574. }
  4575. } else {
  4576. std::string body;
  4577. content_reader([&](const char *data, size_t data_length) {
  4578. EXPECT_EQ(7U, data_length);
  4579. body.append(data, data_length);
  4580. return true;
  4581. });
  4582. EXPECT_EQ(body, "content");
  4583. res.set_content(body, "text/plain");
  4584. }
  4585. })
  4586. .Put("/content_receiver",
  4587. [&](const Request & /*req*/, Response &res,
  4588. const ContentReader &content_reader) {
  4589. std::string body;
  4590. content_reader([&](const char *data, size_t data_length) {
  4591. body.append(data, data_length);
  4592. return true;
  4593. });
  4594. EXPECT_EQ(body, "content");
  4595. res.set_content(body, "text/plain");
  4596. })
  4597. .Patch("/content_receiver",
  4598. [&](const Request & /*req*/, Response &res,
  4599. const ContentReader &content_reader) {
  4600. std::string body;
  4601. content_reader([&](const char *data, size_t data_length) {
  4602. body.append(data, data_length);
  4603. return true;
  4604. });
  4605. EXPECT_EQ(body, "content");
  4606. res.set_content(body, "text/plain");
  4607. })
  4608. .Post("/query-string-and-body",
  4609. [&](const Request &req, Response & /*res*/) {
  4610. ASSERT_TRUE(req.has_param("key"));
  4611. EXPECT_EQ(req.get_param_value("key"), "value");
  4612. EXPECT_EQ(req.body, "content");
  4613. })
  4614. .Get("/last-request",
  4615. [&](const Request &req, Response & /*res*/) {
  4616. EXPECT_EQ("close", req.get_header_value("Connection"));
  4617. })
  4618. .Get(R"(/redirect/(\d+))",
  4619. [&](const Request &req, Response &res) {
  4620. auto num = std::stoi(req.matches[1]) + 1;
  4621. std::string url = "/redirect/" + std::to_string(num);
  4622. res.set_redirect(url);
  4623. })
  4624. .Post("/binary",
  4625. [&](const Request &req, Response &res) {
  4626. EXPECT_EQ(4U, req.body.size());
  4627. EXPECT_EQ("application/octet-stream",
  4628. req.get_header_value("Content-Type"));
  4629. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4630. res.set_content(req.body, "application/octet-stream");
  4631. })
  4632. .Put("/binary",
  4633. [&](const Request &req, Response &res) {
  4634. EXPECT_EQ(4U, req.body.size());
  4635. EXPECT_EQ("application/octet-stream",
  4636. req.get_header_value("Content-Type"));
  4637. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4638. res.set_content(req.body, "application/octet-stream");
  4639. })
  4640. .Patch("/binary",
  4641. [&](const Request &req, Response &res) {
  4642. EXPECT_EQ(4U, req.body.size());
  4643. EXPECT_EQ("application/octet-stream",
  4644. req.get_header_value("Content-Type"));
  4645. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4646. res.set_content(req.body, "application/octet-stream");
  4647. })
  4648. .Delete("/binary",
  4649. [&](const Request &req, Response &res) {
  4650. EXPECT_EQ(4U, req.body.size());
  4651. EXPECT_EQ("application/octet-stream",
  4652. req.get_header_value("Content-Type"));
  4653. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4654. res.set_content(req.body, "application/octet-stream");
  4655. })
  4656. .Get("/issue1772",
  4657. [&](const Request & /*req*/, Response &res) {
  4658. res.status = 401;
  4659. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4660. })
  4661. .Delete("/issue609",
  4662. [](const httplib::Request &, httplib::Response &res,
  4663. const httplib::ContentReader &) {
  4664. res.set_content("ok", "text/plain");
  4665. })
  4666. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4667. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4668. .Get("/compress",
  4669. [&](const Request & /*req*/, Response &res) {
  4670. res.set_content(
  4671. "12345678901234567890123456789012345678901234567890123456789"
  4672. "01234567890123456789012345678901234567890",
  4673. "text/plain");
  4674. })
  4675. .Get("/compress-with-charset",
  4676. [&](const Request & /*req*/, Response &res) {
  4677. res.set_content(
  4678. "12345678901234567890123456789012345678901234567890123456789"
  4679. "01234567890123456789012345678901234567890",
  4680. "application/json; charset=utf-8");
  4681. })
  4682. .Get("/nocompress",
  4683. [&](const Request & /*req*/, Response &res) {
  4684. res.set_content(
  4685. "12345678901234567890123456789012345678901234567890123456789"
  4686. "01234567890123456789012345678901234567890",
  4687. "application/octet-stream");
  4688. })
  4689. .Post("/compress-multipart",
  4690. [&](const Request &req, Response & /*res*/) {
  4691. EXPECT_EQ(2u, req.form.fields.size());
  4692. ASSERT_TRUE(!req.form.has_field("???"));
  4693. {
  4694. const auto &text = req.form.get_field("key1");
  4695. EXPECT_EQ("test", text);
  4696. }
  4697. {
  4698. const auto &text = req.form.get_field("key2");
  4699. EXPECT_EQ("--abcdefg123", text);
  4700. }
  4701. })
  4702. #endif
  4703. ;
  4704. persons_["john"] = "programmer";
  4705. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4706. svr_.wait_until_ready();
  4707. }
  4708. virtual void TearDown() {
  4709. svr_.stop();
  4710. if (!request_threads_.empty()) {
  4711. std::this_thread::sleep_for(std::chrono::seconds(1));
  4712. for (auto &t : request_threads_) {
  4713. t.join();
  4714. }
  4715. }
  4716. t_.join();
  4717. }
  4718. map<string, string> persons_;
  4719. #ifdef CPPHTTPLIB_SSL_ENABLED
  4720. SSLClient cli_;
  4721. SSLServer svr_;
  4722. #else
  4723. Client cli_;
  4724. Server svr_;
  4725. #endif
  4726. thread t_;
  4727. std::vector<thread> request_threads_;
  4728. };
  4729. TEST_F(ServerTest, GetMethod200) {
  4730. auto res = cli_.Get("/hi");
  4731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4732. EXPECT_EQ("HTTP/1.1", res->version);
  4733. EXPECT_EQ(StatusCode::OK_200, res->status);
  4734. EXPECT_EQ("OK", res->reason);
  4735. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4736. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4737. EXPECT_EQ("Hello World!", res->body);
  4738. }
  4739. TEST_F(ServerTest, GetEmptyFile) {
  4740. auto res = cli_.Get("/empty_file");
  4741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4742. EXPECT_EQ(StatusCode::OK_200, res->status);
  4743. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4744. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4745. EXPECT_EQ("", res->body);
  4746. }
  4747. TEST_F(ServerTest, GetFileContent) {
  4748. auto res = cli_.Get("/file_content");
  4749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4750. EXPECT_EQ(StatusCode::OK_200, res->status);
  4751. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4752. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4753. EXPECT_EQ("test.html", res->body);
  4754. }
  4755. TEST_F(ServerTest, GetFileContentWithRange) {
  4756. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4758. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4759. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4760. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4761. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4762. EXPECT_EQ("est", res->body);
  4763. }
  4764. TEST_F(ServerTest, GetFileContentWithContentType) {
  4765. auto res = cli_.Get("/file_content_with_content_type");
  4766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4767. EXPECT_EQ(StatusCode::OK_200, res->status);
  4768. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4769. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4770. EXPECT_EQ("file\n", res->body);
  4771. }
  4772. TEST_F(ServerTest, GetInvalidFileContent) {
  4773. auto res = cli_.Get("/invalid_file_content");
  4774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4775. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4776. }
  4777. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4778. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4780. EXPECT_EQ("HTTP/1.1", res->version);
  4781. EXPECT_EQ(StatusCode::OK_200, res->status);
  4782. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4783. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4784. EXPECT_EQ("Hello World!", res->body);
  4785. }
  4786. TEST_F(ServerTest, GetMethod302) {
  4787. auto res = cli_.Get("/");
  4788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4789. EXPECT_EQ(StatusCode::Found_302, res->status);
  4790. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4791. }
  4792. TEST_F(ServerTest, GetMethod302Redirect) {
  4793. cli_.set_follow_location(true);
  4794. auto res = cli_.Get("/");
  4795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ("Hello World!", res->body);
  4798. EXPECT_EQ("/hi", res->location);
  4799. }
  4800. TEST_F(ServerTest, GetMethod404) {
  4801. auto res = cli_.Get("/invalid");
  4802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4803. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4804. }
  4805. TEST_F(ServerTest, HeadMethod200) {
  4806. auto res = cli_.Head("/hi");
  4807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4808. EXPECT_EQ(StatusCode::OK_200, res->status);
  4809. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4810. EXPECT_TRUE(res->body.empty());
  4811. }
  4812. TEST_F(ServerTest, HeadMethod200Static) {
  4813. auto res = cli_.Head("/mount/dir/index.html");
  4814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4815. EXPECT_EQ(StatusCode::OK_200, res->status);
  4816. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4817. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4818. EXPECT_TRUE(res->body.empty());
  4819. }
  4820. TEST_F(ServerTest, HeadMethod404) {
  4821. auto res = cli_.Head("/invalid");
  4822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4823. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4824. EXPECT_TRUE(res->body.empty());
  4825. }
  4826. TEST_F(ServerTest, GetMethodPersonJohn) {
  4827. auto res = cli_.Get("/person/john");
  4828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4829. EXPECT_EQ(StatusCode::OK_200, res->status);
  4830. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4831. EXPECT_EQ("programmer", res->body);
  4832. }
  4833. TEST_F(ServerTest, PostMethod1) {
  4834. auto res = cli_.Get("/person/john1");
  4835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4836. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4837. res = cli_.Post("/person", "name=john1&note=coder",
  4838. "application/x-www-form-urlencoded");
  4839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4840. ASSERT_EQ(StatusCode::OK_200, res->status);
  4841. res = cli_.Get("/person/john1");
  4842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4843. ASSERT_EQ(StatusCode::OK_200, res->status);
  4844. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4845. ASSERT_EQ("coder", res->body);
  4846. }
  4847. TEST_F(ServerTest, PostMethod2) {
  4848. auto res = cli_.Get("/person/john2");
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4851. Params params;
  4852. params.emplace("name", "john2");
  4853. params.emplace("note", "coder");
  4854. res = cli_.Post("/person", params);
  4855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4856. ASSERT_EQ(StatusCode::OK_200, res->status);
  4857. res = cli_.Get("/person/john2");
  4858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4859. ASSERT_EQ(StatusCode::OK_200, res->status);
  4860. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4861. ASSERT_EQ("coder", res->body);
  4862. }
  4863. TEST_F(ServerTest, PutMethod3) {
  4864. auto res = cli_.Get("/person/john3");
  4865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4866. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4867. Params params;
  4868. params.emplace("name", "john3");
  4869. params.emplace("note", "coder");
  4870. res = cli_.Put("/person", params);
  4871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4872. ASSERT_EQ(StatusCode::OK_200, res->status);
  4873. res = cli_.Get("/person/john3");
  4874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4875. ASSERT_EQ(StatusCode::OK_200, res->status);
  4876. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4877. ASSERT_EQ("coder", res->body);
  4878. }
  4879. TEST_F(ServerTest, DeleteMethod1) {
  4880. auto res = cli_.Get("/person/john4");
  4881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4882. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4883. Params params;
  4884. params.emplace("name", "john4");
  4885. params.emplace("note", "coder");
  4886. res = cli_.Post("/person", params);
  4887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4888. ASSERT_EQ(StatusCode::OK_200, res->status);
  4889. res = cli_.Get("/person/john4");
  4890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4891. ASSERT_EQ(StatusCode::OK_200, res->status);
  4892. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4893. ASSERT_EQ("coder", res->body);
  4894. Params delete_params;
  4895. delete_params.emplace("name", "john4");
  4896. res = cli_.Delete("/person", delete_params);
  4897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4898. ASSERT_EQ(StatusCode::OK_200, res->status);
  4899. ASSERT_EQ("DELETED", res->body);
  4900. res = cli_.Get("/person/john4");
  4901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4902. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4903. }
  4904. TEST_F(ServerTest, DeleteMethod2) {
  4905. auto res = cli_.Get("/person/john5");
  4906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4907. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4908. Params params;
  4909. params.emplace("name", "john5");
  4910. params.emplace("note", "developer");
  4911. res = cli_.Post("/person", params);
  4912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4913. ASSERT_EQ(StatusCode::OK_200, res->status);
  4914. res = cli_.Get("/person/john5");
  4915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4916. ASSERT_EQ(StatusCode::OK_200, res->status);
  4917. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4918. ASSERT_EQ("developer", res->body);
  4919. Params delete_params;
  4920. delete_params.emplace("name", "john5");
  4921. Headers headers;
  4922. headers.emplace("Custom-Header", "test-value");
  4923. res = cli_.Delete("/person", headers, delete_params);
  4924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4925. ASSERT_EQ(StatusCode::OK_200, res->status);
  4926. ASSERT_EQ("DELETED", res->body);
  4927. res = cli_.Get("/person/john5");
  4928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4929. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4930. }
  4931. TEST_F(ServerTest, DeleteMethod3) {
  4932. auto res = cli_.Get("/person/john6");
  4933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4934. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4935. Params params;
  4936. params.emplace("name", "john6");
  4937. params.emplace("note", "tester");
  4938. res = cli_.Post("/person", params);
  4939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4940. ASSERT_EQ(StatusCode::OK_200, res->status);
  4941. res = cli_.Get("/person/john6");
  4942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4943. ASSERT_EQ(StatusCode::OK_200, res->status);
  4944. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4945. ASSERT_EQ("tester", res->body);
  4946. Params delete_params;
  4947. delete_params.emplace("name", "john6");
  4948. Headers headers;
  4949. headers.emplace("Custom-Header", "test-value");
  4950. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4952. ASSERT_EQ(StatusCode::OK_200, res->status);
  4953. ASSERT_EQ("DELETED", res->body);
  4954. res = cli_.Get("/person/john6");
  4955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4956. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4957. }
  4958. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4959. Params params;
  4960. params.emplace("json", JSON_DATA);
  4961. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4963. ASSERT_EQ(StatusCode::OK_200, res->status);
  4964. ASSERT_EQ(JSON_DATA, res->body);
  4965. }
  4966. TEST_F(ServerTest, PostEmptyContent) {
  4967. auto res = cli_.Post("/empty", "", "text/plain");
  4968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4969. ASSERT_EQ(StatusCode::OK_200, res->status);
  4970. ASSERT_EQ("empty", res->body);
  4971. }
  4972. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4973. auto res = cli_.Post("/empty-no-content-type");
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. ASSERT_EQ(StatusCode::OK_200, res->status);
  4976. ASSERT_EQ("empty-no-content-type", res->body);
  4977. }
  4978. TEST_F(ServerTest, PostPathOnly) {
  4979. auto res = cli_.Post("/path-only");
  4980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4981. ASSERT_EQ(StatusCode::OK_200, res->status);
  4982. ASSERT_EQ("path-only", res->body);
  4983. }
  4984. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4985. auto res = cli_.Post("/path-headers-only",
  4986. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4988. ASSERT_EQ(StatusCode::OK_200, res->status);
  4989. ASSERT_EQ("path-headers-only", res->body);
  4990. }
  4991. TEST_F(ServerTest, PostLarge) {
  4992. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4994. ASSERT_EQ(StatusCode::OK_200, res->status);
  4995. EXPECT_EQ(LARGE_DATA, res->body);
  4996. }
  4997. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4998. auto res = cli_.Put("/empty-no-content-type");
  4999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5000. ASSERT_EQ(StatusCode::OK_200, res->status);
  5001. ASSERT_EQ("empty-no-content-type", res->body);
  5002. }
  5003. TEST_F(ServerTest, GetMethodDir) {
  5004. auto res = cli_.Get("/dir/");
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ(StatusCode::OK_200, res->status);
  5007. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5008. auto body = R"(<html>
  5009. <head>
  5010. </head>
  5011. <body>
  5012. <a href="/dir/test.html">Test</a>
  5013. <a href="/hi">hi</a>
  5014. </body>
  5015. </html>
  5016. )";
  5017. EXPECT_EQ(body, res->body);
  5018. }
  5019. TEST_F(ServerTest, GetMethodDirTest) {
  5020. auto res = cli_.Get("/dir/test.html");
  5021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5022. EXPECT_EQ(StatusCode::OK_200, res->status);
  5023. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5024. EXPECT_EQ("test.html", res->body);
  5025. }
  5026. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5027. auto res = cli_.Get("/dir/../dir/test.html");
  5028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5029. EXPECT_EQ(StatusCode::OK_200, res->status);
  5030. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5031. EXPECT_EQ("test.html", res->body);
  5032. }
  5033. TEST_F(ServerTest, GetMethodInvalidPath) {
  5034. auto res = cli_.Get("/dir/../test.html");
  5035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5036. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5037. }
  5038. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5039. auto res = cli_.Get("/../www/dir/test.html");
  5040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5041. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5042. }
  5043. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5044. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5046. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5047. }
  5048. TEST_F(ServerTest, GetMethodDirMountTest) {
  5049. auto res = cli_.Get("/mount/dir/test.html");
  5050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5051. EXPECT_EQ(StatusCode::OK_200, res->status);
  5052. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5053. EXPECT_EQ("test.html", res->body);
  5054. }
  5055. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5056. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5058. EXPECT_EQ(StatusCode::OK_200, res->status);
  5059. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5060. EXPECT_EQ("test.html", res->body);
  5061. }
  5062. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5063. auto res = cli_.Get("/mount/dir/../test.html");
  5064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5065. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5066. }
  5067. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5068. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5070. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5071. }
  5072. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5073. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5075. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5076. }
  5077. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5078. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5080. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5081. }
  5082. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5083. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5086. }
  5087. TEST_F(ServerTest, PostMethod303) {
  5088. auto res = cli_.Post("/1", "body", "text/plain");
  5089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5090. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5091. EXPECT_EQ("/2", res->get_header_value("Location"));
  5092. }
  5093. TEST_F(ServerTest, PostMethod303Redirect) {
  5094. cli_.set_follow_location(true);
  5095. auto res = cli_.Post("/1", "body", "text/plain");
  5096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5097. EXPECT_EQ(StatusCode::OK_200, res->status);
  5098. EXPECT_EQ("redirected.", res->body);
  5099. EXPECT_EQ("/2", res->location);
  5100. }
  5101. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5102. auto res = cli_.Get("/dir/test.abcde");
  5103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5104. EXPECT_EQ(StatusCode::OK_200, res->status);
  5105. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5106. EXPECT_EQ("abcde", res->body);
  5107. }
  5108. TEST_F(ServerTest, StaticFileRange) {
  5109. auto res =
  5110. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5112. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5113. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5114. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5115. EXPECT_EQ(true, res->has_header("Content-Range"));
  5116. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5117. EXPECT_EQ(std::string("cd"), res->body);
  5118. }
  5119. TEST_F(ServerTest, StaticFileRanges) {
  5120. auto res = cli_.Get("/dir/test.abcde",
  5121. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5123. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5124. EXPECT_TRUE(
  5125. res->get_header_value("Content-Type")
  5126. .find(
  5127. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5128. 0);
  5129. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5130. }
  5131. TEST_F(ServerTest, StaticFileRangeHead) {
  5132. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5134. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5135. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5136. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5137. EXPECT_EQ(true, res->has_header("Content-Range"));
  5138. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5139. }
  5140. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5141. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5143. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5144. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5145. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5146. EXPECT_EQ(true, res->has_header("Content-Range"));
  5147. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5148. res->get_header_value("Content-Range"));
  5149. EXPECT_EQ("LAST\n", res->body);
  5150. }
  5151. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5152. auto res =
  5153. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5155. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5157. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5158. EXPECT_EQ(true, res->has_header("Content-Range"));
  5159. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5160. }
  5161. TEST_F(ServerTest, StaticFileBigFile) {
  5162. auto res = cli_.Get("/dir/1MB.txt");
  5163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5164. EXPECT_EQ(StatusCode::OK_200, res->status);
  5165. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5166. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5167. }
  5168. TEST_F(ServerTest, InvalidBaseDirMount) {
  5169. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5170. }
  5171. TEST_F(ServerTest, Binary) {
  5172. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5173. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5174. "application/octet-stream");
  5175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5176. ASSERT_EQ(StatusCode::OK_200, res->status);
  5177. ASSERT_EQ(4U, res->body.size());
  5178. res = cli_.Put("/binary", binary.data(), binary.size(),
  5179. "application/octet-stream");
  5180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5181. ASSERT_EQ(StatusCode::OK_200, res->status);
  5182. ASSERT_EQ(4U, res->body.size());
  5183. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5184. "application/octet-stream");
  5185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5186. ASSERT_EQ(StatusCode::OK_200, res->status);
  5187. ASSERT_EQ(4U, res->body.size());
  5188. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5189. "application/octet-stream");
  5190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5191. ASSERT_EQ(StatusCode::OK_200, res->status);
  5192. ASSERT_EQ(4U, res->body.size());
  5193. }
  5194. TEST_F(ServerTest, BinaryString) {
  5195. auto binary = std::string("\x00\x01\x02\x03", 4);
  5196. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5198. ASSERT_EQ(StatusCode::OK_200, res->status);
  5199. ASSERT_EQ(4U, res->body.size());
  5200. res = cli_.Put("/binary", binary, "application/octet-stream");
  5201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5202. ASSERT_EQ(StatusCode::OK_200, res->status);
  5203. ASSERT_EQ(4U, res->body.size());
  5204. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5206. ASSERT_EQ(StatusCode::OK_200, res->status);
  5207. ASSERT_EQ(4U, res->body.size());
  5208. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5210. ASSERT_EQ(StatusCode::OK_200, res->status);
  5211. ASSERT_EQ(4U, res->body.size());
  5212. }
  5213. TEST_F(ServerTest, EmptyRequest) {
  5214. auto res = cli_.Get("");
  5215. ASSERT_TRUE(!res);
  5216. EXPECT_EQ(Error::Connection, res.error());
  5217. }
  5218. TEST_F(ServerTest, LongRequest) {
  5219. std::string request;
  5220. for (size_t i = 0; i < 545; i++) {
  5221. request += "/TooLongRequest";
  5222. }
  5223. request += "OK";
  5224. auto res = cli_.Get(request.c_str());
  5225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5226. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5227. }
  5228. TEST_F(ServerTest, TooLongRequest) {
  5229. std::string request;
  5230. for (size_t i = 0; i < 546; i++) {
  5231. request += "/TooLongRequest";
  5232. }
  5233. request += "_NG";
  5234. auto start = std::chrono::high_resolution_clock::now();
  5235. cli_.set_keep_alive(true);
  5236. auto res = cli_.Get(request.c_str());
  5237. auto end = std::chrono::high_resolution_clock::now();
  5238. auto elapsed =
  5239. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5240. .count();
  5241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5242. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5243. EXPECT_LE(elapsed, 1000);
  5244. EXPECT_EQ("close", res->get_header_value("Connection"));
  5245. EXPECT_FALSE(cli_.is_socket_open());
  5246. }
  5247. TEST_F(ServerTest, AlmostTooLongRequest) {
  5248. // test for #2046 - URI length check shouldn't include other content on req
  5249. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5250. // leading /, space, HTTP/1.1)
  5251. std::string request =
  5252. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5253. auto res = cli_.Get(request.c_str());
  5254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5255. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5256. }
  5257. TEST_F(ServerTest, LongHeader) {
  5258. Request req;
  5259. req.method = "GET";
  5260. req.path = "/hi";
  5261. std::string host_and_port;
  5262. host_and_port += HOST;
  5263. host_and_port += ":";
  5264. host_and_port += std::to_string(PORT);
  5265. req.headers.emplace("Host", host_and_port.c_str());
  5266. req.headers.emplace("Accept", "*/*");
  5267. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5268. req.headers.emplace(
  5269. "Header-Name",
  5270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5273. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5274. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5275. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5276. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5277. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5278. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5284. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5285. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5286. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5287. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5288. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5289. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5290. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5291. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5298. "@@@@@@@@@@@@@@@@");
  5299. auto res = std::make_shared<Response>();
  5300. auto error = Error::Success;
  5301. auto ret = cli_.send(req, *res, error);
  5302. ASSERT_TRUE(ret);
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. }
  5305. TEST_F(ServerTest, LongQueryValue) {
  5306. auto start = std::chrono::high_resolution_clock::now();
  5307. cli_.set_keep_alive(true);
  5308. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5309. auto end = std::chrono::high_resolution_clock::now();
  5310. auto elapsed =
  5311. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5312. .count();
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5315. EXPECT_LE(elapsed, 1000);
  5316. EXPECT_EQ("close", res->get_header_value("Connection"));
  5317. EXPECT_FALSE(cli_.is_socket_open());
  5318. }
  5319. TEST_F(ServerTest, TooLongQueryValue) {
  5320. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5321. ASSERT_FALSE(res);
  5322. EXPECT_EQ(Error::Read, res.error());
  5323. }
  5324. TEST_F(ServerTest, TooLongHeader) {
  5325. Request req;
  5326. req.method = "GET";
  5327. req.path = "/hi";
  5328. std::string host_and_port;
  5329. host_and_port += HOST;
  5330. host_and_port += ":";
  5331. host_and_port += std::to_string(PORT);
  5332. req.headers.emplace("Host", host_and_port.c_str());
  5333. req.headers.emplace("Accept", "*/*");
  5334. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5335. req.headers.emplace(
  5336. "Header-Name",
  5337. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5338. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5339. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5340. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5341. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5342. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5343. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5344. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5345. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5346. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5347. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5348. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5349. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5352. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5353. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5356. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5358. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5365. "@@@@@@@@@@@@@@@@@");
  5366. auto res = std::make_shared<Response>();
  5367. auto error = Error::Success;
  5368. auto ret = cli_.send(req, *res, error);
  5369. ASSERT_TRUE(ret);
  5370. EXPECT_EQ(StatusCode::OK_200, res->status);
  5371. }
  5372. TEST_F(ServerTest, HeaderCountAtLimit) {
  5373. // Test with headers just under the 100 limit
  5374. httplib::Headers headers;
  5375. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5376. // This should keep us just under the 100 header limit
  5377. for (int i = 0; i < 95; i++) {
  5378. std::string name = "X-Test-Header-" + std::to_string(i);
  5379. std::string value = "value" + std::to_string(i);
  5380. headers.emplace(name, value);
  5381. }
  5382. // This should work fine as we're under the limit
  5383. auto res = cli_.Get("/hi", headers);
  5384. EXPECT_TRUE(res);
  5385. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5386. }
  5387. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5388. // Test with many headers to exceed the 100 limit
  5389. httplib::Headers headers;
  5390. // Add 150 headers to definitely exceed the 100 limit
  5391. for (int i = 0; i < 150; i++) {
  5392. std::string name = "X-Test-Header-" + std::to_string(i);
  5393. std::string value = "value" + std::to_string(i);
  5394. headers.emplace(name, value);
  5395. }
  5396. // This should fail due to exceeding header count limit
  5397. cli_.set_keep_alive(true);
  5398. auto res = cli_.Get("/hi", headers);
  5399. // The server should respond with 400 Bad Request
  5400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5401. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5402. EXPECT_EQ("close", res->get_header_value("Connection"));
  5403. EXPECT_FALSE(cli_.is_socket_open());
  5404. }
  5405. TEST_F(ServerTest, PercentEncoding) {
  5406. auto res = cli_.Get("/e%6edwith%");
  5407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5408. EXPECT_EQ(StatusCode::OK_200, res->status);
  5409. }
  5410. TEST_F(ServerTest, PercentEncodingUnicode) {
  5411. auto res = cli_.Get("/e%u006edwith%");
  5412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5413. EXPECT_EQ(StatusCode::OK_200, res->status);
  5414. }
  5415. TEST_F(ServerTest, InvalidPercentEncoding) {
  5416. auto res = cli_.Get("/%endwith%");
  5417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5418. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5419. }
  5420. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5421. auto res = cli_.Get("/%uendwith%");
  5422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5423. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5424. }
  5425. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5426. auto res = cli_.Get("/hello?aaa=bbb%");
  5427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5428. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5429. }
  5430. TEST_F(ServerTest, PlusSignEncoding) {
  5431. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5433. EXPECT_EQ(StatusCode::OK_200, res->status);
  5434. EXPECT_EQ("a +b", res->body);
  5435. }
  5436. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5437. // This test simulates a potential DoS attack using many headers
  5438. // to verify our security fix prevents memory exhaustion
  5439. httplib::Headers attack_headers;
  5440. // Attempt to add many headers like an attacker would (200 headers to far
  5441. // exceed limit)
  5442. for (int i = 0; i < 200; i++) {
  5443. std::string name = "X-Attack-Header-" + std::to_string(i);
  5444. std::string value = "attack_payload_" + std::to_string(i);
  5445. attack_headers.emplace(name, value);
  5446. }
  5447. // Try to POST with excessive headers
  5448. cli_.set_keep_alive(true);
  5449. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5450. // Should either fail or return 400 Bad Request due to security limit
  5451. if (res) {
  5452. // If we get a response, it should be 400 Bad Request
  5453. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5454. EXPECT_EQ("close", res->get_header_value("Connection"));
  5455. }
  5456. EXPECT_FALSE(cli_.is_socket_open());
  5457. }
  5458. TEST_F(ServerTest, MultipartFormData) {
  5459. UploadFormDataItems items = {
  5460. {"text1", "text default", "", ""},
  5461. {"text2", "aωb", "", ""},
  5462. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5463. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5464. {"file3", "", "", "application/octet-stream"},
  5465. {"file4", "", "", " application/json tmp-string "}};
  5466. auto res = cli_.Post("/multipart", items);
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::OK_200, res->status);
  5469. }
  5470. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5471. UploadFormDataItems items = {
  5472. {"text", "default text", "", ""},
  5473. {"multi_text1", "aaaaa", "", ""},
  5474. {"multi_text1", "bbbbb", "", ""},
  5475. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5476. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5477. "application/json"},
  5478. };
  5479. auto res = cli_.Post("/multipart/multi_file_values", items);
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. EXPECT_EQ(StatusCode::OK_200, res->status);
  5482. }
  5483. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5484. auto res = cli_.Get("/hi");
  5485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5486. EXPECT_EQ(StatusCode::OK_200, res->status);
  5487. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5488. EXPECT_EQ("Hello World!", res->body);
  5489. }
  5490. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5491. Request req;
  5492. req.method = "POST";
  5493. req.path = "/chunked";
  5494. std::string host_and_port;
  5495. host_and_port += HOST;
  5496. host_and_port += ":";
  5497. host_and_port += std::to_string(PORT);
  5498. req.headers.emplace("Host", host_and_port.c_str());
  5499. req.headers.emplace("Accept", "*/*");
  5500. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5501. req.headers.emplace("Content-Type", "text/plain");
  5502. req.headers.emplace("Content-Length", "0");
  5503. req.headers.emplace(
  5504. "Transfer-Encoding",
  5505. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5506. // Client does not chunk, so make a chunked body manually.
  5507. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5508. auto res = std::make_shared<Response>();
  5509. auto error = Error::Success;
  5510. auto ret = cli_.send(req, *res, error);
  5511. ASSERT_TRUE(ret);
  5512. EXPECT_EQ(StatusCode::OK_200, res->status);
  5513. }
  5514. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5515. // rather than treat them as valid lengths.
  5516. template <typename ClientT>
  5517. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5518. Request req;
  5519. req.method = "POST";
  5520. req.path = "/chunked";
  5521. std::string host_and_port;
  5522. host_and_port += HOST;
  5523. host_and_port += ":";
  5524. host_and_port += std::to_string(PORT);
  5525. req.headers.emplace("Host", host_and_port.c_str());
  5526. req.headers.emplace("Content-Length", "0");
  5527. req.headers.emplace("Transfer-Encoding", "chunked");
  5528. req.body = body;
  5529. auto res = std::make_shared<Response>();
  5530. auto error = Error::Success;
  5531. ASSERT_TRUE(cli.send(req, *res, error));
  5532. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5533. }
  5534. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5535. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5536. }
  5537. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5538. expect_chunked_body_rejected(
  5539. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5540. }
  5541. TEST_F(ServerTest, GetStreamed2) {
  5542. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5544. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5545. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5546. EXPECT_EQ(true, res->has_header("Content-Range"));
  5547. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5548. EXPECT_EQ(std::string("ab"), res->body);
  5549. }
  5550. TEST_F(ServerTest, GetStreamed) {
  5551. auto res = cli_.Get("/streamed");
  5552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5553. EXPECT_EQ(StatusCode::OK_200, res->status);
  5554. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5555. EXPECT_EQ(std::string("aaabbb"), res->body);
  5556. }
  5557. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5558. auto res = cli_.Get("/streamed-without-length",
  5559. Headers{make_range_header({{0, -1}})});
  5560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5561. EXPECT_EQ(StatusCode::OK_200, res->status);
  5562. EXPECT_EQ(false, res->has_header("Content-Length"));
  5563. EXPECT_EQ(false, res->has_header("Content-Range"));
  5564. EXPECT_EQ(std::string("abcdefg"), res->body);
  5565. }
  5566. TEST_F(ServerTest, GetStreamedWithRange1) {
  5567. auto res =
  5568. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5570. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5571. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5572. EXPECT_EQ(true, res->has_header("Content-Range"));
  5573. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5574. EXPECT_EQ(std::string("def"), res->body);
  5575. }
  5576. TEST_F(ServerTest, GetStreamedWithRange2) {
  5577. auto res =
  5578. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5580. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5581. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5582. EXPECT_EQ(true, res->has_header("Content-Range"));
  5583. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5584. EXPECT_EQ(std::string("bcdefg"), res->body);
  5585. }
  5586. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5587. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5590. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5591. EXPECT_EQ(true, res->has_header("Content-Range"));
  5592. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5593. EXPECT_EQ(std::string("efg"), res->body);
  5594. }
  5595. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5596. auto res =
  5597. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5599. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5600. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5601. EXPECT_EQ(false, res->has_header("Content-Range"));
  5602. EXPECT_EQ(0U, res->body.size());
  5603. }
  5604. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5605. // Only a 206 is served as a partial representation. Under any other status
  5606. // `apply_ranges()` reported the full content length, so the body must match
  5607. // that header, and the content provider must never be asked for an offset
  5608. // outside the representation.
  5609. auto check = [&](int status, const char *range) {
  5610. auto path =
  5611. std::string("/streamed-with-range?status=") + std::to_string(status);
  5612. auto ctx = path + " Range: " + range;
  5613. auto res = cli_.Get(path, Headers{{"Range", range}});
  5614. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5615. EXPECT_EQ(status, res->status) << ctx;
  5616. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5617. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5618. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5619. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5620. };
  5621. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5622. check(403, "bytes=3-5");
  5623. // The offset is far past the representation.
  5624. check(403, "bytes=100000-100200");
  5625. // `first_pos` is still -1 here, and the bounds asserts in
  5626. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5627. check(403, "bytes=-3");
  5628. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5629. // multipart branch would have written one that is empty.
  5630. check(403, "bytes=1-2, 4-5");
  5631. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5632. // covers the whole representation.
  5633. check(200, "bytes=3-5");
  5634. check(200, "bytes=1-2, 4-5");
  5635. }
  5636. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5637. auto res =
  5638. cli_.Get("/streamed-with-range",
  5639. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5640. "92233720368547758079223372036854775807"}});
  5641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5642. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5643. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5644. EXPECT_EQ(false, res->has_header("Content-Range"));
  5645. EXPECT_EQ(0U, res->body.size());
  5646. }
  5647. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5648. auto res = cli_.Get(
  5649. "/with-range",
  5650. Headers{{"Range",
  5651. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5652. {"Accept-Encoding", ""}});
  5653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5654. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5655. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5656. EXPECT_EQ(true, res->has_header("Content-Range"));
  5657. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5658. EXPECT_EQ(std::string("abcdefg"), res->body);
  5659. }
  5660. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5661. auto res = cli_.Get("/with-range", Headers{
  5662. {"Range", "bytes=0-"},
  5663. {"Accept-Encoding", ""},
  5664. });
  5665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5666. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5667. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5668. EXPECT_EQ(true, res->has_header("Content-Range"));
  5669. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5670. EXPECT_EQ(std::string("abcdefg"), res->body);
  5671. }
  5672. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5673. auto res = cli_.Get("/streamed-with-range",
  5674. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5676. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5677. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5678. EXPECT_EQ(false, res->has_header("Content-Range"));
  5679. EXPECT_EQ(267U, res->body.size());
  5680. // Check that both range contents are present
  5681. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5682. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5683. // Check that Content-Range headers are present for both ranges
  5684. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5685. std::string::npos);
  5686. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5687. std::string::npos);
  5688. }
  5689. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5690. Ranges ranges;
  5691. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5692. ranges.emplace_back(0, -1);
  5693. }
  5694. auto res = cli_.Get("/streamed-with-range?error",
  5695. Headers{{make_range_header(ranges)}});
  5696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5697. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5698. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5699. EXPECT_EQ(false, res->has_header("Content-Range"));
  5700. EXPECT_EQ(0U, res->body.size());
  5701. }
  5702. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5703. auto res = cli_.Get("/streamed-with-range",
  5704. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5706. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5707. EXPECT_EQ(5U, res->body.size());
  5708. // Check that overlapping ranges are coalesced into a single range
  5709. EXPECT_EQ("bcdef", res->body);
  5710. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5711. // Should be single range, not multipart
  5712. EXPECT_TRUE(res->has_header("Content-Range"));
  5713. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5714. }
  5715. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5716. auto res = cli_.Get("/streamed-with-range",
  5717. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5720. EXPECT_EQ(268U, res->body.size());
  5721. // Check that both range contents are present
  5722. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5723. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5724. // Check that Content-Range headers are present for both ranges
  5725. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5726. std::string::npos);
  5727. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5728. std::string::npos);
  5729. }
  5730. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5731. auto res = cli_.Get("/streamed-with-range",
  5732. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5734. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5735. EXPECT_EQ(269U, res->body.size());
  5736. // Check that both duplicate range contents are present
  5737. size_t first_abc = res->body.find("abc\r\n");
  5738. EXPECT_TRUE(first_abc != std::string::npos);
  5739. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5740. EXPECT_TRUE(second_abc != std::string::npos);
  5741. // Check that Content-Range headers are present for both ranges
  5742. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5743. EXPECT_TRUE(first_range != std::string::npos);
  5744. size_t second_range =
  5745. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5746. EXPECT_TRUE(second_range != std::string::npos);
  5747. }
  5748. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5749. auto res =
  5750. cli_.Get("/streamed-with-range?error",
  5751. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5753. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5754. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5755. EXPECT_EQ(false, res->has_header("Content-Range"));
  5756. EXPECT_EQ(0U, res->body.size());
  5757. }
  5758. TEST_F(ServerTest, GetStreamedEndless) {
  5759. uint64_t offset = 0;
  5760. auto res = cli_.Get("/streamed-cancel",
  5761. [&](const char * /*data*/, uint64_t data_length) {
  5762. if (offset < 100) {
  5763. offset += data_length;
  5764. return true;
  5765. }
  5766. return false;
  5767. });
  5768. ASSERT_TRUE(!res);
  5769. EXPECT_EQ(Error::Canceled, res.error());
  5770. }
  5771. TEST_F(ServerTest, ClientStop) {
  5772. std::atomic_size_t count{4};
  5773. std::vector<std::thread> threads;
  5774. for (auto i = count.load(); i != 0; --i) {
  5775. threads.emplace_back([&]() {
  5776. auto res = cli_.Get("/streamed-cancel",
  5777. [&](const char *, uint64_t) { return true; });
  5778. --count;
  5779. ASSERT_TRUE(!res);
  5780. EXPECT_TRUE(res.error() == Error::Canceled ||
  5781. res.error() == Error::Read || res.error() == Error::Write);
  5782. });
  5783. }
  5784. std::this_thread::sleep_for(std::chrono::seconds(2));
  5785. while (count != 0) {
  5786. cli_.stop();
  5787. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5788. }
  5789. for (auto &t : threads) {
  5790. t.join();
  5791. }
  5792. }
  5793. TEST_F(ServerTest, GetWithRange1) {
  5794. auto res = cli_.Get("/with-range", Headers{
  5795. make_range_header({{3, 5}}),
  5796. {"Accept-Encoding", ""},
  5797. });
  5798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5799. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5800. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5801. EXPECT_EQ(true, res->has_header("Content-Range"));
  5802. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5803. EXPECT_EQ(std::string("def"), res->body);
  5804. }
  5805. TEST_F(ServerTest, GetWithRange2) {
  5806. auto res = cli_.Get("/with-range", Headers{
  5807. make_range_header({{1, -1}}),
  5808. {"Accept-Encoding", ""},
  5809. });
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5812. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5813. EXPECT_EQ(true, res->has_header("Content-Range"));
  5814. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5815. EXPECT_EQ(std::string("bcdefg"), res->body);
  5816. }
  5817. TEST_F(ServerTest, GetWithRange3) {
  5818. auto res = cli_.Get("/with-range", Headers{
  5819. make_range_header({{0, 0}}),
  5820. {"Accept-Encoding", ""},
  5821. });
  5822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5823. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5824. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5825. EXPECT_EQ(true, res->has_header("Content-Range"));
  5826. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5827. EXPECT_EQ(std::string("a"), res->body);
  5828. }
  5829. TEST_F(ServerTest, GetWithRange4) {
  5830. auto res = cli_.Get("/with-range", Headers{
  5831. make_range_header({{-1, 2}}),
  5832. {"Accept-Encoding", ""},
  5833. });
  5834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5835. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5836. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5837. EXPECT_EQ(true, res->has_header("Content-Range"));
  5838. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5839. EXPECT_EQ(std::string("fg"), res->body);
  5840. }
  5841. TEST_F(ServerTest, GetWithRange5) {
  5842. auto res = cli_.Get("/with-range", Headers{
  5843. make_range_header({{0, 5}}),
  5844. {"Accept-Encoding", ""},
  5845. });
  5846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5847. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5848. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5849. EXPECT_EQ(true, res->has_header("Content-Range"));
  5850. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5851. EXPECT_EQ(std::string("abcdef"), res->body);
  5852. }
  5853. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5854. auto res =
  5855. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5857. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5858. }
  5859. TEST_F(ServerTest, GetWithRangeMultipart) {
  5860. auto res =
  5861. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5864. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5865. EXPECT_EQ(false, res->has_header("Content-Range"));
  5866. EXPECT_EQ(267U, res->body.size());
  5867. }
  5868. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5869. auto res = cli_.Get("/with-range",
  5870. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5872. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5873. }
  5874. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5875. auto res = cli_.Get("/with-range-customized-response",
  5876. Headers{{make_range_header({{1, 2}})}});
  5877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5878. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5879. EXPECT_EQ(true, res->has_header("Content-Length"));
  5880. EXPECT_EQ(false, res->has_header("Content-Range"));
  5881. EXPECT_EQ(JSON_DATA, res->body);
  5882. }
  5883. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5884. auto res = cli_.Get("/with-range-customized-response",
  5885. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5887. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5888. EXPECT_EQ(true, res->has_header("Content-Length"));
  5889. EXPECT_EQ(false, res->has_header("Content-Range"));
  5890. EXPECT_EQ(JSON_DATA, res->body);
  5891. }
  5892. TEST_F(ServerTest, Issue1772) {
  5893. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5895. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5896. }
  5897. TEST_F(ServerTest, Issue609) {
  5898. auto res = cli_.Delete("/issue609");
  5899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5900. EXPECT_EQ(StatusCode::OK_200, res->status);
  5901. EXPECT_EQ(std::string("ok"), res->body);
  5902. }
  5903. TEST_F(ServerTest, GetStreamedChunked) {
  5904. auto res = cli_.Get("/streamed-chunked");
  5905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5906. EXPECT_EQ(StatusCode::OK_200, res->status);
  5907. EXPECT_EQ(std::string("123456789"), res->body);
  5908. }
  5909. TEST_F(ServerTest, GetStreamedChunked2) {
  5910. auto res = cli_.Get("/streamed-chunked2");
  5911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5912. EXPECT_EQ(StatusCode::OK_200, res->status);
  5913. EXPECT_EQ(std::string("123456789"), res->body);
  5914. }
  5915. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5916. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::OK_200, res->status);
  5919. EXPECT_EQ(std::string("123456789"), res->body);
  5920. EXPECT_TRUE(res->has_header("Trailer"));
  5921. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5922. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5923. // Trailers are now stored separately from headers (security fix)
  5924. EXPECT_EQ(2U, res->trailers.size());
  5925. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5926. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5927. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5928. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5929. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5930. // Verify trailers are NOT in headers (security verification)
  5931. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5932. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5933. }
  5934. TEST_F(ServerTest, LargeChunkedPost) {
  5935. Request req;
  5936. req.method = "POST";
  5937. req.path = "/large-chunked";
  5938. std::string host_and_port;
  5939. host_and_port += HOST;
  5940. host_and_port += ":";
  5941. host_and_port += std::to_string(PORT);
  5942. req.headers.emplace("Host", host_and_port.c_str());
  5943. req.headers.emplace("Accept", "*/*");
  5944. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5945. req.headers.emplace("Content-Type", "text/plain");
  5946. req.headers.emplace("Content-Length", "0");
  5947. req.headers.emplace("Transfer-Encoding", "chunked");
  5948. std::string long_string(30 * 1024u, 'a');
  5949. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5950. // Attempt to make a large enough post to exceed OS buffers, to test that
  5951. // the server handles short reads if the full chunk data isn't available.
  5952. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5953. auto res = std::make_shared<Response>();
  5954. auto error = Error::Success;
  5955. auto ret = cli_.send(req, *res, error);
  5956. ASSERT_TRUE(ret);
  5957. EXPECT_EQ(StatusCode::OK_200, res->status);
  5958. }
  5959. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5960. auto res = cli_.Get("/remote_addr");
  5961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5962. EXPECT_EQ(StatusCode::OK_200, res->status);
  5963. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5964. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5965. }
  5966. TEST_F(ServerTest, GetMethodLocalAddr) {
  5967. auto res = cli_.Get("/local_addr");
  5968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5969. EXPECT_EQ(StatusCode::OK_200, res->status);
  5970. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5971. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5972. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5973. }
  5974. TEST_F(ServerTest, HTTPResponseSplitting) {
  5975. auto res = cli_.Get("/http_response_splitting");
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. }
  5979. TEST_F(ServerTest, SlowRequest) {
  5980. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5981. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5982. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5983. }
  5984. #if 0
  5985. TEST_F(ServerTest, SlowPost) {
  5986. char buffer[64 * 1024];
  5987. memset(buffer, 0x42, sizeof(buffer));
  5988. auto res = cli_.Post(
  5989. "/slowpost", 64 * 1024 * 1024,
  5990. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5991. auto ret = sink.write(buffer, sizeof(buffer));
  5992. EXPECT_TRUE(ret);
  5993. return true;
  5994. },
  5995. "text/plain");
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. EXPECT_EQ(StatusCode::OK_200, res->status);
  5998. }
  5999. TEST_F(ServerTest, SlowPostFail) {
  6000. char buffer[64 * 1024];
  6001. memset(buffer, 0x42, sizeof(buffer));
  6002. cli_.set_write_timeout(std::chrono::seconds(0));
  6003. auto res = cli_.Post(
  6004. "/slowpost", 64 * 1024 * 1024,
  6005. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6006. sink.write(buffer, sizeof(buffer));
  6007. return true;
  6008. },
  6009. "text/plain");
  6010. ASSERT_TRUE(!res);
  6011. EXPECT_EQ(Error::Write, res.error());
  6012. }
  6013. #endif
  6014. TEST_F(ServerTest, Put) {
  6015. auto res = cli_.Put("/put", "PUT", "text/plain");
  6016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6017. EXPECT_EQ(StatusCode::OK_200, res->status);
  6018. EXPECT_EQ("PUT", res->body);
  6019. }
  6020. TEST_F(ServerTest, PutWithContentProvider) {
  6021. auto res = cli_.Put(
  6022. "/put", 3,
  6023. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6024. sink.os << "PUT";
  6025. return true;
  6026. },
  6027. "text/plain");
  6028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6029. EXPECT_EQ(StatusCode::OK_200, res->status);
  6030. EXPECT_EQ("PUT", res->body);
  6031. }
  6032. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6033. auto res = cli_.Post(
  6034. "/post", 42,
  6035. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6036. return false;
  6037. },
  6038. "text/plain");
  6039. ASSERT_TRUE(!res);
  6040. EXPECT_EQ(Error::Canceled, res.error());
  6041. }
  6042. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6043. auto res = cli_.Put(
  6044. "/put",
  6045. [](size_t /*offset*/, DataSink &sink) {
  6046. sink.os << "PUT";
  6047. sink.done();
  6048. return true;
  6049. },
  6050. "text/plain");
  6051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6052. EXPECT_EQ(StatusCode::OK_200, res->status);
  6053. EXPECT_EQ("PUT", res->body);
  6054. }
  6055. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6056. auto res = cli_.Post(
  6057. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6058. "text/plain");
  6059. ASSERT_TRUE(!res);
  6060. EXPECT_EQ(Error::Canceled, res.error());
  6061. }
  6062. TEST_F(ServerTest, PostLoopBack) {
  6063. std::string body;
  6064. auto res = cli_.Post(
  6065. "/post-loopback", 9,
  6066. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6067. EXPECT_EQ(9u, length);
  6068. sink.write("123", 3);
  6069. sink.write("456", 3);
  6070. sink.write("789", 3);
  6071. return true;
  6072. },
  6073. "text/plain",
  6074. [&body](const char *data, size_t data_length) {
  6075. body.append(data, data_length);
  6076. return true;
  6077. });
  6078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6079. EXPECT_EQ(StatusCode::OK_200, res->status);
  6080. EXPECT_EQ("123456789", body);
  6081. }
  6082. TEST_F(ServerTest, PutLoopBack) {
  6083. std::string body;
  6084. auto res = cli_.Put(
  6085. "/put-loopback", 9,
  6086. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6087. EXPECT_EQ(9u, length);
  6088. sink.write("123", 3);
  6089. sink.write("456", 3);
  6090. sink.write("789", 3);
  6091. return true;
  6092. },
  6093. "text/plain",
  6094. [&body](const char *data, size_t data_length) {
  6095. body.append(data, data_length);
  6096. return true;
  6097. });
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::OK_200, res->status);
  6100. EXPECT_EQ("123456789", body);
  6101. }
  6102. TEST_F(ServerTest, PatchLoopBack) {
  6103. std::string body;
  6104. auto res = cli_.Patch(
  6105. "/patch-loopback", 9,
  6106. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6107. EXPECT_EQ(9u, length);
  6108. sink.write("123", 3);
  6109. sink.write("456", 3);
  6110. sink.write("789", 3);
  6111. return true;
  6112. },
  6113. "text/plain",
  6114. [&body](const char *data, size_t data_length) {
  6115. body.append(data, data_length);
  6116. return true;
  6117. });
  6118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6119. EXPECT_EQ(StatusCode::OK_200, res->status);
  6120. EXPECT_EQ("123456789", body);
  6121. }
  6122. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6123. std::string body;
  6124. auto res = cli_.Post(
  6125. "/post-loopback",
  6126. [](size_t /*offset*/, DataSink &sink) {
  6127. sink.write("123", 3);
  6128. sink.write("456", 3);
  6129. sink.write("789", 3);
  6130. sink.done();
  6131. return true;
  6132. },
  6133. "text/plain",
  6134. [&body](const char *data, size_t data_length) {
  6135. body.append(data, data_length);
  6136. return true;
  6137. });
  6138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6139. EXPECT_EQ(StatusCode::OK_200, res->status);
  6140. EXPECT_EQ("123456789", body);
  6141. }
  6142. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6143. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6144. cli_.set_compress(true);
  6145. auto res = cli_.Put(
  6146. "/put", 3,
  6147. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6148. sink.os << "PUT";
  6149. return true;
  6150. },
  6151. "text/plain");
  6152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6153. EXPECT_EQ(StatusCode::OK_200, res->status);
  6154. EXPECT_EQ("PUT", res->body);
  6155. }
  6156. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6157. cli_.set_compress(true);
  6158. auto res = cli_.Post(
  6159. "/post", 42,
  6160. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6161. return false;
  6162. },
  6163. "text/plain");
  6164. ASSERT_TRUE(!res);
  6165. EXPECT_EQ(Error::Canceled, res.error());
  6166. }
  6167. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6168. cli_.set_compress(true);
  6169. auto res = cli_.Put(
  6170. "/put",
  6171. [](size_t /*offset*/, DataSink &sink) {
  6172. sink.os << "PUT";
  6173. sink.done();
  6174. return true;
  6175. },
  6176. "text/plain");
  6177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6178. EXPECT_EQ(StatusCode::OK_200, res->status);
  6179. EXPECT_EQ("PUT", res->body);
  6180. }
  6181. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6182. cli_.set_compress(true);
  6183. auto res = cli_.Post(
  6184. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6185. "text/plain");
  6186. ASSERT_TRUE(!res);
  6187. EXPECT_EQ(Error::Canceled, res.error());
  6188. }
  6189. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6190. cli_.set_compress(true);
  6191. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. EXPECT_EQ(StatusCode::OK_200, res->status);
  6194. EXPECT_EQ(LARGE_DATA, res->body);
  6195. }
  6196. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6197. #ifdef CPPHTTPLIB_SSL_ENABLED
  6198. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6199. Client cli(s.c_str());
  6200. cli.enable_server_certificate_verification(false);
  6201. #else
  6202. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6203. Client cli(s.c_str());
  6204. #endif
  6205. cli.set_compress(true);
  6206. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6208. EXPECT_EQ(StatusCode::OK_200, res->status);
  6209. EXPECT_EQ(LARGE_DATA, res->body);
  6210. // The compressed size should be less than a 10th of the original. May vary
  6211. // depending on the zlib library.
  6212. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6213. static_cast<uint64_t>(10 * 1024 * 1024));
  6214. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6215. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6216. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6217. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6218. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6219. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6220. #endif
  6221. }
  6222. TEST_F(ServerTest, PutContentWithDeflate) {
  6223. cli_.set_compress(false);
  6224. Headers headers;
  6225. headers.emplace("Content-Encoding", "deflate");
  6226. // PUT in deflate format:
  6227. auto res = cli_.Put("/put", headers,
  6228. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6230. EXPECT_EQ(StatusCode::OK_200, res->status);
  6231. EXPECT_EQ("PUT", res->body);
  6232. }
  6233. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6234. Headers headers;
  6235. headers.emplace("Accept-Encoding", "gzip, deflate");
  6236. auto res = cli_.Get("/streamed-chunked", headers);
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. EXPECT_EQ(StatusCode::OK_200, res->status);
  6239. EXPECT_EQ(std::string("123456789"), res->body);
  6240. }
  6241. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6242. Headers headers;
  6243. headers.emplace("Accept-Encoding", "gzip, deflate");
  6244. auto res = cli_.Get("/streamed-chunked2", headers);
  6245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6246. EXPECT_EQ(StatusCode::OK_200, res->status);
  6247. EXPECT_EQ(std::string("123456789"), res->body);
  6248. }
  6249. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6250. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6252. EXPECT_EQ(StatusCode::OK_200, res->status);
  6253. }
  6254. TEST(GzipDecompressor, ChunkedDecompression) {
  6255. std::string data;
  6256. for (size_t i = 0; i < 32 * 1024; ++i) {
  6257. data.push_back(static_cast<char>('a' + i % 26));
  6258. }
  6259. std::string compressed_data;
  6260. {
  6261. httplib::detail::gzip_compressor compressor;
  6262. bool result = compressor.compress(
  6263. data.data(), data.size(),
  6264. /*last=*/true,
  6265. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6266. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6267. compressed_data_size);
  6268. return true;
  6269. });
  6270. ASSERT_TRUE(result);
  6271. }
  6272. std::string decompressed_data;
  6273. {
  6274. httplib::detail::gzip_decompressor decompressor;
  6275. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6276. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6277. size_t chunk_size = 130;
  6278. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6279. chunk_begin += chunk_size) {
  6280. size_t current_chunk_size =
  6281. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6282. bool result = decompressor.decompress(
  6283. compressed_data.data() + chunk_begin, current_chunk_size,
  6284. [&](const char *decompressed_data_chunk,
  6285. size_t decompressed_data_chunk_size) {
  6286. decompressed_data.insert(decompressed_data.size(),
  6287. decompressed_data_chunk,
  6288. decompressed_data_chunk_size);
  6289. return true;
  6290. });
  6291. ASSERT_TRUE(result);
  6292. }
  6293. }
  6294. ASSERT_EQ(data, decompressed_data);
  6295. }
  6296. TEST(GzipDecompressor, DeflateDecompression) {
  6297. std::string original_text = "Raw deflate without gzip";
  6298. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6299. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6300. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6301. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6302. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6303. std::string decompressed_data;
  6304. {
  6305. httplib::detail::gzip_decompressor decompressor;
  6306. bool result = decompressor.decompress(
  6307. compressed_data.data(), compressed_data.size(),
  6308. [&](const char *decompressed_data_chunk,
  6309. size_t decompressed_data_chunk_size) {
  6310. decompressed_data.insert(decompressed_data.size(),
  6311. decompressed_data_chunk,
  6312. decompressed_data_chunk_size);
  6313. return true;
  6314. });
  6315. ASSERT_TRUE(result);
  6316. }
  6317. ASSERT_EQ(original_text, decompressed_data);
  6318. }
  6319. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6320. std::string original_text = "Raw deflate without gzip";
  6321. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6322. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6323. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6324. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6325. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6326. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6327. std::string decompressed_data;
  6328. {
  6329. httplib::detail::gzip_decompressor decompressor;
  6330. bool result = decompressor.decompress(
  6331. compressed_data.data(), compressed_data.size(),
  6332. [&](const char *decompressed_data_chunk,
  6333. size_t decompressed_data_chunk_size) {
  6334. decompressed_data.insert(decompressed_data.size(),
  6335. decompressed_data_chunk,
  6336. decompressed_data_chunk_size);
  6337. return true;
  6338. });
  6339. ASSERT_TRUE(result);
  6340. }
  6341. ASSERT_EQ(original_text, decompressed_data);
  6342. }
  6343. #endif
  6344. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6345. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6346. Headers headers;
  6347. headers.emplace("Accept-Encoding", "br");
  6348. auto res = cli_.Get("/streamed-chunked", headers);
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. EXPECT_EQ(StatusCode::OK_200, res->status);
  6351. EXPECT_EQ(std::string("123456789"), res->body);
  6352. }
  6353. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6354. Headers headers;
  6355. headers.emplace("Accept-Encoding", "br");
  6356. auto res = cli_.Get("/streamed-chunked2", headers);
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. EXPECT_EQ(StatusCode::OK_200, res->status);
  6359. EXPECT_EQ(std::string("123456789"), res->body);
  6360. }
  6361. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6362. cli_.set_compress(true);
  6363. auto res = cli_.Put(
  6364. "/put", 3,
  6365. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6366. sink.os << "PUT";
  6367. return true;
  6368. },
  6369. "text/plain");
  6370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6371. EXPECT_EQ(StatusCode::OK_200, res->status);
  6372. EXPECT_EQ("PUT", res->body);
  6373. }
  6374. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6375. cli_.set_compress(true);
  6376. auto res = cli_.Put(
  6377. "/put",
  6378. [](size_t /*offset*/, DataSink &sink) {
  6379. sink.os << "PUT";
  6380. sink.done();
  6381. return true;
  6382. },
  6383. "text/plain");
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. EXPECT_EQ(StatusCode::OK_200, res->status);
  6386. EXPECT_EQ("PUT", res->body);
  6387. }
  6388. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6389. cli_.set_compress(true);
  6390. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. EXPECT_EQ(StatusCode::OK_200, res->status);
  6393. EXPECT_EQ(LARGE_DATA, res->body);
  6394. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6395. }
  6396. #endif
  6397. TEST_F(ServerTest, Patch) {
  6398. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::OK_200, res->status);
  6401. EXPECT_EQ("PATCH", res->body);
  6402. }
  6403. TEST_F(ServerTest, Delete) {
  6404. auto res = cli_.Delete("/delete");
  6405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6406. EXPECT_EQ(StatusCode::OK_200, res->status);
  6407. EXPECT_EQ("DELETE", res->body);
  6408. }
  6409. TEST_F(ServerTest, DeleteContentReceiver) {
  6410. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6412. EXPECT_EQ(StatusCode::OK_200, res->status);
  6413. EXPECT_EQ("content", res->body);
  6414. }
  6415. TEST_F(ServerTest, Options) {
  6416. auto res = cli_.Options("*");
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. EXPECT_EQ(StatusCode::OK_200, res->status);
  6419. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6420. EXPECT_TRUE(res->body.empty());
  6421. }
  6422. TEST_F(ServerTest, URL) {
  6423. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6425. EXPECT_EQ(StatusCode::OK_200, res->status);
  6426. }
  6427. TEST_F(ServerTest, ArrayParam) {
  6428. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. EXPECT_EQ(StatusCode::OK_200, res->status);
  6431. }
  6432. TEST_F(ServerTest, ArrayParamValues) {
  6433. auto res =
  6434. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6436. EXPECT_EQ(StatusCode::OK_200, res->status);
  6437. }
  6438. TEST_F(ServerTest, NoMultipleHeaders) {
  6439. Headers headers = {{"Content-Length", "5"}};
  6440. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6441. "text/plain");
  6442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6443. EXPECT_EQ(StatusCode::OK_200, res->status);
  6444. }
  6445. TEST_F(ServerTest, PostContentReceiver) {
  6446. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6448. ASSERT_EQ(StatusCode::OK_200, res->status);
  6449. ASSERT_EQ("content", res->body);
  6450. }
  6451. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6452. UploadFormDataItems items = {
  6453. {"text1", "text default", "", ""},
  6454. {"text2", "aωb", "", ""},
  6455. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6456. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6457. {"file3", "", "", "application/octet-stream"},
  6458. };
  6459. auto res = cli_.Post("/content_receiver", items);
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. EXPECT_EQ(StatusCode::OK_200, res->status);
  6462. }
  6463. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6464. UploadFormDataItems items = {
  6465. {"text1", "text default", "", ""},
  6466. {"text2", "aωb", "", ""},
  6467. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6468. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6469. {"file3", "", "", "application/octet-stream"},
  6470. };
  6471. auto boundary = std::string("+++++");
  6472. std::string body;
  6473. for (const auto &item : items) {
  6474. body += "--" + boundary + "\r\n";
  6475. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6476. if (!item.filename.empty()) {
  6477. body += "; filename=\"" + item.filename + "\"";
  6478. }
  6479. body += "\r\n";
  6480. if (!item.content_type.empty()) {
  6481. body += "Content-Type: " + item.content_type + "\r\n";
  6482. }
  6483. body += "\r\n";
  6484. body += item.content + "\r\n";
  6485. }
  6486. body += "--" + boundary + "--\r\n";
  6487. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6488. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. EXPECT_EQ(StatusCode::OK_200, res->status);
  6491. }
  6492. TEST(MultipartFormDataTest, FieldEscaping) {
  6493. Server svr;
  6494. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6495. const ContentReader &content_reader) {
  6496. ASSERT_TRUE(req.is_multipart_form_data());
  6497. std::vector<FormData> received;
  6498. content_reader(
  6499. [&](const FormData &file) {
  6500. received.push_back(file);
  6501. return true;
  6502. },
  6503. [&](const char *data, size_t data_length) {
  6504. received.back().content.append(data, data_length);
  6505. return true;
  6506. });
  6507. // '"', CR and LF in names and filenames are escaped following the
  6508. // WHATWG HTML standard, so each part still parses as a single part
  6509. // with no injected headers. Content types get CR/LF escaped too,
  6510. // while '"' (legal there, e.g. quoted charset) is preserved.
  6511. ASSERT_EQ(4U, received.size());
  6512. EXPECT_EQ("na%22me", received[0].name);
  6513. EXPECT_EQ("quoted name", received[0].content);
  6514. EXPECT_EQ("file", received[1].name);
  6515. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6516. received[1].filename);
  6517. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6518. EXPECT_EQ("injected", received[1].content);
  6519. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6520. EXPECT_EQ("my%22file.txt", received[2].filename);
  6521. EXPECT_EQ("cr lf name", received[2].content);
  6522. EXPECT_EQ("typed", received[3].name);
  6523. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6524. received[3].content_type);
  6525. EXPECT_EQ("typed content", received[3].content);
  6526. });
  6527. auto port = svr.bind_to_any_port("localhost");
  6528. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6529. auto se = detail::scope_exit([&] {
  6530. svr.stop();
  6531. t.join();
  6532. ASSERT_FALSE(svr.is_running());
  6533. });
  6534. svr.wait_until_ready();
  6535. Client cli("localhost", port);
  6536. UploadFormDataItems items = {
  6537. {"na\"me", "quoted name", "", ""},
  6538. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6539. "application/octet-stream"},
  6540. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6541. {"typed", "typed content", "",
  6542. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6543. };
  6544. auto res = cli.Post("/post", items);
  6545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6546. EXPECT_EQ(StatusCode::OK_200, res->status);
  6547. }
  6548. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6549. const UploadFormDataItems items = {
  6550. {"name1", "Content 1", "", ""},
  6551. {"name2", "Content 2", "file2.txt", "text/plain"},
  6552. };
  6553. Server svr;
  6554. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6555. const ContentReader &content_reader) {
  6556. ASSERT_TRUE(req.is_multipart_form_data());
  6557. std::vector<FormData> received;
  6558. content_reader(
  6559. [&](const FormData &file) {
  6560. received.push_back(file);
  6561. return true;
  6562. },
  6563. [&](const char *data, size_t data_length) {
  6564. received.back().content.append(data, data_length);
  6565. return true;
  6566. });
  6567. ASSERT_EQ(2U, received.size());
  6568. EXPECT_EQ("name1", received[0].name);
  6569. EXPECT_EQ("Content 1", received[0].content);
  6570. EXPECT_EQ("name2", received[1].name);
  6571. EXPECT_EQ("Content 2", received[1].content);
  6572. EXPECT_EQ("file2.txt", received[1].filename);
  6573. EXPECT_EQ("text/plain", received[1].content_type);
  6574. });
  6575. auto port = svr.bind_to_any_port("localhost");
  6576. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6577. auto se = detail::scope_exit([&] {
  6578. svr.stop();
  6579. t.join();
  6580. ASSERT_FALSE(svr.is_running());
  6581. });
  6582. svr.wait_until_ready();
  6583. Client cli("localhost", port);
  6584. // Whole-body serialization with a generated boundary
  6585. {
  6586. MultipartFormDataWriter writer;
  6587. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6588. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6589. writer.content_type());
  6590. auto body = writer.serialize(items);
  6591. EXPECT_EQ(body.size(), writer.content_length(items));
  6592. auto res = cli.Post("/post", body, writer.content_type());
  6593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6594. EXPECT_EQ(StatusCode::OK_200, res->status);
  6595. }
  6596. // Per-part framing with a custom boundary via a content provider
  6597. {
  6598. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6599. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6600. MultipartFormDataWriter writer("custom-boundary_123");
  6601. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6602. std::string body;
  6603. for (const auto &item : items) {
  6604. body += writer.item_begin(item);
  6605. body += item.content;
  6606. body += MultipartFormDataWriter::item_end();
  6607. }
  6608. body += writer.finish();
  6609. EXPECT_EQ(body.size(), writer.content_length(items));
  6610. auto res = cli.Post(
  6611. "/post", body.size(),
  6612. [&](size_t offset, size_t length, DataSink &sink) {
  6613. sink.write(body.data() + offset, length);
  6614. return true;
  6615. },
  6616. writer.content_type());
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. EXPECT_EQ(StatusCode::OK_200, res->status);
  6619. }
  6620. }
  6621. TEST_F(ServerTest, PostContentReceiverGzip) {
  6622. cli_.set_compress(true);
  6623. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6625. ASSERT_EQ(StatusCode::OK_200, res->status);
  6626. ASSERT_EQ("content", res->body);
  6627. }
  6628. TEST_F(ServerTest, PutContentReceiver) {
  6629. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6631. ASSERT_EQ(StatusCode::OK_200, res->status);
  6632. ASSERT_EQ("content", res->body);
  6633. }
  6634. TEST_F(ServerTest, PatchContentReceiver) {
  6635. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6637. ASSERT_EQ(StatusCode::OK_200, res->status);
  6638. ASSERT_EQ("content", res->body);
  6639. }
  6640. template <typename ClientType>
  6641. void TestWithHeadersAndContentReceiver(
  6642. ClientType &cli,
  6643. std::function<Result(ClientType &, const std::string &, const Headers &,
  6644. const std::string &, const std::string &,
  6645. ContentReceiver, DownloadProgress)>
  6646. request_func) {
  6647. Headers headers;
  6648. headers.emplace("X-Custom-Header", "test-value");
  6649. std::string received_body;
  6650. auto res = request_func(
  6651. cli, "/content_receiver", headers, "content", "application/json",
  6652. [&](const char *data, size_t data_length) {
  6653. received_body.append(data, data_length);
  6654. return true;
  6655. },
  6656. nullptr);
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::OK_200, res->status);
  6659. EXPECT_EQ("content", received_body);
  6660. }
  6661. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6662. #ifdef CPPHTTPLIB_SSL_ENABLED
  6663. using ClientT = SSLClient;
  6664. #else
  6665. using ClientT = Client;
  6666. #endif
  6667. TestWithHeadersAndContentReceiver<ClientT>(
  6668. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6669. const std::string &body, const std::string &content_type,
  6670. ContentReceiver receiver, DownloadProgress progress) {
  6671. return cli.Post(path, headers, body, content_type, receiver, progress);
  6672. });
  6673. }
  6674. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6675. #ifdef CPPHTTPLIB_SSL_ENABLED
  6676. using ClientT = SSLClient;
  6677. #else
  6678. using ClientT = Client;
  6679. #endif
  6680. TestWithHeadersAndContentReceiver<ClientT>(
  6681. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6682. const std::string &body, const std::string &content_type,
  6683. ContentReceiver receiver, DownloadProgress progress) {
  6684. return cli.Put(path, headers, body, content_type, receiver, progress);
  6685. });
  6686. }
  6687. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6688. #ifdef CPPHTTPLIB_SSL_ENABLED
  6689. using ClientT = SSLClient;
  6690. #else
  6691. using ClientT = Client;
  6692. #endif
  6693. TestWithHeadersAndContentReceiver<ClientT>(
  6694. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6695. const std::string &body, const std::string &content_type,
  6696. ContentReceiver receiver, DownloadProgress progress) {
  6697. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6698. });
  6699. }
  6700. template <typename ClientType>
  6701. void TestWithHeadersAndContentReceiverWithProgress(
  6702. ClientType &cli,
  6703. std::function<Result(ClientType &, const std::string &, const Headers &,
  6704. const std::string &, const std::string &,
  6705. ContentReceiver, DownloadProgress)>
  6706. request_func) {
  6707. Headers headers;
  6708. headers.emplace("X-Test-Header", "progress-test");
  6709. std::string received_body;
  6710. auto progress_called = false;
  6711. auto res = request_func(
  6712. cli, "/content_receiver", headers, "content", "text/plain",
  6713. [&](const char *data, size_t data_length) {
  6714. received_body.append(data, data_length);
  6715. return true;
  6716. },
  6717. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6718. progress_called = true;
  6719. return true;
  6720. });
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::OK_200, res->status);
  6723. EXPECT_EQ("content", received_body);
  6724. EXPECT_TRUE(progress_called);
  6725. }
  6726. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6727. #ifdef CPPHTTPLIB_SSL_ENABLED
  6728. using ClientT = SSLClient;
  6729. #else
  6730. using ClientT = Client;
  6731. #endif
  6732. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6733. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6734. const std::string &body, const std::string &content_type,
  6735. ContentReceiver receiver, DownloadProgress progress) {
  6736. return cli.Post(path, headers, body, content_type, receiver, progress);
  6737. });
  6738. }
  6739. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6740. #ifdef CPPHTTPLIB_SSL_ENABLED
  6741. using ClientT = SSLClient;
  6742. #else
  6743. using ClientT = Client;
  6744. #endif
  6745. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6746. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6747. const std::string &body, const std::string &content_type,
  6748. ContentReceiver receiver, DownloadProgress progress) {
  6749. return cli.Put(path, headers, body, content_type, receiver, progress);
  6750. });
  6751. }
  6752. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6753. #ifdef CPPHTTPLIB_SSL_ENABLED
  6754. using ClientT = SSLClient;
  6755. #else
  6756. using ClientT = Client;
  6757. #endif
  6758. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6759. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6760. const std::string &body, const std::string &content_type,
  6761. ContentReceiver receiver, DownloadProgress progress) {
  6762. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6763. });
  6764. }
  6765. template <typename ClientType>
  6766. void TestWithHeadersAndContentReceiverError(
  6767. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6768. const Headers &, const std::string &,
  6769. const std::string &, ContentReceiver)>
  6770. request_func) {
  6771. Headers headers;
  6772. headers.emplace("X-Error-Test", "true");
  6773. std::string received_body;
  6774. auto receiver_failed = false;
  6775. auto res =
  6776. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6777. [&](const char *data, size_t data_length) {
  6778. received_body.append(data, data_length);
  6779. receiver_failed = true;
  6780. return false;
  6781. });
  6782. ASSERT_FALSE(res);
  6783. EXPECT_TRUE(receiver_failed);
  6784. }
  6785. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6786. #ifdef CPPHTTPLIB_SSL_ENABLED
  6787. using ClientT = SSLClient;
  6788. #else
  6789. using ClientT = Client;
  6790. #endif
  6791. TestWithHeadersAndContentReceiverError<ClientT>(
  6792. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6793. const std::string &body, const std::string &content_type,
  6794. ContentReceiver receiver) {
  6795. return cli.Post(path, headers, body, content_type, receiver);
  6796. });
  6797. }
  6798. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6799. #ifdef CPPHTTPLIB_SSL_ENABLED
  6800. using ClientT = SSLClient;
  6801. #else
  6802. using ClientT = Client;
  6803. #endif
  6804. TestWithHeadersAndContentReceiverError<ClientT>(
  6805. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6806. const std::string &body, const std::string &content_type,
  6807. ContentReceiver receiver) {
  6808. return cli.Put(path, headers, body, content_type, receiver);
  6809. });
  6810. }
  6811. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6812. #ifdef CPPHTTPLIB_SSL_ENABLED
  6813. using ClientT = SSLClient;
  6814. #else
  6815. using ClientT = Client;
  6816. #endif
  6817. TestWithHeadersAndContentReceiverError<ClientT>(
  6818. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6819. const std::string &body, const std::string &content_type,
  6820. ContentReceiver receiver) {
  6821. return cli.Patch(path, headers, body, content_type, receiver);
  6822. });
  6823. }
  6824. TEST_F(ServerTest, PostQueryStringAndBody) {
  6825. auto res =
  6826. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6828. ASSERT_EQ(StatusCode::OK_200, res->status);
  6829. }
  6830. TEST_F(ServerTest, HTTP2Magic) {
  6831. Request req;
  6832. req.method = "PRI";
  6833. req.path = "*";
  6834. req.body = "SM";
  6835. auto res = std::make_shared<Response>();
  6836. auto error = Error::Success;
  6837. auto ret = cli_.send(req, *res, error);
  6838. ASSERT_TRUE(ret);
  6839. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6840. }
  6841. TEST_F(ServerTest, KeepAlive) {
  6842. auto res = cli_.Get("/hi");
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. EXPECT_EQ(StatusCode::OK_200, res->status);
  6845. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6846. EXPECT_EQ("Hello World!", res->body);
  6847. res = cli_.Get("/hi");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::OK_200, res->status);
  6850. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6851. EXPECT_EQ("Hello World!", res->body);
  6852. res = cli_.Get("/hi");
  6853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6854. EXPECT_EQ(StatusCode::OK_200, res->status);
  6855. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6856. EXPECT_EQ("Hello World!", res->body);
  6857. res = cli_.Get("/not-exist");
  6858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6860. res = cli_.Post("/empty", "", "text/plain");
  6861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6862. EXPECT_EQ(StatusCode::OK_200, res->status);
  6863. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6864. EXPECT_EQ("empty", res->body);
  6865. EXPECT_EQ("close", res->get_header_value("Connection"));
  6866. res = cli_.Post(
  6867. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6868. "text/plain");
  6869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6870. EXPECT_EQ(StatusCode::OK_200, res->status);
  6871. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6872. EXPECT_EQ("empty", res->body);
  6873. cli_.set_keep_alive(false);
  6874. res = cli_.Get("/last-request");
  6875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6876. EXPECT_EQ(StatusCode::OK_200, res->status);
  6877. EXPECT_EQ("close", res->get_header_value("Connection"));
  6878. }
  6879. TEST_F(ServerTest, TooManyRedirect) {
  6880. cli_.set_follow_location(true);
  6881. auto res = cli_.Get("/redirect/0");
  6882. ASSERT_TRUE(!res);
  6883. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6884. }
  6885. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6886. Request req;
  6887. req.method = "FOOBAR";
  6888. req.path = "/hi";
  6889. cli_.set_keep_alive(true);
  6890. auto res = cli_.send(req);
  6891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6892. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6893. EXPECT_EQ("close", res->get_header_value("Connection"));
  6894. EXPECT_FALSE(cli_.is_socket_open());
  6895. }
  6896. TEST_F(ServerTest, CustomRouteReadsBody) {
  6897. const std::string xml =
  6898. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  6899. Request req;
  6900. req.method = "PROPFIND";
  6901. req.path = "/dav/dir";
  6902. req.set_header("Depth", "1");
  6903. req.body = xml;
  6904. auto res = cli_.send(req);
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6907. EXPECT_EQ(xml, res->body);
  6908. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  6909. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  6910. }
  6911. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  6912. Request req;
  6913. req.method = "PROPFIND";
  6914. req.path = "/dav/42";
  6915. auto res = cli_.send(req);
  6916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6917. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6918. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  6919. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  6920. }
  6921. TEST_F(ServerTest, CustomRouteRegexPattern) {
  6922. Request req;
  6923. req.method = "PROPFIND";
  6924. req.path = "/dav-re/123";
  6925. auto res = cli_.send(req);
  6926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6927. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6928. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  6929. }
  6930. TEST_F(ServerTest, CustomRouteWithoutBody) {
  6931. Request req;
  6932. req.method = "MKCOL";
  6933. req.path = "/dav-mkcol";
  6934. auto res = cli_.send(req);
  6935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6936. EXPECT_EQ(StatusCode::Created_201, res->status);
  6937. }
  6938. TEST_F(ServerTest, CustomRouteWithContentReader) {
  6939. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  6940. Request req;
  6941. req.method = "REPORT";
  6942. req.path = "/dav-report";
  6943. req.body = xml;
  6944. auto res = cli_.send(req);
  6945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6946. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6947. EXPECT_EQ(xml, res->body);
  6948. }
  6949. // A content reader route must fire even when the request carries no body,
  6950. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  6951. // Without that, a body-less PROPFIND-style request would fall through to 404.
  6952. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  6953. Request req;
  6954. req.method = "REPORT";
  6955. req.path = "/dav-report";
  6956. auto res = cli_.send(req);
  6957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6958. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6959. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  6960. }
  6961. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  6962. Request req;
  6963. req.method = "PROPFIND";
  6964. req.path = "/not-dav";
  6965. auto res = cli_.send(req);
  6966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6967. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6968. }
  6969. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  6970. Request req;
  6971. req.method = "UNLOCK";
  6972. req.path = "/dav/dir";
  6973. cli_.set_keep_alive(true);
  6974. auto res = cli_.send(req);
  6975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6976. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6977. EXPECT_EQ("close", res->get_header_value("Connection"));
  6978. EXPECT_FALSE(cli_.is_socket_open());
  6979. }
  6980. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  6981. // The mount point serves this path, but only for GET and HEAD.
  6982. auto get_res = cli_.Get("/dir/index.html");
  6983. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  6984. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  6985. Request req;
  6986. req.method = "PROPFIND";
  6987. req.path = "/dir/index.html";
  6988. auto res = cli_.send(req);
  6989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6990. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6991. }
  6992. TEST_F(ServerTest, CustomRouteKeepAlive) {
  6993. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  6994. cli_.set_keep_alive(true);
  6995. for (auto i = 0; i < 2; i++) {
  6996. Request req;
  6997. req.method = "PROPFIND";
  6998. req.path = "/dav/dir";
  6999. req.body = xml;
  7000. auto res = cli_.send(req);
  7001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7002. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7003. EXPECT_EQ(xml, res->body);
  7004. EXPECT_TRUE(cli_.is_socket_open());
  7005. }
  7006. // A built-in method must still be served on the same connection.
  7007. cli_.set_keep_alive(false);
  7008. auto res = cli_.Get("/hi");
  7009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7010. EXPECT_EQ(StatusCode::OK_200, res->status);
  7011. EXPECT_EQ("close", res->get_header_value("Connection"));
  7012. }
  7013. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7014. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7015. Request req;
  7016. req.method = "PROPFIND";
  7017. req.path = "/dav/dir";
  7018. req.set_header("Expect", "100-continue");
  7019. req.body = xml;
  7020. auto res = cli_.send(req);
  7021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7022. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7023. EXPECT_EQ(xml, res->body);
  7024. }
  7025. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7026. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7027. TEST_F(ServerTest, Gzip) {
  7028. Headers headers;
  7029. headers.emplace("Accept-Encoding", "gzip, deflate");
  7030. auto res = cli_.Get("/compress", headers);
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7033. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7034. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7035. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7036. "7890123456789012345678901234567890",
  7037. res->body);
  7038. EXPECT_EQ(StatusCode::OK_200, res->status);
  7039. }
  7040. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7041. Headers headers;
  7042. headers.emplace("Accept-Encoding", "gzip, deflate");
  7043. auto res = cli_.Get("/compress-with-charset", headers);
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7046. EXPECT_EQ("application/json; charset=utf-8",
  7047. res->get_header_value("Content-Type"));
  7048. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7049. "7890123456789012345678901234567890",
  7050. res->body);
  7051. EXPECT_EQ(StatusCode::OK_200, res->status);
  7052. }
  7053. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7054. Headers headers;
  7055. headers.emplace("Accept-Encoding", "");
  7056. auto res = cli_.Get("/compress", headers);
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7059. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7060. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7061. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7062. "7890123456789012345678901234567890",
  7063. res->body);
  7064. EXPECT_EQ(StatusCode::OK_200, res->status);
  7065. }
  7066. TEST_F(ServerTest, GzipWithContentReceiver) {
  7067. Headers headers;
  7068. headers.emplace("Accept-Encoding", "gzip, deflate");
  7069. std::string body;
  7070. auto res = cli_.Get("/compress", headers,
  7071. [&](const char *data, uint64_t data_length) {
  7072. EXPECT_EQ(100U, data_length);
  7073. body.append(data, data_length);
  7074. return true;
  7075. });
  7076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7077. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7079. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7080. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7081. "7890123456789012345678901234567890",
  7082. body);
  7083. EXPECT_EQ(StatusCode::OK_200, res->status);
  7084. }
  7085. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7086. Headers headers;
  7087. headers.emplace("Accept-Encoding", "gzip, deflate");
  7088. cli_.set_decompress(false);
  7089. auto res = cli_.Get("/compress", headers);
  7090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7091. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7092. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7093. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7094. EXPECT_EQ(33U, res->body.size());
  7095. EXPECT_EQ(StatusCode::OK_200, res->status);
  7096. }
  7097. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7098. Headers headers;
  7099. headers.emplace("Accept-Encoding", "");
  7100. std::string body;
  7101. auto res = cli_.Get("/compress", headers,
  7102. [&](const char *data, uint64_t data_length) {
  7103. EXPECT_EQ(100U, data_length);
  7104. body.append(data, data_length);
  7105. return true;
  7106. });
  7107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7108. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7109. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7110. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7111. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7112. "7890123456789012345678901234567890",
  7113. body);
  7114. EXPECT_EQ(StatusCode::OK_200, res->status);
  7115. }
  7116. TEST_F(ServerTest, NoGzip) {
  7117. Headers headers;
  7118. headers.emplace("Accept-Encoding", "gzip, deflate");
  7119. auto res = cli_.Get("/nocompress", headers);
  7120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7121. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7122. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7123. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7124. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7125. "7890123456789012345678901234567890",
  7126. res->body);
  7127. EXPECT_EQ(StatusCode::OK_200, res->status);
  7128. }
  7129. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7130. Headers headers;
  7131. headers.emplace("Accept-Encoding", "gzip, deflate");
  7132. std::string body;
  7133. auto res = cli_.Get("/nocompress", headers,
  7134. [&](const char *data, uint64_t data_length) {
  7135. EXPECT_EQ(100U, data_length);
  7136. body.append(data, data_length);
  7137. return true;
  7138. });
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7141. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7142. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7143. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7144. "7890123456789012345678901234567890",
  7145. body);
  7146. EXPECT_EQ(StatusCode::OK_200, res->status);
  7147. }
  7148. TEST_F(ServerTest, MultipartFormDataGzip) {
  7149. UploadFormDataItems items = {
  7150. {"key1", "test", "", ""},
  7151. {"key2", "--abcdefg123", "", ""},
  7152. };
  7153. cli_.set_compress(true);
  7154. auto res = cli_.Post("/compress-multipart", items);
  7155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7156. EXPECT_EQ(StatusCode::OK_200, res->status);
  7157. }
  7158. #endif
  7159. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7160. TEST_F(ServerTest, Brotli) {
  7161. Headers headers;
  7162. headers.emplace("Accept-Encoding", "br");
  7163. auto res = cli_.Get("/compress", headers);
  7164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7165. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7167. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7168. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7169. "7890123456789012345678901234567890",
  7170. res->body);
  7171. EXPECT_EQ(StatusCode::OK_200, res->status);
  7172. }
  7173. #endif
  7174. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7175. TEST_F(ServerTest, Zstd) {
  7176. Headers headers;
  7177. headers.emplace("Accept-Encoding", "zstd");
  7178. auto res = cli_.Get("/compress", headers);
  7179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7180. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7181. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7182. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7183. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7184. "7890123456789012345678901234567890",
  7185. res->body);
  7186. EXPECT_EQ(StatusCode::OK_200, res->status);
  7187. }
  7188. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7189. Headers headers;
  7190. headers.emplace("Accept-Encoding", "");
  7191. auto res = cli_.Get("/compress", headers);
  7192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7193. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7194. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7195. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7196. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7197. "7890123456789012345678901234567890",
  7198. res->body);
  7199. EXPECT_EQ(StatusCode::OK_200, res->status);
  7200. }
  7201. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7202. Headers headers;
  7203. headers.emplace("Accept-Encoding", "zstd");
  7204. std::string body;
  7205. auto res = cli_.Get("/compress", headers,
  7206. [&](const char *data, uint64_t data_length) {
  7207. EXPECT_EQ(100U, data_length);
  7208. body.append(data, data_length);
  7209. return true;
  7210. });
  7211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7212. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7214. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7215. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7216. "7890123456789012345678901234567890",
  7217. body);
  7218. EXPECT_EQ(StatusCode::OK_200, res->status);
  7219. }
  7220. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7221. Headers headers;
  7222. headers.emplace("Accept-Encoding", "zstd");
  7223. cli_.set_decompress(false);
  7224. auto res = cli_.Get("/compress", headers);
  7225. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7226. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7227. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7228. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7230. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7231. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7232. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7233. EXPECT_EQ(StatusCode::OK_200, res->status);
  7234. ASSERT_EQ(26U, res->body.size());
  7235. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7236. 0);
  7237. }
  7238. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7239. Headers headers;
  7240. headers.emplace("Accept-Encoding", "");
  7241. std::string body;
  7242. auto res = cli_.Get("/compress", headers,
  7243. [&](const char *data, uint64_t data_length) {
  7244. EXPECT_EQ(100U, data_length);
  7245. body.append(data, data_length);
  7246. return true;
  7247. });
  7248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7249. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7250. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7251. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7252. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7253. "7890123456789012345678901234567890",
  7254. body);
  7255. EXPECT_EQ(StatusCode::OK_200, res->status);
  7256. }
  7257. TEST_F(ServerTest, NoZstd) {
  7258. Headers headers;
  7259. headers.emplace("Accept-Encoding", "zstd");
  7260. auto res = cli_.Get("/nocompress", headers);
  7261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7262. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7263. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7264. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7265. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7266. "7890123456789012345678901234567890",
  7267. res->body);
  7268. EXPECT_EQ(StatusCode::OK_200, res->status);
  7269. }
  7270. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7271. Headers headers;
  7272. headers.emplace("Accept-Encoding", "zstd");
  7273. std::string body;
  7274. auto res = cli_.Get("/nocompress", headers,
  7275. [&](const char *data, uint64_t data_length) {
  7276. EXPECT_EQ(100U, data_length);
  7277. body.append(data, data_length);
  7278. return true;
  7279. });
  7280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7281. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7282. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7283. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7284. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7285. "7890123456789012345678901234567890",
  7286. body);
  7287. EXPECT_EQ(StatusCode::OK_200, res->status);
  7288. }
  7289. // TODO: How to enable zstd ??
  7290. TEST_F(ServerTest, MultipartFormDataZstd) {
  7291. UploadFormDataItems items = {
  7292. {"key1", "test", "", ""},
  7293. {"key2", "--abcdefg123", "", ""},
  7294. };
  7295. Headers headers;
  7296. headers.emplace("Accept-Encoding", "zstd");
  7297. cli_.set_compress(true);
  7298. auto res = cli_.Post("/compress-multipart", headers, items);
  7299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7300. EXPECT_EQ(StatusCode::OK_200, res->status);
  7301. }
  7302. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7303. Headers headers;
  7304. headers.emplace("Accept-Encoding", "zstd");
  7305. cli_.set_compress(true);
  7306. auto res = cli_.Put(
  7307. "/put", headers, 3,
  7308. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7309. sink.os << "PUT";
  7310. return true;
  7311. },
  7312. "text/plain");
  7313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7314. EXPECT_EQ(StatusCode::OK_200, res->status);
  7315. EXPECT_EQ("PUT", res->body);
  7316. }
  7317. // Pre-compression logging tests
  7318. TEST_F(ServerTest, PreCompressionLogging) {
  7319. // Test data for compression (matches the actual /compress endpoint content)
  7320. const std::string test_content =
  7321. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7322. "3456789012345678901234567890";
  7323. // Variables to capture logging data
  7324. std::string pre_compression_body;
  7325. std::string pre_compression_content_type;
  7326. std::string pre_compression_content_encoding;
  7327. std::string post_compression_body;
  7328. std::string post_compression_content_type;
  7329. std::string post_compression_content_encoding;
  7330. // Set up pre-compression logger
  7331. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7332. const Response &res) {
  7333. pre_compression_body = res.body;
  7334. pre_compression_content_type = res.get_header_value("Content-Type");
  7335. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7336. });
  7337. // Set up post-compression logger
  7338. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7339. post_compression_body = res.body;
  7340. post_compression_content_type = res.get_header_value("Content-Type");
  7341. post_compression_content_encoding =
  7342. res.get_header_value("Content-Encoding");
  7343. });
  7344. // Test with gzip compression
  7345. Headers headers;
  7346. headers.emplace("Accept-Encoding", "gzip");
  7347. auto res = cli_.Get("/compress", headers);
  7348. // Verify response was compressed
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. EXPECT_EQ(StatusCode::OK_200, res->status);
  7351. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7352. // Verify pre-compression logger captured uncompressed content
  7353. EXPECT_EQ(test_content, pre_compression_body);
  7354. EXPECT_EQ("text/plain", pre_compression_content_type);
  7355. EXPECT_TRUE(pre_compression_content_encoding
  7356. .empty()); // No encoding header before compression
  7357. // Verify post-compression logger captured compressed content
  7358. EXPECT_NE(test_content,
  7359. post_compression_body); // Should be different after compression
  7360. EXPECT_EQ("text/plain", post_compression_content_type);
  7361. EXPECT_EQ("gzip", post_compression_content_encoding);
  7362. // Verify compressed content is smaller
  7363. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7364. }
  7365. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7366. const std::string test_content =
  7367. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7368. "3456789012345678901234567890";
  7369. std::string pre_compression_body;
  7370. std::string post_compression_body;
  7371. svr_.set_pre_compression_logger(
  7372. [&](const Request & /*req*/, const Response &res) {
  7373. pre_compression_body = res.body;
  7374. });
  7375. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7376. post_compression_body = res.body;
  7377. });
  7378. Headers headers;
  7379. headers.emplace("Accept-Encoding", "br");
  7380. auto res = cli_.Get("/compress", headers);
  7381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7382. EXPECT_EQ(StatusCode::OK_200, res->status);
  7383. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7384. // Verify pre-compression content is uncompressed
  7385. EXPECT_EQ(test_content, pre_compression_body);
  7386. // Verify post-compression content is compressed
  7387. EXPECT_NE(test_content, post_compression_body);
  7388. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7389. }
  7390. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7391. const std::string test_content =
  7392. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7393. "3456789012345678901234567890";
  7394. std::string pre_compression_body;
  7395. std::string post_compression_body;
  7396. svr_.set_pre_compression_logger(
  7397. [&](const Request & /*req*/, const Response &res) {
  7398. pre_compression_body = res.body;
  7399. });
  7400. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7401. post_compression_body = res.body;
  7402. });
  7403. // Request without compression (use /nocompress endpoint)
  7404. Headers headers;
  7405. auto res = cli_.Get("/nocompress", headers);
  7406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7407. EXPECT_EQ(StatusCode::OK_200, res->status);
  7408. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7409. // Pre-compression logger should not be called when no compression is applied
  7410. EXPECT_TRUE(
  7411. pre_compression_body.empty()); // Pre-compression logger not called
  7412. EXPECT_EQ(
  7413. test_content,
  7414. post_compression_body); // Post-compression logger captures final content
  7415. }
  7416. TEST_F(ServerTest, LoggerSeesContentLength) {
  7417. size_t logged_content_length = 0;
  7418. std::string logged_content_length_header;
  7419. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7420. logged_content_length = res.content_length_;
  7421. logged_content_length_header = res.get_header_value("Content-Length");
  7422. });
  7423. auto res = cli_.Get("/nocompress");
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. EXPECT_EQ(res->body.size(), logged_content_length);
  7427. EXPECT_EQ(std::to_string(logged_content_length),
  7428. logged_content_length_header);
  7429. }
  7430. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7431. const std::string test_content =
  7432. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7433. "3456789012345678901234567890";
  7434. std::string pre_compression_body;
  7435. bool pre_logger_called = false;
  7436. // Set only pre-compression logger
  7437. svr_.set_pre_compression_logger(
  7438. [&](const Request & /*req*/, const Response &res) {
  7439. pre_compression_body = res.body;
  7440. pre_logger_called = true;
  7441. });
  7442. Headers headers;
  7443. headers.emplace("Accept-Encoding", "gzip");
  7444. auto res = cli_.Get("/compress", headers);
  7445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7446. EXPECT_EQ(StatusCode::OK_200, res->status);
  7447. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7448. // Verify pre-compression logger was called
  7449. EXPECT_TRUE(pre_logger_called);
  7450. EXPECT_EQ(test_content, pre_compression_body);
  7451. }
  7452. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7453. {
  7454. // Test with Expect: 100-continue header - success case
  7455. // Server returns 100 Continue, client sends body, server returns 200 OK
  7456. Request req;
  7457. req.method = "POST";
  7458. req.path = "/post-large";
  7459. req.set_header("Expect", "100-continue");
  7460. req.body = LARGE_DATA;
  7461. Response res;
  7462. auto error = Error::Success;
  7463. cli_.set_keep_alive(true);
  7464. auto ret = cli_.send(req, res, error);
  7465. EXPECT_TRUE(ret);
  7466. EXPECT_EQ(StatusCode::OK_200, res.status);
  7467. EXPECT_EQ(LARGE_DATA, res.body);
  7468. }
  7469. {
  7470. // Test with Expect: 100-continue header - error case
  7471. // Client should not send the body when server returns an error
  7472. Request req;
  7473. req.method = "POST";
  7474. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7475. req.set_header("Expect", "100-continue");
  7476. req.body = LARGE_DATA;
  7477. Response res;
  7478. auto error = Error::Success;
  7479. auto start = std::chrono::high_resolution_clock::now();
  7480. cli_.set_keep_alive(true);
  7481. auto ret = cli_.send(req, res, error);
  7482. auto end = std::chrono::high_resolution_clock::now();
  7483. auto elapsed =
  7484. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7485. .count();
  7486. // With Expect: 100-continue, request completes successfully but with error
  7487. EXPECT_TRUE(ret);
  7488. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7489. EXPECT_EQ("close", res.get_header_value("Connection"));
  7490. EXPECT_FALSE(cli_.is_socket_open());
  7491. EXPECT_LE(elapsed, 2000);
  7492. }
  7493. {
  7494. // Send an extra GET request to ensure error recovery without hanging
  7495. Request req;
  7496. req.method = "GET";
  7497. req.path = "/hi";
  7498. auto start = std::chrono::high_resolution_clock::now();
  7499. auto res = cli_.send(req);
  7500. auto end = std::chrono::high_resolution_clock::now();
  7501. auto elapsed =
  7502. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7503. .count();
  7504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7505. EXPECT_EQ(StatusCode::OK_200, res->status);
  7506. EXPECT_EQ("Hello World!", res->body);
  7507. EXPECT_LE(elapsed, 500);
  7508. }
  7509. }
  7510. TEST(ZstdDecompressor, ChunkedDecompression) {
  7511. std::string data;
  7512. for (size_t i = 0; i < 32 * 1024; ++i) {
  7513. data.push_back(static_cast<char>('a' + i % 26));
  7514. }
  7515. std::string compressed_data;
  7516. {
  7517. httplib::detail::zstd_compressor compressor;
  7518. bool result = compressor.compress(
  7519. data.data(), data.size(),
  7520. /*last=*/true,
  7521. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7522. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7523. compressed_data_size);
  7524. return true;
  7525. });
  7526. ASSERT_TRUE(result);
  7527. }
  7528. std::string decompressed_data;
  7529. {
  7530. httplib::detail::zstd_decompressor decompressor;
  7531. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7532. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7533. size_t chunk_size = 130;
  7534. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7535. chunk_begin += chunk_size) {
  7536. size_t current_chunk_size =
  7537. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7538. bool result = decompressor.decompress(
  7539. compressed_data.data() + chunk_begin, current_chunk_size,
  7540. [&](const char *decompressed_data_chunk,
  7541. size_t decompressed_data_chunk_size) {
  7542. decompressed_data.insert(decompressed_data.size(),
  7543. decompressed_data_chunk,
  7544. decompressed_data_chunk_size);
  7545. return true;
  7546. });
  7547. ASSERT_TRUE(result);
  7548. }
  7549. }
  7550. ASSERT_EQ(data, decompressed_data);
  7551. }
  7552. TEST(ZstdDecompressor, Decompress) {
  7553. std::string original_text = "Compressed with ZSTD";
  7554. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7555. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7556. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7557. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7558. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7559. std::string decompressed_data;
  7560. {
  7561. httplib::detail::zstd_decompressor decompressor;
  7562. bool result = decompressor.decompress(
  7563. compressed_data.data(), compressed_data.size(),
  7564. [&](const char *decompressed_data_chunk,
  7565. size_t decompressed_data_chunk_size) {
  7566. decompressed_data.insert(decompressed_data.size(),
  7567. decompressed_data_chunk,
  7568. decompressed_data_chunk_size);
  7569. return true;
  7570. });
  7571. ASSERT_TRUE(result);
  7572. }
  7573. ASSERT_EQ(original_text, decompressed_data);
  7574. }
  7575. #endif
  7576. // Sends a raw request to a server listening at HOST:PORT, writing it in
  7577. // separate chunks so that the server sees each part in its own read(). Used to
  7578. // place a read boundary at a specific offset of a request body.
  7579. static bool send_request_in_parts(time_t read_timeout_sec,
  7580. const std::vector<std::string> &parts,
  7581. std::string *resp = nullptr,
  7582. int port = PORT) {
  7583. auto error = Error::Success;
  7584. auto client_sock = detail::create_client_socket(
  7585. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7586. /*connection_timeout_sec=*/5, 0,
  7587. /*read_timeout_sec=*/5, 0,
  7588. /*write_timeout_sec=*/5, 0, std::string(), error);
  7589. if (client_sock == INVALID_SOCKET) { return false; }
  7590. auto ret = detail::process_client_socket(
  7591. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7592. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7593. for (size_t i = 0; i < parts.size(); i++) {
  7594. const auto &part = parts[i];
  7595. if (part.size() !=
  7596. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  7597. return false;
  7598. }
  7599. if (i + 1 < parts.size()) {
  7600. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7601. }
  7602. }
  7603. char buf[512];
  7604. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7605. while (line_reader.getline()) {
  7606. if (resp) { *resp += line_reader.ptr(); }
  7607. }
  7608. return true;
  7609. });
  7610. detail::close_socket(client_sock);
  7611. return ret;
  7612. }
  7613. // Sends a raw request to a server listening at HOST:PORT.
  7614. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7615. std::string *resp = nullptr, int port = PORT) {
  7616. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  7617. }
  7618. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7619. Server svr;
  7620. std::string header_value;
  7621. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7622. header_value = req.get_header_value("foo");
  7623. res.set_content("ok", "text/plain");
  7624. });
  7625. thread t = thread([&] { svr.listen(HOST, PORT); });
  7626. auto se = detail::scope_exit([&] {
  7627. svr.stop();
  7628. t.join();
  7629. ASSERT_FALSE(svr.is_running());
  7630. });
  7631. svr.wait_until_ready();
  7632. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7633. // like characters are not treated the same - use vertical tab and escape.
  7634. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7635. "foo: \t \v bar \x1B\t \r\n"
  7636. "Connection: close\r\n"
  7637. "\r\n";
  7638. std::string res;
  7639. ASSERT_TRUE(send_request(5, req, &res));
  7640. EXPECT_EQ(header_value, "");
  7641. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7642. }
  7643. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7644. Server svr;
  7645. std::string received;
  7646. svr.Get("/order", [&](const Request &req, Response &res) {
  7647. received = entries_to_string(req.headers);
  7648. res.set_content("ok", "text/plain");
  7649. });
  7650. auto port = svr.bind_to_any_port(HOST);
  7651. thread t = thread([&] { svr.listen_after_bind(); });
  7652. auto se = detail::scope_exit([&] {
  7653. svr.stop();
  7654. t.join();
  7655. ASSERT_FALSE(svr.is_running());
  7656. });
  7657. svr.wait_until_ready();
  7658. const std::string req = "GET /order HTTP/1.1\r\n"
  7659. "X-First: 1\r\n"
  7660. "X-Dup: a\r\n"
  7661. "X-Second: 2\r\n"
  7662. "X-Dup: b\r\n"
  7663. "Connection: close\r\n"
  7664. "\r\n";
  7665. std::string res;
  7666. ASSERT_TRUE(send_request(5, req, &res, port));
  7667. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7668. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7669. }
  7670. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7671. Server svr;
  7672. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7673. res.set_header("Set-Cookie", "first=1");
  7674. res.set_header("X-Between", "y");
  7675. res.set_header("Set-Cookie", "second=2");
  7676. res.set_content("ok", "text/plain");
  7677. });
  7678. auto port = svr.bind_to_any_port(HOST);
  7679. thread t = thread([&] { svr.listen_after_bind(); });
  7680. auto se = detail::scope_exit([&] {
  7681. svr.stop();
  7682. t.join();
  7683. ASSERT_FALSE(svr.is_running());
  7684. });
  7685. svr.wait_until_ready();
  7686. Client cli(HOST, port);
  7687. auto res = cli.Get("/cookies");
  7688. ASSERT_TRUE(res);
  7689. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7690. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7691. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7692. }
  7693. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7694. Server svr;
  7695. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7696. auto i = new int(0);
  7697. res.set_header("Trailer", "X-Safe, X-Reflected");
  7698. res.set_chunked_content_provider(
  7699. "text/plain",
  7700. [i](size_t /*offset*/, DataSink &sink) {
  7701. if (*i == 0) {
  7702. sink.os << "body";
  7703. } else {
  7704. Headers trailer;
  7705. // A valid trailer that must survive.
  7706. trailer.emplace("X-Safe", "safe");
  7707. // Attacker-controlled value carrying CR/LF (response splitting).
  7708. trailer.emplace("X-Reflected",
  7709. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7710. // Attacker-controlled name carrying CR/LF.
  7711. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7712. sink.done_with_trailer(trailer);
  7713. }
  7714. (*i)++;
  7715. return true;
  7716. },
  7717. [i](bool /*success*/) { delete i; });
  7718. });
  7719. thread t = thread([&] { svr.listen(HOST, PORT); });
  7720. auto se = detail::scope_exit([&] {
  7721. svr.stop();
  7722. t.join();
  7723. ASSERT_FALSE(svr.is_running());
  7724. });
  7725. svr.wait_until_ready();
  7726. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7727. "Host: " + HOST +
  7728. "\r\n"
  7729. "Connection: close\r\n"
  7730. "\r\n";
  7731. std::string res;
  7732. ASSERT_TRUE(send_request(5, req, &res));
  7733. // The injected fields must not appear anywhere in the raw response.
  7734. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7735. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7736. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7737. // Invalid trailers are dropped entirely, matching set_header().
  7738. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7739. // The valid trailer still passes through.
  7740. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7741. }
  7742. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7743. Server svr;
  7744. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7745. // res.headers is a public field an application can populate directly,
  7746. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7747. // A valid header that must survive.
  7748. res.headers.emplace("X-Safe", "safe");
  7749. // Attacker-controlled value carrying CR/LF (response splitting).
  7750. res.headers.emplace("X-Reflected",
  7751. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7752. // Attacker-controlled name carrying CR/LF.
  7753. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7754. res.set_content("body", "text/plain");
  7755. });
  7756. thread t = thread([&] { svr.listen(HOST, PORT); });
  7757. auto se = detail::scope_exit([&] {
  7758. svr.stop();
  7759. t.join();
  7760. ASSERT_FALSE(svr.is_running());
  7761. });
  7762. svr.wait_until_ready();
  7763. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7764. "Host: " + HOST +
  7765. "\r\n"
  7766. "Connection: close\r\n"
  7767. "\r\n";
  7768. std::string res;
  7769. ASSERT_TRUE(send_request(5, req, &res));
  7770. // The injected fields must not appear anywhere in the raw response.
  7771. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7772. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7773. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7774. // Invalid headers are dropped entirely, matching set_header().
  7775. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7776. // The valid header still passes through.
  7777. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7778. }
  7779. // Forward declaration: in split builds split.py strips `inline` and moves the
  7780. // definition into httplib.cc, so detail::write_request_line is not visible from
  7781. // the public httplib.h. Re-declaring it here lets the tests link against the
  7782. // symbol in both header-only and split builds.
  7783. namespace httplib {
  7784. namespace detail {
  7785. ssize_t write_request_line(Stream &strm, const std::string &method,
  7786. const std::string &path);
  7787. } // namespace detail
  7788. } // namespace httplib
  7789. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7790. // A well-formed target is written verbatim.
  7791. {
  7792. detail::BufferStream strm;
  7793. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7794. EXPECT_GT(n, 0);
  7795. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7796. }
  7797. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7798. // otherwise it splits the request line and injects a header or a whole
  7799. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7800. // when path encoding is disabled.
  7801. const std::string evil_targets[] = {
  7802. "/a\r\nInjected: pwned",
  7803. "/a\rInjected",
  7804. "/a\nInjected",
  7805. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7806. };
  7807. for (const auto &evil : evil_targets) {
  7808. detail::BufferStream strm;
  7809. auto n = detail::write_request_line(strm, "GET", evil);
  7810. EXPECT_LT(n, 0);
  7811. EXPECT_TRUE(strm.get_buffer().empty());
  7812. }
  7813. }
  7814. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7815. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7816. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7817. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7818. // client must fail cleanly with Error::Write instead of putting a
  7819. // request-line-less, header-injecting request on the wire.
  7820. Server svr;
  7821. svr.Get("/a", [](const Request &, Response &res) {
  7822. res.set_content("ok", "text/plain");
  7823. });
  7824. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7825. auto se = detail::scope_exit([&] {
  7826. svr.stop();
  7827. thread.join();
  7828. ASSERT_FALSE(svr.is_running());
  7829. });
  7830. svr.wait_until_ready();
  7831. {
  7832. Client cli(HOST, PORT);
  7833. cli.set_path_encode(false);
  7834. // The request is rejected before anything is written, so the connection
  7835. // stays silent and the subsequent response read would otherwise block for
  7836. // the full default read timeout. Shorten it -- the assertion is on the
  7837. // error, not the timeout.
  7838. cli.set_read_timeout(1, 0);
  7839. auto res = cli.Get("/a\r\nInjected: pwned");
  7840. EXPECT_FALSE(res);
  7841. EXPECT_EQ(Error::Write, res.error());
  7842. }
  7843. }
  7844. // Sends a raw request and verifies that there isn't a crash or exception.
  7845. static void test_raw_request(const std::string &req,
  7846. std::string *out = nullptr) {
  7847. Server svr;
  7848. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7849. res.set_content("ok", "text/plain");
  7850. });
  7851. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7852. res.set_content("ok", "text/plain");
  7853. });
  7854. svr.Get("/header_field_value_check",
  7855. [&](const Request & /*req*/, Response &res) {
  7856. res.set_content("ok", "text/plain");
  7857. });
  7858. svr.CustomRoute("PROPFIND", "/dav",
  7859. [&](const Request & /*req*/, Response &res) {
  7860. res.status = StatusCode::MultiStatus_207;
  7861. });
  7862. // Server read timeout must be longer than the client read timeout for the
  7863. // bug to reproduce, probably to force the server to process a request
  7864. // without a trailing blank line.
  7865. const time_t client_read_timeout_sec = 1;
  7866. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7867. bool listen_thread_ok = false;
  7868. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7869. auto se = detail::scope_exit([&] {
  7870. svr.stop();
  7871. t.join();
  7872. ASSERT_FALSE(svr.is_running());
  7873. EXPECT_TRUE(listen_thread_ok);
  7874. });
  7875. svr.wait_until_ready();
  7876. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7877. }
  7878. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7879. // A certain header line causes an exception if the header property is parsed
  7880. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7881. test_raw_request(
  7882. "GET /hi HTTP/1.1\r\n"
  7883. " : "
  7884. " "
  7885. " ");
  7886. }
  7887. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7888. // A certain header line causes an exception if the header property *name* is
  7889. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7890. // greedy matcher and requires backtracking when there are a lot of ":"
  7891. // characters.
  7892. // This occurs with libc++ but not libstdc++.
  7893. test_raw_request(
  7894. "GET /hi HTTP/1.1\r\n"
  7895. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7896. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7897. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7898. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7899. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7900. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7901. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7902. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7903. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7904. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7905. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7906. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7907. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7908. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7909. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7910. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7911. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7912. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7913. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7914. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7915. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7916. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7917. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7918. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7919. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7920. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7921. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7922. "&&&%%%");
  7923. }
  7924. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7925. // Make sure this doesn't crash the server.
  7926. // In a previous version of the header line regex, the "\r" rendered the line
  7927. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7928. // a new position where the leading white space ended and the field value
  7929. // began.
  7930. // The crash occurs with libc++ but not libstdc++.
  7931. test_raw_request("GET /hi HTTP/1.1\r\n"
  7932. "a:" +
  7933. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7934. "\r\n"
  7935. "\r\n");
  7936. }
  7937. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7938. std::string out;
  7939. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7940. "Content-Type: text/plain\r\n"
  7941. "Transfer-Encoding: chunked\r\n"
  7942. "\r\n"
  7943. "nothex\r\n",
  7944. &out);
  7945. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7946. }
  7947. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7948. std::string out;
  7949. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7950. "Content-Type: text/plain\r\n"
  7951. "Transfer-Encoding: chunked\r\n"
  7952. "\r\n"
  7953. "3\r\n"
  7954. "xyz\r\n"
  7955. "NaN\r\n",
  7956. &out);
  7957. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7958. }
  7959. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7960. std::string out;
  7961. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7962. "Content-Type: text/plain\r\n"
  7963. "Transfer-Encoding: chunked\r\n"
  7964. "\r\n"
  7965. // Length is too large for 64 bits.
  7966. "1ffffffffffffffff\r\n"
  7967. "xyz\r\n",
  7968. &out);
  7969. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7970. }
  7971. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7972. test_raw_request("GET /hi HTTP/1.1\r\n"
  7973. "Content-Type: text/plain\r\n\r");
  7974. }
  7975. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7976. std::string out;
  7977. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7978. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7979. }
  7980. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7981. Server svr;
  7982. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7983. EXPECT_TRUE(!req.remote_addr.empty());
  7984. });
  7985. thread t = thread([&] { svr.listen(HOST, PORT); });
  7986. auto se = detail::scope_exit([&] {
  7987. svr.stop();
  7988. t.join();
  7989. ASSERT_FALSE(svr.is_running());
  7990. });
  7991. svr.wait_until_ready();
  7992. // Send an invalid request line to trigger Bad Request
  7993. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7994. std::string out;
  7995. ASSERT_TRUE(send_request(5, bad_req, &out));
  7996. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7997. }
  7998. // A custom method with neither Content-Length nor Transfer-Encoding must be
  7999. // answered right away rather than blocking on a read that waits for EOF.
  8000. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8001. std::string out;
  8002. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8003. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8004. }
  8005. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8006. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8007. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8008. for (const auto *method : methods) {
  8009. Server svr;
  8010. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8011. EXPECT_FALSE(svr.is_valid()) << method;
  8012. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8013. }
  8014. }
  8015. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8016. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8017. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8018. for (const auto *method : methods) {
  8019. Server svr;
  8020. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8021. EXPECT_FALSE(svr.is_valid()) << method;
  8022. }
  8023. }
  8024. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8025. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8026. "COPY", "MOVE", "LOCK",
  8027. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8028. Server svr;
  8029. for (const auto *method : methods) {
  8030. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8031. }
  8032. EXPECT_TRUE(svr.is_valid());
  8033. }
  8034. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8035. Server svr;
  8036. svr.CustomRoute("POST", "/x",
  8037. [](const Request &, Response &, const ContentReader &) {});
  8038. EXPECT_FALSE(svr.is_valid());
  8039. }
  8040. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8041. Server svr;
  8042. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8043. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8044. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8045. EXPECT_FALSE(svr.is_valid());
  8046. }
  8047. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8048. Server svr;
  8049. auto captured = Error::Success;
  8050. svr.set_error_logger(
  8051. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8052. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8053. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8054. }
  8055. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8056. std::string out;
  8057. std::string request(
  8058. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8059. test_raw_request(request, &out);
  8060. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8061. }
  8062. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8063. std::string out;
  8064. std::string request(
  8065. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8066. test_raw_request(request, &out);
  8067. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8068. }
  8069. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8070. std::string out;
  8071. std::string request(
  8072. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8073. test_raw_request(request, &out);
  8074. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8075. }
  8076. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8077. std::string out;
  8078. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8079. "Test: \r\n\r\n",
  8080. &out);
  8081. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8082. }
  8083. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8084. Server svr;
  8085. std::string x_custom;
  8086. std::string cookie;
  8087. std::string xff;
  8088. std::string x_unicode;
  8089. std::string x_iis;
  8090. svr.Get("/check", [&](const Request &req, Response &res) {
  8091. x_custom = req.get_header_value("X-Custom");
  8092. cookie = req.get_header_value("Cookie");
  8093. xff = req.get_header_value("X-Forwarded-For");
  8094. x_unicode = req.get_header_value("X-Unicode");
  8095. x_iis = req.get_header_value("X-IIS");
  8096. res.set_content("ok", "text/plain");
  8097. });
  8098. thread t = thread([&] { svr.listen(HOST, PORT); });
  8099. auto se = detail::scope_exit([&] {
  8100. svr.stop();
  8101. t.join();
  8102. ASSERT_FALSE(svr.is_running());
  8103. });
  8104. svr.wait_until_ready();
  8105. const std::string req = "GET /check HTTP/1.1\r\n"
  8106. "Host: localhost\r\n"
  8107. "X-Custom: a%0D%0AInjected: b\r\n"
  8108. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8109. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8110. "X-Unicode: %E3%81%82\r\n"
  8111. "X-IIS: %u00E9\r\n"
  8112. "Connection: close\r\n"
  8113. "\r\n";
  8114. std::string res;
  8115. ASSERT_TRUE(send_request(5, req, &res));
  8116. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8117. // Every value must be returned verbatim (wire form), with no decoding.
  8118. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8119. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8120. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8121. EXPECT_EQ("%E3%81%82", x_unicode);
  8122. EXPECT_EQ("%u00E9", x_iis);
  8123. }
  8124. // Applications that previously relied on automatic percent-decoding can
  8125. // reproduce the old behavior by explicitly calling decode_path_component()
  8126. // or, for RFC 3986 conformance, decode_uri_component().
  8127. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8128. Server svr;
  8129. std::string decoded;
  8130. svr.Get("/check", [&](const Request &req, Response &res) {
  8131. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8132. res.set_content("ok", "text/plain");
  8133. });
  8134. thread t = thread([&] { svr.listen(HOST, PORT); });
  8135. auto se = detail::scope_exit([&] {
  8136. svr.stop();
  8137. t.join();
  8138. ASSERT_FALSE(svr.is_running());
  8139. });
  8140. svr.wait_until_ready();
  8141. const std::string req = "GET /check HTTP/1.1\r\n"
  8142. "Host: localhost\r\n"
  8143. "X-Custom: hello%20world\r\n"
  8144. "Connection: close\r\n"
  8145. "\r\n";
  8146. std::string res;
  8147. ASSERT_TRUE(send_request(5, req, &res));
  8148. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8149. EXPECT_EQ("hello world", decoded);
  8150. }
  8151. // Regression test for #2033. Browsers send Referer values that include
  8152. // percent-encoded characters such as %0A inside the URL. Decoding the
  8153. // header value would either trip the post-decode CR/LF/NUL guard (the
  8154. // original bug, returning 400) or, after that guard was relaxed, silently
  8155. // store a literal LF — both unacceptable. The wire form must round-trip.
  8156. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8157. Server svr;
  8158. std::string referer;
  8159. svr.Get("/check", [&](const Request &req, Response &res) {
  8160. referer = req.get_header_value("Referer");
  8161. res.set_content("ok", "text/plain");
  8162. });
  8163. thread t = thread([&] { svr.listen(HOST, PORT); });
  8164. auto se = detail::scope_exit([&] {
  8165. svr.stop();
  8166. t.join();
  8167. ASSERT_FALSE(svr.is_running());
  8168. });
  8169. svr.wait_until_ready();
  8170. const std::string req = "GET /check HTTP/1.1\r\n"
  8171. "Host: localhost\r\n"
  8172. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8173. "Connection: close\r\n"
  8174. "\r\n";
  8175. std::string res;
  8176. ASSERT_TRUE(send_request(5, req, &res));
  8177. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8178. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8179. }
  8180. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8181. Server svr;
  8182. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8183. res.set_header("Cache-Control", "no-cache");
  8184. res.set_chunked_content_provider(
  8185. "text/event-stream", [](size_t offset, DataSink &sink) {
  8186. std::string s = "data:";
  8187. s += std::to_string(offset);
  8188. s += "\n\n";
  8189. auto ret = sink.write(s.data(), s.size());
  8190. EXPECT_TRUE(ret);
  8191. std::this_thread::sleep_for(std::chrono::seconds(1));
  8192. return true;
  8193. });
  8194. });
  8195. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8196. svr.wait_until_ready();
  8197. Client client(HOST, PORT);
  8198. const Headers headers = {{"Accept", "text/event-stream"}};
  8199. auto get_thread = std::thread([&client, &headers]() {
  8200. auto res = client.Get(
  8201. "/events", headers,
  8202. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8203. });
  8204. auto se = detail::scope_exit([&] {
  8205. svr.stop();
  8206. get_thread.join();
  8207. listen_thread.join();
  8208. ASSERT_FALSE(svr.is_running());
  8209. });
  8210. // Give GET time to get a few messages.
  8211. std::this_thread::sleep_for(std::chrono::seconds(2));
  8212. }
  8213. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8214. httplib::Server svr;
  8215. svr.Post("/hi",
  8216. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8217. res.status = StatusCode::OK_200;
  8218. });
  8219. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8220. svr.wait_until_ready();
  8221. Client cli(HOST, PORT);
  8222. auto res = cli.Post("/hi", "data", "text/plain");
  8223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8224. EXPECT_EQ(StatusCode::OK_200, res->status);
  8225. svr.stop();
  8226. thread.join();
  8227. ASSERT_FALSE(svr.is_running());
  8228. res = cli.Post("/hi", "data", "text/plain");
  8229. ASSERT_FALSE(res);
  8230. }
  8231. TEST(ServerStopTest, ListenFailure) {
  8232. Server svr;
  8233. auto t = thread([&]() {
  8234. auto ret = svr.listen("????", PORT);
  8235. EXPECT_FALSE(ret);
  8236. });
  8237. svr.wait_until_ready();
  8238. svr.stop();
  8239. t.join();
  8240. }
  8241. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8242. TEST(ServerStopTest, Decommision) {
  8243. Server svr;
  8244. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8245. for (int i = 0; i < 4; i++) {
  8246. auto is_even = !(i % 2);
  8247. std::thread t{[&] {
  8248. try {
  8249. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8250. if (is_even) {
  8251. throw std::runtime_error("Some thing that happens to go wrong.");
  8252. }
  8253. svr.listen(HOST, PORT);
  8254. } catch (...) { svr.decommission(); }
  8255. }};
  8256. svr.wait_until_ready();
  8257. // Server is up
  8258. {
  8259. Client cli(HOST, PORT);
  8260. auto res = cli.Get("/hi");
  8261. if (is_even) {
  8262. EXPECT_FALSE(res);
  8263. } else {
  8264. EXPECT_TRUE(res);
  8265. EXPECT_EQ("hi...", res->body);
  8266. }
  8267. }
  8268. svr.stop();
  8269. t.join();
  8270. // Server is down...
  8271. {
  8272. Client cli(HOST, PORT);
  8273. auto res = cli.Get("/hi");
  8274. EXPECT_FALSE(res);
  8275. }
  8276. }
  8277. }
  8278. #endif
  8279. // Helper function for string body upload progress tests
  8280. template <typename SetupHandler, typename ClientCall>
  8281. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  8282. ClientCall &&client_call,
  8283. const string &body) {
  8284. Server svr;
  8285. setup_handler(svr);
  8286. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8287. auto se = detail::scope_exit([&] {
  8288. svr.stop();
  8289. t.join();
  8290. });
  8291. svr.wait_until_ready();
  8292. Client cli(HOST, PORT);
  8293. vector<uint64_t> progress_values;
  8294. bool progress_called = false;
  8295. auto res =
  8296. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8297. progress_values.push_back(current);
  8298. progress_called = true;
  8299. return true;
  8300. });
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(200, res->status);
  8303. EXPECT_TRUE(progress_called);
  8304. }
  8305. TEST(UploadProgressTest, PostStringBodyBasic) {
  8306. TestStringBodyUploadProgress(
  8307. [](Server &svr) {
  8308. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8309. res.set_content("received", "text/plain");
  8310. });
  8311. },
  8312. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8313. return cli.Post("/test", body, "text/plain", progress_callback);
  8314. },
  8315. "test data for upload progress");
  8316. }
  8317. TEST(UploadProgressTest, PutStringBodyBasic) {
  8318. TestStringBodyUploadProgress(
  8319. [](Server &svr) {
  8320. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  8321. res.set_content("put received", "text/plain");
  8322. });
  8323. },
  8324. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8325. return cli.Put("/test", body, "text/plain", progress_callback);
  8326. },
  8327. "put test data for upload progress");
  8328. }
  8329. TEST(UploadProgressTest, PatchStringBodyBasic) {
  8330. TestStringBodyUploadProgress(
  8331. [](Server &svr) {
  8332. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  8333. res.set_content("patch received", "text/plain");
  8334. });
  8335. },
  8336. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8337. return cli.Patch("/test", body, "text/plain", progress_callback);
  8338. },
  8339. "patch test data for upload progress");
  8340. }
  8341. // Helper function for content provider upload progress tests
  8342. template <typename SetupHandler, typename ClientCall>
  8343. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  8344. ClientCall &&client_call) {
  8345. Server svr;
  8346. setup_handler(svr);
  8347. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8348. auto se = detail::scope_exit([&] {
  8349. svr.stop();
  8350. t.join();
  8351. });
  8352. svr.wait_until_ready();
  8353. Client cli(HOST, PORT);
  8354. vector<uint64_t> progress_values;
  8355. auto res =
  8356. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8357. progress_values.push_back(current);
  8358. return true;
  8359. });
  8360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8361. EXPECT_EQ(200, res->status);
  8362. EXPECT_FALSE(progress_values.empty());
  8363. }
  8364. TEST(UploadProgressTest, PostContentProviderProgress) {
  8365. TestContentProviderUploadProgress(
  8366. [](Server &svr) {
  8367. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8368. res.set_content("provider received", "text/plain");
  8369. });
  8370. },
  8371. [](Client &cli, UploadProgress progress_callback) {
  8372. return cli.Post(
  8373. "/test", 10,
  8374. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  8375. sink.os << "test data";
  8376. return true;
  8377. },
  8378. "text/plain", progress_callback);
  8379. });
  8380. }
  8381. // Helper function for multipart upload progress tests
  8382. template <typename SetupHandler, typename ClientCall>
  8383. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  8384. ClientCall &&client_call,
  8385. const string &endpoint) {
  8386. Server svr;
  8387. setup_handler(svr);
  8388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8389. auto se = detail::scope_exit([&] {
  8390. svr.stop();
  8391. t.join();
  8392. });
  8393. svr.wait_until_ready();
  8394. Client cli(HOST, PORT);
  8395. vector<uint64_t> progress_values;
  8396. UploadFormDataItems items = {
  8397. {"field1", "value1", "", ""},
  8398. {"field2", "longer value for progress tracking test", "", ""},
  8399. {"file1", "file content data for upload progress", "test.txt",
  8400. "text/plain"}};
  8401. auto res = client_call(cli, endpoint, items,
  8402. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8403. progress_values.push_back(current);
  8404. return true;
  8405. });
  8406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8407. EXPECT_EQ(200, res->status);
  8408. EXPECT_FALSE(progress_values.empty());
  8409. }
  8410. TEST(UploadProgressTest, PostMultipartProgress) {
  8411. TestMultipartUploadProgress(
  8412. [](Server &svr) {
  8413. svr.Post("/multipart", [](const Request &req, Response &res) {
  8414. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8415. res.set_content("multipart received", "text/plain");
  8416. });
  8417. },
  8418. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8419. UploadProgress progress_callback) {
  8420. return cli.Post(endpoint, items, progress_callback);
  8421. },
  8422. "/multipart");
  8423. }
  8424. // Helper function for basic download progress tests
  8425. template <typename SetupHandler, typename ClientCall>
  8426. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8427. ClientCall &&client_call, const string &endpoint,
  8428. size_t expected_content_size) {
  8429. Server svr;
  8430. setup_handler(svr);
  8431. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8432. auto se = detail::scope_exit([&] {
  8433. svr.stop();
  8434. t.join();
  8435. });
  8436. svr.wait_until_ready();
  8437. Client cli(HOST, PORT);
  8438. vector<uint64_t> progress_values;
  8439. auto res = client_call(cli, endpoint,
  8440. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8441. progress_values.push_back(current);
  8442. return true;
  8443. });
  8444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8445. EXPECT_EQ(200, res->status);
  8446. EXPECT_FALSE(progress_values.empty());
  8447. EXPECT_EQ(expected_content_size, res->body.size());
  8448. }
  8449. TEST(DownloadProgressTest, GetBasic) {
  8450. TestBasicDownloadProgress(
  8451. [](Server &svr) {
  8452. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8453. string content(1000, 'D');
  8454. res.set_content(content, "text/plain");
  8455. });
  8456. },
  8457. [](Client &cli, const string &endpoint,
  8458. DownloadProgress progress_callback) {
  8459. return cli.Get(endpoint, progress_callback);
  8460. },
  8461. "/download", 1000u);
  8462. }
  8463. // Helper function for content receiver download progress tests
  8464. template <typename SetupHandler, typename ClientCall>
  8465. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8466. ClientCall &&client_call,
  8467. const string &endpoint,
  8468. size_t expected_content_size) {
  8469. Server svr;
  8470. setup_handler(svr);
  8471. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8472. auto se = detail::scope_exit([&] {
  8473. svr.stop();
  8474. t.join();
  8475. });
  8476. svr.wait_until_ready();
  8477. Client cli(HOST, PORT);
  8478. vector<uint64_t> progress_values;
  8479. string received_body;
  8480. auto res = client_call(
  8481. cli, endpoint,
  8482. [&](const char *data, size_t data_length) -> bool {
  8483. received_body.append(data, data_length);
  8484. return true;
  8485. },
  8486. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8487. progress_values.push_back(current);
  8488. return true;
  8489. });
  8490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8491. EXPECT_EQ(200, res->status);
  8492. EXPECT_FALSE(progress_values.empty());
  8493. EXPECT_EQ(expected_content_size, received_body.size());
  8494. EXPECT_TRUE(res->body.empty());
  8495. }
  8496. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8497. TestContentReceiverDownloadProgress(
  8498. [](Server &svr) {
  8499. svr.Get("/download-receiver",
  8500. [](const Request & /*req*/, Response &res) {
  8501. string content(2000, 'R');
  8502. res.set_content(content, "text/plain");
  8503. });
  8504. },
  8505. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8506. DownloadProgress progress_callback) {
  8507. return cli.Get(endpoint, content_receiver, progress_callback);
  8508. },
  8509. "/download-receiver", 2000u);
  8510. }
  8511. TEST(StreamingTest, NoContentLengthStreaming) {
  8512. Server svr;
  8513. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8514. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8515. if (offset < 6) {
  8516. sink.os << (offset < 3 ? "a" : "b");
  8517. } else {
  8518. sink.done();
  8519. }
  8520. return true;
  8521. });
  8522. });
  8523. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8524. auto listen_se = detail::scope_exit([&] {
  8525. svr.stop();
  8526. listen_thread.join();
  8527. ASSERT_FALSE(svr.is_running());
  8528. });
  8529. svr.wait_until_ready();
  8530. Client client(HOST, PORT);
  8531. auto get_thread = std::thread([&client]() {
  8532. std::string s;
  8533. auto res =
  8534. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8535. s += std::string(data, len);
  8536. return true;
  8537. });
  8538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8539. EXPECT_EQ(StatusCode::OK_200, res->status);
  8540. EXPECT_EQ("aaabbb", s);
  8541. });
  8542. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8543. // Give GET time to get a few messages.
  8544. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8545. }
  8546. TEST(MountTest, Unmount) {
  8547. Server svr;
  8548. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8549. auto se = detail::scope_exit([&] {
  8550. svr.stop();
  8551. listen_thread.join();
  8552. ASSERT_FALSE(svr.is_running());
  8553. });
  8554. svr.wait_until_ready();
  8555. Client cli("localhost", PORT);
  8556. svr.set_mount_point("/mount2", "./www2");
  8557. auto res = cli.Get("/");
  8558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8560. res = cli.Get("/mount2/dir/test.html");
  8561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8562. EXPECT_EQ(StatusCode::OK_200, res->status);
  8563. svr.set_mount_point("/", "./www");
  8564. res = cli.Get("/dir/");
  8565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8566. EXPECT_EQ(StatusCode::OK_200, res->status);
  8567. svr.remove_mount_point("/");
  8568. res = cli.Get("/dir/");
  8569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8570. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8571. svr.remove_mount_point("/mount2");
  8572. res = cli.Get("/mount2/dir/test.html");
  8573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8574. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8575. }
  8576. TEST(MountTest, PathSegmentBoundary) {
  8577. Server svr;
  8578. svr.set_mount_point("/mount2", "./www2");
  8579. svr.set_mount_point("/", "./www");
  8580. auto port = svr.bind_to_any_port(HOST);
  8581. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8582. auto se = detail::scope_exit([&] {
  8583. svr.stop();
  8584. listen_thread.join();
  8585. ASSERT_FALSE(svr.is_running());
  8586. });
  8587. svr.wait_until_ready();
  8588. Client cli(HOST, port);
  8589. auto res = cli.Get("/mount2/dir/test.html");
  8590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8591. EXPECT_EQ(StatusCode::OK_200, res->status);
  8592. // "/mount2" must not match part-way through a path segment.
  8593. res = cli.Get("/mount2dir/test.html");
  8594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8596. // A mount point ending in '/' keeps matching every path below it.
  8597. res = cli.Get("/dir/test.html");
  8598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8599. EXPECT_EQ(StatusCode::OK_200, res->status);
  8600. }
  8601. TEST(MountTest, Redicect) {
  8602. Server svr;
  8603. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8604. auto se = detail::scope_exit([&] {
  8605. svr.stop();
  8606. listen_thread.join();
  8607. ASSERT_FALSE(svr.is_running());
  8608. });
  8609. svr.set_mount_point("/", "./www");
  8610. svr.wait_until_ready();
  8611. Client cli("localhost", PORT);
  8612. auto res = cli.Get("/dir/");
  8613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8614. EXPECT_EQ(StatusCode::OK_200, res->status);
  8615. res = cli.Get("/dir");
  8616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8617. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8618. res = cli.Get("/file");
  8619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8620. EXPECT_EQ(StatusCode::OK_200, res->status);
  8621. res = cli.Get("/file/");
  8622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8623. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8624. cli.set_follow_location(true);
  8625. res = cli.Get("/dir");
  8626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8627. EXPECT_EQ(StatusCode::OK_200, res->status);
  8628. }
  8629. TEST(MountTest, MultibytesPathName) {
  8630. Server svr;
  8631. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8632. auto se = detail::scope_exit([&] {
  8633. svr.stop();
  8634. listen_thread.join();
  8635. ASSERT_FALSE(svr.is_running());
  8636. });
  8637. svr.set_mount_point("/", "./www");
  8638. svr.wait_until_ready();
  8639. Client cli("localhost", PORT);
  8640. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8642. EXPECT_EQ(StatusCode::OK_200, res->status);
  8643. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8644. }
  8645. #ifdef _WIN32
  8646. // Issue #2435: mmap::open() must succeed even when another handle holds
  8647. // the file open for writing (e.g. an active log file).
  8648. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8649. const char *path = "mmap_concurrent_writer_test.txt";
  8650. const char *content = "hello";
  8651. {
  8652. std::ofstream f(path, std::ios::binary);
  8653. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8654. }
  8655. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8656. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8657. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8658. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8659. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8660. detail::mmap m(path);
  8661. ASSERT_TRUE(m.is_open());
  8662. EXPECT_EQ(strlen(content), m.size());
  8663. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8664. }
  8665. #endif
  8666. #ifndef _WIN32
  8667. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8668. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8669. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8670. TEST(MmapTest, FailedMappingIsNotOpen) {
  8671. const char *path = "./mmap_failed_mapping_test_dir";
  8672. ASSERT_EQ(0, ::mkdir(path, 0755));
  8673. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8674. detail::mmap m(path);
  8675. EXPECT_FALSE(m.is_open());
  8676. EXPECT_EQ(0U, m.size());
  8677. EXPECT_NE(static_cast<const void *>(m.data()),
  8678. static_cast<const void *>(MAP_FAILED));
  8679. }
  8680. #endif
  8681. TEST(KeepAliveTest, ReadTimeout) {
  8682. Server svr;
  8683. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8684. std::this_thread::sleep_for(std::chrono::seconds(2));
  8685. res.set_content("a", "text/plain");
  8686. });
  8687. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8688. res.set_content("b", "text/plain");
  8689. });
  8690. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8691. auto se = detail::scope_exit([&] {
  8692. svr.stop();
  8693. listen_thread.join();
  8694. ASSERT_FALSE(svr.is_running());
  8695. });
  8696. svr.wait_until_ready();
  8697. Client cli("localhost", PORT);
  8698. cli.set_keep_alive(true);
  8699. cli.set_read_timeout(std::chrono::seconds(1));
  8700. auto resa = cli.Get("/a");
  8701. ASSERT_FALSE(resa);
  8702. EXPECT_EQ(Error::Read, resa.error());
  8703. auto resb = cli.Get("/b");
  8704. ASSERT_TRUE(resb);
  8705. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8706. EXPECT_EQ("b", resb->body);
  8707. }
  8708. TEST(KeepAliveTest, MaxCount) {
  8709. size_t keep_alive_max_count = 3;
  8710. Server svr;
  8711. svr.set_keep_alive_max_count(keep_alive_max_count);
  8712. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8713. res.set_content("Hello World!", "text/plain");
  8714. });
  8715. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8716. auto se = detail::scope_exit([&] {
  8717. svr.stop();
  8718. listen_thread.join();
  8719. ASSERT_FALSE(svr.is_running());
  8720. });
  8721. svr.wait_until_ready();
  8722. Client cli(HOST, PORT);
  8723. cli.set_keep_alive(true);
  8724. for (size_t i = 0; i < 5; i++) {
  8725. auto result = cli.Get("/hi");
  8726. ASSERT_TRUE(result);
  8727. EXPECT_EQ(StatusCode::OK_200, result->status);
  8728. if (i == keep_alive_max_count - 1) {
  8729. EXPECT_EQ("close", result->get_header_value("Connection"));
  8730. } else {
  8731. EXPECT_FALSE(result->has_header("Connection"));
  8732. }
  8733. }
  8734. }
  8735. TEST(KeepAliveTest, Issue1041) {
  8736. Server svr;
  8737. svr.set_keep_alive_timeout(3);
  8738. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8739. res.set_content("Hello World!", "text/plain");
  8740. });
  8741. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8742. auto se = detail::scope_exit([&] {
  8743. svr.stop();
  8744. listen_thread.join();
  8745. ASSERT_FALSE(svr.is_running());
  8746. });
  8747. svr.wait_until_ready();
  8748. Client cli(HOST, PORT);
  8749. cli.set_keep_alive(true);
  8750. auto result = cli.Get("/hi");
  8751. ASSERT_TRUE(result);
  8752. EXPECT_EQ(StatusCode::OK_200, result->status);
  8753. std::this_thread::sleep_for(std::chrono::seconds(5));
  8754. result = cli.Get("/hi");
  8755. ASSERT_TRUE(result);
  8756. EXPECT_EQ(StatusCode::OK_200, result->status);
  8757. }
  8758. TEST(KeepAliveTest, Issue1959) {
  8759. Server svr;
  8760. svr.set_keep_alive_timeout(5);
  8761. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8762. res.set_content("a", "text/plain");
  8763. });
  8764. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8765. auto se = detail::scope_exit([&] {
  8766. if (!svr.is_running()) return;
  8767. svr.stop();
  8768. listen_thread.join();
  8769. ASSERT_FALSE(svr.is_running());
  8770. });
  8771. svr.wait_until_ready();
  8772. Client cli("localhost", PORT);
  8773. cli.set_keep_alive(true);
  8774. using namespace std::chrono;
  8775. auto start = steady_clock::now();
  8776. cli.Get("/a");
  8777. svr.stop();
  8778. listen_thread.join();
  8779. auto end = steady_clock::now();
  8780. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8781. EXPECT_LT(elapsed, 5000);
  8782. }
  8783. #ifdef CPPHTTPLIB_SSL_ENABLED
  8784. TEST(KeepAliveTest, SSLClientReconnection) {
  8785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8786. ASSERT_TRUE(svr.is_valid());
  8787. svr.set_keep_alive_timeout(1);
  8788. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8789. res.set_content("Hello World!", "text/plain");
  8790. });
  8791. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8792. auto se = detail::scope_exit([&] {
  8793. svr.stop();
  8794. listen_thread.join();
  8795. ASSERT_FALSE(svr.is_running());
  8796. });
  8797. svr.wait_until_ready();
  8798. SSLClient cli(HOST, PORT);
  8799. cli.enable_server_certificate_verification(false);
  8800. cli.set_keep_alive(true);
  8801. auto result = cli.Get("/hi");
  8802. ASSERT_TRUE(result);
  8803. EXPECT_EQ(StatusCode::OK_200, result->status);
  8804. result = cli.Get("/hi");
  8805. ASSERT_TRUE(result);
  8806. EXPECT_EQ(StatusCode::OK_200, result->status);
  8807. std::this_thread::sleep_for(std::chrono::seconds(2));
  8808. // Recoonect
  8809. result = cli.Get("/hi");
  8810. ASSERT_TRUE(result);
  8811. EXPECT_EQ(StatusCode::OK_200, result->status);
  8812. result = cli.Get("/hi");
  8813. ASSERT_TRUE(result);
  8814. EXPECT_EQ(StatusCode::OK_200, result->status);
  8815. }
  8816. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8817. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8818. ASSERT_TRUE(svr.is_valid());
  8819. svr.set_keep_alive_timeout(1);
  8820. std::string content = "reconnect";
  8821. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8822. res.set_content("Hello World!", "text/plain");
  8823. });
  8824. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8825. auto se = detail::scope_exit([&] {
  8826. svr.stop();
  8827. listen_thread.join();
  8828. ASSERT_FALSE(svr.is_running());
  8829. });
  8830. svr.wait_until_ready();
  8831. SSLClient cli(HOST, PORT);
  8832. cli.enable_server_certificate_verification(false);
  8833. cli.set_keep_alive(true);
  8834. auto result = cli.Post(
  8835. "/hi", content.size(),
  8836. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8837. sink.write(content.c_str(), content.size());
  8838. return true;
  8839. },
  8840. "text/plain");
  8841. ASSERT_TRUE(result);
  8842. EXPECT_EQ(200, result->status);
  8843. std::this_thread::sleep_for(std::chrono::seconds(2));
  8844. // Recoonect
  8845. result = cli.Post(
  8846. "/hi", content.size(),
  8847. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8848. sink.write(content.c_str(), content.size());
  8849. return true;
  8850. },
  8851. "text/plain");
  8852. ASSERT_TRUE(result);
  8853. EXPECT_EQ(200, result->status);
  8854. result = cli.Post(
  8855. "/hi", content.size(),
  8856. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8857. sink.write(content.c_str(), content.size());
  8858. return true;
  8859. },
  8860. "text/plain");
  8861. ASSERT_TRUE(result);
  8862. EXPECT_EQ(200, result->status);
  8863. }
  8864. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8865. using namespace httplib::tls;
  8866. {
  8867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8868. ASSERT_TRUE(svr.is_valid());
  8869. svr.Get("/sni", [&](const Request &req, Response &res) {
  8870. std::string expected = req.sni();
  8871. EXPECT_EQ(expected, req.get_param_value("expected"));
  8872. res.set_content("ok", "text/plain");
  8873. });
  8874. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8875. auto se = detail::scope_exit([&] {
  8876. svr.stop();
  8877. listen_thread.join();
  8878. ASSERT_FALSE(svr.is_running());
  8879. });
  8880. svr.wait_until_ready();
  8881. {
  8882. SSLClient cli("localhost", PORT);
  8883. cli.enable_server_certificate_verification(false);
  8884. auto res = cli.Get("/sni?expected=localhost");
  8885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8886. }
  8887. {
  8888. SSLClient cli("::1", PORT);
  8889. cli.enable_server_certificate_verification(false);
  8890. auto res = cli.Get("/sni?expected=");
  8891. // NOTE: This may fail if the server is listening on IPv4 only
  8892. // (e.g., when localhost resolves to 127.0.0.1 only)
  8893. if (res) {
  8894. EXPECT_EQ(StatusCode::OK_200, res->status);
  8895. } else {
  8896. EXPECT_EQ(Error::Connection, res.error());
  8897. }
  8898. }
  8899. }
  8900. }
  8901. #endif
  8902. TEST(ClientProblemDetectionTest, ContentProvider) {
  8903. Server svr;
  8904. size_t content_length = 1024 * 1024;
  8905. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8906. res.set_content_provider(
  8907. content_length, "text/plain",
  8908. [&](size_t offset, size_t length, DataSink &sink) {
  8909. auto out_len = std::min(length, static_cast<size_t>(1024));
  8910. std::string out(out_len, '@');
  8911. sink.write(out.data(), out_len);
  8912. return offset < 4096;
  8913. },
  8914. [](bool success) { ASSERT_FALSE(success); });
  8915. });
  8916. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8917. res.set_content_provider(
  8918. 0, "text/plain",
  8919. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8920. EXPECT_TRUE(false);
  8921. return true;
  8922. },
  8923. [](bool success) { ASSERT_FALSE(success); });
  8924. });
  8925. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8926. auto se = detail::scope_exit([&] {
  8927. svr.stop();
  8928. listen_thread.join();
  8929. ASSERT_FALSE(svr.is_running());
  8930. });
  8931. svr.wait_until_ready();
  8932. Client cli("localhost", PORT);
  8933. {
  8934. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8935. size_t /*data_length*/) { return false; });
  8936. ASSERT_FALSE(res);
  8937. }
  8938. {
  8939. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8940. size_t /*data_length*/) { return false; });
  8941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8942. }
  8943. }
  8944. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8945. Server svr;
  8946. svr.set_error_handler([](Request const &, Response &res) -> void {
  8947. res.set_chunked_content_provider(
  8948. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8949. sink.os << "hello";
  8950. sink.os << "world";
  8951. sink.done();
  8952. return true;
  8953. });
  8954. });
  8955. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8956. auto se = detail::scope_exit([&] {
  8957. svr.stop();
  8958. listen_thread.join();
  8959. ASSERT_FALSE(svr.is_running());
  8960. });
  8961. svr.wait_until_ready();
  8962. Client cli("localhost", PORT);
  8963. auto res = cli.Get("/");
  8964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8965. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8966. EXPECT_EQ("helloworld", res->body);
  8967. }
  8968. TEST(LongPollingTest, ClientCloseDetection) {
  8969. Server svr;
  8970. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8971. res.set_chunked_content_provider(
  8972. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8973. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8974. sink.os << "hello";
  8975. auto count = 10;
  8976. while (count > 0 && sink.is_writable()) {
  8977. this_thread::sleep_for(chrono::milliseconds(10));
  8978. count--;
  8979. }
  8980. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8981. return true;
  8982. });
  8983. });
  8984. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8985. auto se = detail::scope_exit([&] {
  8986. svr.stop();
  8987. listen_thread.join();
  8988. ASSERT_FALSE(svr.is_running());
  8989. });
  8990. svr.wait_until_ready();
  8991. Client cli("localhost", PORT);
  8992. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8993. EXPECT_EQ("hello", string(data, data_length));
  8994. return false; // close the socket immediately.
  8995. });
  8996. ASSERT_FALSE(res);
  8997. }
  8998. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8999. Server svr;
  9000. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9001. res.set_chunked_content_provider(
  9002. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9003. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9004. sink.os << "hello";
  9005. EXPECT_TRUE(sink.os.good());
  9006. // Wait for the client to close the connection
  9007. auto count = 10;
  9008. while (count > 0 && sink.is_writable()) {
  9009. this_thread::sleep_for(chrono::milliseconds(10));
  9010. count--;
  9011. }
  9012. // After client disconnect, write repeatedly until the socket
  9013. // write actually fails (small writes may be absorbed by the
  9014. // kernel buffer)
  9015. std::string chunk(1024, 'x');
  9016. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9017. sink.os << chunk;
  9018. }
  9019. EXPECT_TRUE(sink.os.fail());
  9020. return true;
  9021. });
  9022. });
  9023. auto port = svr.bind_to_any_port("localhost");
  9024. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9025. auto se = detail::scope_exit([&] {
  9026. svr.stop();
  9027. listen_thread.join();
  9028. ASSERT_FALSE(svr.is_running());
  9029. });
  9030. svr.wait_until_ready();
  9031. Client cli("localhost", port);
  9032. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9033. EXPECT_EQ("hello", string(data, data_length));
  9034. return false; // close the socket immediately.
  9035. });
  9036. ASSERT_FALSE(res);
  9037. }
  9038. TEST(GetWithParametersTest, GetWithParameters) {
  9039. Server svr;
  9040. svr.Get("/", [&](const Request &req, Response &) {
  9041. EXPECT_EQ("world", req.get_param_value("hello"));
  9042. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9043. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9044. });
  9045. svr.Get("/params", [&](const Request &req, Response &) {
  9046. EXPECT_EQ("world", req.get_param_value("hello"));
  9047. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9048. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9049. });
  9050. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  9051. EXPECT_EQ("resource-id", req.matches[1]);
  9052. EXPECT_EQ("foo", req.get_param_value("param1"));
  9053. EXPECT_EQ("bar", req.get_param_value("param2"));
  9054. });
  9055. svr.Get("/users/:id", [&](const Request &req, Response &) {
  9056. EXPECT_EQ("user-id", req.path_params.at("id"));
  9057. EXPECT_EQ("foo", req.get_param_value("param1"));
  9058. EXPECT_EQ("bar", req.get_param_value("param2"));
  9059. });
  9060. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9061. auto se = detail::scope_exit([&] {
  9062. svr.stop();
  9063. listen_thread.join();
  9064. ASSERT_FALSE(svr.is_running());
  9065. });
  9066. svr.wait_until_ready();
  9067. {
  9068. Client cli(HOST, PORT);
  9069. Params params;
  9070. params.emplace("hello", "world");
  9071. params.emplace("hello2", "world2");
  9072. params.emplace("hello3", "world3");
  9073. auto res = cli.Get("/", params, Headers{});
  9074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9075. EXPECT_EQ(StatusCode::OK_200, res->status);
  9076. }
  9077. {
  9078. Client cli(HOST, PORT);
  9079. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9081. EXPECT_EQ(StatusCode::OK_200, res->status);
  9082. }
  9083. {
  9084. Client cli(HOST, PORT);
  9085. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9087. EXPECT_EQ(StatusCode::OK_200, res->status);
  9088. }
  9089. {
  9090. Client cli(HOST, PORT);
  9091. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9093. EXPECT_EQ(StatusCode::OK_200, res->status);
  9094. }
  9095. }
  9096. TEST(GetWithParametersTest, GetWithParameters2) {
  9097. Server svr;
  9098. svr.Get("/", [&](const Request &req, Response &res) {
  9099. auto text = req.get_param_value("hello");
  9100. res.set_content(text, "text/plain");
  9101. });
  9102. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9103. auto se = detail::scope_exit([&] {
  9104. svr.stop();
  9105. listen_thread.join();
  9106. ASSERT_FALSE(svr.is_running());
  9107. });
  9108. svr.wait_until_ready();
  9109. Client cli("localhost", PORT);
  9110. Params params;
  9111. params.emplace("hello", "world");
  9112. std::string body;
  9113. auto res = cli.Get("/", params, Headers{},
  9114. [&](const char *data, size_t data_length) {
  9115. body.append(data, data_length);
  9116. return true;
  9117. });
  9118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9119. EXPECT_EQ(StatusCode::OK_200, res->status);
  9120. EXPECT_EQ("world", body);
  9121. }
  9122. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9123. Server svr;
  9124. svr.Get("/search", [&](const Request &req, Response &res) {
  9125. auto q = req.get_param_value("q");
  9126. res.set_content(q, "text/plain");
  9127. });
  9128. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9129. auto se = detail::scope_exit([&] {
  9130. svr.stop();
  9131. listen_thread.join();
  9132. ASSERT_FALSE(svr.is_running());
  9133. });
  9134. svr.wait_until_ready();
  9135. Client cli("localhost", PORT);
  9136. // Verify that Get(path, params) works without requiring Headers argument
  9137. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9139. EXPECT_EQ(StatusCode::OK_200, res->status);
  9140. EXPECT_EQ("cpp-httplib", res->body);
  9141. }
  9142. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9143. auto host = "httpbingo.org";
  9144. auto path = std::string{"/range/32"};
  9145. #ifdef CPPHTTPLIB_SSL_ENABLED
  9146. SSLClient cli(host);
  9147. #else
  9148. Client cli(host);
  9149. #endif
  9150. cli.set_default_headers({make_range_header({{1, 10}})});
  9151. cli.set_connection_timeout(5);
  9152. {
  9153. auto res = cli.Get(path);
  9154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9155. EXPECT_EQ("bcdefghijk", res->body);
  9156. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9157. }
  9158. {
  9159. auto res = cli.Get(path);
  9160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9161. EXPECT_EQ("bcdefghijk", res->body);
  9162. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9163. }
  9164. }
  9165. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  9166. Server svr;
  9167. svr.set_default_headers({{"Hello", "World"}});
  9168. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9169. res.set_content("ok", "text/plain");
  9170. });
  9171. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9172. auto se = detail::scope_exit([&] {
  9173. svr.stop();
  9174. listen_thread.join();
  9175. ASSERT_FALSE(svr.is_running());
  9176. });
  9177. svr.wait_until_ready();
  9178. Client cli("localhost", PORT);
  9179. auto res = cli.Get("/");
  9180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9181. EXPECT_EQ(StatusCode::OK_200, res->status);
  9182. EXPECT_EQ("ok", res->body);
  9183. EXPECT_EQ("World", res->get_header_value("Hello"));
  9184. }
  9185. #ifdef CPPHTTPLIB_SSL_ENABLED
  9186. TEST(KeepAliveTest, ReadTimeoutSSL) {
  9187. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9188. ASSERT_TRUE(svr.is_valid());
  9189. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9190. std::this_thread::sleep_for(std::chrono::seconds(2));
  9191. res.set_content("a", "text/plain");
  9192. });
  9193. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9194. res.set_content("b", "text/plain");
  9195. });
  9196. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9197. auto se = detail::scope_exit([&] {
  9198. svr.stop();
  9199. listen_thread.join();
  9200. ASSERT_FALSE(svr.is_running());
  9201. });
  9202. svr.wait_until_ready();
  9203. SSLClient cli("localhost", PORT);
  9204. cli.enable_server_certificate_verification(false);
  9205. cli.set_keep_alive(true);
  9206. cli.set_read_timeout(std::chrono::seconds(1));
  9207. auto resa = cli.Get("/a");
  9208. ASSERT_TRUE(!resa);
  9209. EXPECT_EQ(Error::Read, resa.error());
  9210. auto resb = cli.Get("/b");
  9211. ASSERT_TRUE(resb);
  9212. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9213. EXPECT_EQ("b", resb->body);
  9214. }
  9215. #endif
  9216. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  9217. protected:
  9218. ServerTestWithAI_PASSIVE()
  9219. : cli_(HOST, PORT)
  9220. #ifdef CPPHTTPLIB_SSL_ENABLED
  9221. ,
  9222. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9223. #endif
  9224. {
  9225. #ifdef CPPHTTPLIB_SSL_ENABLED
  9226. cli_.enable_server_certificate_verification(false);
  9227. #endif
  9228. }
  9229. virtual void SetUp() {
  9230. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9231. res.set_content("Hello World!", "text/plain");
  9232. });
  9233. t_ = thread(
  9234. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  9235. svr_.wait_until_ready();
  9236. }
  9237. virtual void TearDown() {
  9238. svr_.stop();
  9239. t_.join();
  9240. }
  9241. #ifdef CPPHTTPLIB_SSL_ENABLED
  9242. SSLClient cli_;
  9243. SSLServer svr_;
  9244. #else
  9245. Client cli_;
  9246. Server svr_;
  9247. #endif
  9248. thread t_;
  9249. };
  9250. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  9251. auto res = cli_.Get("/hi");
  9252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9253. EXPECT_EQ(StatusCode::OK_200, res->status);
  9254. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9255. EXPECT_EQ("Hello World!", res->body);
  9256. }
  9257. class ServerUpDownTest : public ::testing::Test {
  9258. protected:
  9259. ServerUpDownTest() : cli_(HOST, PORT) {}
  9260. virtual void SetUp() {
  9261. t_ = thread([&]() {
  9262. svr_.bind_to_any_port(HOST);
  9263. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9264. ASSERT_TRUE(svr_.listen_after_bind());
  9265. });
  9266. svr_.wait_until_ready();
  9267. }
  9268. virtual void TearDown() {
  9269. svr_.stop();
  9270. t_.join();
  9271. }
  9272. Client cli_;
  9273. Server svr_;
  9274. thread t_;
  9275. };
  9276. TEST_F(ServerUpDownTest, QuickStartStop) {
  9277. // Should not crash, especially when run with
  9278. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  9279. }
  9280. class PayloadMaxLengthTest : public ::testing::Test {
  9281. protected:
  9282. PayloadMaxLengthTest()
  9283. : cli_(HOST, PORT)
  9284. #ifdef CPPHTTPLIB_SSL_ENABLED
  9285. ,
  9286. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9287. #endif
  9288. {
  9289. #ifdef CPPHTTPLIB_SSL_ENABLED
  9290. cli_.enable_server_certificate_verification(false);
  9291. #endif
  9292. }
  9293. virtual void SetUp() {
  9294. svr_.set_payload_max_length(8);
  9295. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9296. res.set_content("test", "text/plain");
  9297. });
  9298. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9299. svr_.wait_until_ready();
  9300. }
  9301. virtual void TearDown() {
  9302. svr_.stop();
  9303. t_.join();
  9304. }
  9305. #ifdef CPPHTTPLIB_SSL_ENABLED
  9306. SSLClient cli_;
  9307. SSLServer svr_;
  9308. #else
  9309. Client cli_;
  9310. Server svr_;
  9311. #endif
  9312. thread t_;
  9313. };
  9314. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  9315. auto res = cli_.Post("/test", "123456789", "text/plain");
  9316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9317. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9318. res = cli_.Post("/test", "12345678", "text/plain");
  9319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9320. EXPECT_EQ(StatusCode::OK_200, res->status);
  9321. }
  9322. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  9323. // Test chunked encoding with payload exceeding the 8-byte limit
  9324. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  9325. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  9326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9327. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9328. }
  9329. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  9330. // Test chunked encoding with payload within the 8-byte limit
  9331. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  9332. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  9333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9334. EXPECT_EQ(StatusCode::OK_200, res->status);
  9335. }
  9336. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  9337. // Test using send_request to send chunked data exceeding payload limit
  9338. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  9339. "Host: " +
  9340. std::string(HOST) + ":" + std::to_string(PORT) +
  9341. "\r\n"
  9342. "Transfer-Encoding: chunked\r\n"
  9343. "Connection: close\r\n"
  9344. "\r\n"
  9345. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  9346. "0123456789\r\n"
  9347. "0\r\n" // End chunk
  9348. "\r\n";
  9349. std::string response;
  9350. bool result = send_request(1, chunked_request, &response);
  9351. if (!result) {
  9352. // If send_request fails, it might be because the server closed the
  9353. // connection due to payload limit enforcement, which is acceptable
  9354. SUCCEED()
  9355. << "Server rejected oversized chunked request (connection closed)";
  9356. } else {
  9357. // If we got a response, check if it's an error response or connection was
  9358. // closed early Short response length indicates connection was closed due to
  9359. // payload limit
  9360. if (response.length() <= 10) {
  9361. SUCCEED() << "Server closed connection for oversized chunked request";
  9362. } else {
  9363. // Check for error status codes
  9364. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9365. response.find("Payload Too Large") != std::string::npos ||
  9366. response.find("400") != std::string::npos);
  9367. }
  9368. }
  9369. }
  9370. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  9371. // Test request without Content-Length header exceeding payload limit
  9372. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9373. "Host: " +
  9374. std::string(HOST) + ":" +
  9375. std::to_string(PORT) +
  9376. "\r\n"
  9377. "Connection: close\r\n"
  9378. "\r\n";
  9379. // Add payload exceeding the 8-byte limit
  9380. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  9381. request_without_content_length += large_payload;
  9382. std::string response;
  9383. bool result = send_request(1, request_without_content_length, &response);
  9384. if (!result) {
  9385. // If send_request fails, server likely closed connection due to payload
  9386. // limit
  9387. SUCCEED() << "Server rejected oversized request without Content-Length "
  9388. "(connection closed)";
  9389. } else {
  9390. // Check if server responded with error or closed connection early
  9391. if (response.length() <= 10) {
  9392. SUCCEED() << "Server closed connection for oversized request without "
  9393. "Content-Length";
  9394. } else {
  9395. // Check for error status codes
  9396. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9397. response.find("Payload Too Large") != std::string::npos ||
  9398. response.find("400") != std::string::npos);
  9399. }
  9400. }
  9401. }
  9402. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  9403. // Test request without Content-Length header within payload limit
  9404. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9405. "Host: " +
  9406. std::string(HOST) + ":" +
  9407. std::to_string(PORT) +
  9408. "\r\n"
  9409. "Connection: close\r\n"
  9410. "\r\n";
  9411. // Add payload within the 8-byte limit
  9412. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9413. request_without_content_length += small_payload;
  9414. std::string response;
  9415. bool result = send_request(1, request_without_content_length, &response);
  9416. // For requests without Content-Length, the server may have different behavior
  9417. // The key is that it should not reject due to payload limit for small
  9418. // payloads
  9419. if (result) {
  9420. // Check for any HTTP response (success or error, but not connection closed)
  9421. if (response.length() > 10) {
  9422. SUCCEED()
  9423. << "Server processed request without Content-Length within limit";
  9424. } else {
  9425. // Short response might indicate connection closed, which is acceptable
  9426. SUCCEED() << "Server closed connection for request without "
  9427. "Content-Length (acceptable behavior)";
  9428. }
  9429. } else {
  9430. // Connection failure might be due to protocol requirements
  9431. SUCCEED() << "Connection issue with request without Content-Length "
  9432. "(environment-specific)";
  9433. }
  9434. }
  9435. class LargePayloadMaxLengthTest : public ::testing::Test {
  9436. protected:
  9437. LargePayloadMaxLengthTest()
  9438. : cli_(HOST, PORT)
  9439. #ifdef CPPHTTPLIB_SSL_ENABLED
  9440. ,
  9441. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9442. #endif
  9443. {
  9444. #ifdef CPPHTTPLIB_SSL_ENABLED
  9445. cli_.enable_server_certificate_verification(false);
  9446. #endif
  9447. }
  9448. virtual void SetUp() {
  9449. // Set 10MB payload limit
  9450. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9451. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9452. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9453. res.set_content("Large payload test", "text/plain");
  9454. });
  9455. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9456. svr_.wait_until_ready();
  9457. }
  9458. virtual void TearDown() {
  9459. svr_.stop();
  9460. t_.join();
  9461. }
  9462. #ifdef CPPHTTPLIB_SSL_ENABLED
  9463. SSLClient cli_;
  9464. SSLServer svr_;
  9465. #else
  9466. Client cli_;
  9467. Server svr_;
  9468. #endif
  9469. thread t_;
  9470. };
  9471. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9472. // Test chunked encoding with payload within 10MB limit
  9473. std::string medium_payload(5 * 1024 * 1024,
  9474. 'A'); // 5MB payload, within 10MB limit
  9475. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9477. EXPECT_EQ(StatusCode::OK_200, res->status);
  9478. }
  9479. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9480. // Test chunked encoding with payload exceeding 10MB limit
  9481. std::string large_payload(12 * 1024 * 1024,
  9482. 'B'); // 12MB payload, exceeds 10MB limit
  9483. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9484. // Server may either return 413 or close the connection
  9485. if (res) {
  9486. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9487. } else {
  9488. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9489. }
  9490. }
  9491. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9492. // Test request without Content-Length header within 10MB limit
  9493. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9494. "Host: " +
  9495. std::string(HOST) + ":" +
  9496. std::to_string(PORT) +
  9497. "\r\n"
  9498. "Connection: close\r\n"
  9499. "\r\n";
  9500. // Add 1MB payload (within 10MB limit)
  9501. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9502. request_without_content_length += medium_payload;
  9503. std::string response;
  9504. bool result = send_request(5, request_without_content_length, &response);
  9505. if (result) {
  9506. // Should get a proper HTTP response for payloads within limit
  9507. if (response.length() > 10) {
  9508. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9509. "10MB limit";
  9510. } else {
  9511. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9512. "Content-Length)";
  9513. }
  9514. } else {
  9515. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9516. }
  9517. }
  9518. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9519. // Test request without Content-Length header exceeding 10MB limit
  9520. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9521. "Host: " +
  9522. std::string(HOST) + ":" +
  9523. std::to_string(PORT) +
  9524. "\r\n"
  9525. "Connection: close\r\n"
  9526. "\r\n";
  9527. // Add 12MB payload (exceeds 10MB limit)
  9528. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9529. request_without_content_length += large_payload;
  9530. std::string response;
  9531. bool result = send_request(10, request_without_content_length, &response);
  9532. if (!result) {
  9533. // Server should close connection due to payload limit
  9534. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9535. "(connection closed)";
  9536. } else {
  9537. // Check for error response
  9538. if (response.length() <= 10) {
  9539. SUCCEED()
  9540. << "Server closed connection for 12MB request exceeding 10MB limit";
  9541. } else {
  9542. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9543. response.find("Payload Too Large") != std::string::npos ||
  9544. response.find("400") != std::string::npos);
  9545. }
  9546. }
  9547. }
  9548. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9549. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9550. // path.
  9551. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9552. Server svr;
  9553. const size_t LIMIT = 64 * 1024; // 64KB
  9554. svr.set_payload_max_length(LIMIT);
  9555. size_t total = 0;
  9556. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9557. const ContentReader &content_reader) {
  9558. content_reader([&](const char * /*data*/, size_t len) {
  9559. total += len;
  9560. return true;
  9561. });
  9562. res.status = 200;
  9563. res.set_content("stream_ok", "text/plain");
  9564. });
  9565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9566. auto se = detail::scope_exit([&] {
  9567. svr.stop();
  9568. thread.join();
  9569. ASSERT_FALSE(svr.is_running());
  9570. });
  9571. svr.wait_until_ready();
  9572. // Prepare 256KB raw data and gzip-compress it
  9573. std::string raw(256 * 1024, 'A');
  9574. std::string gz;
  9575. {
  9576. z_stream zs{};
  9577. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9578. Z_DEFAULT_STRATEGY);
  9579. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9580. zs.avail_in = static_cast<uInt>(raw.size());
  9581. char outbuf[4096];
  9582. int ret;
  9583. do {
  9584. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9585. zs.avail_out = sizeof(outbuf);
  9586. ret = deflate(&zs, Z_FINISH);
  9587. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9588. } while (ret != Z_STREAM_END);
  9589. deflateEnd(&zs);
  9590. }
  9591. Client cli(HOST, PORT);
  9592. cli.set_connection_timeout(std::chrono::seconds(5));
  9593. Headers headers = {{"Content-Encoding", "gzip"}};
  9594. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9595. "application/octet-stream");
  9596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9597. // Server must reject oversized decompressed payloads with 413.
  9598. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9599. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9600. EXPECT_LE(total, LIMIT);
  9601. }
  9602. #ifndef CPPHTTPLIB_SSL_ENABLED
  9603. // For a request with neither Content-Length nor Transfer-Encoding, the
  9604. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9605. // compressed wire bytes straight to the ContentReader without ever routing
  9606. // them through the decompressor, so payload_max_length_ only bounded the
  9607. // compressed size on the wire, not the decompressed size.
  9608. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9609. Server svr;
  9610. const size_t LIMIT = 64 * 1024; // 64KB
  9611. svr.set_payload_max_length(LIMIT);
  9612. size_t total = 0;
  9613. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9614. const ContentReader &content_reader) {
  9615. content_reader([&](const char * /*data*/, size_t len) {
  9616. total += len;
  9617. return true;
  9618. });
  9619. res.status = 200;
  9620. res.set_content("stream_ok", "text/plain");
  9621. });
  9622. auto port = svr.bind_to_any_port(HOST);
  9623. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9624. auto se = detail::scope_exit([&] {
  9625. svr.stop();
  9626. thread.join();
  9627. ASSERT_FALSE(svr.is_running());
  9628. });
  9629. svr.wait_until_ready();
  9630. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9631. // StreamingGzipDecompression test above.
  9632. std::string raw(256 * 1024, 'A');
  9633. std::string gz;
  9634. {
  9635. httplib::detail::gzip_compressor compressor;
  9636. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9637. [&](const char *chunk, size_t len) {
  9638. gz.append(chunk, len);
  9639. return true;
  9640. });
  9641. ASSERT_TRUE(result);
  9642. }
  9643. // Send the gzip body over raw TCP with neither Content-Length nor
  9644. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  9645. // kicks in.
  9646. std::string req = "POST /stream HTTP/1.1\r\n"
  9647. "Host: " +
  9648. std::string(HOST) + ":" + std::to_string(port) +
  9649. "\r\n"
  9650. "Content-Encoding: gzip\r\n"
  9651. "Connection: close\r\n"
  9652. "\r\n" +
  9653. gz;
  9654. std::string response;
  9655. ASSERT_TRUE(send_request(5, req, &response, port));
  9656. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9657. EXPECT_LE(total, LIMIT);
  9658. }
  9659. #endif
  9660. #endif
  9661. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9662. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9663. // the payload must be passed through untouched instead of being rejected.
  9664. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9665. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9666. Server svr;
  9667. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9668. res.set_content(body, "image/jpeg");
  9669. res.set_header("Content-Encoding", "UTF-8");
  9670. });
  9671. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9672. res.set_content(body, "image/jpeg");
  9673. res.set_header("Content-Encoding", "identity");
  9674. });
  9675. svr.Post("/echo", [](const Request &req, Response &res) {
  9676. res.set_content(req.body, "image/jpeg");
  9677. });
  9678. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9679. auto se = detail::scope_exit([&] {
  9680. svr.stop();
  9681. t.join();
  9682. ASSERT_FALSE(svr.is_running());
  9683. });
  9684. svr.wait_until_ready();
  9685. Client cli(HOST, PORT);
  9686. {
  9687. auto res = cli.Get("/image");
  9688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9689. EXPECT_EQ(StatusCode::OK_200, res->status);
  9690. EXPECT_EQ(body, res->body);
  9691. }
  9692. {
  9693. auto res = cli.Get("/identity");
  9694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9695. EXPECT_EQ(StatusCode::OK_200, res->status);
  9696. EXPECT_EQ(body, res->body);
  9697. }
  9698. {
  9699. // The same applies to a request body reaching the server.
  9700. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9701. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9703. EXPECT_EQ(StatusCode::OK_200, res->status);
  9704. EXPECT_EQ(body, res->body);
  9705. }
  9706. }
  9707. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9708. // gzip-encoded response even when the build has no zlib support.
  9709. static const char GZIPPED_HELLO_WORLD[] = {
  9710. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9711. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9712. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9713. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9714. // A content coding is a whole token, not something the field value merely
  9715. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  9716. // as "fibre" look like Brotli, and turned a multi-coding value like
  9717. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  9718. // it was never meant to see.
  9719. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  9720. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9721. Server svr;
  9722. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  9723. res.set_content(body, "image/jpeg");
  9724. res.set_header("Content-Encoding", "fibre");
  9725. });
  9726. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  9727. res.set_content(body, "image/jpeg");
  9728. res.set_header("Content-Encoding", "gzip, br");
  9729. });
  9730. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  9731. res.set_content(body, "image/jpeg");
  9732. res.set_header("Content-Encoding", "x-zstd-ish");
  9733. });
  9734. auto port = svr.bind_to_any_port(HOST);
  9735. thread t = thread([&]() { svr.listen_after_bind(); });
  9736. auto se = detail::scope_exit([&] {
  9737. svr.stop();
  9738. t.join();
  9739. ASSERT_FALSE(svr.is_running());
  9740. });
  9741. svr.wait_until_ready();
  9742. Client cli(HOST, port);
  9743. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  9744. auto res = cli.Get(path);
  9745. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9746. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9747. // Not a coding we recognize, so the payload comes back untouched
  9748. EXPECT_EQ(body, res->body) << path;
  9749. }
  9750. }
  9751. // A content coding cpp-httplib recognizes but was not built with must be
  9752. // reported as such. Handing the still-compressed payload back to the caller
  9753. // would silently corrupt it.
  9754. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9755. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9756. Server svr;
  9757. // "image/jpeg" keeps the server from applying a content coding of its own,
  9758. // so the hand-crafted Content-Encoding below survives.
  9759. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9760. res.set_content(gzipped, "image/jpeg");
  9761. res.set_header("Content-Encoding", "gzip");
  9762. });
  9763. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9764. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9765. res.set_content(gzipped, "image/jpeg");
  9766. res.set_header("Content-Encoding", "GZIP");
  9767. });
  9768. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9769. auto se = detail::scope_exit([&] {
  9770. svr.stop();
  9771. t.join();
  9772. ASSERT_FALSE(svr.is_running());
  9773. });
  9774. svr.wait_until_ready();
  9775. Client cli(HOST, PORT);
  9776. {
  9777. auto res = cli.Get("/gzipped");
  9778. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9780. EXPECT_EQ("Hello World!", res->body);
  9781. #else
  9782. ASSERT_FALSE(res);
  9783. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9784. #endif
  9785. }
  9786. {
  9787. // open_stream() must behave the same way.
  9788. auto handle = cli.open_stream("GET", "/gzipped");
  9789. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9790. ASSERT_TRUE(handle.is_valid());
  9791. std::string received;
  9792. char buf[256];
  9793. ssize_t n;
  9794. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9795. received.append(buf, static_cast<size_t>(n));
  9796. }
  9797. EXPECT_EQ("Hello World!", received);
  9798. #else
  9799. EXPECT_FALSE(handle.is_valid());
  9800. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9801. #endif
  9802. }
  9803. {
  9804. // A differently-cased coding must not be mistaken for an unknown one, or
  9805. // the body would be handed back still compressed.
  9806. auto res = cli.Get("/gzipped-uppercase");
  9807. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9809. EXPECT_EQ("Hello World!", res->body);
  9810. #else
  9811. ASSERT_FALSE(res);
  9812. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9813. #endif
  9814. }
  9815. }
  9816. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  9817. // the same message as the comma-joined one, so both have to be read the same
  9818. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  9819. // single gzip coding, and a body the sender says was encoded twice was handed
  9820. // back after one pass, still compressed but presented as decoded.
  9821. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  9822. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9823. Server svr;
  9824. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  9825. res.set_content(body, "image/jpeg");
  9826. res.headers.emplace("Content-Encoding", "gzip");
  9827. res.headers.emplace("Content-Encoding", "gzip");
  9828. });
  9829. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  9830. res.set_content(body, "image/jpeg");
  9831. res.set_header("Content-Encoding", "gzip, gzip");
  9832. });
  9833. auto port = svr.bind_to_any_port(HOST);
  9834. thread t = thread([&]() { svr.listen_after_bind(); });
  9835. auto se = detail::scope_exit([&] {
  9836. svr.stop();
  9837. t.join();
  9838. ASSERT_FALSE(svr.is_running());
  9839. });
  9840. svr.wait_until_ready();
  9841. Client cli(HOST, port);
  9842. // Two codings is not something cpp-httplib decodes, so both representations
  9843. // take the pass-through path rather than one of them being gunzipped once.
  9844. for (const char *path : {"/split", "/joined"}) {
  9845. auto res = cli.Get(path);
  9846. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9847. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9848. EXPECT_EQ(body, res->body) << path;
  9849. }
  9850. }
  9851. // Regression test for DoS vulnerability: a malicious server sending a response
  9852. // without Content-Length header must not cause unbounded memory consumption on
  9853. // the client side. The client should stop reading after a reasonable limit,
  9854. // similar to the server-side set_payload_max_length protection.
  9855. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9856. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9857. #ifndef _WIN32
  9858. signal(SIGPIPE, SIG_IGN);
  9859. #endif
  9860. auto server_thread = std::thread([] {
  9861. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9862. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9863. default_socket_options(srv);
  9864. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9865. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9866. sockaddr_in addr{};
  9867. addr.sin_family = AF_INET;
  9868. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9869. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9870. int opt = 1;
  9871. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9872. #ifdef _WIN32
  9873. reinterpret_cast<const char *>(&opt),
  9874. #else
  9875. &opt,
  9876. #endif
  9877. sizeof(opt));
  9878. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9879. ::listen(srv, 1);
  9880. sockaddr_in cli_addr{};
  9881. socklen_t cli_len = sizeof(cli_addr);
  9882. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9883. if (cli != INVALID_SOCKET) {
  9884. char buf[4096];
  9885. ::recv(cli, buf, sizeof(buf), 0);
  9886. // Malicious response: no Content-Length, no chunked encoding
  9887. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9888. "Connection: close\r\n"
  9889. "\r\n";
  9890. ::send(cli,
  9891. #ifdef _WIN32
  9892. static_cast<const char *>(response_header.c_str()),
  9893. static_cast<int>(response_header.size()),
  9894. #else
  9895. response_header.c_str(), response_header.size(),
  9896. #endif
  9897. 0);
  9898. // Send 10MB of data
  9899. std::string chunk(64 * 1024, 'A');
  9900. size_t total_sent = 0;
  9901. while (total_sent < MALICIOUS_DATA_SIZE) {
  9902. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9903. auto sent = ::send(cli,
  9904. #ifdef _WIN32
  9905. static_cast<const char *>(chunk.c_str()),
  9906. static_cast<int>(to_send),
  9907. #else
  9908. chunk.c_str(), to_send,
  9909. #endif
  9910. 0);
  9911. if (sent <= 0) break;
  9912. total_sent += static_cast<size_t>(sent);
  9913. }
  9914. detail::close_socket(cli);
  9915. }
  9916. detail::close_socket(srv);
  9917. });
  9918. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9919. size_t total_read = 0;
  9920. {
  9921. Client cli("127.0.0.1", PORT + 2);
  9922. cli.set_read_timeout(5, 0);
  9923. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9924. auto stream = cli.open_stream("GET", "/malicious");
  9925. ASSERT_TRUE(stream.is_valid());
  9926. char buffer[64 * 1024];
  9927. ssize_t n;
  9928. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9929. total_read += static_cast<size_t>(n);
  9930. }
  9931. } // StreamHandle and Client destroyed here, closing the socket
  9932. server_thread.join();
  9933. // With set_payload_max_length, the client must stop reading before consuming
  9934. // all 10MB. The read loop should be cut off at or near the configured limit.
  9935. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9936. << "Client read " << total_read << " bytes, exceeding the configured "
  9937. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9938. }
  9939. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9940. // the entire response body without truncation.
  9941. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9942. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9943. #ifndef _WIN32
  9944. signal(SIGPIPE, SIG_IGN);
  9945. #endif
  9946. auto server_thread = std::thread([] {
  9947. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9948. default_socket_options(srv);
  9949. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9950. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9951. sockaddr_in addr{};
  9952. addr.sin_family = AF_INET;
  9953. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9954. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9955. int opt = 1;
  9956. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9957. #ifdef _WIN32
  9958. reinterpret_cast<const char *>(&opt),
  9959. #else
  9960. &opt,
  9961. #endif
  9962. sizeof(opt));
  9963. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9964. ::listen(srv, 1);
  9965. sockaddr_in cli_addr{};
  9966. socklen_t cli_len = sizeof(cli_addr);
  9967. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9968. if (cli != INVALID_SOCKET) {
  9969. char buf[4096];
  9970. ::recv(cli, buf, sizeof(buf), 0);
  9971. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9972. "Connection: close\r\n"
  9973. "\r\n";
  9974. ::send(cli,
  9975. #ifdef _WIN32
  9976. static_cast<const char *>(response_header.c_str()),
  9977. static_cast<int>(response_header.size()),
  9978. #else
  9979. response_header.c_str(), response_header.size(),
  9980. #endif
  9981. 0);
  9982. std::string chunk(64 * 1024, 'A');
  9983. size_t total_sent = 0;
  9984. while (total_sent < DATA_SIZE) {
  9985. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9986. auto sent = ::send(cli,
  9987. #ifdef _WIN32
  9988. static_cast<const char *>(chunk.c_str()),
  9989. static_cast<int>(to_send),
  9990. #else
  9991. chunk.c_str(), to_send,
  9992. #endif
  9993. 0);
  9994. if (sent <= 0) break;
  9995. total_sent += static_cast<size_t>(sent);
  9996. }
  9997. #ifdef _WIN32
  9998. ::shutdown(cli, SD_SEND);
  9999. #else
  10000. ::shutdown(cli, SHUT_WR);
  10001. #endif
  10002. // Drain until the client closes its end, ensuring all data is delivered
  10003. char drain[1024];
  10004. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10005. detail::close_socket(cli);
  10006. }
  10007. detail::close_socket(srv);
  10008. });
  10009. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10010. size_t total_read = 0;
  10011. {
  10012. Client cli("127.0.0.1", PORT + 2);
  10013. cli.set_read_timeout(5, 0);
  10014. cli.set_payload_max_length(0); // 0 means no limit
  10015. auto stream = cli.open_stream("GET", "/data");
  10016. ASSERT_TRUE(stream.is_valid());
  10017. char buffer[64 * 1024];
  10018. ssize_t n;
  10019. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10020. total_read += static_cast<size_t>(n);
  10021. }
  10022. }
  10023. server_thread.join();
  10024. EXPECT_EQ(total_read, DATA_SIZE)
  10025. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  10026. << " bytes without truncation, but only read " << total_read << " bytes.";
  10027. }
  10028. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  10029. // enormous Content-Length must not cause the client to pre-allocate a huge
  10030. // response body buffer. The reservation is capped at payload_max_length_, and
  10031. // the read itself fails when the body exceeds the limit.
  10032. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  10033. #ifndef _WIN32
  10034. signal(SIGPIPE, SIG_IGN);
  10035. #endif
  10036. auto server_thread = std::thread([] {
  10037. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10038. default_socket_options(srv);
  10039. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10040. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10041. sockaddr_in addr{};
  10042. addr.sin_family = AF_INET;
  10043. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10044. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10045. int opt = 1;
  10046. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10047. #ifdef _WIN32
  10048. reinterpret_cast<const char *>(&opt),
  10049. #else
  10050. &opt,
  10051. #endif
  10052. sizeof(opt));
  10053. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10054. ::listen(srv, 1);
  10055. sockaddr_in cli_addr{};
  10056. socklen_t cli_len = sizeof(cli_addr);
  10057. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10058. if (cli != INVALID_SOCKET) {
  10059. char buf[4096];
  10060. ::recv(cli, buf, sizeof(buf), 0);
  10061. // Malicious response: claim a 20GB body but send only a tiny payload.
  10062. std::string response = "HTTP/1.1 200 OK\r\n"
  10063. "Content-Length: 20000000000\r\n"
  10064. "\r\n"
  10065. "abc";
  10066. ::send(cli,
  10067. #ifdef _WIN32
  10068. static_cast<const char *>(response.c_str()),
  10069. static_cast<int>(response.size()),
  10070. #else
  10071. response.c_str(), response.size(),
  10072. #endif
  10073. 0);
  10074. detail::close_socket(cli);
  10075. }
  10076. detail::close_socket(srv);
  10077. });
  10078. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10079. {
  10080. Client cli("127.0.0.1", PORT + 2);
  10081. cli.set_read_timeout(5, 0);
  10082. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  10083. // result in a 20GB pre-allocation. The Get() call is expected to fail
  10084. // (server claims more bytes than payload_max_length permits), but it must
  10085. // not exhaust memory before getting there.
  10086. auto res = cli.Get("/malicious");
  10087. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  10088. }
  10089. server_thread.join();
  10090. }
  10091. // Verify that content_receiver bypasses the default payload_max_length,
  10092. // allowing streaming downloads larger than 100MB without requiring an explicit
  10093. // set_payload_max_length call.
  10094. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  10095. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10096. #ifndef _WIN32
  10097. signal(SIGPIPE, SIG_IGN);
  10098. #endif
  10099. auto server_thread = std::thread([] {
  10100. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10101. default_socket_options(srv);
  10102. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10103. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10104. sockaddr_in addr{};
  10105. addr.sin_family = AF_INET;
  10106. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10107. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10108. int opt = 1;
  10109. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10110. #ifdef _WIN32
  10111. reinterpret_cast<const char *>(&opt),
  10112. #else
  10113. &opt,
  10114. #endif
  10115. sizeof(opt));
  10116. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10117. ::listen(srv, 1);
  10118. sockaddr_in cli_addr{};
  10119. socklen_t cli_len = sizeof(cli_addr);
  10120. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10121. if (cli != INVALID_SOCKET) {
  10122. char buf[4096];
  10123. ::recv(cli, buf, sizeof(buf), 0);
  10124. // Response with Content-Length larger than default 100MB limit
  10125. auto content_length = std::to_string(DATA_SIZE);
  10126. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10127. "Content-Length: " +
  10128. content_length +
  10129. "\r\n"
  10130. "Connection: close\r\n"
  10131. "\r\n";
  10132. ::send(cli,
  10133. #ifdef _WIN32
  10134. static_cast<const char *>(response_header.c_str()),
  10135. static_cast<int>(response_header.size()),
  10136. #else
  10137. response_header.c_str(), response_header.size(),
  10138. #endif
  10139. 0);
  10140. std::string chunk(64 * 1024, 'A');
  10141. size_t total_sent = 0;
  10142. while (total_sent < DATA_SIZE) {
  10143. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10144. auto sent = ::send(cli,
  10145. #ifdef _WIN32
  10146. static_cast<const char *>(chunk.c_str()),
  10147. static_cast<int>(to_send),
  10148. #else
  10149. chunk.c_str(), to_send,
  10150. #endif
  10151. 0);
  10152. if (sent <= 0) break;
  10153. total_sent += static_cast<size_t>(sent);
  10154. }
  10155. detail::close_socket(cli);
  10156. }
  10157. detail::close_socket(srv);
  10158. });
  10159. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10160. size_t total_received = 0;
  10161. {
  10162. Client cli("127.0.0.1", PORT + 2);
  10163. cli.set_read_timeout(10, 0);
  10164. // Do NOT call set_payload_max_length — use the default 100MB limit
  10165. auto res =
  10166. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10167. total_received += data_length;
  10168. return true;
  10169. });
  10170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10171. EXPECT_EQ(StatusCode::OK_200, res->status);
  10172. }
  10173. server_thread.join();
  10174. EXPECT_EQ(total_received, DATA_SIZE)
  10175. << "With content_receiver, the client should read all " << DATA_SIZE
  10176. << " bytes despite the default 100MB payload_max_length, but only read "
  10177. << total_received << " bytes.";
  10178. }
  10179. // Verify that an explicit set_payload_max_length smaller than the response is
  10180. // enforced even when a content_receiver is used.
  10181. TEST(ClientVulnerabilityTest,
  10182. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  10183. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10184. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  10185. #ifndef _WIN32
  10186. signal(SIGPIPE, SIG_IGN);
  10187. #endif
  10188. auto server_thread = std::thread([] {
  10189. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10190. default_socket_options(srv);
  10191. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10192. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10193. sockaddr_in addr{};
  10194. addr.sin_family = AF_INET;
  10195. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10196. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10197. int opt = 1;
  10198. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10199. #ifdef _WIN32
  10200. reinterpret_cast<const char *>(&opt),
  10201. #else
  10202. &opt,
  10203. #endif
  10204. sizeof(opt));
  10205. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10206. ::listen(srv, 1);
  10207. sockaddr_in cli_addr{};
  10208. socklen_t cli_len = sizeof(cli_addr);
  10209. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10210. if (cli != INVALID_SOCKET) {
  10211. char buf[4096];
  10212. ::recv(cli, buf, sizeof(buf), 0);
  10213. auto content_length = std::to_string(DATA_SIZE);
  10214. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10215. "Content-Length: " +
  10216. content_length +
  10217. "\r\n"
  10218. "Connection: close\r\n"
  10219. "\r\n";
  10220. ::send(cli,
  10221. #ifdef _WIN32
  10222. static_cast<const char *>(response_header.c_str()),
  10223. static_cast<int>(response_header.size()),
  10224. #else
  10225. response_header.c_str(), response_header.size(),
  10226. #endif
  10227. 0);
  10228. std::string chunk(64 * 1024, 'A');
  10229. size_t total_sent = 0;
  10230. while (total_sent < DATA_SIZE) {
  10231. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10232. auto sent = ::send(cli,
  10233. #ifdef _WIN32
  10234. static_cast<const char *>(chunk.c_str()),
  10235. static_cast<int>(to_send),
  10236. #else
  10237. chunk.c_str(), to_send,
  10238. #endif
  10239. 0);
  10240. if (sent <= 0) break;
  10241. total_sent += static_cast<size_t>(sent);
  10242. }
  10243. detail::close_socket(cli);
  10244. }
  10245. detail::close_socket(srv);
  10246. });
  10247. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10248. size_t total_received = 0;
  10249. {
  10250. Client cli("127.0.0.1", PORT + 2);
  10251. cli.set_read_timeout(10, 0);
  10252. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  10253. auto res =
  10254. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10255. total_received += data_length;
  10256. return true;
  10257. });
  10258. // Should fail because 200MB exceeds the explicit 150MB limit
  10259. EXPECT_FALSE(res);
  10260. }
  10261. server_thread.join();
  10262. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  10263. << "Client with content_receiver should respect the explicit "
  10264. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  10265. << total_received << " bytes.";
  10266. }
  10267. // Verify that an explicit set_payload_max_length larger than the response
  10268. // allows the content_receiver to read all data successfully.
  10269. TEST(ClientVulnerabilityTest,
  10270. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  10271. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10272. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  10273. #ifndef _WIN32
  10274. signal(SIGPIPE, SIG_IGN);
  10275. #endif
  10276. auto server_thread = std::thread([] {
  10277. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10278. default_socket_options(srv);
  10279. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10280. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10281. sockaddr_in addr{};
  10282. addr.sin_family = AF_INET;
  10283. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10284. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10285. int opt = 1;
  10286. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10287. #ifdef _WIN32
  10288. reinterpret_cast<const char *>(&opt),
  10289. #else
  10290. &opt,
  10291. #endif
  10292. sizeof(opt));
  10293. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10294. ::listen(srv, 1);
  10295. sockaddr_in cli_addr{};
  10296. socklen_t cli_len = sizeof(cli_addr);
  10297. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10298. if (cli != INVALID_SOCKET) {
  10299. char buf[4096];
  10300. ::recv(cli, buf, sizeof(buf), 0);
  10301. auto content_length = std::to_string(DATA_SIZE);
  10302. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10303. "Content-Length: " +
  10304. content_length +
  10305. "\r\n"
  10306. "Connection: close\r\n"
  10307. "\r\n";
  10308. ::send(cli,
  10309. #ifdef _WIN32
  10310. static_cast<const char *>(response_header.c_str()),
  10311. static_cast<int>(response_header.size()),
  10312. #else
  10313. response_header.c_str(), response_header.size(),
  10314. #endif
  10315. 0);
  10316. std::string chunk(64 * 1024, 'A');
  10317. size_t total_sent = 0;
  10318. while (total_sent < DATA_SIZE) {
  10319. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10320. auto sent = ::send(cli,
  10321. #ifdef _WIN32
  10322. static_cast<const char *>(chunk.c_str()),
  10323. static_cast<int>(to_send),
  10324. #else
  10325. chunk.c_str(), to_send,
  10326. #endif
  10327. 0);
  10328. if (sent <= 0) break;
  10329. total_sent += static_cast<size_t>(sent);
  10330. }
  10331. #ifdef _WIN32
  10332. ::shutdown(cli, SD_SEND);
  10333. #else
  10334. ::shutdown(cli, SHUT_WR);
  10335. #endif
  10336. char drain[1024];
  10337. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10338. detail::close_socket(cli);
  10339. }
  10340. detail::close_socket(srv);
  10341. });
  10342. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10343. size_t total_received = 0;
  10344. {
  10345. Client cli("127.0.0.1", PORT + 2);
  10346. cli.set_read_timeout(10, 0);
  10347. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  10348. auto res =
  10349. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10350. total_received += data_length;
  10351. return true;
  10352. });
  10353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10354. EXPECT_EQ(StatusCode::OK_200, res->status);
  10355. }
  10356. server_thread.join();
  10357. EXPECT_EQ(total_received, DATA_SIZE)
  10358. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  10359. << " bytes (larger than " << DATA_SIZE
  10360. << " bytes response), content_receiver should read all data, but only "
  10361. "read "
  10362. << total_received << " bytes.";
  10363. }
  10364. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  10365. // Regression test for "zip bomb" attack on the client side: a malicious server
  10366. // sends a small gzip-compressed response that decompresses to a huge payload.
  10367. // The client must enforce payload_max_length on the decompressed size.
  10368. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  10369. constexpr size_t DECOMPRESSED_SIZE =
  10370. 10 * 1024 * 1024; // 10MB after decompression
  10371. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10372. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  10373. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  10374. std::string compressed;
  10375. {
  10376. httplib::detail::gzip_compressor compressor;
  10377. bool ok =
  10378. compressor.compress(uncompressed.data(), uncompressed.size(),
  10379. /*last=*/true, [&](const char *buf, size_t len) {
  10380. compressed.append(buf, len);
  10381. return true;
  10382. });
  10383. ASSERT_TRUE(ok);
  10384. }
  10385. // Sanity: compressed data should be much smaller than the decompressed size
  10386. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  10387. #ifndef _WIN32
  10388. signal(SIGPIPE, SIG_IGN);
  10389. #endif
  10390. // Set up the listening socket in the main thread so the server is guaranteed
  10391. // to be ready before the client connects (eliminates race condition).
  10392. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10393. default_socket_options(srv);
  10394. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10395. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10396. sockaddr_in addr{};
  10397. addr.sin_family = AF_INET;
  10398. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  10399. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10400. int opt = 1;
  10401. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10402. #ifdef _WIN32
  10403. reinterpret_cast<const char *>(&opt),
  10404. #else
  10405. &opt,
  10406. #endif
  10407. sizeof(opt));
  10408. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  10409. ASSERT_EQ(0, ::listen(srv, 1));
  10410. auto server_thread = std::thread([&compressed, srv] {
  10411. sockaddr_in cli_addr{};
  10412. socklen_t cli_len = sizeof(cli_addr);
  10413. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10414. if (cli != INVALID_SOCKET) {
  10415. // Read the full HTTP request (until \r\n\r\n)
  10416. char buf[4096];
  10417. size_t total = 0;
  10418. while (total < sizeof(buf)) {
  10419. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  10420. if (n <= 0) break;
  10421. total += static_cast<size_t>(n);
  10422. // Check for end of headers
  10423. if (total >= 4) {
  10424. std::string req(buf, total);
  10425. if (req.find("\r\n\r\n") != std::string::npos) break;
  10426. }
  10427. }
  10428. // Malicious response: gzip-compressed body, no Content-Length
  10429. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10430. "Content-Encoding: gzip\r\n"
  10431. "Connection: close\r\n"
  10432. "\r\n";
  10433. ::send(cli,
  10434. #ifdef _WIN32
  10435. static_cast<const char *>(response_header.c_str()),
  10436. static_cast<int>(response_header.size()),
  10437. #else
  10438. response_header.c_str(), response_header.size(),
  10439. #endif
  10440. 0);
  10441. // Send the compressed payload (small on the wire, huge when decompressed)
  10442. size_t total_sent = 0;
  10443. while (total_sent < compressed.size()) {
  10444. auto to_send = std::min(compressed.size() - total_sent,
  10445. static_cast<size_t>(64 * 1024));
  10446. auto sent =
  10447. ::send(cli,
  10448. #ifdef _WIN32
  10449. static_cast<const char *>(compressed.c_str() + total_sent),
  10450. static_cast<int>(to_send),
  10451. #else
  10452. compressed.c_str() + total_sent, to_send,
  10453. #endif
  10454. 0);
  10455. if (sent <= 0) break;
  10456. total_sent += static_cast<size_t>(sent);
  10457. }
  10458. detail::close_socket(cli);
  10459. }
  10460. });
  10461. auto se = detail::scope_exit([&] {
  10462. detail::close_socket(srv);
  10463. server_thread.join();
  10464. });
  10465. size_t total_decompressed = 0;
  10466. {
  10467. Client cli("127.0.0.1", PORT + 3);
  10468. cli.set_read_timeout(5, 0);
  10469. cli.set_decompress(true);
  10470. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10471. auto stream = cli.open_stream("GET", "/zipbomb");
  10472. ASSERT_TRUE(stream.is_valid());
  10473. char buffer[64 * 1024];
  10474. ssize_t n;
  10475. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10476. total_decompressed += static_cast<size_t>(n);
  10477. }
  10478. }
  10479. // The decompressed size must be capped by payload_max_length. Without
  10480. // protection, the client would decompress the full 10MB from a tiny
  10481. // compressed payload, enabling a zip bomb DoS attack.
  10482. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10483. << "Client decompressed " << total_decompressed
  10484. << " bytes from a gzip response. The decompressed size should be "
  10485. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10486. }
  10487. #endif
  10488. TEST(HostAndPortPropertiesTest, NoSSL) {
  10489. httplib::Client cli("www.google.com", 1234);
  10490. ASSERT_EQ("www.google.com", cli.host());
  10491. ASSERT_EQ(1234, cli.port());
  10492. }
  10493. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10494. httplib::Client cli("www.google.com:1234");
  10495. ASSERT_EQ("www.google.com", cli.host());
  10496. ASSERT_EQ(1234, cli.port());
  10497. }
  10498. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10499. // Port number that overflows int — should not crash, client becomes invalid
  10500. httplib::Client cli("http://www.google.com:99999999999999999999");
  10501. ASSERT_FALSE(cli.is_valid());
  10502. }
  10503. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10504. // Port 99999 exceeds valid range (1-65535) — should not crash
  10505. httplib::Client cli("http://www.google.com:99999");
  10506. ASSERT_FALSE(cli.is_valid());
  10507. }
  10508. #ifdef CPPHTTPLIB_SSL_ENABLED
  10509. TEST(HostAndPortPropertiesTest, SSL) {
  10510. httplib::SSLClient cli("www.google.com");
  10511. ASSERT_EQ("www.google.com", cli.host());
  10512. ASSERT_EQ(443, cli.port());
  10513. }
  10514. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10515. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10516. std::string cert;
  10517. read_file(CA_CERT_FILE, cert);
  10518. httplib::SSLClient httplib_client("www.google.com");
  10519. // Load CA store first time
  10520. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10521. // Load CA store second time (update)
  10522. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10523. // Verify client is still valid and can make connections
  10524. httplib_client.enable_server_certificate_verification(true);
  10525. auto res = httplib_client.Get("/");
  10526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10527. // Google may return 200 or 301 depending on various factors
  10528. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10529. res->status == StatusCode::MovedPermanently_301);
  10530. }
  10531. TEST(SSLClientTest, ServerNameIndication_Online) {
  10532. auto host = "httpbingo.org";
  10533. auto path = std::string{"/get"};
  10534. SSLClient cli(host, 443);
  10535. auto res = cli.Get(path);
  10536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10537. ASSERT_EQ(StatusCode::OK_200, res->status);
  10538. }
  10539. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10540. // Use a site that will cause SSL verification failure due to self-signed cert
  10541. SSLClient cli("self-signed.badssl.com", 443);
  10542. cli.enable_server_certificate_verification(true);
  10543. auto res = cli.Get("/");
  10544. ASSERT_TRUE(!res);
  10545. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10546. // Verify backend error is captured for SSLServerVerification
  10547. // This occurs when certificate verification fails
  10548. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10549. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10550. EXPECT_NE(0UL, res.ssl_backend_error());
  10551. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10552. // For OpenSSL, ssl_error is 0 for verification errors
  10553. EXPECT_EQ(0, res.ssl_error());
  10554. #if !defined(_WIN32) || \
  10555. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10556. // On non-Windows or when Windows Schannel is disabled, the error comes
  10557. // from OpenSSL's verification
  10558. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10559. res.ssl_backend_error());
  10560. #endif
  10561. #endif
  10562. }
  10563. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10564. // Use a site where hostname doesn't match the certificate
  10565. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10566. SSLClient cli("wrong.host.badssl.com", 443);
  10567. cli.enable_server_certificate_verification(true);
  10568. cli.enable_server_hostname_verification(true);
  10569. auto res = cli.Get("/");
  10570. ASSERT_TRUE(!res);
  10571. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10572. // Verify backend error is captured for hostname verification failure
  10573. EXPECT_NE(0UL, res.ssl_backend_error());
  10574. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10575. // For OpenSSL, ssl_error is 0 for verification errors
  10576. EXPECT_EQ(0, res.ssl_error());
  10577. #if !defined(_WIN32) || \
  10578. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10579. // On non-Windows or when Windows Schannel is disabled, the error comes
  10580. // from OpenSSL's hostname verification
  10581. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10582. res.ssl_backend_error());
  10583. #endif
  10584. #endif
  10585. }
  10586. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10587. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10588. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10589. SSLClient cli("www.google.com", 443);
  10590. cli.enable_server_certificate_verification(true);
  10591. auto res = cli.Get("/");
  10592. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10593. }
  10594. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10595. SSLClient cli("www.google.com", 443);
  10596. cli.enable_server_certificate_verification(true);
  10597. cli.enable_windows_certificate_verification(false);
  10598. auto res = cli.Get("/");
  10599. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10600. }
  10601. #endif
  10602. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10603. Client cli("https://google.com");
  10604. auto res = cli.Get("/");
  10605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10606. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10607. }
  10608. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10609. SSLClient cli("google.com");
  10610. cli.set_ca_cert_path(CA_CERT_FILE);
  10611. auto res = cli.Get("/");
  10612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10613. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10614. }
  10615. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10616. SSLClient cli("google.com");
  10617. cli.enable_server_certificate_verification(true);
  10618. cli.set_ca_cert_path("hello");
  10619. auto res = cli.Get("/");
  10620. ASSERT_TRUE(!res);
  10621. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10622. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10623. // should be set
  10624. EXPECT_EQ(0, res.ssl_error());
  10625. // Verify backend error is captured for SSLLoadingCerts
  10626. // This error occurs when loading CA certificates fails
  10627. EXPECT_NE(0UL, res.ssl_backend_error());
  10628. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10629. // OpenSSL specific error codes:
  10630. // > openssl errstr 0x80000002
  10631. // error:80000002:system library::No such file or directory
  10632. // > openssl errstr 0xA000126
  10633. // error:0A000126:SSL routines::unexpected eof while reading
  10634. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10635. res.ssl_backend_error() == 0xA000126);
  10636. #endif
  10637. }
  10638. TEST(SSLClientTest, ServerCertificateVerification4) {
  10639. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10640. ASSERT_TRUE(svr.is_valid());
  10641. svr.Get("/test", [&](const Request &, Response &res) {
  10642. res.set_content("test", "text/plain");
  10643. svr.stop();
  10644. ASSERT_TRUE(true);
  10645. });
  10646. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10647. auto se = detail::scope_exit([&] {
  10648. t.join();
  10649. ASSERT_FALSE(svr.is_running());
  10650. });
  10651. svr.wait_until_ready();
  10652. SSLClient cli("127.0.0.1", PORT);
  10653. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10654. cli.enable_server_certificate_verification(true);
  10655. cli.set_connection_timeout(30);
  10656. auto res = cli.Get("/test");
  10657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10658. ASSERT_EQ(StatusCode::OK_200, res->status);
  10659. }
  10660. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10661. std::string cert;
  10662. read_file(CA_CERT_FILE, cert);
  10663. SSLClient cli("google.com");
  10664. cli.load_ca_cert_store(cert.data(), cert.size());
  10665. const auto res = cli.Get("/");
  10666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10667. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10668. }
  10669. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10670. // clang-format off
  10671. static constexpr char cert[] =
  10672. "GlobalSign Root CA\n"
  10673. "==================\n"
  10674. "-----BEGIN CERTIFICATE-----\n"
  10675. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10676. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10677. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10678. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10679. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10680. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10681. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10682. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10683. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10684. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10685. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10686. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10687. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10688. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10689. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10690. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10691. "-----END CERTIFICATE-----\n";
  10692. // clang-format on
  10693. SSLClient cli("google.com");
  10694. cli.load_ca_cert_store(cert, sizeof(cert));
  10695. const auto res = cli.Get("/");
  10696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10697. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10698. }
  10699. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10700. SSLClient cli("www.youtube.com");
  10701. cli.set_ca_cert_path(CA_CERT_FILE);
  10702. cli.enable_server_certificate_verification(true);
  10703. cli.set_follow_location(true);
  10704. auto res = cli.Get("/");
  10705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10706. ASSERT_EQ(StatusCode::OK_200, res->status);
  10707. }
  10708. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10709. SSLClient cli("wWw.YouTube.Com");
  10710. cli.set_ca_cert_path(CA_CERT_FILE);
  10711. cli.enable_server_certificate_verification(true);
  10712. cli.enable_server_hostname_verification(true);
  10713. cli.set_follow_location(true);
  10714. auto res = cli.Get("/");
  10715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10716. ASSERT_EQ(StatusCode::OK_200, res->status);
  10717. }
  10718. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10719. SSLClient cli("gOoGlE.COm");
  10720. cli.enable_server_certificate_verification(true);
  10721. cli.enable_server_hostname_verification(true);
  10722. cli.set_follow_location(true);
  10723. auto res = cli.Get("/");
  10724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10725. ASSERT_EQ(StatusCode::OK_200, res->status);
  10726. }
  10727. TEST(SSLClientTest, Issue2004_Online) {
  10728. Client client("https://google.com");
  10729. client.set_follow_location(true);
  10730. auto res = client.Get("/");
  10731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10732. ASSERT_EQ(StatusCode::OK_200, res->status);
  10733. auto body = res->body;
  10734. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10735. }
  10736. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10737. // Create SSLClient with invalid cert/key to make is_valid() return false
  10738. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10739. "nonexistent_key.pem");
  10740. // is_valid() should be false due to cert loading failure
  10741. ASSERT_FALSE(cli.is_valid());
  10742. auto res = cli.Get("/");
  10743. ASSERT_FALSE(res);
  10744. EXPECT_EQ(Error::SSLConnection, res.error());
  10745. }
  10746. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10747. // Test for Issue #2251: SSL error not properly reported when client cert
  10748. // and key paths are swapped or mismatched
  10749. // This simulates the scenario where user accidentally swaps the cert and key
  10750. // files
  10751. // Using client cert file as private key and vice versa (completely wrong)
  10752. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10753. // Should fail validation due to cert/key mismatch
  10754. ASSERT_FALSE(cli.is_valid());
  10755. // Attempt to make a request should fail with proper error
  10756. auto res = cli.Get("/");
  10757. ASSERT_FALSE(res);
  10758. EXPECT_EQ(Error::SSLConnection, res.error());
  10759. // SSL error should be recorded in the Result object (this is the key fix for
  10760. // Issue #2251)
  10761. auto backend_error = res.ssl_backend_error();
  10762. EXPECT_NE(0u, backend_error);
  10763. }
  10764. // Tests cert/key mismatch detection at the TLS context level
  10765. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10766. // Test that using mismatched cert/key causes connection failure.
  10767. // We verify this at the SSLClient level rather than through internal
  10768. // TLS API functions.
  10769. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10770. cli.enable_server_certificate_verification(false);
  10771. cli.set_connection_timeout(2);
  10772. // The mismatch should cause a connection or handshake error
  10773. auto res = cli.Get("/test");
  10774. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10775. // Either way, the request should fail
  10776. EXPECT_FALSE(res);
  10777. }
  10778. #endif
  10779. #if 0
  10780. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10781. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10782. ASSERT_TRUE(cli != nullptr);
  10783. cli->set_address_family(AF_INET6);
  10784. cli->set_interface("en0");
  10785. auto res = cli->Get("/get");
  10786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10787. ASSERT_EQ(StatusCode::OK_200, res->status);
  10788. }
  10789. #endif
  10790. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10791. #ifdef CPPHTTPLIB_SSL_ENABLED
  10792. void ClientCertPresent(
  10793. const std::string &client_cert_file,
  10794. const std::string &client_private_key_file,
  10795. const std::string &client_encrypted_private_key_pass = std::string()) {
  10796. using namespace httplib::tls;
  10797. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10798. CLIENT_CA_CERT_DIR);
  10799. ASSERT_TRUE(svr.is_valid());
  10800. svr.Get("/test", [&](const Request &req, Response &res) {
  10801. res.set_content("test", "text/plain");
  10802. auto cert = req.peer_cert();
  10803. ASSERT_TRUE(static_cast<bool>(cert));
  10804. std::string common_name = cert.subject_cn();
  10805. EXPECT_EQ("Common Name", common_name);
  10806. });
  10807. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10808. auto se = detail::scope_exit([&] {
  10809. svr.stop();
  10810. t.join();
  10811. ASSERT_FALSE(svr.is_running());
  10812. });
  10813. svr.wait_until_ready();
  10814. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10815. client_encrypted_private_key_pass);
  10816. cli.enable_server_certificate_verification(false);
  10817. cli.set_connection_timeout(30);
  10818. auto res = cli.Get("/test");
  10819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10820. ASSERT_EQ(StatusCode::OK_200, res->status);
  10821. }
  10822. TEST(SSLClientServerTest, ClientCertPresent) {
  10823. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10824. }
  10825. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10826. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10827. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10828. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10829. }
  10830. // PEM memory-based constructor tests (works with all TLS backends)
  10831. void PemMemoryClientCertPresent(
  10832. const std::string &client_cert_file,
  10833. const std::string &client_private_key_file,
  10834. const std::string &client_encrypted_private_key_pass = std::string()) {
  10835. // Read PEM files into memory
  10836. std::string server_cert_pem, server_key_pem;
  10837. std::string client_ca_pem;
  10838. std::string client_cert_pem, client_key_pem;
  10839. read_file(SERVER_CERT_FILE, server_cert_pem);
  10840. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10841. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10842. read_file(client_cert_file, client_cert_pem);
  10843. read_file(client_private_key_file, client_key_pem);
  10844. // Create server with PEM memory
  10845. SSLServer::PemMemory server_pem = {
  10846. server_cert_pem.c_str(),
  10847. server_cert_pem.size(),
  10848. server_key_pem.c_str(),
  10849. server_key_pem.size(),
  10850. client_ca_pem.c_str(),
  10851. client_ca_pem.size(),
  10852. nullptr // no password for server key
  10853. };
  10854. SSLServer svr(server_pem);
  10855. ASSERT_TRUE(svr.is_valid());
  10856. svr.Get("/test", [&](const Request &, Response &res) {
  10857. res.set_content("test", "text/plain");
  10858. });
  10859. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10860. auto se = detail::scope_exit([&] {
  10861. svr.stop();
  10862. t.join();
  10863. ASSERT_FALSE(svr.is_running());
  10864. });
  10865. svr.wait_until_ready();
  10866. // Create client with PEM memory
  10867. const char *password = client_encrypted_private_key_pass.empty()
  10868. ? nullptr
  10869. : client_encrypted_private_key_pass.c_str();
  10870. SSLClient::PemMemory client_pem = {
  10871. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10872. client_key_pem.size(), password};
  10873. SSLClient cli(HOST, PORT, client_pem);
  10874. cli.enable_server_certificate_verification(false);
  10875. cli.set_connection_timeout(30);
  10876. auto res = cli.Get("/test");
  10877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10878. ASSERT_EQ(StatusCode::OK_200, res->status);
  10879. }
  10880. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10881. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10882. }
  10883. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10884. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10885. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10886. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10887. }
  10888. TEST(SSLClientServerTest, ClientCertMissing) {
  10889. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10890. CLIENT_CA_CERT_DIR);
  10891. ASSERT_TRUE(svr.is_valid());
  10892. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10893. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10894. auto se = detail::scope_exit([&] {
  10895. svr.stop();
  10896. t.join();
  10897. ASSERT_FALSE(svr.is_running());
  10898. });
  10899. svr.wait_until_ready();
  10900. SSLClient cli(HOST, PORT);
  10901. cli.set_connection_timeout(30);
  10902. auto res = cli.Get("/test");
  10903. ASSERT_TRUE(!res);
  10904. // When client cert is missing and server requires it, connection fails
  10905. // Error type depends on backend implementation
  10906. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10907. res.error() == Error::SSLConnection);
  10908. // Verify backend error is captured
  10909. // Note: This test may have different error codes depending on the exact
  10910. // verification failure
  10911. EXPECT_NE(0UL, res.ssl_backend_error());
  10912. }
  10913. TEST(SSLClientServerTest, TrustDirOptional) {
  10914. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10915. ASSERT_TRUE(svr.is_valid());
  10916. svr.Get("/test", [&](const Request &, Response &res) {
  10917. res.set_content("test", "text/plain");
  10918. });
  10919. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10920. auto se = detail::scope_exit([&] {
  10921. svr.stop();
  10922. t.join();
  10923. ASSERT_FALSE(svr.is_running());
  10924. });
  10925. svr.wait_until_ready();
  10926. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10927. cli.enable_server_certificate_verification(false);
  10928. cli.set_connection_timeout(30);
  10929. auto res = cli.Get("/test");
  10930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10931. ASSERT_EQ(StatusCode::OK_200, res->status);
  10932. }
  10933. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10934. class NoListenSSLServer : public SSLServer {
  10935. public:
  10936. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10937. const char *client_ca_cert_file_path,
  10938. const char *client_ca_cert_dir_path = nullptr)
  10939. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10940. client_ca_cert_dir_path),
  10941. stop_(false) {}
  10942. std::atomic_bool stop_;
  10943. private:
  10944. bool process_and_close_socket(socket_t /*sock*/) override {
  10945. // Don't create SSL context
  10946. while (!stop_.load()) {
  10947. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10948. }
  10949. return true;
  10950. }
  10951. };
  10952. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10953. CLIENT_CA_CERT_FILE);
  10954. ASSERT_TRUE(svr.is_valid());
  10955. svr.Get("/test", [&](const Request &, Response &res) {
  10956. res.set_content("test", "text/plain");
  10957. });
  10958. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10959. auto se = detail::scope_exit([&] {
  10960. svr.stop_ = true;
  10961. svr.stop();
  10962. t.join();
  10963. ASSERT_FALSE(svr.is_running());
  10964. });
  10965. svr.wait_until_ready();
  10966. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10967. cli.enable_server_certificate_verification(false);
  10968. cli.set_connection_timeout(1);
  10969. auto res = cli.Get("/test");
  10970. ASSERT_TRUE(!res);
  10971. EXPECT_EQ(Error::SSLConnection, res.error());
  10972. // Timeout results in WantRead error code (maps to backend-specific value)
  10973. EXPECT_NE(0, res.ssl_error());
  10974. }
  10975. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10976. // Test SSLServer with client certificate verification using the standard
  10977. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10978. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10979. CLIENT_CA_CERT_DIR);
  10980. ASSERT_TRUE(svr.is_valid());
  10981. svr.Get("/test", [&](const Request &req, Response &res) {
  10982. res.set_content("test", "text/plain");
  10983. auto cert = req.peer_cert();
  10984. ASSERT_TRUE(static_cast<bool>(cert));
  10985. auto common_name = cert.subject_cn();
  10986. EXPECT_EQ("Common Name", common_name);
  10987. });
  10988. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10989. auto se = detail::scope_exit([&] {
  10990. svr.stop();
  10991. t.join();
  10992. ASSERT_FALSE(svr.is_running());
  10993. });
  10994. svr.wait_until_ready();
  10995. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10996. cli.enable_server_certificate_verification(false);
  10997. cli.set_connection_timeout(30);
  10998. auto res = cli.Get("/test");
  10999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11000. ASSERT_EQ(StatusCode::OK_200, res->status);
  11001. }
  11002. // Test verify_hostname for both OpenSSL and MbedTLS backends
  11003. // Verifies that wildcard matching and exact matching work consistently
  11004. TEST(SSLClientServerTest, TlsVerifyHostname) {
  11005. using namespace httplib::tls;
  11006. // We need a running server to test against
  11007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11008. ASSERT_TRUE(svr.is_valid());
  11009. svr.Get("/test", [](const Request &, Response &res) {
  11010. res.set_content("ok", "text/plain");
  11011. });
  11012. thread t([&]() { svr.listen(HOST, PORT); });
  11013. auto se = detail::scope_exit([&] {
  11014. svr.stop();
  11015. t.join();
  11016. });
  11017. svr.wait_until_ready();
  11018. bool verify_callback_called = false;
  11019. bool verify_result_wrong = false;
  11020. SSLClient cli(HOST, PORT);
  11021. cli.enable_server_certificate_verification(true);
  11022. cli.set_ca_cert_path(CA_CERT_FILE);
  11023. cli.set_connection_timeout(5);
  11024. // Note: Test certificate has CN="Common Name", not "localhost"
  11025. bool verify_result_cn = false;
  11026. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11027. verify_callback_called = true;
  11028. if (!ctx.cert) return false;
  11029. // Test 1: "Common Name" should match (our test server cert CN)
  11030. verify_result_cn = ctx.check_hostname("Common Name");
  11031. // Test 2: wrong hostname should not match
  11032. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  11033. return true; // Accept for the purpose of this test
  11034. });
  11035. auto res = cli.Get("/test");
  11036. // The request may succeed or fail depending on cert configuration
  11037. // but the callback should have been called
  11038. ASSERT_TRUE(verify_callback_called)
  11039. << "Verify callback should have been called";
  11040. // CN="Common Name" should match our test certificate
  11041. //
  11042. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  11043. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  11044. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  11045. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  11046. // <openssl/base.h>, which is included transitively when
  11047. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  11048. #if defined(OPENSSL_IS_BORINGSSL)
  11049. EXPECT_FALSE(verify_result_cn)
  11050. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  11051. #else
  11052. EXPECT_TRUE(verify_result_cn)
  11053. << "verify_hostname should match 'Common Name' (certificate CN)";
  11054. #endif
  11055. // Wrong hostname should not match
  11056. EXPECT_FALSE(verify_result_wrong)
  11057. << "verify_hostname should not match 'wronghost.example.com'";
  11058. }
  11059. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  11060. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  11061. // X509_check_ip behavior and must hold for every backend.
  11062. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  11063. using namespace httplib::tls;
  11064. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  11065. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  11066. ASSERT_TRUE(svr.is_valid());
  11067. svr.Get("/test", [](const Request &, Response &res) {
  11068. res.set_content("ok", "text/plain");
  11069. });
  11070. thread t([&]() { svr.listen(HOST, PORT); });
  11071. auto se = detail::scope_exit([&] {
  11072. svr.stop();
  11073. t.join();
  11074. });
  11075. svr.wait_until_ready();
  11076. bool verify_callback_called = false;
  11077. bool ip_matched_via_cn = true;
  11078. SSLClient cli(HOST, PORT);
  11079. cli.enable_server_certificate_verification(true);
  11080. cli.set_ca_cert_path(CA_CERT_FILE);
  11081. cli.set_connection_timeout(5);
  11082. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11083. verify_callback_called = true;
  11084. if (!ctx.cert) return false;
  11085. // The IP appears only in the CN, so it must NOT be accepted.
  11086. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  11087. return true; // Accept for the purpose of this test
  11088. });
  11089. cli.Get("/test");
  11090. ASSERT_TRUE(verify_callback_called)
  11091. << "Verify callback should have been called";
  11092. EXPECT_FALSE(ip_matched_via_cn)
  11093. << "An IP host must not be authenticated via the certificate CN";
  11094. }
  11095. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  11096. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  11097. using namespace httplib::tls;
  11098. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  11099. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  11100. ASSERT_TRUE(svr.is_valid());
  11101. svr.Get("/test", [](const Request &, Response &res) {
  11102. res.set_content("ok", "text/plain");
  11103. });
  11104. thread t([&]() { svr.listen(HOST, PORT); });
  11105. auto se = detail::scope_exit([&] {
  11106. svr.stop();
  11107. t.join();
  11108. });
  11109. svr.wait_until_ready();
  11110. bool verify_callback_called = false;
  11111. bool san_matched = false;
  11112. bool wrong_ipv6_matched = true;
  11113. bool cn_ipv6_matched = true;
  11114. SSLClient cli(HOST, PORT);
  11115. cli.enable_server_certificate_verification(true);
  11116. cli.set_ca_cert_path(CA_CERT_FILE);
  11117. cli.set_connection_timeout(5);
  11118. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11119. verify_callback_called = true;
  11120. if (!ctx.cert) return false;
  11121. // Matches the IPv6 iPAddress SAN.
  11122. san_matched = ctx.check_hostname("2001:db8::1");
  11123. // A different IPv6 address must not match.
  11124. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  11125. // "::1" lives only in the CN, so it must not be accepted.
  11126. cn_ipv6_matched = ctx.check_hostname("::1");
  11127. return true; // Accept for the purpose of this test
  11128. });
  11129. cli.Get("/test");
  11130. ASSERT_TRUE(verify_callback_called)
  11131. << "Verify callback should have been called";
  11132. EXPECT_TRUE(san_matched)
  11133. << "verify_hostname should match an IPv6 iPAddress SAN";
  11134. EXPECT_FALSE(wrong_ipv6_matched)
  11135. << "verify_hostname should not match a non-matching IPv6 address";
  11136. EXPECT_FALSE(cn_ipv6_matched)
  11137. << "An IPv6 host must not be authenticated via the certificate CN";
  11138. }
  11139. #endif
  11140. // mbedTLS-specific callback constructor test
  11141. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  11142. #ifdef CPPHTTPLIB_SSL_ENABLED
  11143. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  11144. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11145. ASSERT_TRUE(svr.is_valid());
  11146. // Set up a handler to verify client certificate is present
  11147. bool client_cert_verified = false;
  11148. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11149. // Verify that client certificate was provided
  11150. client_cert_verified = true;
  11151. res.set_content("success", "text/plain");
  11152. });
  11153. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11154. auto se = detail::scope_exit([&] {
  11155. svr.stop();
  11156. t.join();
  11157. ASSERT_FALSE(svr.is_running());
  11158. });
  11159. svr.wait_until_ready();
  11160. // Client with certificate
  11161. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11162. cli.enable_server_certificate_verification(false);
  11163. cli.set_connection_timeout(30);
  11164. auto res = cli.Get("/test");
  11165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11166. ASSERT_EQ(StatusCode::OK_200, res->status);
  11167. ASSERT_TRUE(client_cert_verified);
  11168. EXPECT_EQ("success", res->body);
  11169. }
  11170. #endif
  11171. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  11172. // backends
  11173. #ifdef CPPHTTPLIB_SSL_ENABLED
  11174. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  11175. using namespace httplib::tls;
  11176. // Test that when client CA cert file is provided,
  11177. // the server properly requests and validates client certificates
  11178. // Create a server with client authentication
  11179. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11180. ASSERT_TRUE(svr.is_valid());
  11181. bool handler_called = false;
  11182. svr.Get("/test", [&](const Request &req, Response &res) {
  11183. handler_called = true;
  11184. // Verify that a client certificate was provided
  11185. auto cert = req.peer_cert();
  11186. ASSERT_TRUE(static_cast<bool>(cert));
  11187. // Get the issuer name
  11188. std::string issuer_str = cert.issuer_name();
  11189. ASSERT_FALSE(issuer_str.empty());
  11190. // The client certificate should be issued by our test CA
  11191. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  11192. res.set_content("authenticated", "text/plain");
  11193. });
  11194. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11195. auto se = detail::scope_exit([&] {
  11196. svr.stop();
  11197. t.join();
  11198. ASSERT_FALSE(svr.is_running());
  11199. });
  11200. svr.wait_until_ready();
  11201. // Connect with a client certificate issued by the CA
  11202. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11203. cli.enable_server_certificate_verification(false);
  11204. cli.set_connection_timeout(30);
  11205. auto res = cli.Get("/test");
  11206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11207. ASSERT_EQ(StatusCode::OK_200, res->status);
  11208. ASSERT_TRUE(handler_called);
  11209. EXPECT_EQ("authenticated", res->body);
  11210. }
  11211. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  11212. using namespace httplib::tls;
  11213. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11214. ASSERT_TRUE(svr.is_valid());
  11215. svr.Get("/test", [](const Request &, Response &res) {
  11216. res.set_content("ok", "text/plain");
  11217. });
  11218. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11219. auto se = detail::scope_exit([&] {
  11220. svr.stop();
  11221. t.join();
  11222. });
  11223. svr.wait_until_ready();
  11224. SSLClient cli(HOST, PORT);
  11225. cli.enable_server_certificate_verification(false);
  11226. cli.set_connection_timeout(30);
  11227. bool cert_checked = false;
  11228. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11229. if (ctx.cert) {
  11230. auto sans = ctx.sans();
  11231. // Test certificate may or may not have SANs - just verify the API
  11232. // works If SANs exist, verify the types are valid
  11233. for (const auto &san : sans) {
  11234. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  11235. san.type == SanType::EMAIL || san.type == SanType::URI ||
  11236. san.type == SanType::OTHER);
  11237. EXPECT_FALSE(san.value.empty());
  11238. }
  11239. cert_checked = true;
  11240. }
  11241. return true;
  11242. });
  11243. auto res = cli.Get("/test");
  11244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11245. EXPECT_TRUE(cert_checked);
  11246. }
  11247. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  11248. using namespace httplib::tls;
  11249. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11250. ASSERT_TRUE(svr.is_valid());
  11251. svr.Get("/test", [](const Request &, Response &res) {
  11252. res.set_content("ok", "text/plain");
  11253. });
  11254. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11255. auto se = detail::scope_exit([&] {
  11256. svr.stop();
  11257. t.join();
  11258. });
  11259. svr.wait_until_ready();
  11260. SSLClient cli(HOST, PORT);
  11261. cli.enable_server_certificate_verification(false);
  11262. cli.set_connection_timeout(30);
  11263. bool validity_checked = false;
  11264. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11265. if (ctx.cert) {
  11266. time_t not_before = 0, not_after = 0;
  11267. bool result = ctx.validity(not_before, not_after);
  11268. EXPECT_TRUE(result);
  11269. // Verify that not_before < now < not_after for a valid cert
  11270. time_t now = time(nullptr);
  11271. EXPECT_LT(not_before, now);
  11272. EXPECT_GT(not_after, now);
  11273. validity_checked = true;
  11274. }
  11275. return true;
  11276. });
  11277. auto res = cli.Get("/test");
  11278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11279. EXPECT_TRUE(validity_checked);
  11280. }
  11281. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  11282. using namespace httplib::tls;
  11283. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11284. ASSERT_TRUE(svr.is_valid());
  11285. svr.Get("/test", [](const Request &, Response &res) {
  11286. res.set_content("ok", "text/plain");
  11287. });
  11288. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11289. auto se = detail::scope_exit([&] {
  11290. svr.stop();
  11291. t.join();
  11292. });
  11293. svr.wait_until_ready();
  11294. SSLClient cli(HOST, PORT);
  11295. cli.enable_server_certificate_verification(false);
  11296. cli.set_connection_timeout(30);
  11297. bool serial_checked = false;
  11298. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11299. if (ctx.cert) {
  11300. std::string serial = ctx.serial();
  11301. EXPECT_FALSE(serial.empty());
  11302. // Serial should be a hex string
  11303. for (char c : serial) {
  11304. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  11305. (c >= 'a' && c <= 'f'));
  11306. }
  11307. serial_checked = true;
  11308. }
  11309. return true;
  11310. });
  11311. auto res = cli.Get("/test");
  11312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11313. EXPECT_TRUE(serial_checked);
  11314. }
  11315. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  11316. // Test 1: Valid CA file - no error should be recorded
  11317. {
  11318. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11319. CLIENT_CA_CERT_FILE);
  11320. ASSERT_TRUE(svr.is_valid());
  11321. // With valid setup, last_ssl_error should be 0
  11322. EXPECT_EQ(0, svr.ssl_last_error());
  11323. }
  11324. // Test 2: Invalid CA file content
  11325. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  11326. {
  11327. // Create a temporary file with completely invalid content
  11328. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  11329. {
  11330. std::ofstream ofs(temp_invalid_ca);
  11331. ofs << "This is not a certificate file at all\n";
  11332. ofs << "Just plain text content\n";
  11333. }
  11334. // Create server with invalid CA file
  11335. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  11336. // Clean up temporary file
  11337. std::remove(temp_invalid_ca);
  11338. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  11339. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  11340. // Note: SSL_CTX_load_verify_locations typically fails first,
  11341. // but our error handling code path is still exercised
  11342. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  11343. }
  11344. }
  11345. TEST(VerifyCallbackTest, VerifyContextFields) {
  11346. using namespace httplib::tls;
  11347. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11348. ASSERT_TRUE(svr.is_valid());
  11349. svr.Get("/test", [](const Request &, Response &res) {
  11350. res.set_content("ok", "text/plain");
  11351. });
  11352. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11353. auto se = detail::scope_exit([&] {
  11354. svr.stop();
  11355. t.join();
  11356. });
  11357. svr.wait_until_ready();
  11358. SSLClient cli(HOST, PORT);
  11359. cli.enable_server_certificate_verification(false);
  11360. cli.set_connection_timeout(30);
  11361. int callback_count = 0;
  11362. bool saw_leaf_cert = false;
  11363. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11364. if (ctx.cert) {
  11365. callback_count++;
  11366. // We should see at least one certificate (the leaf)
  11367. std::string cn = ctx.subject_cn();
  11368. if (!cn.empty()) { saw_leaf_cert = true; }
  11369. // Verify context fields are populated
  11370. EXPECT_NE(ctx.session, nullptr);
  11371. EXPECT_GE(ctx.depth, 0);
  11372. }
  11373. return true;
  11374. });
  11375. auto res = cli.Get("/test");
  11376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11377. EXPECT_GT(callback_count, 0);
  11378. EXPECT_TRUE(saw_leaf_cert);
  11379. }
  11380. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  11381. using httplib::tls::TlsError;
  11382. // Test that verify_error_to_string returns empty for success
  11383. std::string success_str = TlsError::verify_error_to_string(0);
  11384. EXPECT_TRUE(success_str.empty());
  11385. // Test that verify_error_to_string returns non-empty for error codes
  11386. // Using a common error code (certificate expired)
  11387. std::string error_str =
  11388. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  11389. EXPECT_FALSE(error_str.empty());
  11390. }
  11391. TEST(SessionVerifierTest, CertificateAccepted) {
  11392. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11393. ASSERT_TRUE(svr.is_valid());
  11394. svr.Get("/test", [](const Request &, Response &res) {
  11395. res.set_content("ok", "text/plain");
  11396. });
  11397. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11398. auto se = detail::scope_exit([&] {
  11399. svr.stop();
  11400. t.join();
  11401. });
  11402. svr.wait_until_ready();
  11403. SSLClient cli(HOST, PORT);
  11404. cli.enable_server_certificate_verification(false);
  11405. cli.set_connection_timeout(30);
  11406. bool callback_called = false;
  11407. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11408. EXPECT_NE(session, nullptr);
  11409. callback_called = true;
  11410. return SSLVerifierResponse::CertificateAccepted;
  11411. });
  11412. auto res = cli.Get("/test");
  11413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11414. EXPECT_EQ(200, res->status);
  11415. EXPECT_TRUE(callback_called);
  11416. }
  11417. TEST(SessionVerifierTest, CertificateRejected) {
  11418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11419. ASSERT_TRUE(svr.is_valid());
  11420. svr.Get("/test", [](const Request &, Response &res) {
  11421. res.set_content("ok", "text/plain");
  11422. });
  11423. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11424. auto se = detail::scope_exit([&] {
  11425. svr.stop();
  11426. t.join();
  11427. });
  11428. svr.wait_until_ready();
  11429. SSLClient cli(HOST, PORT);
  11430. cli.enable_server_certificate_verification(false);
  11431. cli.set_connection_timeout(30);
  11432. bool callback_called = false;
  11433. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11434. EXPECT_NE(session, nullptr);
  11435. callback_called = true;
  11436. return SSLVerifierResponse::CertificateRejected;
  11437. });
  11438. auto res = cli.Get("/test");
  11439. EXPECT_FALSE(res);
  11440. EXPECT_TRUE(callback_called);
  11441. }
  11442. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11444. ASSERT_TRUE(svr.is_valid());
  11445. svr.Get("/test", [](const Request &, Response &res) {
  11446. res.set_content("ok", "text/plain");
  11447. });
  11448. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11449. auto se = detail::scope_exit([&] {
  11450. svr.stop();
  11451. t.join();
  11452. });
  11453. svr.wait_until_ready();
  11454. // NoDecisionMade with verification disabled should succeed (no default check)
  11455. SSLClient cli(HOST, PORT);
  11456. cli.enable_server_certificate_verification(false);
  11457. cli.set_connection_timeout(30);
  11458. bool callback_called = false;
  11459. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11460. EXPECT_NE(session, nullptr);
  11461. callback_called = true;
  11462. return SSLVerifierResponse::NoDecisionMade;
  11463. });
  11464. auto res = cli.Get("/test");
  11465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11466. EXPECT_EQ(200, res->status);
  11467. EXPECT_TRUE(callback_called);
  11468. }
  11469. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11470. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11471. ASSERT_TRUE(svr.is_valid());
  11472. svr.Get("/test", [](const Request &, Response &res) {
  11473. res.set_content("ok", "text/plain");
  11474. });
  11475. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11476. auto se = detail::scope_exit([&] {
  11477. svr.stop();
  11478. t.join();
  11479. });
  11480. svr.wait_until_ready();
  11481. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11482. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11483. // so we only check that the request fails, not whether the callback was
  11484. // called.
  11485. SSLClient cli(HOST, PORT);
  11486. cli.enable_server_certificate_verification(true);
  11487. cli.set_connection_timeout(30);
  11488. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11489. EXPECT_NE(session, nullptr);
  11490. return SSLVerifierResponse::NoDecisionMade;
  11491. });
  11492. auto res = cli.Get("/test");
  11493. EXPECT_FALSE(res);
  11494. }
  11495. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11496. // Test SSL server using PemMemory constructor with client CA certificates
  11497. // Read PEM files
  11498. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11499. read_file(SERVER_CERT_FILE, server_cert_pem);
  11500. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11501. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11502. // Create SSLServer with PemMemory constructor including client CA
  11503. SSLServer::PemMemory server_pem = {
  11504. server_cert_pem.c_str(),
  11505. server_cert_pem.size(),
  11506. server_key_pem.c_str(),
  11507. server_key_pem.size(),
  11508. client_ca_pem.c_str(),
  11509. client_ca_pem.size(),
  11510. nullptr // no password for server key
  11511. };
  11512. SSLServer svr(server_pem);
  11513. ASSERT_TRUE(svr.is_valid());
  11514. // No SSL error should be recorded for valid setup
  11515. EXPECT_EQ(0, svr.ssl_last_error());
  11516. // Set up server endpoints
  11517. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11518. res.set_content("ok", "text/plain");
  11519. });
  11520. // Start server in a thread
  11521. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11522. svr.wait_until_ready();
  11523. // Connect with client certificate (using constructor with paths)
  11524. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11525. cli.enable_server_certificate_verification(false);
  11526. auto res = cli.Get("/test-pem-ca");
  11527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11528. EXPECT_EQ(200, res->status);
  11529. EXPECT_EQ("ok", res->body);
  11530. svr.stop();
  11531. server_thread.join();
  11532. }
  11533. #endif
  11534. #ifdef _WIN32
  11535. TEST(CleanupTest, WSACleanup) {
  11536. int ret = WSACleanup();
  11537. ASSERT_EQ(0, ret);
  11538. }
  11539. #endif
  11540. #ifndef CPPHTTPLIB_SSL_ENABLED
  11541. TEST(NoSSLSupport, SimpleInterface) {
  11542. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11543. }
  11544. #endif
  11545. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11546. TEST(InvalidScheme, SimpleInterface) {
  11547. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11548. }
  11549. #endif
  11550. TEST(NoScheme, SimpleInterface) {
  11551. Client cli("yahoo.com:80");
  11552. ASSERT_TRUE(cli.is_valid());
  11553. }
  11554. TEST(SendAPI, SimpleInterface_Online) {
  11555. Client cli("http://yahoo.com");
  11556. Request req;
  11557. req.method = "GET";
  11558. req.path = "/";
  11559. auto res = cli.send(req);
  11560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11561. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11562. }
  11563. TEST(SendAPI, WithParamsInRequest) {
  11564. Server svr;
  11565. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11566. EXPECT_TRUE(req.has_param("test"));
  11567. EXPECT_EQ("test_value", req.get_param_value("test"));
  11568. });
  11569. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11570. auto se = detail::scope_exit([&] {
  11571. svr.stop();
  11572. t.join();
  11573. ASSERT_FALSE(svr.is_running());
  11574. });
  11575. svr.wait_until_ready();
  11576. Client cli(HOST, PORT);
  11577. {
  11578. Request req;
  11579. req.method = "GET";
  11580. req.path = "/";
  11581. req.params.emplace("test", "test_value");
  11582. auto res = cli.send(req);
  11583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11584. }
  11585. {
  11586. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11588. }
  11589. }
  11590. TEST(ClientImplMethods, GetSocketTest) {
  11591. httplib::Server svr;
  11592. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11593. res.status = StatusCode::OK_200;
  11594. });
  11595. auto port = svr.bind_to_any_port("127.0.0.1");
  11596. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11597. auto se = detail::scope_exit([&] {
  11598. svr.stop();
  11599. thread.join();
  11600. ASSERT_FALSE(svr.is_running());
  11601. });
  11602. svr.wait_until_ready();
  11603. {
  11604. httplib::Client cli("127.0.0.1", port);
  11605. cli.set_keep_alive(true);
  11606. // Use the behavior of cpp-httplib of opening the connection
  11607. // only when the first request happens. If that changes,
  11608. // this test would be obsolete.
  11609. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11610. // This also implicitly tests the server. But other tests would fail much
  11611. // earlier than this one to be considered.
  11612. auto res = cli.Get("/");
  11613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11614. EXPECT_EQ(StatusCode::OK_200, res->status);
  11615. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11616. }
  11617. }
  11618. #ifdef CPPHTTPLIB_SSL_ENABLED
  11619. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11620. Client cli("http://yahoo.com");
  11621. auto res = cli.Get("/");
  11622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11623. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11624. cli.set_follow_location(true);
  11625. res = cli.Get("/");
  11626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11627. EXPECT_EQ(StatusCode::OK_200, res->status);
  11628. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11629. }
  11630. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11631. Client cli("https://yahoo.com");
  11632. auto res = cli.Get("/");
  11633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11634. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11635. cli.set_follow_location(true);
  11636. res = cli.Get("/");
  11637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11638. EXPECT_EQ(StatusCode::OK_200, res->status);
  11639. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11640. }
  11641. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11642. Client cli("https://yahoo.com");
  11643. auto res = cli.Get("/");
  11644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11645. ASSERT_FALSE(!res);
  11646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11647. ASSERT_FALSE(res == nullptr);
  11648. ASSERT_TRUE(res != nullptr);
  11649. EXPECT_EQ(Error::Success, res.error());
  11650. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11651. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11652. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11653. cli.set_follow_location(true);
  11654. res = cli.Get("/");
  11655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11656. EXPECT_EQ(Error::Success, res.error());
  11657. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11658. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11659. EXPECT_EQ(StatusCode::OK_200, res->status);
  11660. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11661. }
  11662. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11663. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11664. Client cli("https://cdnjs.cloudflare.com");
  11665. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11666. Headers{{"Accept-Encoding", "br"}});
  11667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11668. EXPECT_EQ(StatusCode::OK_200, res->status);
  11669. EXPECT_EQ(287630U, res->body.size());
  11670. EXPECT_EQ("application/javascript; charset=utf-8",
  11671. res->get_header_value("Content-Type"));
  11672. }
  11673. #endif
  11674. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11675. #undef REDIR_HOST // Silence compiler warning
  11676. #define REDIR_HOST "https://httpbingo.org"
  11677. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11678. Client cli(REDIR_HOST);
  11679. cli.set_follow_location(true);
  11680. auto res =
  11681. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11683. EXPECT_EQ(StatusCode::OK_200, res->status);
  11684. }
  11685. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11686. Client cli(REDIR_HOST);
  11687. cli.set_follow_location(true);
  11688. Params params;
  11689. params.emplace("url", "http://example.com");
  11690. params.emplace("status_code", "302");
  11691. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11693. EXPECT_EQ(StatusCode::OK_200, res->status);
  11694. }
  11695. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11696. Client cli(REDIR_HOST);
  11697. cli.set_follow_location(true);
  11698. Params params;
  11699. params.emplace("url", "http://example.com");
  11700. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11702. EXPECT_EQ(StatusCode::OK_200, res->status);
  11703. }
  11704. TEST(HttpToHttpsRedirectTest, CertFile) {
  11705. auto ssl_port = PORT + 1;
  11706. Server svr;
  11707. ASSERT_TRUE(svr.is_valid());
  11708. svr.Get("/index", [&](const Request &, Response &res) {
  11709. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11710. "/index");
  11711. svr.stop();
  11712. });
  11713. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11714. ASSERT_TRUE(ssl_svr.is_valid());
  11715. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11716. res.set_content("test", "text/plain");
  11717. ssl_svr.stop();
  11718. });
  11719. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11720. thread t2 =
  11721. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11722. auto se = detail::scope_exit([&] {
  11723. t2.join();
  11724. t.join();
  11725. ASSERT_FALSE(svr.is_running());
  11726. });
  11727. svr.wait_until_ready();
  11728. ssl_svr.wait_until_ready();
  11729. Client cli("127.0.0.1", PORT);
  11730. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11731. cli.enable_server_certificate_verification(true);
  11732. cli.set_follow_location(true);
  11733. cli.set_connection_timeout(30);
  11734. auto res = cli.Get("/index");
  11735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11736. ASSERT_EQ(StatusCode::OK_200, res->status);
  11737. }
  11738. TEST(SSLClientRedirectTest, CertFile) {
  11739. auto ssl_port = PORT + 1;
  11740. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11741. ASSERT_TRUE(ssl_svr1.is_valid());
  11742. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11743. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11744. "/index");
  11745. ssl_svr1.stop();
  11746. });
  11747. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11748. ASSERT_TRUE(ssl_svr2.is_valid());
  11749. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11750. res.set_content("test", "text/plain");
  11751. ssl_svr2.stop();
  11752. });
  11753. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11754. thread t2 =
  11755. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11756. auto se = detail::scope_exit([&] {
  11757. t2.join();
  11758. t.join();
  11759. ASSERT_FALSE(ssl_svr1.is_running());
  11760. });
  11761. ssl_svr1.wait_until_ready();
  11762. ssl_svr2.wait_until_ready();
  11763. SSLClient cli("127.0.0.1", PORT);
  11764. std::string cert;
  11765. read_file(SERVER_CERT2_FILE, cert);
  11766. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11767. cli.enable_server_certificate_verification(true);
  11768. cli.set_follow_location(true);
  11769. cli.set_connection_timeout(30);
  11770. auto res = cli.Get("/index");
  11771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11772. ASSERT_EQ(StatusCode::OK_200, res->status);
  11773. }
  11774. #endif
  11775. #ifdef CPPHTTPLIB_SSL_ENABLED
  11776. // Test that set_ca_cert_store() skips system certs (consistent with
  11777. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11778. // should be trusted - system certs should NOT be loaded.
  11779. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11780. // Load a specific cert that is NOT a system CA cert
  11781. std::string cert;
  11782. read_file(SERVER_CERT2_FILE, cert);
  11783. SSLClient cli("google.com");
  11784. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11785. cli.enable_server_certificate_verification(true);
  11786. // This should FAIL because:
  11787. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11788. // 2. System certs should NOT be loaded when custom store is set
  11789. // If system certs WERE loaded, this would succeed
  11790. auto res = cli.Get("/");
  11791. ASSERT_FALSE(res);
  11792. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11793. }
  11794. // Same as above, but through the native store handle path. Regression test:
  11795. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11796. // merged system certs into the user-provided store.
  11797. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11798. std::string cert;
  11799. read_file(SERVER_CERT2_FILE, cert);
  11800. SSLClient cli("google.com");
  11801. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11802. cli.enable_server_certificate_verification(true);
  11803. auto res = cli.Get("/");
  11804. ASSERT_FALSE(res);
  11805. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11806. }
  11807. // A custom store set via the native handle must still verify a server whose
  11808. // cert it does contain.
  11809. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11810. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11811. ASSERT_TRUE(svr.is_valid());
  11812. svr.Get("/test", [&](const Request &, Response &res) {
  11813. res.set_content("test", "text/plain");
  11814. });
  11815. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11816. auto se = detail::scope_exit([&] {
  11817. svr.stop();
  11818. t.join();
  11819. ASSERT_FALSE(svr.is_running());
  11820. });
  11821. svr.wait_until_ready();
  11822. SSLClient cli("127.0.0.1", PORT);
  11823. std::string cert;
  11824. read_file(SERVER_CERT2_FILE, cert);
  11825. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11826. cli.enable_server_certificate_verification(true);
  11827. cli.set_connection_timeout(30);
  11828. auto res = cli.Get("/test");
  11829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11830. ASSERT_EQ(StatusCode::OK_200, res->status);
  11831. }
  11832. // CA certs loaded through the universal Client must be transferred to the
  11833. // client created internally for following an HTTPS redirect. Regression test:
  11834. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11835. // the CA data for redirect transfer.
  11836. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11837. auto ssl_port = PORT + 1;
  11838. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11839. ASSERT_TRUE(ssl_svr1.is_valid());
  11840. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11841. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11842. "/index");
  11843. });
  11844. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11845. ASSERT_TRUE(ssl_svr2.is_valid());
  11846. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11847. res.set_content("test", "text/plain");
  11848. });
  11849. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11850. thread t2 =
  11851. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11852. auto se = detail::scope_exit([&] {
  11853. ssl_svr2.stop();
  11854. ssl_svr1.stop();
  11855. t2.join();
  11856. t.join();
  11857. ASSERT_FALSE(ssl_svr1.is_running());
  11858. });
  11859. ssl_svr1.wait_until_ready();
  11860. ssl_svr2.wait_until_ready();
  11861. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11862. std::string cert;
  11863. read_file(SERVER_CERT2_FILE, cert);
  11864. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11865. cli.enable_server_certificate_verification(true);
  11866. cli.set_follow_location(true);
  11867. cli.set_connection_timeout(30);
  11868. auto res = cli.Get("/index");
  11869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11870. ASSERT_EQ(StatusCode::OK_200, res->status);
  11871. }
  11872. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11873. // so a host signed by a system CA verifies even though a custom CA is set
  11874. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11875. std::string cert;
  11876. read_file(SERVER_CERT2_FILE, cert);
  11877. SSLClient cli("google.com");
  11878. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11879. cli.enable_system_ca(true);
  11880. cli.enable_server_certificate_verification(true);
  11881. auto res = cli.Get("/");
  11882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11883. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11884. }
  11885. // The custom CA remains effective when combined with the system CA
  11886. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11887. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11888. ASSERT_TRUE(svr.is_valid());
  11889. svr.Get("/test", [&](const Request &, Response &res) {
  11890. res.set_content("test", "text/plain");
  11891. });
  11892. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11893. auto se = detail::scope_exit([&] {
  11894. svr.stop();
  11895. t.join();
  11896. ASSERT_FALSE(svr.is_running());
  11897. });
  11898. svr.wait_until_ready();
  11899. SSLClient cli("127.0.0.1", PORT);
  11900. std::string cert;
  11901. read_file(SERVER_CERT2_FILE, cert);
  11902. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11903. cli.enable_system_ca(true);
  11904. cli.enable_server_certificate_verification(true);
  11905. cli.set_connection_timeout(30);
  11906. auto res = cli.Get("/test");
  11907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11908. ASSERT_EQ(StatusCode::OK_200, res->status);
  11909. }
  11910. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11911. // skip chain verification entirely (only the certificate identity was
  11912. // checked), so a server presenting an untrusted certificate with a matching
  11913. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11914. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11915. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11916. ASSERT_TRUE(svr.is_valid());
  11917. svr.Get("/test", [&](const Request &, Response &res) {
  11918. res.set_content("test", "text/plain");
  11919. });
  11920. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11921. auto se = detail::scope_exit([&] {
  11922. svr.stop();
  11923. t.join();
  11924. ASSERT_FALSE(svr.is_running());
  11925. });
  11926. svr.wait_until_ready();
  11927. SSLClient cli("127.0.0.1", PORT);
  11928. std::string cert;
  11929. // A trusted CA that did not sign the server certificate. The server cert
  11930. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11931. // this connection.
  11932. read_file(CLIENT_CA_CERT_FILE, cert);
  11933. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11934. cli.enable_server_certificate_verification(true);
  11935. cli.set_connection_timeout(30);
  11936. auto res = cli.Get("/test");
  11937. ASSERT_FALSE(res);
  11938. }
  11939. // enable_system_ca(false) prevents system CA loading entirely
  11940. TEST(SSLClientTest, DisableSystemCa_Online) {
  11941. SSLClient cli("google.com");
  11942. cli.enable_system_ca(false);
  11943. cli.enable_server_certificate_verification(true);
  11944. auto res = cli.Get("/");
  11945. ASSERT_FALSE(res);
  11946. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11947. // itself when the CA chain is empty
  11948. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11949. res.error() == Error::SSLConnection);
  11950. }
  11951. // The universal Client forwards enable_system_ca()
  11952. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11953. std::string cert;
  11954. read_file(SERVER_CERT2_FILE, cert);
  11955. Client cli("https://google.com");
  11956. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11957. cli.enable_system_ca(true);
  11958. cli.enable_server_certificate_verification(true);
  11959. auto res = cli.Get("/");
  11960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11961. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11962. }
  11963. // The system CA policy must carry over to the client created internally for
  11964. // following a cross-host HTTPS redirect
  11965. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11966. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11967. ASSERT_TRUE(svr.is_valid());
  11968. svr.Get("/index", [&](const Request &, Response &res) {
  11969. res.set_redirect("https://www.google.com/");
  11970. });
  11971. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11972. auto se = detail::scope_exit([&] {
  11973. svr.stop();
  11974. t.join();
  11975. ASSERT_FALSE(svr.is_running());
  11976. });
  11977. svr.wait_until_ready();
  11978. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11979. std::string cert;
  11980. read_file(SERVER_CERT2_FILE, cert);
  11981. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11982. cli.enable_system_ca(true);
  11983. cli.enable_server_certificate_verification(true);
  11984. cli.set_follow_location(true);
  11985. cli.set_connection_timeout(30);
  11986. // Receiving any response proves the redirect client completed the TLS
  11987. // handshake with a system-CA-signed host
  11988. auto res = cli.Get("/index");
  11989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11990. }
  11991. TEST(MultipartFormDataTest, LargeData) {
  11992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11993. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11994. const ContentReader &content_reader) {
  11995. if (req.is_multipart_form_data()) {
  11996. std::vector<FormData> items;
  11997. content_reader(
  11998. [&](const FormData &file) {
  11999. items.push_back(file);
  12000. return true;
  12001. },
  12002. [&](const char *data, size_t data_length) {
  12003. items.back().content.append(data, data_length);
  12004. return true;
  12005. });
  12006. EXPECT_TRUE(std::string(items[0].name) == "document");
  12007. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12008. EXPECT_TRUE(items[0].filename == "2MB_data");
  12009. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12010. EXPECT_TRUE(items[1].name == "hello");
  12011. EXPECT_TRUE(items[1].content == "world");
  12012. EXPECT_TRUE(items[1].filename == "");
  12013. EXPECT_TRUE(items[1].content_type == "");
  12014. } else {
  12015. std::string body;
  12016. content_reader([&](const char *data, size_t data_length) {
  12017. body.append(data, data_length);
  12018. return true;
  12019. });
  12020. }
  12021. });
  12022. auto port = svr.bind_to_any_port(HOST);
  12023. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12024. auto se = detail::scope_exit([&] {
  12025. svr.stop();
  12026. t.join();
  12027. ASSERT_FALSE(svr.is_running());
  12028. });
  12029. svr.wait_until_ready();
  12030. {
  12031. std::string data(1024 * 1024 * 2, '.');
  12032. std::stringstream buffer;
  12033. buffer << data;
  12034. SSLClient cli(HOST, port);
  12035. cli.enable_server_certificate_verification(false);
  12036. UploadFormDataItems items{
  12037. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12038. {"hello", "world", "", ""},
  12039. };
  12040. auto res = cli.Post("/post", items);
  12041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12042. ASSERT_EQ(StatusCode::OK_200, res->status);
  12043. }
  12044. }
  12045. TEST(MultipartFormDataTest, DataProviderItems) {
  12046. std::random_device seed_gen;
  12047. std::mt19937 random(seed_gen());
  12048. std::string rand1;
  12049. rand1.resize(1000);
  12050. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  12051. std::string rand2;
  12052. rand2.resize(3000);
  12053. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  12054. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12055. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  12056. const ContentReader &content_reader) {
  12057. ASSERT_FALSE(req.is_multipart_form_data());
  12058. std::string body;
  12059. content_reader([&](const char *data, size_t data_length) {
  12060. body.append(data, data_length);
  12061. return true;
  12062. });
  12063. EXPECT_EQ(body, "");
  12064. });
  12065. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  12066. const ContentReader &content_reader) {
  12067. ASSERT_TRUE(req.is_multipart_form_data());
  12068. std::vector<FormData> items;
  12069. content_reader(
  12070. [&](const FormData &file) {
  12071. items.push_back(file);
  12072. return true;
  12073. },
  12074. [&](const char *data, size_t data_length) {
  12075. items.back().content.append(data, data_length);
  12076. return true;
  12077. });
  12078. ASSERT_TRUE(items.size() == 2);
  12079. EXPECT_EQ(std::string(items[0].name), "name1");
  12080. EXPECT_EQ(items[0].content, "Testing123");
  12081. EXPECT_EQ(items[0].filename, "filename1");
  12082. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12083. EXPECT_EQ(items[1].name, "name2");
  12084. EXPECT_EQ(items[1].content, "Testing456");
  12085. EXPECT_EQ(items[1].filename, "");
  12086. EXPECT_EQ(items[1].content_type, "");
  12087. });
  12088. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  12089. const ContentReader &content_reader) {
  12090. ASSERT_TRUE(req.is_multipart_form_data());
  12091. std::vector<FormData> items;
  12092. content_reader(
  12093. [&](const FormData &file) {
  12094. items.push_back(file);
  12095. return true;
  12096. },
  12097. [&](const char *data, size_t data_length) {
  12098. items.back().content.append(data, data_length);
  12099. return true;
  12100. });
  12101. ASSERT_TRUE(items.size() == 2);
  12102. EXPECT_EQ(items[0].name, "name3");
  12103. EXPECT_EQ(items[0].content, rand1);
  12104. EXPECT_EQ(items[0].filename, "filename3");
  12105. EXPECT_EQ(items[0].content_type, "");
  12106. EXPECT_EQ(items[1].name, "name4");
  12107. EXPECT_EQ(items[1].content, rand2);
  12108. EXPECT_EQ(items[1].filename, "filename4");
  12109. EXPECT_EQ(items[1].content_type, "");
  12110. });
  12111. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  12112. const ContentReader &content_reader) {
  12113. ASSERT_TRUE(req.is_multipart_form_data());
  12114. std::vector<FormData> items;
  12115. content_reader(
  12116. [&](const FormData &file) {
  12117. items.push_back(file);
  12118. return true;
  12119. },
  12120. [&](const char *data, size_t data_length) {
  12121. items.back().content.append(data, data_length);
  12122. return true;
  12123. });
  12124. ASSERT_TRUE(items.size() == 4);
  12125. EXPECT_EQ(std::string(items[0].name), "name1");
  12126. EXPECT_EQ(items[0].content, "Testing123");
  12127. EXPECT_EQ(items[0].filename, "filename1");
  12128. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12129. EXPECT_EQ(items[1].name, "name2");
  12130. EXPECT_EQ(items[1].content, "Testing456");
  12131. EXPECT_EQ(items[1].filename, "");
  12132. EXPECT_EQ(items[1].content_type, "");
  12133. EXPECT_EQ(items[2].name, "name3");
  12134. EXPECT_EQ(items[2].content, rand1);
  12135. EXPECT_EQ(items[2].filename, "filename3");
  12136. EXPECT_EQ(items[2].content_type, "");
  12137. EXPECT_EQ(items[3].name, "name4");
  12138. EXPECT_EQ(items[3].content, rand2);
  12139. EXPECT_EQ(items[3].filename, "filename4");
  12140. EXPECT_EQ(items[3].content_type, "");
  12141. });
  12142. auto port = svr.bind_to_any_port("localhost");
  12143. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12144. auto se = detail::scope_exit([&] {
  12145. svr.stop();
  12146. t.join();
  12147. ASSERT_FALSE(svr.is_running());
  12148. });
  12149. svr.wait_until_ready();
  12150. {
  12151. SSLClient cli("localhost", port);
  12152. cli.enable_server_certificate_verification(false);
  12153. UploadFormDataItems items{
  12154. {"name1", "Testing123", "filename1", "application/octet-stream"},
  12155. {"name2", "Testing456", "", ""}, // not a file
  12156. };
  12157. {
  12158. auto res = cli.Post("/post-none", {}, {}, {});
  12159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12160. ASSERT_EQ(StatusCode::OK_200, res->status);
  12161. }
  12162. FormDataProviderItems providers;
  12163. {
  12164. auto res =
  12165. cli.Post("/post-items", {}, items, providers); // empty providers
  12166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12167. ASSERT_EQ(StatusCode::OK_200, res->status);
  12168. }
  12169. providers.push_back({"name3",
  12170. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12171. // test the offset is given correctly at each step
  12172. if (!offset)
  12173. sink.os.write(rand1.data(), 30);
  12174. else if (offset == 30)
  12175. sink.os.write(rand1.data() + 30, 300);
  12176. else if (offset == 330)
  12177. sink.os.write(rand1.data() + 330, 670);
  12178. else if (offset == rand1.size())
  12179. sink.done();
  12180. return true;
  12181. },
  12182. "filename3",
  12183. {}});
  12184. providers.push_back({"name4",
  12185. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12186. // test the offset is given correctly at each step
  12187. if (!offset)
  12188. sink.os.write(rand2.data(), 2000);
  12189. else if (offset == 2000)
  12190. sink.os.write(rand2.data() + 2000, 1);
  12191. else if (offset == 2001)
  12192. sink.os.write(rand2.data() + 2001, 999);
  12193. else if (offset == rand2.size())
  12194. sink.done();
  12195. return true;
  12196. },
  12197. "filename4",
  12198. {}});
  12199. {
  12200. auto res = cli.Post("/post-providers", {}, {}, providers);
  12201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12202. ASSERT_EQ(StatusCode::OK_200, res->status);
  12203. }
  12204. {
  12205. auto res = cli.Post("/post-both", {}, items, providers);
  12206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12207. ASSERT_EQ(StatusCode::OK_200, res->status);
  12208. }
  12209. }
  12210. }
  12211. TEST(MultipartFormDataTest, BadHeader) {
  12212. Server svr;
  12213. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12214. res.set_content("ok", "text/plain");
  12215. });
  12216. thread t = thread([&] { svr.listen(HOST, PORT); });
  12217. auto se = detail::scope_exit([&] {
  12218. svr.stop();
  12219. t.join();
  12220. ASSERT_FALSE(svr.is_running());
  12221. });
  12222. svr.wait_until_ready();
  12223. const std::string body =
  12224. "This is the preamble. It is to be ignored, though it\r\n"
  12225. "is a handy place for composition agents to include an\r\n"
  12226. "explanatory note to non-MIME conformant readers.\r\n"
  12227. "\r\n"
  12228. "\r\n"
  12229. "--simple boundary\r\n"
  12230. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12231. ": BAD...\r\n"
  12232. "\r\n"
  12233. "value1\r\n"
  12234. "--simple boundary\r\n"
  12235. "Content-Disposition: form-data; name=\"field2\"; "
  12236. "filename=\"example.txt\"\r\n"
  12237. "\r\n"
  12238. "value2\r\n"
  12239. "--simple boundary--\r\n"
  12240. "This is the epilogue. It is also to be ignored.\r\n";
  12241. std::string content_type =
  12242. R"(multipart/form-data; boundary="simple boundary")";
  12243. Client cli(HOST, PORT);
  12244. auto res = cli.Post("/post", body, content_type.c_str());
  12245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12246. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12247. }
  12248. TEST(MultipartFormDataTest, WithPreamble) {
  12249. Server svr;
  12250. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12251. res.set_content("ok", "text/plain");
  12252. });
  12253. thread t = thread([&] { svr.listen(HOST, PORT); });
  12254. auto se = detail::scope_exit([&] {
  12255. svr.stop();
  12256. t.join();
  12257. ASSERT_FALSE(svr.is_running());
  12258. });
  12259. svr.wait_until_ready();
  12260. const std::string body =
  12261. "This is the preamble. It is to be ignored, though it\r\n"
  12262. "is a handy place for composition agents to include an\r\n"
  12263. "explanatory note to non-MIME conformant readers.\r\n"
  12264. "\r\n"
  12265. "\r\n"
  12266. "--simple boundary\r\n"
  12267. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12268. "\r\n"
  12269. "value1\r\n"
  12270. "--simple boundary\r\n"
  12271. "Content-Disposition: form-data; name=\"field2\"; "
  12272. "filename=\"example.txt\"\r\n"
  12273. "\r\n"
  12274. "value2\r\n"
  12275. "--simple boundary--\r\n"
  12276. "This is the epilogue. It is also to be ignored.\r\n";
  12277. std::string content_type =
  12278. R"(multipart/form-data; boundary="simple boundary")";
  12279. Client cli(HOST, PORT);
  12280. auto res = cli.Post("/post", body, content_type.c_str());
  12281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12282. EXPECT_EQ(StatusCode::OK_200, res->status);
  12283. }
  12284. TEST(MultipartFormDataTest, PostCustomBoundary) {
  12285. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12286. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  12287. const ContentReader &content_reader) {
  12288. if (req.is_multipart_form_data()) {
  12289. std::vector<FormData> items;
  12290. content_reader(
  12291. [&](const FormData &file) {
  12292. items.push_back(file);
  12293. return true;
  12294. },
  12295. [&](const char *data, size_t data_length) {
  12296. items.back().content.append(data, data_length);
  12297. return true;
  12298. });
  12299. EXPECT_TRUE(std::string(items[0].name) == "document");
  12300. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12301. EXPECT_TRUE(items[0].filename == "2MB_data");
  12302. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12303. EXPECT_TRUE(items[1].name == "hello");
  12304. EXPECT_TRUE(items[1].content == "world");
  12305. EXPECT_TRUE(items[1].filename == "");
  12306. EXPECT_TRUE(items[1].content_type == "");
  12307. } else {
  12308. std::string body;
  12309. content_reader([&](const char *data, size_t data_length) {
  12310. body.append(data, data_length);
  12311. return true;
  12312. });
  12313. }
  12314. });
  12315. auto port = svr.bind_to_any_port("localhost");
  12316. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12317. auto se = detail::scope_exit([&] {
  12318. svr.stop();
  12319. t.join();
  12320. ASSERT_FALSE(svr.is_running());
  12321. });
  12322. svr.wait_until_ready();
  12323. {
  12324. std::string data(1024 * 1024 * 2, '.');
  12325. std::stringstream buffer;
  12326. buffer << data;
  12327. SSLClient cli("localhost", port);
  12328. cli.enable_server_certificate_verification(false);
  12329. UploadFormDataItems items{
  12330. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12331. {"hello", "world", "", ""},
  12332. };
  12333. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  12334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12335. ASSERT_EQ(StatusCode::OK_200, res->status);
  12336. }
  12337. }
  12338. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  12339. std::string data(1024 * 1024 * 2, '&');
  12340. std::stringstream buffer;
  12341. buffer << data;
  12342. Client cli("https://localhost:8080");
  12343. UploadFormDataItems items{
  12344. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12345. {"hello", "world", "", ""},
  12346. };
  12347. for (const char &c : " \t\r\n") {
  12348. auto res =
  12349. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  12350. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12351. ASSERT_FALSE(res);
  12352. }
  12353. }
  12354. TEST(MultipartFormDataTest, PutFormData) {
  12355. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12356. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  12357. const ContentReader &content_reader) {
  12358. if (req.is_multipart_form_data()) {
  12359. std::vector<FormData> items;
  12360. content_reader(
  12361. [&](const FormData &file) {
  12362. items.push_back(file);
  12363. return true;
  12364. },
  12365. [&](const char *data, size_t data_length) {
  12366. items.back().content.append(data, data_length);
  12367. return true;
  12368. });
  12369. EXPECT_TRUE(std::string(items[0].name) == "document");
  12370. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12371. EXPECT_TRUE(items[0].filename == "2MB_data");
  12372. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12373. EXPECT_TRUE(items[1].name == "hello");
  12374. EXPECT_TRUE(items[1].content == "world");
  12375. EXPECT_TRUE(items[1].filename == "");
  12376. EXPECT_TRUE(items[1].content_type == "");
  12377. } else {
  12378. std::string body;
  12379. content_reader([&](const char *data, size_t data_length) {
  12380. body.append(data, data_length);
  12381. return true;
  12382. });
  12383. }
  12384. });
  12385. auto port = svr.bind_to_any_port("localhost");
  12386. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12387. auto se = detail::scope_exit([&] {
  12388. svr.stop();
  12389. t.join();
  12390. ASSERT_FALSE(svr.is_running());
  12391. });
  12392. svr.wait_until_ready();
  12393. {
  12394. std::string data(1024 * 1024 * 2, '&');
  12395. std::stringstream buffer;
  12396. buffer << data;
  12397. SSLClient cli("localhost", port);
  12398. cli.enable_server_certificate_verification(false);
  12399. UploadFormDataItems items{
  12400. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12401. {"hello", "world", "", ""},
  12402. };
  12403. auto res = cli.Put("/put", items);
  12404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12405. ASSERT_EQ(StatusCode::OK_200, res->status);
  12406. }
  12407. }
  12408. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  12409. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12410. svr.Put("/put_customboundary",
  12411. [&](const Request &req, const Response & /*res*/,
  12412. const ContentReader &content_reader) {
  12413. if (req.is_multipart_form_data()) {
  12414. std::vector<FormData> items;
  12415. content_reader(
  12416. [&](const FormData &file) {
  12417. items.push_back(file);
  12418. return true;
  12419. },
  12420. [&](const char *data, size_t data_length) {
  12421. items.back().content.append(data, data_length);
  12422. return true;
  12423. });
  12424. EXPECT_TRUE(std::string(items[0].name) == "document");
  12425. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12426. EXPECT_TRUE(items[0].filename == "2MB_data");
  12427. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12428. EXPECT_TRUE(items[1].name == "hello");
  12429. EXPECT_TRUE(items[1].content == "world");
  12430. EXPECT_TRUE(items[1].filename == "");
  12431. EXPECT_TRUE(items[1].content_type == "");
  12432. } else {
  12433. std::string body;
  12434. content_reader([&](const char *data, size_t data_length) {
  12435. body.append(data, data_length);
  12436. return true;
  12437. });
  12438. }
  12439. });
  12440. auto port = svr.bind_to_any_port("localhost");
  12441. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12442. auto se = detail::scope_exit([&] {
  12443. svr.stop();
  12444. t.join();
  12445. ASSERT_FALSE(svr.is_running());
  12446. });
  12447. svr.wait_until_ready();
  12448. {
  12449. std::string data(1024 * 1024 * 2, '&');
  12450. std::stringstream buffer;
  12451. buffer << data;
  12452. SSLClient cli("localhost", port);
  12453. cli.enable_server_certificate_verification(false);
  12454. UploadFormDataItems items{
  12455. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12456. {"hello", "world", "", ""},
  12457. };
  12458. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12460. ASSERT_EQ(StatusCode::OK_200, res->status);
  12461. }
  12462. }
  12463. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12464. std::string data(1024 * 1024 * 2, '&');
  12465. std::stringstream buffer;
  12466. buffer << data;
  12467. Client cli("https://localhost:8080");
  12468. cli.enable_server_certificate_verification(false);
  12469. UploadFormDataItems items{
  12470. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12471. {"hello", "world", "", ""},
  12472. };
  12473. for (const char &c : " \t\r\n") {
  12474. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12475. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12476. ASSERT_FALSE(res);
  12477. }
  12478. }
  12479. TEST(MultipartFormDataTest, AlternateFilename) {
  12480. auto handled = false;
  12481. Server svr;
  12482. svr.Post("/test", [&](const Request &req, Response &res) {
  12483. ASSERT_EQ(2u, req.form.files.size());
  12484. ASSERT_EQ(1u, req.form.fields.size());
  12485. // Test files
  12486. const auto &file1 = req.form.get_file("file1");
  12487. ASSERT_EQ("file1", file1.name);
  12488. ASSERT_EQ("A.txt", file1.filename);
  12489. ASSERT_EQ("text/plain", file1.content_type);
  12490. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12491. const auto &file2 = req.form.get_file("file2");
  12492. ASSERT_EQ("file2", file2.name);
  12493. ASSERT_EQ("a.html", file2.filename);
  12494. ASSERT_EQ("text/html", file2.content_type);
  12495. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12496. file2.content);
  12497. // Test text field
  12498. const auto &text = req.form.get_field("text");
  12499. ASSERT_EQ("text default", text);
  12500. res.set_content("ok", "text/plain");
  12501. handled = true;
  12502. });
  12503. thread t = thread([&] { svr.listen(HOST, PORT); });
  12504. auto se = detail::scope_exit([&] {
  12505. svr.stop();
  12506. t.join();
  12507. ASSERT_FALSE(svr.is_running());
  12508. ASSERT_TRUE(handled);
  12509. });
  12510. svr.wait_until_ready();
  12511. auto req = "POST /test HTTP/1.1\r\n"
  12512. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12513. "Content-Length: 399\r\n"
  12514. "\r\n"
  12515. "----------\r\n"
  12516. "Content-Disposition: form-data; name=\"text\"\r\n"
  12517. "\r\n"
  12518. "text default\r\n"
  12519. "----------\r\n"
  12520. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12521. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12522. "Content-Type: text/plain\r\n"
  12523. "\r\n"
  12524. "Content of a.txt.\r\n"
  12525. "\r\n"
  12526. "----------\r\n"
  12527. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12528. "\"a.html\"\r\n"
  12529. "Content-Type: text/html\r\n"
  12530. "\r\n"
  12531. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12532. "\r\n"
  12533. "------------\r\n";
  12534. ASSERT_TRUE(send_request(1, req));
  12535. }
  12536. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12537. auto handled = false;
  12538. Server svr;
  12539. svr.Post("/test", [&](const Request &req, Response &res) {
  12540. // Case-insensitive "utf-8''" prefix with a long value
  12541. const auto &file = req.form.get_file("file1");
  12542. ASSERT_EQ("file1", file.name);
  12543. // 8000 chars exercises both the Content-Disposition parser and the
  12544. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12545. // Prior to the fix, std::regex_match on this header would cause O(N)
  12546. // stack recursion in libstdc++, leading to SIGSEGV.
  12547. std::string expected_filename(8000, 'A');
  12548. ASSERT_EQ(expected_filename, file.filename);
  12549. res.set_content("ok", "text/plain");
  12550. handled = true;
  12551. });
  12552. thread t = thread([&] { svr.listen(HOST, PORT); });
  12553. auto se = detail::scope_exit([&] {
  12554. svr.stop();
  12555. t.join();
  12556. ASSERT_FALSE(svr.is_running());
  12557. ASSERT_TRUE(handled);
  12558. });
  12559. svr.wait_until_ready();
  12560. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12561. // Regression test for GHSA-qq6v-r583-3h69
  12562. std::string long_filename(8000, 'A');
  12563. std::string body = "----------\r\n"
  12564. "Content-Disposition: form-data; name=\"file1\"; "
  12565. "filename*=\"Utf-8''" +
  12566. long_filename +
  12567. "\"\r\n"
  12568. "\r\n"
  12569. "hello\r\n"
  12570. "------------\r\n";
  12571. auto req = "POST /test HTTP/1.1\r\n"
  12572. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12573. "Content-Length: " +
  12574. std::to_string(body.size()) + "\r\n\r\n" + body;
  12575. ASSERT_TRUE(send_request(1, req));
  12576. }
  12577. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12578. auto handled = false;
  12579. Server svr;
  12580. svr.Post("/test", [&](const Request &req, Response &) {
  12581. ASSERT_EQ(2u, req.form.fields.size());
  12582. const auto &text1 = req.form.get_field("text1");
  12583. ASSERT_EQ("text1", text1);
  12584. const auto &text2 = req.form.get_field("text2");
  12585. ASSERT_EQ("text2", text2);
  12586. handled = true;
  12587. });
  12588. thread t = thread([&] { svr.listen(HOST, PORT); });
  12589. auto se = detail::scope_exit([&] {
  12590. svr.stop();
  12591. t.join();
  12592. ASSERT_FALSE(svr.is_running());
  12593. ASSERT_TRUE(handled);
  12594. });
  12595. svr.wait_until_ready();
  12596. auto req = "POST /test HTTP/1.1\r\n"
  12597. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12598. "Content-Length: 146\r\n"
  12599. "\r\n----------\r\n"
  12600. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12601. "\r\n"
  12602. "text1"
  12603. "\r\n----------\r\n"
  12604. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12605. "\r\n"
  12606. "text2"
  12607. "\r\n------------";
  12608. std::string response;
  12609. ASSERT_TRUE(send_request(1, req, &response));
  12610. ASSERT_EQ("200", response.substr(9, 3));
  12611. }
  12612. TEST(MultipartFormDataTest, ContentLength) {
  12613. auto handled = false;
  12614. Server svr;
  12615. svr.Post("/test", [&](const Request &req, Response &) {
  12616. ASSERT_EQ(2u, req.form.fields.size());
  12617. const auto &text1 = req.form.get_field("text1");
  12618. ASSERT_EQ("text1", text1);
  12619. const auto &text2 = req.form.get_field("text2");
  12620. ASSERT_EQ("text2", text2);
  12621. handled = true;
  12622. });
  12623. thread t = thread([&] { svr.listen(HOST, PORT); });
  12624. auto se = detail::scope_exit([&] {
  12625. svr.stop();
  12626. t.join();
  12627. ASSERT_FALSE(svr.is_running());
  12628. ASSERT_TRUE(handled);
  12629. });
  12630. svr.wait_until_ready();
  12631. auto req = "POST /test HTTP/1.1\r\n"
  12632. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12633. "Content-Length: 167\r\n"
  12634. "\r\n----------\r\n"
  12635. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12636. "Content-Length: 5\r\n"
  12637. "\r\n"
  12638. "text1"
  12639. "\r\n----------\r\n"
  12640. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12641. "\r\n"
  12642. "text2"
  12643. "\r\n------------\r\n";
  12644. std::string response;
  12645. ASSERT_TRUE(send_request(1, req, &response));
  12646. ASSERT_EQ("200", response.substr(9, 3));
  12647. }
  12648. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12649. auto handled = false;
  12650. Server svr;
  12651. svr.Post("/test", [&](const Request &req, Response &) {
  12652. ASSERT_EQ(2u, req.form.fields.size());
  12653. const auto &text1 = req.form.get_field("text1");
  12654. ASSERT_EQ("text1", text1);
  12655. // TODO: Add header access for text fields if needed
  12656. const auto &text2 = req.form.get_field("text2");
  12657. ASSERT_EQ("text2", text2);
  12658. // TODO: Header access for text fields needs to be implemented
  12659. // auto &headers = it->second.headers;
  12660. // ASSERT_EQ(3U, headers.size());
  12661. // auto custom_header = headers.find("x-whatever");
  12662. // ASSERT_TRUE(custom_header != headers.end());
  12663. // ASSERT_NE("customvalue", custom_header->second);
  12664. // ASSERT_EQ("CustomValue", custom_header->second);
  12665. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12666. handled = true;
  12667. });
  12668. thread t = thread([&] { svr.listen(HOST, PORT); });
  12669. auto se = detail::scope_exit([&] {
  12670. svr.stop();
  12671. t.join();
  12672. ASSERT_FALSE(svr.is_running());
  12673. ASSERT_TRUE(handled);
  12674. });
  12675. svr.wait_until_ready();
  12676. auto req = "POST /test HTTP/1.1\r\n"
  12677. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12678. "Content-Length: 232\r\n"
  12679. "\r\n----------\r\n"
  12680. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12681. "Content-Length: 5\r\n"
  12682. "X-Test: 1\r\n"
  12683. "\r\n"
  12684. "text1"
  12685. "\r\n----------\r\n"
  12686. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12687. "Content-Type: text/plain\r\n"
  12688. "X-Whatever: CustomValue\r\n"
  12689. "\r\n"
  12690. "text2"
  12691. "\r\n------------\r\n"
  12692. "That should be disregarded. Not even read";
  12693. std::string response;
  12694. ASSERT_TRUE(send_request(1, req, &response));
  12695. ASSERT_EQ("200", response.substr(9, 3));
  12696. }
  12697. TEST(MultipartFormDataTest, LargeHeader) {
  12698. auto handled = false;
  12699. Server svr;
  12700. svr.Post("/test", [&](const Request &req, Response &) {
  12701. ASSERT_EQ(1u, req.form.fields.size());
  12702. const auto &text = req.form.get_field("name1");
  12703. ASSERT_EQ("text1", text);
  12704. handled = true;
  12705. });
  12706. thread t = thread([&] { svr.listen(HOST, PORT); });
  12707. auto se = detail::scope_exit([&] {
  12708. svr.stop();
  12709. t.join();
  12710. ASSERT_FALSE(svr.is_running());
  12711. ASSERT_TRUE(handled);
  12712. });
  12713. svr.wait_until_ready();
  12714. auto boundary = std::string("cpp-httplib-multipart-data");
  12715. std::string content = "--" + boundary +
  12716. "\r\n"
  12717. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12718. "\r\n"
  12719. "text1\r\n"
  12720. "--" +
  12721. boundary + "--\r\n";
  12722. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12723. "Content-Type: multipart/form-data;boundary=" +
  12724. boundary +
  12725. "\r\n"
  12726. "Content-Length: " +
  12727. std::to_string(content.size()) +
  12728. "\r\n"
  12729. "Dummy-Header: ";
  12730. std::string header_suffix = "\r\n"
  12731. "\r\n";
  12732. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12733. size_t header_dummy_size =
  12734. read_buff_size -
  12735. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12736. auto header_dummy = std::string(header_dummy_size, '@');
  12737. auto req = header_prefix + header_dummy + header_suffix + content;
  12738. std::string response;
  12739. ASSERT_TRUE(send_request(1, req, &response));
  12740. ASSERT_EQ("200", response.substr(9, 3));
  12741. }
  12742. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12743. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12744. // (not chunked Transfer-Encoding) after the streaming refactor.
  12745. auto handled = false;
  12746. Server svr;
  12747. svr.Post("/upload", [&](const Request &req, Response &res) {
  12748. auto cl_it = req.headers.find("Content-Length");
  12749. EXPECT_TRUE(cl_it != req.headers.end());
  12750. auto te_it = req.headers.find("Transfer-Encoding");
  12751. EXPECT_TRUE(te_it == req.headers.end());
  12752. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12753. res.set_content("ok", "text/plain");
  12754. handled = true;
  12755. });
  12756. auto port = svr.bind_to_any_port(HOST);
  12757. auto t = thread([&] { svr.listen_after_bind(); });
  12758. auto se = detail::scope_exit([&] {
  12759. svr.stop();
  12760. t.join();
  12761. ASSERT_FALSE(svr.is_running());
  12762. ASSERT_TRUE(handled);
  12763. });
  12764. svr.wait_until_ready();
  12765. UploadFormDataItems items = {
  12766. {"field1", "hello", "", "text/plain"},
  12767. {"file1", "world", "test.txt", "application/octet-stream"},
  12768. };
  12769. Client cli(HOST, port);
  12770. auto res = cli.Post("/upload", {}, items);
  12771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12772. EXPECT_EQ(StatusCode::OK_200, res->status);
  12773. }
  12774. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12775. // Verify that make_multipart_content_provider coalesces many small segments
  12776. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12777. constexpr size_t kItemCount = 1000;
  12778. UploadFormDataItems items;
  12779. items.reserve(kItemCount);
  12780. for (size_t i = 0; i < kItemCount; i++) {
  12781. items.push_back(
  12782. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12783. }
  12784. const std::string boundary = "----test-boundary";
  12785. auto content_length = detail::get_multipart_content_length(items, boundary);
  12786. auto provider = detail::make_multipart_content_provider(items, boundary);
  12787. // Drive the provider the same way write_content_with_progress does
  12788. size_t write_count = 0;
  12789. size_t total_bytes = 0;
  12790. DataSink sink;
  12791. size_t offset = 0;
  12792. sink.write = [&](const char *d, size_t l) -> bool {
  12793. (void)d;
  12794. write_count++;
  12795. total_bytes += l;
  12796. offset += l;
  12797. return true;
  12798. };
  12799. sink.is_writable = []() -> bool { return true; };
  12800. while (offset < content_length) {
  12801. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12802. }
  12803. EXPECT_EQ(content_length, total_bytes);
  12804. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12805. // With buffering into 64KB blocks, write_count should be much smaller.
  12806. auto segment_count = 3 * kItemCount + 1;
  12807. EXPECT_LT(write_count, segment_count / 10);
  12808. }
  12809. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12810. // Integration test: send many UploadFormDataItems and verify the server
  12811. // receives all of them correctly (#2410).
  12812. constexpr size_t kItemCount = 500;
  12813. auto handled = false;
  12814. Server svr;
  12815. svr.Post("/upload", [&](const Request &req, Response &res) {
  12816. EXPECT_EQ(kItemCount, req.form.fields.size());
  12817. for (size_t i = 0; i < kItemCount; i++) {
  12818. auto key = "field" + std::to_string(i);
  12819. auto val = "value" + std::to_string(i);
  12820. auto it = req.form.fields.find(key);
  12821. if (it != req.form.fields.end()) {
  12822. EXPECT_EQ(val, it->second.content);
  12823. } else {
  12824. ADD_FAILURE() << "Missing field: " << key;
  12825. }
  12826. }
  12827. res.set_content("ok", "text/plain");
  12828. handled = true;
  12829. });
  12830. auto port = svr.bind_to_any_port(HOST);
  12831. auto t = thread([&] { svr.listen_after_bind(); });
  12832. auto se = detail::scope_exit([&] {
  12833. svr.stop();
  12834. t.join();
  12835. ASSERT_FALSE(svr.is_running());
  12836. ASSERT_TRUE(handled);
  12837. });
  12838. svr.wait_until_ready();
  12839. UploadFormDataItems items;
  12840. items.reserve(kItemCount);
  12841. for (size_t i = 0; i < kItemCount; i++) {
  12842. items.push_back(
  12843. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12844. }
  12845. Client cli(HOST, port);
  12846. auto res = cli.Post("/upload", items);
  12847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12848. EXPECT_EQ(StatusCode::OK_200, res->status);
  12849. }
  12850. TEST(MultipartFormDataTest, MakeFileProvider) {
  12851. // Verify make_file_provider sends a file's contents correctly.
  12852. const std::string file_content(4096, 'Z');
  12853. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12854. {
  12855. std::ofstream ofs(tmp_path, std::ios::binary);
  12856. ofs.write(file_content.data(),
  12857. static_cast<std::streamsize>(file_content.size()));
  12858. }
  12859. auto handled = false;
  12860. Server svr;
  12861. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12862. const ContentReader &content_reader) {
  12863. ASSERT_TRUE(req.is_multipart_form_data());
  12864. std::vector<FormData> items;
  12865. content_reader(
  12866. [&](const FormData &file) {
  12867. items.push_back(file);
  12868. return true;
  12869. },
  12870. [&](const char *data, size_t data_length) {
  12871. items.back().content.append(data, data_length);
  12872. return true;
  12873. });
  12874. ASSERT_EQ(1u, items.size());
  12875. EXPECT_EQ("myfile", items[0].name);
  12876. EXPECT_EQ("data.bin", items[0].filename);
  12877. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12878. EXPECT_EQ(file_content, items[0].content);
  12879. handled = true;
  12880. });
  12881. auto port = svr.bind_to_any_port(HOST);
  12882. auto t = thread([&] { svr.listen_after_bind(); });
  12883. auto se = detail::scope_exit([&] {
  12884. svr.stop();
  12885. t.join();
  12886. ASSERT_FALSE(svr.is_running());
  12887. ASSERT_TRUE(handled);
  12888. std::remove(tmp_path.c_str());
  12889. });
  12890. svr.wait_until_ready();
  12891. FormDataProviderItems providers;
  12892. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12893. "application/octet-stream"));
  12894. Client cli(HOST, port);
  12895. auto res = cli.Post("/upload", {}, {}, providers);
  12896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12897. EXPECT_EQ(StatusCode::OK_200, res->status);
  12898. }
  12899. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12900. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12901. // (100) headers is rejected with a 400 Bad Request response.
  12902. Server svr;
  12903. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12904. res.set_content("ok", "text/plain");
  12905. });
  12906. thread t = thread([&] { svr.listen(HOST, PORT); });
  12907. auto se = detail::scope_exit([&] {
  12908. svr.stop();
  12909. t.join();
  12910. ASSERT_FALSE(svr.is_running());
  12911. });
  12912. svr.wait_until_ready();
  12913. // Build a multipart part with 101 custom headers (exceeding
  12914. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12915. std::stringstream body;
  12916. body << "--simpleboundary\r\n"
  12917. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12918. for (int i = 0; i < 101; i++) {
  12919. body << "X-Custom-Header-" << i << ": value\r\n";
  12920. }
  12921. body << "\r\n"
  12922. << "value1\r\n"
  12923. << "--simpleboundary--\r\n";
  12924. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12925. Client cli(HOST, PORT);
  12926. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12928. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12929. }
  12930. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  12931. // A body that never contains the declared boundary must not be accumulated
  12932. // while the parser waits for it. Buffering it would also make every read
  12933. // rescan everything seen so far, which is quadratic in the body size.
  12934. Server svr;
  12935. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  12936. res.set_content("ok", "text/plain");
  12937. });
  12938. auto port = svr.bind_to_any_port(HOST);
  12939. thread t = thread([&] { svr.listen_after_bind(); });
  12940. auto se = detail::scope_exit([&] {
  12941. svr.stop();
  12942. t.join();
  12943. ASSERT_FALSE(svr.is_running());
  12944. });
  12945. svr.wait_until_ready();
  12946. Client cli(HOST, port);
  12947. cli.set_read_timeout(60, 0);
  12948. cli.set_write_timeout(60, 0);
  12949. // '-' is the worst case: it matches the first character of the boundary, so
  12950. // every position has to be checked against it.
  12951. auto post_dashes = [&](size_t size) {
  12952. const std::string body(size, '-');
  12953. auto start = std::chrono::steady_clock::now();
  12954. auto res =
  12955. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  12956. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  12957. std::chrono::steady_clock::now() - start)
  12958. .count();
  12959. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  12960. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  12961. return ms;
  12962. };
  12963. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  12964. // Windows.
  12965. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  12966. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  12967. // Comparing the two sizes rather than checking an absolute duration keeps
  12968. // this meaningful across build types and CI load, both of which move the
  12969. // absolute numbers by more than an order of magnitude. Four times the bytes
  12970. // costs about four times the time when parsing is linear, and about sixteen
  12971. // times when the body is buffered and rescanned.
  12972. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  12973. EXPECT_LT(ms_16mb, ms_4mb * 10)
  12974. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  12975. << "ms, which suggests the body is being buffered and rescanned";
  12976. }
  12977. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  12978. // A boundary can only be followed by CRLF or by "--", so anything else is
  12979. // malformed no matter what comes next. The parser must say so right away
  12980. // instead of buffering the rest of the declared body.
  12981. Server svr;
  12982. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  12983. res.set_content("ok", "text/plain");
  12984. });
  12985. auto port = svr.bind_to_any_port(HOST);
  12986. thread t = thread([&] { svr.listen_after_bind(); });
  12987. auto se = detail::scope_exit([&] {
  12988. svr.stop();
  12989. t.join();
  12990. ASSERT_FALSE(svr.is_running());
  12991. });
  12992. svr.wait_until_ready();
  12993. // Announce a 1 MB body but send only the malformed prefix. A parser that
  12994. // buffers instead of failing would still be waiting for the remaining bytes.
  12995. const std::string body = "--zzzz\r\n"
  12996. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12997. "\r\n"
  12998. "text1"
  12999. "\r\n--zzzzXX";
  13000. const std::string req = "POST /post HTTP/1.1\r\n"
  13001. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13002. "Content-Length: 1048576\r\n"
  13003. "\r\n" +
  13004. body;
  13005. std::string response;
  13006. ASSERT_TRUE(send_request(3, req, &response, port));
  13007. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  13008. EXPECT_EQ("400", response.substr(9, 3));
  13009. }
  13010. // Posts a multipart body split into two writes, so that the server sees the
  13011. // split at whatever offset the caller chose, and expects the single "text1"
  13012. // field to come through.
  13013. static void expect_split_multipart_ok(const std::string &body1,
  13014. const std::string &body2) {
  13015. auto handled = false;
  13016. Server svr;
  13017. svr.Post("/post", [&](const Request &req, Response &) {
  13018. EXPECT_EQ(1u, req.form.fields.size());
  13019. EXPECT_EQ("text1", req.form.get_field("text1"));
  13020. handled = true;
  13021. });
  13022. auto port = svr.bind_to_any_port(HOST);
  13023. thread t = thread([&] { svr.listen_after_bind(); });
  13024. auto se = detail::scope_exit([&] {
  13025. svr.stop();
  13026. t.join();
  13027. ASSERT_FALSE(svr.is_running());
  13028. ASSERT_TRUE(handled);
  13029. });
  13030. svr.wait_until_ready();
  13031. // "Connection: close" makes the server close once it has answered, so the
  13032. // response drain ends immediately instead of idling until the read timeout.
  13033. const std::string head =
  13034. "POST /post HTTP/1.1\r\n"
  13035. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13036. "Connection: close\r\n"
  13037. "Content-Length: " +
  13038. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  13039. std::string response;
  13040. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  13041. ASSERT_GE(response.size(), 12u) << "no response";
  13042. EXPECT_EQ("200", response.substr(9, 3));
  13043. }
  13044. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  13045. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  13046. // ignored, including when it does not arrive in the same read as the
  13047. // close-delimiter itself.
  13048. expect_split_multipart_ok("--zzzz\r\n"
  13049. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13050. "\r\n"
  13051. "text1"
  13052. "\r\n--zzzz--",
  13053. "\r\nthis epilogue must be ignored\r\n");
  13054. }
  13055. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  13056. // The initial boundary may be preceded by a preamble of any length and may
  13057. // straddle a read boundary. Discarding data while waiting for it must not
  13058. // throw away a partial boundary sitting at the end of the buffer.
  13059. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  13060. "zz\r\n"
  13061. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13062. "\r\n"
  13063. "text1"
  13064. "\r\n--zzzz--\r\n");
  13065. }
  13066. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  13067. // The received boundary was only checked for being non-empty, so it could be
  13068. // as long as a header is allowed to be. The parser scans the body for
  13069. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  13070. // costs a nearly full comparison at nearly every position, making the
  13071. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  13072. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  13073. Server svr;
  13074. svr.Post("/post", [](const Request &req, Response &res) {
  13075. EXPECT_EQ(1u, req.form.fields.size());
  13076. EXPECT_EQ("text1", req.form.get_field("text1"));
  13077. res.set_content("ok", "text/plain");
  13078. });
  13079. auto port = svr.bind_to_any_port(HOST);
  13080. thread t = thread([&] { svr.listen_after_bind(); });
  13081. auto se = detail::scope_exit([&] {
  13082. svr.stop();
  13083. t.join();
  13084. ASSERT_FALSE(svr.is_running());
  13085. });
  13086. svr.wait_until_ready();
  13087. Client cli(HOST, port);
  13088. auto post_with_boundary_of_length = [&](size_t len) {
  13089. const std::string boundary(len, 'a');
  13090. const std::string body =
  13091. "--" + boundary +
  13092. "\r\n"
  13093. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13094. "\r\n"
  13095. "text1"
  13096. "\r\n--" +
  13097. boundary + "--\r\n";
  13098. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  13099. };
  13100. auto res = post_with_boundary_of_length(70);
  13101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13102. EXPECT_EQ(StatusCode::OK_200, res->status);
  13103. res = post_with_boundary_of_length(71);
  13104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13105. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13106. }
  13107. TEST(MakeFileBodyTest, Basic) {
  13108. const std::string file_content(4096, 'Z');
  13109. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  13110. {
  13111. std::ofstream ofs(tmp_path, std::ios::binary);
  13112. ofs.write(file_content.data(),
  13113. static_cast<std::streamsize>(file_content.size()));
  13114. }
  13115. auto handled = false;
  13116. Server svr;
  13117. svr.Post("/upload", [&](const Request &req, Response &res) {
  13118. EXPECT_EQ(file_content, req.body);
  13119. handled = true;
  13120. res.status = StatusCode::OK_200;
  13121. });
  13122. auto port = svr.bind_to_any_port(HOST);
  13123. auto t = thread([&] { svr.listen_after_bind(); });
  13124. auto se = detail::scope_exit([&] {
  13125. svr.stop();
  13126. t.join();
  13127. ASSERT_FALSE(svr.is_running());
  13128. ASSERT_TRUE(handled);
  13129. std::remove(tmp_path.c_str());
  13130. });
  13131. svr.wait_until_ready();
  13132. auto fb = make_file_body(tmp_path);
  13133. ASSERT_GT(fb.first, 0u);
  13134. Client cli(HOST, port);
  13135. auto res =
  13136. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  13137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13138. EXPECT_EQ(StatusCode::OK_200, res->status);
  13139. }
  13140. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  13141. static constexpr unsigned int number_of_tasks{1000000};
  13142. std::atomic_uint count{0};
  13143. std::unique_ptr<TaskQueue> task_queue{
  13144. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  13145. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13146. auto queued = task_queue->enqueue(
  13147. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  13148. EXPECT_TRUE(queued);
  13149. }
  13150. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13151. task_queue->shutdown();
  13152. #else
  13153. EXPECT_NO_THROW(task_queue->shutdown());
  13154. #endif
  13155. EXPECT_EQ(number_of_tasks, count.load());
  13156. }
  13157. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  13158. static constexpr unsigned int number_of_tasks{1000000};
  13159. static constexpr unsigned int qlimit{2};
  13160. unsigned int queued_count{0};
  13161. std::atomic_uint count{0};
  13162. std::unique_ptr<TaskQueue> task_queue{
  13163. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  13164. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13165. if (task_queue->enqueue(
  13166. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  13167. queued_count++;
  13168. }
  13169. }
  13170. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13171. task_queue->shutdown();
  13172. #else
  13173. EXPECT_NO_THROW(task_queue->shutdown());
  13174. #endif
  13175. EXPECT_EQ(queued_count, count.load());
  13176. EXPECT_TRUE(queued_count <= number_of_tasks);
  13177. EXPECT_TRUE(queued_count >= qlimit);
  13178. }
  13179. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  13180. // Use a short idle timeout so a dynamic thread spawns, times out and
  13181. // exits during the test, and the pool keeps working afterwards.
  13182. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  13183. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  13184. /*idle_timeout_sec=*/1}};
  13185. std::atomic_uint count{0};
  13186. std::condition_variable cv;
  13187. std::mutex mtx;
  13188. bool release = false;
  13189. // Block the base thread so the second task spawns a dynamic thread.
  13190. EXPECT_TRUE(task_queue->enqueue([&] {
  13191. std::unique_lock<std::mutex> lock(mtx);
  13192. while (!release) {
  13193. cv.wait(lock);
  13194. }
  13195. count++;
  13196. }));
  13197. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13198. // Let the dynamic thread finish its task and exceed the idle timeout.
  13199. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  13200. {
  13201. std::unique_lock<std::mutex> lock(mtx);
  13202. release = true;
  13203. }
  13204. cv.notify_all();
  13205. // The pool must still accept and run tasks after the dynamic thread exited.
  13206. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13207. task_queue->shutdown();
  13208. EXPECT_EQ(3u, count.load());
  13209. }
  13210. TEST(TaskQueueTest, MaxQueuedRequests) {
  13211. static constexpr unsigned int qlimit{3};
  13212. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  13213. std::condition_variable sem_cv;
  13214. std::mutex sem_mtx;
  13215. int credits = 0;
  13216. bool queued;
  13217. /* Fill up the queue with tasks that will block until we give them credits to
  13218. * complete. */
  13219. for (unsigned int n = 0; n <= qlimit;) {
  13220. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  13221. std::unique_lock<std::mutex> lock(sem_mtx);
  13222. while (credits <= 0) {
  13223. sem_cv.wait(lock);
  13224. }
  13225. /* Consume the credit and signal the test code if they are all gone. */
  13226. if (--credits == 0) { sem_cv.notify_one(); }
  13227. });
  13228. if (n < qlimit) {
  13229. /* The first qlimit enqueues must succeed. */
  13230. EXPECT_TRUE(queued);
  13231. } else {
  13232. /* The last one will succeed only when the worker thread
  13233. * starts and dequeues the first blocking task. Although
  13234. * not necessary for the correctness of this test, we sleep for
  13235. * a short while to avoid busy waiting. */
  13236. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13237. }
  13238. if (queued) { n++; }
  13239. }
  13240. /* Further enqueues must fail since the queue is full. */
  13241. for (auto i = 0; i < 4; i++) {
  13242. queued = task_queue->enqueue([] {});
  13243. EXPECT_FALSE(queued);
  13244. }
  13245. /* Give the credits to allow the previous tasks to complete. */
  13246. {
  13247. std::unique_lock<std::mutex> lock(sem_mtx);
  13248. credits += qlimit + 1;
  13249. }
  13250. sem_cv.notify_all();
  13251. /* Wait for all the credits to be consumed. */
  13252. {
  13253. std::unique_lock<std::mutex> lock(sem_mtx);
  13254. while (credits > 0) {
  13255. sem_cv.wait(lock);
  13256. }
  13257. }
  13258. /* Check that we are able again to enqueue at least qlimit tasks. */
  13259. for (unsigned int i = 0; i < qlimit; i++) {
  13260. queued = task_queue->enqueue([] {});
  13261. EXPECT_TRUE(queued);
  13262. }
  13263. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13264. task_queue->shutdown();
  13265. #else
  13266. EXPECT_NO_THROW(task_queue->shutdown());
  13267. #endif
  13268. }
  13269. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  13270. Server svr;
  13271. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13272. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  13273. });
  13274. svr.Get("/hello", [](const Request &req, Response &res) {
  13275. res.set_content(req.get_param_value("key"), "text/plain");
  13276. });
  13277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13278. auto se = detail::scope_exit([&] {
  13279. svr.stop();
  13280. thread.join();
  13281. ASSERT_FALSE(svr.is_running());
  13282. });
  13283. svr.wait_until_ready();
  13284. {
  13285. Client cli(HOST, PORT);
  13286. cli.set_follow_location(true);
  13287. auto res = cli.Get("/");
  13288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13289. EXPECT_EQ(StatusCode::OK_200, res->status);
  13290. EXPECT_EQ("val&key2=val2", res->body);
  13291. }
  13292. }
  13293. #endif
  13294. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  13295. Server svr;
  13296. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13297. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  13298. });
  13299. svr.Get("/hello", [](const Request &req, Response &res) {
  13300. res.set_content(req.get_param_value("key"), "text/plain");
  13301. });
  13302. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13303. auto se = detail::scope_exit([&] {
  13304. svr.stop();
  13305. thread.join();
  13306. ASSERT_FALSE(svr.is_running());
  13307. });
  13308. svr.wait_until_ready();
  13309. {
  13310. Client cli(HOST, PORT);
  13311. cli.set_follow_location(true);
  13312. auto res = cli.Get("/");
  13313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13314. EXPECT_EQ(StatusCode::OK_200, res->status);
  13315. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  13316. }
  13317. }
  13318. TEST(RedirectTest, RedirectWithPlusInPath) {
  13319. Server svr;
  13320. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13321. res.set_redirect("/a+b");
  13322. });
  13323. // Route pattern uses regex; escape + as \\+
  13324. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  13325. res.set_content(req.path, "text/plain");
  13326. });
  13327. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13328. auto se = detail::scope_exit([&] {
  13329. svr.stop();
  13330. thread.join();
  13331. ASSERT_FALSE(svr.is_running());
  13332. });
  13333. svr.wait_until_ready();
  13334. {
  13335. Client cli(HOST, PORT);
  13336. cli.set_follow_location(true);
  13337. auto res = cli.Get("/");
  13338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13339. EXPECT_EQ(StatusCode::OK_200, res->status);
  13340. EXPECT_EQ("/a+b", res->body);
  13341. }
  13342. }
  13343. #ifdef CPPHTTPLIB_SSL_ENABLED
  13344. TEST(RedirectTest, Issue2185_Online) {
  13345. SSLClient client("github.com");
  13346. client.set_follow_location(true);
  13347. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  13348. "Coollab-Windows.zip");
  13349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13350. EXPECT_EQ(StatusCode::OK_200, res->status);
  13351. EXPECT_EQ(9920427U, res->body.size());
  13352. }
  13353. #endif
  13354. TEST(VulnerabilityTest, CRLFInjection) {
  13355. Server svr;
  13356. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  13357. res.set_content("Hello 1", "text/plain");
  13358. });
  13359. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  13360. res.set_content("Hello 2", "text/plain");
  13361. });
  13362. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  13363. res.set_content("Hello 3", "text/plain");
  13364. });
  13365. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  13366. res.set_content("Hello 4", "text/plain");
  13367. });
  13368. svr.set_logger([](const Request &req, const Response & /*res*/) {
  13369. for (const auto &x : req.headers) {
  13370. auto key = x.first;
  13371. EXPECT_STRNE("evil", key.c_str());
  13372. }
  13373. });
  13374. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13375. auto se = detail::scope_exit([&] {
  13376. svr.stop();
  13377. thread.join();
  13378. ASSERT_FALSE(svr.is_running());
  13379. });
  13380. svr.wait_until_ready();
  13381. {
  13382. Client cli(HOST, PORT);
  13383. cli.Post("/test1", "A=B",
  13384. "application/x-www-form-urlencoded\r\nevil: hello1");
  13385. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  13386. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  13387. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  13388. }
  13389. }
  13390. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  13391. auto server_thread = std::thread([] {
  13392. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13393. default_socket_options(srv);
  13394. sockaddr_in addr{};
  13395. addr.sin_family = AF_INET;
  13396. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  13397. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13398. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13399. ::listen(srv, 1);
  13400. sockaddr_in cli_addr{};
  13401. socklen_t cli_len = sizeof(cli_addr);
  13402. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13403. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  13404. std::string buf_all;
  13405. char buf[2048];
  13406. ssize_t n;
  13407. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  13408. buf_all.append(buf, static_cast<size_t>(n));
  13409. size_t pos;
  13410. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  13411. auto request_block = buf_all.substr(0, pos + 4); // include separator
  13412. auto e = request_block.find("\r\n");
  13413. if (e != std::string::npos) {
  13414. auto request_line = request_block.substr(0, e);
  13415. std::string msg =
  13416. "CRLF injection detected in request line: '" + request_line + "'";
  13417. EXPECT_FALSE(true) << msg;
  13418. }
  13419. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  13420. ::send(cli,
  13421. #ifdef _WIN32
  13422. static_cast<const char *>(resp.c_str()),
  13423. static_cast<int>(resp.size()),
  13424. #else
  13425. resp.c_str(), resp.size(),
  13426. #endif
  13427. 0);
  13428. buf_all.erase(0, pos + 4);
  13429. }
  13430. }
  13431. detail::close_socket(cli);
  13432. detail::close_socket(srv);
  13433. });
  13434. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13435. auto cli = Client("127.0.0.1", PORT + 1);
  13436. auto headers = Headers{
  13437. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  13438. {"Connection", "keep-alive"}};
  13439. auto res = cli.Get("/hi", headers);
  13440. EXPECT_FALSE(res);
  13441. EXPECT_EQ(Error::InvalidHeaders, res.error());
  13442. server_thread.join();
  13443. }
  13444. TEST(PathParamsTest, StaticMatch) {
  13445. const auto pattern = "/users/all";
  13446. detail::PathParamsMatcher matcher(pattern);
  13447. Request request;
  13448. request.path = "/users/all";
  13449. ASSERT_TRUE(matcher.match(request));
  13450. std::unordered_map<std::string, std::string> expected_params = {};
  13451. EXPECT_EQ(request.path_params, expected_params);
  13452. }
  13453. TEST(PathParamsTest, StaticMismatch) {
  13454. const auto pattern = "/users/all";
  13455. detail::PathParamsMatcher matcher(pattern);
  13456. Request request;
  13457. request.path = "/users/1";
  13458. ASSERT_FALSE(matcher.match(request));
  13459. }
  13460. TEST(PathParamsTest, SingleParamInTheMiddle) {
  13461. const auto pattern = "/users/:id/subscriptions";
  13462. detail::PathParamsMatcher matcher(pattern);
  13463. Request request;
  13464. request.path = "/users/42/subscriptions";
  13465. ASSERT_TRUE(matcher.match(request));
  13466. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13467. EXPECT_EQ(request.path_params, expected_params);
  13468. }
  13469. TEST(PathParamsTest, SingleParamInTheEnd) {
  13470. const auto pattern = "/users/:id";
  13471. detail::PathParamsMatcher matcher(pattern);
  13472. Request request;
  13473. request.path = "/users/24";
  13474. ASSERT_TRUE(matcher.match(request));
  13475. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  13476. EXPECT_EQ(request.path_params, expected_params);
  13477. }
  13478. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  13479. const auto pattern = "/users/:id/";
  13480. detail::PathParamsMatcher matcher(pattern);
  13481. Request request;
  13482. request.path = "/users/42/";
  13483. ASSERT_TRUE(matcher.match(request));
  13484. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13485. EXPECT_EQ(request.path_params, expected_params);
  13486. }
  13487. TEST(PathParamsTest, EmptyParam) {
  13488. const auto pattern = "/users/:id/";
  13489. detail::PathParamsMatcher matcher(pattern);
  13490. Request request;
  13491. request.path = "/users//";
  13492. ASSERT_TRUE(matcher.match(request));
  13493. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  13494. EXPECT_EQ(request.path_params, expected_params);
  13495. }
  13496. TEST(PathParamsTest, FragmentMismatch) {
  13497. const auto pattern = "/users/:id/";
  13498. detail::PathParamsMatcher matcher(pattern);
  13499. Request request;
  13500. request.path = "/admins/24/";
  13501. ASSERT_FALSE(matcher.match(request));
  13502. }
  13503. TEST(PathParamsTest, ExtraFragments) {
  13504. const auto pattern = "/users/:id";
  13505. detail::PathParamsMatcher matcher(pattern);
  13506. Request request;
  13507. request.path = "/users/42/subscriptions";
  13508. ASSERT_FALSE(matcher.match(request));
  13509. }
  13510. TEST(PathParamsTest, MissingTrailingParam) {
  13511. const auto pattern = "/users/:id";
  13512. detail::PathParamsMatcher matcher(pattern);
  13513. Request request;
  13514. request.path = "/users";
  13515. ASSERT_FALSE(matcher.match(request));
  13516. }
  13517. TEST(PathParamsTest, MissingParamInTheMiddle) {
  13518. const auto pattern = "/users/:id/subscriptions";
  13519. detail::PathParamsMatcher matcher(pattern);
  13520. Request request;
  13521. request.path = "/users/subscriptions";
  13522. ASSERT_FALSE(matcher.match(request));
  13523. }
  13524. TEST(PathParamsTest, MultipleParams) {
  13525. const auto pattern = "/users/:userid/subscriptions/:subid";
  13526. detail::PathParamsMatcher matcher(pattern);
  13527. Request request;
  13528. request.path = "/users/42/subscriptions/2";
  13529. ASSERT_TRUE(matcher.match(request));
  13530. std::unordered_map<std::string, std::string> expected_params = {
  13531. {"userid", "42"}, {"subid", "2"}};
  13532. EXPECT_EQ(request.path_params, expected_params);
  13533. }
  13534. TEST(PathParamsTest, SequenceOfParams) {
  13535. const auto pattern = "/values/:x/:y/:z";
  13536. detail::PathParamsMatcher matcher(pattern);
  13537. Request request;
  13538. request.path = "/values/1/2/3";
  13539. ASSERT_TRUE(matcher.match(request));
  13540. std::unordered_map<std::string, std::string> expected_params = {
  13541. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  13542. EXPECT_EQ(request.path_params, expected_params);
  13543. }
  13544. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  13545. const auto pattern = "/prefix:suffix";
  13546. detail::PathParamsMatcher matcher(pattern);
  13547. Request request;
  13548. request.path = "/prefix:suffix";
  13549. ASSERT_TRUE(matcher.match(request));
  13550. const std::unordered_map<std::string, std::string> expected_params = {};
  13551. EXPECT_EQ(request.path_params, expected_params);
  13552. }
  13553. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  13554. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  13555. // calling thread's stack on a long enough path for a quantified pattern;
  13556. // RegexMatcher must refuse to run regex matching on paths beyond
  13557. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  13558. detail::RegexMatcher matcher("/files/(.*)");
  13559. Request within_limit;
  13560. within_limit.path = "/files/" + std::string(10, 'A');
  13561. EXPECT_TRUE(matcher.match(within_limit));
  13562. Request over_limit;
  13563. over_limit.path =
  13564. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  13565. EXPECT_FALSE(matcher.match(over_limit));
  13566. }
  13567. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  13568. Server svr;
  13569. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  13570. res.set_content("ok", "text/plain");
  13571. });
  13572. auto port = svr.bind_to_any_port(HOST);
  13573. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13574. auto se = detail::scope_exit([&] {
  13575. svr.stop();
  13576. thread.join();
  13577. ASSERT_FALSE(svr.is_running());
  13578. });
  13579. svr.wait_until_ready();
  13580. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  13581. // request URI limit; this used to be able to crash the process.
  13582. std::string path =
  13583. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  13584. std::string req = "GET " + path +
  13585. " HTTP/1.1\r\n"
  13586. "Host: " +
  13587. std::string(HOST) + ":" + std::to_string(port) +
  13588. "\r\n"
  13589. "Connection: close\r\n"
  13590. "\r\n";
  13591. std::string response;
  13592. ASSERT_TRUE(send_request(5, req, &response, port));
  13593. EXPECT_NE(std::string::npos, response.find("404"));
  13594. }
  13595. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  13596. Server svr;
  13597. auto handler = [](const Request & /*req*/, Response &res) {
  13598. res.set_content("hit", "text/plain");
  13599. };
  13600. // No regex metacharacter, so this one is compared literally
  13601. svr.Get("/literal/route", handler);
  13602. // '.' is a regex metacharacter, so this one must keep regex semantics
  13603. svr.Get("/a.c", handler);
  13604. auto port = svr.bind_to_any_port(HOST);
  13605. std::thread t([&]() { svr.listen_after_bind(); });
  13606. auto se = detail::scope_exit([&] {
  13607. svr.stop();
  13608. t.join();
  13609. ASSERT_FALSE(svr.is_running());
  13610. });
  13611. svr.wait_until_ready();
  13612. Client cli(HOST, port);
  13613. struct {
  13614. const char *path;
  13615. int status;
  13616. } cases[] = {
  13617. {"/literal/route", StatusCode::OK_200},
  13618. {"/literal/routes", StatusCode::NotFound_404},
  13619. {"/literal/rout", StatusCode::NotFound_404},
  13620. {"/abc", StatusCode::OK_200},
  13621. {"/a.c", StatusCode::OK_200},
  13622. };
  13623. for (const auto &x : cases) {
  13624. auto res = cli.Get(x.path);
  13625. ASSERT_TRUE(res) << x.path;
  13626. EXPECT_EQ(x.status, res->status) << x.path;
  13627. }
  13628. }
  13629. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  13630. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  13631. // from exhausting the stack, so it must only constrain routes that actually
  13632. // run a regular expression. A literal route is matched by comparison and
  13633. // stays usable at any length.
  13634. Server svr;
  13635. const std::string pattern =
  13636. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  13637. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  13638. res.set_content("hit", "text/plain");
  13639. });
  13640. auto port = svr.bind_to_any_port(HOST);
  13641. std::thread t([&]() { svr.listen_after_bind(); });
  13642. auto se = detail::scope_exit([&] {
  13643. svr.stop();
  13644. t.join();
  13645. ASSERT_FALSE(svr.is_running());
  13646. });
  13647. svr.wait_until_ready();
  13648. Client cli(HOST, port);
  13649. auto res = cli.Get(pattern);
  13650. ASSERT_TRUE(res);
  13651. EXPECT_EQ(StatusCode::OK_200, res->status);
  13652. }
  13653. TEST(ParseUrlTest, VariousPatterns) {
  13654. {
  13655. detail::UrlComponents uc;
  13656. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  13657. EXPECT_EQ("http", uc.scheme);
  13658. EXPECT_EQ("example.com", uc.host);
  13659. EXPECT_EQ("8080", uc.port);
  13660. EXPECT_EQ("/path", uc.path);
  13661. EXPECT_EQ("?q=1", uc.query);
  13662. }
  13663. {
  13664. detail::UrlComponents uc;
  13665. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  13666. EXPECT_EQ("https", uc.scheme);
  13667. EXPECT_EQ("example.com", uc.host);
  13668. EXPECT_TRUE(uc.port.empty());
  13669. EXPECT_EQ("/path", uc.path);
  13670. }
  13671. {
  13672. detail::UrlComponents uc;
  13673. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13674. EXPECT_EQ("::1", uc.host);
  13675. EXPECT_EQ("8080", uc.port);
  13676. EXPECT_EQ("/path", uc.path);
  13677. }
  13678. {
  13679. detail::UrlComponents uc;
  13680. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13681. }
  13682. {
  13683. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13684. // the path while the connection still targets the bracketed host.
  13685. detail::UrlComponents uc;
  13686. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13687. }
  13688. {
  13689. detail::UrlComponents uc;
  13690. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13691. }
  13692. {
  13693. detail::UrlComponents uc;
  13694. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13695. EXPECT_EQ("::1", uc.host);
  13696. EXPECT_TRUE(uc.port.empty());
  13697. EXPECT_EQ("/path", uc.path);
  13698. }
  13699. {
  13700. detail::UrlComponents uc;
  13701. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13702. EXPECT_TRUE(uc.scheme.empty());
  13703. EXPECT_EQ("example.com", uc.host);
  13704. EXPECT_EQ("/path", uc.path);
  13705. EXPECT_EQ("?q=1", uc.query);
  13706. }
  13707. {
  13708. detail::UrlComponents uc;
  13709. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13710. EXPECT_TRUE(uc.host.empty());
  13711. EXPECT_EQ("/path", uc.path);
  13712. EXPECT_EQ("?q=1", uc.query);
  13713. }
  13714. {
  13715. detail::UrlComponents uc;
  13716. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13717. EXPECT_EQ("example.com", uc.host);
  13718. EXPECT_EQ("8080", uc.port);
  13719. }
  13720. {
  13721. // Unix socket path — must not be parsed as host
  13722. detail::UrlComponents uc;
  13723. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13724. EXPECT_TRUE(uc.host.empty());
  13725. }
  13726. {
  13727. detail::UrlComponents uc;
  13728. ASSERT_TRUE(detail::parse_url("", uc));
  13729. EXPECT_TRUE(uc.host.empty());
  13730. EXPECT_TRUE(uc.path.empty());
  13731. }
  13732. {
  13733. detail::UrlComponents uc;
  13734. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13735. }
  13736. {
  13737. detail::UrlComponents uc;
  13738. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13739. }
  13740. {
  13741. // Accepted by parse_url; callers restrict to http/https
  13742. detail::UrlComponents uc;
  13743. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13744. EXPECT_EQ("ftp", uc.scheme);
  13745. }
  13746. {
  13747. detail::UrlComponents uc;
  13748. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13749. }
  13750. {
  13751. detail::UrlComponents uc;
  13752. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13753. }
  13754. }
  13755. TEST(ParseUrlTest, FragmentHandling) {
  13756. {
  13757. detail::UrlComponents uc;
  13758. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13759. EXPECT_EQ("/path", uc.path);
  13760. EXPECT_TRUE(uc.query.empty());
  13761. }
  13762. {
  13763. detail::UrlComponents uc;
  13764. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13765. EXPECT_TRUE(uc.path.empty());
  13766. EXPECT_TRUE(uc.query.empty());
  13767. }
  13768. }
  13769. TEST(ParseUrlTest, UserinfoHandling) {
  13770. // Userinfo with @ but no colon — host includes @
  13771. detail::UrlComponents uc;
  13772. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13773. EXPECT_EQ("user@host.com", uc.host);
  13774. EXPECT_EQ("/path", uc.path);
  13775. }
  13776. TEST(ParseUrlTest, IPv6EdgeCases) {
  13777. {
  13778. detail::UrlComponents uc;
  13779. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13780. EXPECT_TRUE(uc.scheme.empty());
  13781. EXPECT_EQ("::1", uc.host);
  13782. EXPECT_EQ("8080", uc.port);
  13783. }
  13784. {
  13785. // Zone ID '%25' is not in [a-fA-F0-9:]
  13786. detail::UrlComponents uc;
  13787. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13788. }
  13789. }
  13790. TEST(ParseUrlTest, SchemeEdgeCases) {
  13791. {
  13792. detail::UrlComponents uc;
  13793. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13794. }
  13795. {
  13796. detail::UrlComponents uc;
  13797. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13798. }
  13799. {
  13800. detail::UrlComponents uc;
  13801. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13802. }
  13803. }
  13804. TEST(ParseUrlTest, PortEdgeCases) {
  13805. {
  13806. detail::UrlComponents uc;
  13807. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13808. EXPECT_TRUE(uc.port.empty());
  13809. EXPECT_EQ("/path", uc.path);
  13810. }
  13811. {
  13812. // parse_url accepts any port string; validation is done by parse_port
  13813. detail::UrlComponents uc;
  13814. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13815. EXPECT_EQ("abc", uc.port);
  13816. }
  13817. }
  13818. TEST(ParseUrlTest, WebSocketPatterns) {
  13819. {
  13820. detail::UrlComponents uc;
  13821. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13822. EXPECT_EQ("ws", uc.scheme);
  13823. EXPECT_EQ("echo.example.com", uc.host);
  13824. EXPECT_EQ("8080", uc.port);
  13825. EXPECT_EQ("/ws", uc.path);
  13826. }
  13827. {
  13828. detail::UrlComponents uc;
  13829. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13830. EXPECT_EQ("wss", uc.scheme);
  13831. EXPECT_EQ("echo.example.com", uc.host);
  13832. EXPECT_TRUE(uc.port.empty());
  13833. EXPECT_EQ("/ws", uc.path);
  13834. }
  13835. }
  13836. TEST(ParseUrlTest, QueryOnly) {
  13837. detail::UrlComponents uc;
  13838. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13839. EXPECT_TRUE(uc.host.empty());
  13840. EXPECT_TRUE(uc.path.empty());
  13841. EXPECT_EQ("?q=1&r=2", uc.query);
  13842. }
  13843. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13844. detail::UrlComponents uc;
  13845. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13846. EXPECT_TRUE(uc.scheme.empty());
  13847. EXPECT_EQ("example.com", uc.host);
  13848. EXPECT_EQ("443", uc.port);
  13849. EXPECT_EQ("/path", uc.path);
  13850. }
  13851. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13852. // If ipv6 regex working, regex match codepath is taken.
  13853. // else port will default to 80 in Client impl
  13854. int clientImplMagicPort = 80;
  13855. int port = 4321;
  13856. // above ports must be different to avoid false negative
  13857. EXPECT_NE(clientImplMagicPort, port);
  13858. std::string ipV6TestURL = "http://[ff06::c3]";
  13859. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13860. CLIENT_PRIVATE_KEY_FILE);
  13861. EXPECT_EQ(cli.port(), port);
  13862. }
  13863. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13864. auto file_path = "./www/dir/index.html";
  13865. auto dir_path = "./www/dir";
  13866. detail::FileStat stat_file(file_path);
  13867. EXPECT_TRUE(stat_file.is_file());
  13868. EXPECT_FALSE(stat_file.is_dir());
  13869. detail::FileStat stat_dir(dir_path);
  13870. EXPECT_FALSE(stat_dir.is_file());
  13871. EXPECT_TRUE(stat_dir.is_dir());
  13872. }
  13873. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13874. // IPv4 with default HTTP port (80)
  13875. EXPECT_EQ("example.com",
  13876. detail::make_host_and_port_string("example.com", 80, false));
  13877. // IPv4 with default HTTPS port (443)
  13878. EXPECT_EQ("example.com",
  13879. detail::make_host_and_port_string("example.com", 443, true));
  13880. // IPv4 with non-default HTTP port
  13881. EXPECT_EQ("example.com:8080",
  13882. detail::make_host_and_port_string("example.com", 8080, false));
  13883. // IPv4 with non-default HTTPS port
  13884. EXPECT_EQ("example.com:8443",
  13885. detail::make_host_and_port_string("example.com", 8443, true));
  13886. // IPv6 with default HTTP port (80)
  13887. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13888. // IPv6 with default HTTPS port (443)
  13889. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13890. // IPv6 with non-default HTTP port
  13891. EXPECT_EQ("[::1]:8080",
  13892. detail::make_host_and_port_string("::1", 8080, false));
  13893. // IPv6 with non-default HTTPS port
  13894. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13895. // IPv6 full address with default port
  13896. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13897. detail::make_host_and_port_string(
  13898. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13899. // IPv6 full address with non-default port
  13900. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13901. detail::make_host_and_port_string(
  13902. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13903. // IPv6 localhost with non-default port
  13904. EXPECT_EQ("[::1]:3000",
  13905. detail::make_host_and_port_string("::1", 3000, false));
  13906. // IPv6 with zone ID (link-local address) with default port
  13907. EXPECT_EQ("[fe80::1%eth0]",
  13908. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13909. // IPv6 with zone ID (link-local address) with non-default port
  13910. EXPECT_EQ("[fe80::1%eth0]:8080",
  13911. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13912. // Edge case: Port 443 with is_ssl=false (should add port)
  13913. EXPECT_EQ("example.com:443",
  13914. detail::make_host_and_port_string("example.com", 443, false));
  13915. // Edge case: Port 80 with is_ssl=true (should add port)
  13916. EXPECT_EQ("example.com:80",
  13917. detail::make_host_and_port_string("example.com", 80, true));
  13918. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13919. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13920. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13921. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13922. // Security fix: Already bracketed IPv6 should not get double brackets
  13923. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13924. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13925. EXPECT_EQ("[::1]:8080",
  13926. detail::make_host_and_port_string("[::1]", 8080, false));
  13927. EXPECT_EQ("[2001:db8::1]:8080",
  13928. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13929. EXPECT_EQ("[fe80::1%eth0]",
  13930. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13931. EXPECT_EQ("[fe80::1%eth0]:8080",
  13932. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13933. // Edge case: Empty host (should return as-is)
  13934. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13935. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13936. // This is a known limitation but shouldn't crash
  13937. EXPECT_EQ("[host:name]",
  13938. detail::make_host_and_port_string("host:name", 80, false));
  13939. // Port number edge cases (no validation, but should not crash)
  13940. EXPECT_EQ("example.com:0",
  13941. detail::make_host_and_port_string("example.com", 0, false));
  13942. EXPECT_EQ("example.com:-1",
  13943. detail::make_host_and_port_string("example.com", -1, false));
  13944. EXPECT_EQ("example.com:65535",
  13945. detail::make_host_and_port_string("example.com", 65535, false));
  13946. EXPECT_EQ("example.com:65536",
  13947. detail::make_host_and_port_string("example.com", 65536, false));
  13948. }
  13949. #ifdef CPPHTTPLIB_SSL_ENABLED
  13950. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13951. httplib::SSLClient cli("roblox.com", 443);
  13952. cli.set_follow_location(true);
  13953. auto res = cli.Get("/");
  13954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13955. EXPECT_EQ(StatusCode::OK_200, res->status);
  13956. }
  13957. #endif
  13958. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13959. Server svr;
  13960. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13961. EXPECT_EQ(res.status, 400);
  13962. });
  13963. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13964. auto se = detail::scope_exit([&] {
  13965. svr.stop();
  13966. thread.join();
  13967. ASSERT_FALSE(svr.is_running());
  13968. });
  13969. svr.wait_until_ready();
  13970. Client cli(HOST, PORT);
  13971. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13972. }
  13973. TEST(InvalidHeaderCharsTest, is_field_name) {
  13974. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13975. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13976. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13977. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13978. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13979. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13980. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13981. EXPECT_FALSE(detail::fields::is_field_name(""));
  13982. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13983. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13984. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13985. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13986. }
  13987. TEST(InvalidHeaderCharsTest, is_field_value) {
  13988. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13989. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13990. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13991. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13992. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13993. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13994. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13995. EXPECT_TRUE(detail::fields::is_field_value(""));
  13996. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13997. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13998. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13999. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  14000. EXPECT_TRUE(detail::fields::is_field_value("0"));
  14001. }
  14002. TEST(InvalidHeaderCharsTest, OnServer) {
  14003. Server svr;
  14004. svr.Get("/test_name", [&](const Request &req, Response &res) {
  14005. std::string header = "Not Set";
  14006. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14007. res.set_header(header, "value");
  14008. res.set_content("Page Content Page Content", "text/plain");
  14009. });
  14010. svr.Get("/test_value", [&](const Request &req, Response &res) {
  14011. std::string header = "Not Set";
  14012. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14013. res.set_header("X-Test", header);
  14014. res.set_content("Page Content Page Content", "text/plain");
  14015. });
  14016. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14017. auto se = detail::scope_exit([&] {
  14018. svr.stop();
  14019. thread.join();
  14020. ASSERT_FALSE(svr.is_running());
  14021. });
  14022. svr.wait_until_ready();
  14023. Client cli(HOST, PORT);
  14024. {
  14025. auto res = cli.Get(
  14026. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14028. EXPECT_EQ("Page Content Page Content", res->body);
  14029. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14030. }
  14031. {
  14032. auto res = cli.Get(
  14033. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14035. EXPECT_EQ("Page Content Page Content", res->body);
  14036. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14037. }
  14038. }
  14039. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  14040. auto handled = false;
  14041. Server svr;
  14042. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14043. thread t = thread([&] { svr.listen(HOST, PORT); });
  14044. auto se = detail::scope_exit([&] {
  14045. svr.stop();
  14046. t.join();
  14047. ASSERT_FALSE(svr.is_running());
  14048. ASSERT_FALSE(handled);
  14049. });
  14050. svr.wait_until_ready();
  14051. auto req = "POST /test HTTP/1.1\r\n"
  14052. "Content-Length: x\r\n"
  14053. "\r\n";
  14054. std::string response;
  14055. ASSERT_TRUE(send_request(1, req, &response));
  14056. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14057. response.substr(0, response.find("\r\n")));
  14058. }
  14059. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  14060. // case-insensitive, and a server that receives a 100-continue expectation in
  14061. // an HTTP/1.0 request MUST ignore it.
  14062. static void probe_expect(int port, const std::string &req, bool *got_100) {
  14063. std::string response;
  14064. ASSERT_TRUE(send_request(1, req, &response, port));
  14065. *got_100 = response.find("100 Continue") != std::string::npos;
  14066. }
  14067. class ExpectTokenTest : public ::testing::Test {
  14068. protected:
  14069. void SetUp() override {
  14070. svr_.Post("/p", [](const Request &, Response &res) {
  14071. res.set_content("ok", "text/plain");
  14072. });
  14073. port_ = svr_.bind_to_any_port(HOST);
  14074. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14075. svr_.wait_until_ready();
  14076. }
  14077. void TearDown() override {
  14078. svr_.stop();
  14079. if (thread_.joinable()) { thread_.join(); }
  14080. }
  14081. std::string request(const char *version, const char *expect_value) const {
  14082. return std::string("POST /p ") + version +
  14083. "\r\n"
  14084. "Host: localhost\r\n"
  14085. "Content-Length: 2\r\n"
  14086. "Connection: close\r\n"
  14087. "Expect: " +
  14088. expect_value +
  14089. "\r\n"
  14090. "\r\n"
  14091. "hi";
  14092. }
  14093. Server svr_;
  14094. int port_ = 0;
  14095. thread thread_;
  14096. };
  14097. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  14098. bool got_100 = false;
  14099. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  14100. EXPECT_TRUE(got_100);
  14101. }
  14102. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  14103. bool got_100 = true;
  14104. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  14105. EXPECT_FALSE(got_100);
  14106. }
  14107. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  14108. bool got_100 = false;
  14109. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  14110. EXPECT_TRUE(got_100);
  14111. }
  14112. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  14113. bool got_100 = false;
  14114. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  14115. EXPECT_TRUE(got_100);
  14116. }
  14117. #ifndef _WIN32
  14118. TEST(Expect100ContinueTest, ServerClosesConnection) {
  14119. static constexpr char reject[] = "Unauthorized";
  14120. static constexpr char accept[] = "Upload accepted";
  14121. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  14122. Server svr;
  14123. svr.set_expect_100_continue_handler(
  14124. [](const Request & /*req*/, Response &res) {
  14125. res.status = StatusCode::Unauthorized_401;
  14126. res.set_content(reject, "text/plain");
  14127. return res.status;
  14128. });
  14129. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  14130. res.set_content(accept, "text/plain");
  14131. });
  14132. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14133. auto se = detail::scope_exit([&] {
  14134. svr.stop();
  14135. thread.join();
  14136. ASSERT_FALSE(svr.is_running());
  14137. });
  14138. svr.wait_until_ready();
  14139. {
  14140. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  14141. curl_easy_init(), &curl_easy_cleanup};
  14142. ASSERT_NE(curl, nullptr);
  14143. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  14144. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  14145. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  14146. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  14147. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  14148. &curl_slist_free_all};
  14149. ASSERT_NE(list, nullptr);
  14150. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  14151. struct read_data {
  14152. size_t read_size;
  14153. size_t total_size;
  14154. } data = {0, total_size};
  14155. using read_callback_t =
  14156. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14157. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  14158. void *userdata) -> size_t {
  14159. read_data *d = (read_data *)userdata;
  14160. if (!userdata || d->read_size >= d->total_size) { return 0; }
  14161. std::fill_n(ptr, size * nmemb, 'A');
  14162. d->read_size += size * nmemb;
  14163. return size * nmemb;
  14164. };
  14165. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  14166. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  14167. std::vector<char> buffer;
  14168. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  14169. using write_callback_t =
  14170. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14171. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  14172. void *userdata) -> size_t {
  14173. std::vector<char> *buf = (std::vector<char> *)userdata;
  14174. buf->reserve(buf->size() + size * nmemb + 1);
  14175. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  14176. return size * nmemb;
  14177. };
  14178. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  14179. {
  14180. const auto res = curl_easy_perform(curl.get());
  14181. ASSERT_EQ(res, CURLE_OK);
  14182. }
  14183. {
  14184. auto response_code = long{};
  14185. const auto res =
  14186. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  14187. ASSERT_EQ(res, CURLE_OK);
  14188. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  14189. }
  14190. {
  14191. auto dl = curl_off_t{};
  14192. const auto res =
  14193. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  14194. ASSERT_EQ(res, CURLE_OK);
  14195. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  14196. }
  14197. {
  14198. buffer.push_back('\0');
  14199. ASSERT_STRCASEEQ(buffer.data(), reject);
  14200. }
  14201. }
  14202. }
  14203. #endif
  14204. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  14205. // Regression test for #2458.
  14206. //
  14207. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  14208. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  14209. // ticket can make the client socket spuriously readable during the
  14210. // 100-continue wait. If the readiness is mistaken for an incoming response,
  14211. // the client withholds the body and then blocks reading a response that never
  14212. // comes, failing with `Failed to read connection`.
  14213. //
  14214. // A correct client (like curl) sends the body once no `100 Continue` arrives
  14215. // within the timeout. This raw OpenSSL server deliberately never sends
  14216. // `100 Continue`; the client must still deliver the body and receive 200.
  14217. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  14218. signal(SIGPIPE, SIG_IGN);
  14219. const auto port = PORT + 4;
  14220. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14221. ASSERT_NE(srv, INVALID_SOCKET);
  14222. int opt = 1;
  14223. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  14224. sockaddr_in addr{};
  14225. addr.sin_family = AF_INET;
  14226. addr.sin_port = htons(static_cast<uint16_t>(port));
  14227. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14228. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14229. ASSERT_EQ(0, ::listen(srv, 1));
  14230. std::atomic<size_t> server_body_bytes{0};
  14231. auto server_thread = std::thread([&] {
  14232. sockaddr_in cli_addr{};
  14233. socklen_t cli_len = sizeof(cli_addr);
  14234. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14235. if (cli == INVALID_SOCKET) { return; }
  14236. // Bound the lifetime of the server side so a buggy client (which never
  14237. // sends the body) cannot make this thread block forever on join.
  14238. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  14239. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14240. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  14241. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  14242. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  14243. SSL *ssl = SSL_new(ctx);
  14244. SSL_set_fd(ssl, static_cast<int>(cli));
  14245. if (SSL_accept(ssl) > 0) {
  14246. // Read the request headers. Reading here also flushes the TLS 1.3
  14247. // session tickets to the client. Deliberately do NOT send
  14248. // `100 Continue`.
  14249. std::string buf;
  14250. char tmp[1024];
  14251. while (buf.find("\r\n\r\n") == std::string::npos) {
  14252. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14253. if (n <= 0) { break; }
  14254. buf.append(tmp, static_cast<size_t>(n));
  14255. }
  14256. // A correct client sends the body now; count what arrives.
  14257. auto pos = buf.find("\r\n\r\n");
  14258. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  14259. while (body < 4096) {
  14260. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14261. if (n <= 0) { break; }
  14262. body += static_cast<size_t>(n);
  14263. }
  14264. server_body_bytes = body;
  14265. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  14266. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  14267. SSL_shutdown(ssl);
  14268. }
  14269. SSL_free(ssl);
  14270. detail::close_socket(cli);
  14271. SSL_CTX_free(ctx);
  14272. });
  14273. auto se = detail::scope_exit([&] {
  14274. server_thread.join();
  14275. detail::close_socket(srv);
  14276. });
  14277. SSLClient cli("127.0.0.1", port);
  14278. cli.enable_server_certificate_verification(false);
  14279. cli.set_connection_timeout(5, 0);
  14280. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  14281. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  14282. std::string body(4096, 'A');
  14283. auto res = cli.Put("/api/test", body, "application/json");
  14284. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  14285. EXPECT_EQ(StatusCode::OK_200, res->status);
  14286. EXPECT_EQ(body.size(), server_body_bytes.load());
  14287. }
  14288. #endif
  14289. template <typename S, typename C>
  14290. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  14291. svr.Get("/stream", [&](const Request &, Response &res) {
  14292. auto data = new std::string("01234567890123456789");
  14293. res.set_content_provider(
  14294. data->size(), "text/plain",
  14295. [&, data](size_t offset, size_t length, DataSink &sink) {
  14296. const size_t DATA_CHUNK_SIZE = 4;
  14297. const auto &d = *data;
  14298. std::this_thread::sleep_for(std::chrono::seconds(1));
  14299. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  14300. return true;
  14301. },
  14302. [data](bool success) {
  14303. EXPECT_FALSE(success);
  14304. delete data;
  14305. });
  14306. });
  14307. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  14308. auto i = new size_t(0);
  14309. res.set_content_provider(
  14310. "text/plain",
  14311. [i](size_t, DataSink &sink) {
  14312. if (*i < 5) {
  14313. std::this_thread::sleep_for(std::chrono::seconds(1));
  14314. sink.write("abcd", 4);
  14315. (*i)++;
  14316. } else {
  14317. sink.done();
  14318. }
  14319. return true;
  14320. },
  14321. [i](bool success) {
  14322. EXPECT_FALSE(success);
  14323. delete i;
  14324. });
  14325. });
  14326. svr.Get("/chunked", [&](const Request &, Response &res) {
  14327. auto i = new size_t(0);
  14328. res.set_chunked_content_provider(
  14329. "text/plain",
  14330. [i](size_t, DataSink &sink) {
  14331. if (*i < 5) {
  14332. std::this_thread::sleep_for(std::chrono::seconds(1));
  14333. sink.os << "abcd";
  14334. (*i)++;
  14335. } else {
  14336. sink.done();
  14337. }
  14338. return true;
  14339. },
  14340. [i](bool success) {
  14341. EXPECT_FALSE(success);
  14342. delete i;
  14343. });
  14344. });
  14345. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14346. auto se = detail::scope_exit([&] {
  14347. svr.stop();
  14348. listen_thread.join();
  14349. ASSERT_FALSE(svr.is_running());
  14350. });
  14351. svr.wait_until_ready();
  14352. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  14353. {
  14354. auto start = std::chrono::steady_clock::now();
  14355. auto res = cli.Get("/stream");
  14356. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14357. std::chrono::steady_clock::now() - start)
  14358. .count();
  14359. ASSERT_FALSE(res);
  14360. EXPECT_EQ(Error::Read, res.error());
  14361. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14362. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14363. }
  14364. {
  14365. auto start = std::chrono::steady_clock::now();
  14366. auto res = cli.Get("/stream_without_length");
  14367. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14368. std::chrono::steady_clock::now() - start)
  14369. .count();
  14370. ASSERT_FALSE(res);
  14371. EXPECT_EQ(Error::Read, res.error());
  14372. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14373. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14374. }
  14375. {
  14376. auto start = std::chrono::steady_clock::now();
  14377. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  14378. EXPECT_EQ("abcd", string(data, data_length));
  14379. return true;
  14380. });
  14381. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14382. std::chrono::steady_clock::now() - start)
  14383. .count();
  14384. ASSERT_FALSE(res);
  14385. EXPECT_EQ(Error::Read, res.error());
  14386. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14387. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14388. }
  14389. }
  14390. TEST(MaxTimeoutTest, ContentStream) {
  14391. time_t timeout = 2000;
  14392. time_t threshold = 200;
  14393. Server svr;
  14394. Client cli("localhost", PORT);
  14395. max_timeout_test(svr, cli, timeout, threshold);
  14396. }
  14397. #ifdef CPPHTTPLIB_SSL_ENABLED
  14398. TEST(MaxTimeoutTest, ContentStreamSSL) {
  14399. time_t timeout = 2000;
  14400. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  14401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14402. SSLClient cli("localhost", PORT);
  14403. cli.enable_server_certificate_verification(false);
  14404. max_timeout_test(svr, cli, timeout, threshold);
  14405. }
  14406. #endif
  14407. class EventDispatcher {
  14408. public:
  14409. EventDispatcher() {}
  14410. bool wait_event(DataSink *sink) {
  14411. unique_lock<mutex> lk(m_);
  14412. int id = id_;
  14413. // Wait with timeout to prevent hanging if client disconnects
  14414. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  14415. [&] { return cid_ == id; })) {
  14416. return false; // Timeout occurred
  14417. }
  14418. sink->write(message_.data(), message_.size());
  14419. return true;
  14420. }
  14421. void send_event(const string &message) {
  14422. lock_guard<mutex> lk(m_);
  14423. cid_ = id_++;
  14424. message_ = message;
  14425. cv_.notify_all();
  14426. }
  14427. private:
  14428. mutex m_;
  14429. condition_variable cv_;
  14430. atomic_int id_{0};
  14431. atomic_int cid_{-1};
  14432. string message_;
  14433. };
  14434. TEST(ClientInThreadTest, Issue2068) {
  14435. EventDispatcher ed;
  14436. Server svr;
  14437. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  14438. res.set_chunked_content_provider("text/event-stream",
  14439. [&](size_t /*offset*/, DataSink &sink) {
  14440. return ed.wait_event(&sink);
  14441. });
  14442. });
  14443. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  14444. svr.wait_until_ready();
  14445. thread event_thread([&] {
  14446. int id = 0;
  14447. while (svr.is_running()) {
  14448. this_thread::sleep_for(chrono::milliseconds(500));
  14449. std::stringstream ss;
  14450. ss << "data: " << id << "\n\n";
  14451. ed.send_event(ss.str());
  14452. id++;
  14453. }
  14454. });
  14455. auto se = detail::scope_exit([&] {
  14456. svr.stop();
  14457. listen_thread.join();
  14458. event_thread.join();
  14459. ASSERT_FALSE(svr.is_running());
  14460. });
  14461. {
  14462. auto client = detail::make_unique<Client>(HOST, PORT);
  14463. client->set_read_timeout(std::chrono::minutes(10));
  14464. std::atomic<bool> stop{false};
  14465. std::thread t([&] {
  14466. client->Get("/event1",
  14467. [&](const char *, size_t) -> bool { return !stop; });
  14468. });
  14469. std::this_thread::sleep_for(std::chrono::seconds(2));
  14470. stop = true;
  14471. client->stop();
  14472. t.join();
  14473. // Reset client after thread has finished
  14474. client.reset();
  14475. }
  14476. }
  14477. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  14478. auto handled = false;
  14479. Server svr;
  14480. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14481. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14482. auto se = detail::scope_exit([&] {
  14483. svr.stop();
  14484. t.join();
  14485. ASSERT_FALSE(svr.is_running());
  14486. ASSERT_FALSE(handled);
  14487. });
  14488. svr.wait_until_ready();
  14489. // Two Content-Length headers with different values — must be rejected
  14490. auto req = "POST /test HTTP/1.1\r\n"
  14491. "Content-Length: 5\r\n"
  14492. "Content-Length: 10\r\n"
  14493. "\r\n"
  14494. "hello";
  14495. std::string response;
  14496. ASSERT_TRUE(send_request(1, req, &response));
  14497. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14498. response.substr(0, response.find("\r\n")));
  14499. }
  14500. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  14501. auto handled = false;
  14502. Server svr;
  14503. svr.Post("/test", [&](const Request &, Response &res) {
  14504. handled = true;
  14505. res.set_content("ok", "text/plain");
  14506. });
  14507. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14508. auto se = detail::scope_exit([&] {
  14509. svr.stop();
  14510. t.join();
  14511. ASSERT_FALSE(svr.is_running());
  14512. ASSERT_TRUE(handled);
  14513. });
  14514. svr.wait_until_ready();
  14515. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  14516. auto req = "POST /test HTTP/1.1\r\n"
  14517. "Content-Length: 5\r\n"
  14518. "Content-Length: 5\r\n"
  14519. "\r\n"
  14520. "hello";
  14521. std::string response;
  14522. ASSERT_TRUE(send_request(1, req, &response));
  14523. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  14524. }
  14525. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  14526. Server svr;
  14527. svr.Get("/", [](const Request &req, Response &res) {
  14528. EXPECT_EQ(2U, req.trailers.size());
  14529. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  14530. // Denied
  14531. EXPECT_FALSE(req.has_trailer("Content-Length"));
  14532. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  14533. // Accepted
  14534. EXPECT_TRUE(req.has_trailer("X-Hello"));
  14535. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  14536. EXPECT_TRUE(req.has_trailer("X-World"));
  14537. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  14538. res.set_content("ok", "text/plain");
  14539. });
  14540. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14541. auto se = detail::scope_exit([&] {
  14542. svr.stop();
  14543. t.join();
  14544. ASSERT_FALSE(svr.is_running());
  14545. });
  14546. svr.wait_until_ready();
  14547. const std::string req = "GET / HTTP/1.1\r\n"
  14548. "Transfer-Encoding: chunked\r\n"
  14549. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  14550. "\r\n"
  14551. "0\r\n"
  14552. "Content-Length: 10\r\n"
  14553. "Host: internal.local\r\n"
  14554. "Content-Type: malicious/content\r\n"
  14555. "Cookie: any\r\n"
  14556. "Set-Cookie: any\r\n"
  14557. "X-Forwarded-For: attacker.com\r\n"
  14558. "X-Real-Ip: 1.1.1.1\r\n"
  14559. "X-Hello: hello\r\n"
  14560. "X-World: world\r\n"
  14561. "\r\n";
  14562. std::string res;
  14563. ASSERT_TRUE(send_request(1, req, &res));
  14564. }
  14565. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  14566. // several field lines, and the combined value is what has to be parsed. A
  14567. // Trailer field split across lines therefore declares every name it lists;
  14568. // reading only the first line silently drops the trailers the later lines
  14569. // declare. The prohibited-trailer filter still applies to every line.
  14570. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  14571. Server svr;
  14572. size_t observed_trailer_count = 0;
  14573. std::string observed_hello;
  14574. std::string observed_world;
  14575. bool observed_content_length = true;
  14576. svr.Get("/", [&](const Request &req, Response &res) {
  14577. observed_trailer_count = req.trailers.size();
  14578. observed_hello = req.get_trailer_value("X-Hello");
  14579. observed_world = req.get_trailer_value("X-World");
  14580. observed_content_length = req.has_trailer("Content-Length");
  14581. res.set_content("ok", "text/plain");
  14582. });
  14583. auto port = svr.bind_to_any_port(HOST);
  14584. thread t = thread([&]() { svr.listen_after_bind(); });
  14585. auto se = detail::scope_exit([&] {
  14586. svr.stop();
  14587. t.join();
  14588. ASSERT_FALSE(svr.is_running());
  14589. });
  14590. svr.wait_until_ready();
  14591. const std::string req = "GET / HTTP/1.1\r\n"
  14592. "Transfer-Encoding: chunked\r\n"
  14593. "Trailer: X-Hello\r\n"
  14594. "Trailer: X-World, Content-Length\r\n"
  14595. "\r\n"
  14596. "0\r\n"
  14597. "X-Hello: hello\r\n"
  14598. "X-World: world\r\n"
  14599. "Content-Length: 10\r\n"
  14600. "\r\n";
  14601. std::string res;
  14602. ASSERT_TRUE(send_request(1, req, &res, port));
  14603. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  14604. // Accepted: both field lines contribute to the declared set
  14605. EXPECT_EQ(2U, observed_trailer_count);
  14606. EXPECT_EQ(observed_hello, "hello");
  14607. EXPECT_EQ(observed_world, "world");
  14608. // Denied: a prohibited name stays prohibited on a later field line
  14609. EXPECT_FALSE(observed_content_length);
  14610. }
  14611. // A direct client that is not listed in trusted_proxies must not be able to
  14612. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  14613. // the peer address on the actual TCP connection determines whether the
  14614. // header is honored.
  14615. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  14616. Server svr;
  14617. // Deliberately does NOT include the loopback address the test client
  14618. // actually connects from, so the direct connection is not a trusted proxy.
  14619. svr.set_trusted_proxies({"203.0.113.66"});
  14620. std::string observed_remote_addr;
  14621. svr.Get("/ip", [&](const Request &req, Response &res) {
  14622. observed_remote_addr = req.remote_addr;
  14623. res.set_content("ok", "text/plain");
  14624. });
  14625. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14626. auto se = detail::scope_exit([&] {
  14627. svr.stop();
  14628. t.join();
  14629. ASSERT_FALSE(svr.is_running());
  14630. });
  14631. svr.wait_until_ready();
  14632. Client cli(HOST, PORT);
  14633. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  14634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14635. EXPECT_EQ(StatusCode::OK_200, res->status);
  14636. // The connecting peer is not a trusted proxy, so the spoofed header must be
  14637. // ignored entirely and the real connection-level address retained.
  14638. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14639. observed_remote_addr == "127.0.0.1");
  14640. }
  14641. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  14642. Server svr;
  14643. std::string observed_remote_addr;
  14644. std::string observed_xff;
  14645. svr.Get("/ip", [&](const Request &req, Response &res) {
  14646. observed_remote_addr = req.remote_addr;
  14647. observed_xff = req.get_header_value("X-Forwarded-For");
  14648. res.set_content("ok", "text/plain");
  14649. });
  14650. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14651. auto se = detail::scope_exit([&] {
  14652. svr.stop();
  14653. t.join();
  14654. ASSERT_FALSE(svr.is_running());
  14655. });
  14656. svr.wait_until_ready();
  14657. Client cli(HOST, PORT);
  14658. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  14659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14660. EXPECT_EQ(StatusCode::OK_200, res->status);
  14661. EXPECT_EQ(observed_xff, "203.0.113.66");
  14662. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14663. observed_remote_addr == "127.0.0.1");
  14664. }
  14665. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  14666. Server svr;
  14667. svr.set_trusted_proxies({"203.0.113.66"});
  14668. std::string observed_remote_addr;
  14669. std::string observed_xff;
  14670. svr.Get("/ip", [&](const Request &req, Response &res) {
  14671. observed_remote_addr = req.remote_addr;
  14672. observed_xff = req.get_header_value("X-Forwarded-For");
  14673. res.set_content("ok", "text/plain");
  14674. });
  14675. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14676. auto se = detail::scope_exit([&] {
  14677. svr.stop();
  14678. t.join();
  14679. ASSERT_FALSE(svr.is_running());
  14680. });
  14681. svr.wait_until_ready();
  14682. Client cli(HOST, PORT);
  14683. auto res = cli.Get("/ip");
  14684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14685. EXPECT_EQ(StatusCode::OK_200, res->status);
  14686. EXPECT_EQ(observed_xff, "");
  14687. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14688. observed_remote_addr == "127.0.0.1");
  14689. }
  14690. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  14691. Server svr;
  14692. // Include the loopback address the test client actually connects from, so
  14693. // the direct connection itself is recognized as the trusted proxy hop.
  14694. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  14695. std::string observed_remote_addr;
  14696. std::string observed_xff;
  14697. svr.Get("/ip", [&](const Request &req, Response &res) {
  14698. observed_remote_addr = req.remote_addr;
  14699. observed_xff = req.get_header_value("X-Forwarded-For");
  14700. res.set_content("ok", "text/plain");
  14701. });
  14702. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14703. auto se = detail::scope_exit([&] {
  14704. svr.stop();
  14705. t.join();
  14706. ASSERT_FALSE(svr.is_running());
  14707. });
  14708. svr.wait_until_ready();
  14709. Client cli(HOST, PORT);
  14710. auto res = cli.Get(
  14711. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  14712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14713. EXPECT_EQ(StatusCode::OK_200, res->status);
  14714. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  14715. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14716. }
  14717. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  14718. Server svr;
  14719. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  14720. std::string observed_remote_addr;
  14721. std::string observed_xff;
  14722. svr.Get("/ip", [&](const Request &req, Response &res) {
  14723. observed_remote_addr = req.remote_addr;
  14724. observed_xff = req.get_header_value("X-Forwarded-For");
  14725. res.set_content("ok", "text/plain");
  14726. });
  14727. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14728. auto se = detail::scope_exit([&] {
  14729. svr.stop();
  14730. t.join();
  14731. ASSERT_FALSE(svr.is_running());
  14732. });
  14733. svr.wait_until_ready();
  14734. Client cli(HOST, PORT);
  14735. auto res = cli.Get(
  14736. "/ip",
  14737. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14739. EXPECT_EQ(StatusCode::OK_200, res->status);
  14740. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14741. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14742. }
  14743. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  14744. Server svr;
  14745. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14746. std::string observed_remote_addr;
  14747. std::string observed_xff;
  14748. svr.Get("/ip", [&](const Request &req, Response &res) {
  14749. observed_remote_addr = req.remote_addr;
  14750. observed_xff = req.get_header_value("X-Forwarded-For");
  14751. res.set_content("ok", "text/plain");
  14752. });
  14753. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14754. auto se = detail::scope_exit([&] {
  14755. svr.stop();
  14756. t.join();
  14757. ASSERT_FALSE(svr.is_running());
  14758. });
  14759. svr.wait_until_ready();
  14760. Client cli(HOST, PORT);
  14761. auto res = cli.Get(
  14762. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  14763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14764. EXPECT_EQ(StatusCode::OK_200, res->status);
  14765. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  14766. // by the closest hop) is used. The leftmost entry is fully client-controlled
  14767. // and must not be selected.
  14768. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  14769. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  14770. }
  14771. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  14772. Server svr;
  14773. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14774. std::string observed_remote_addr;
  14775. svr.Get("/ip", [&](const Request &req, Response &res) {
  14776. observed_remote_addr = req.remote_addr;
  14777. res.set_content("ok", "text/plain");
  14778. });
  14779. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14780. auto se = detail::scope_exit([&] {
  14781. svr.stop();
  14782. t.join();
  14783. ASSERT_FALSE(svr.is_running());
  14784. });
  14785. svr.wait_until_ready();
  14786. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14787. // a forged address and the trusted proxy's own address; the forged value must
  14788. // not win over the address the trusted proxy actually recorded.
  14789. Client cli(HOST, PORT);
  14790. auto res = cli.Get(
  14791. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14793. EXPECT_EQ(StatusCode::OK_200, res->status);
  14794. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14795. }
  14796. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14797. Server svr;
  14798. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14799. std::string observed_remote_addr;
  14800. std::string observed_xff;
  14801. svr.Get("/ip", [&](const Request &req, Response &res) {
  14802. observed_remote_addr = req.remote_addr;
  14803. observed_xff = req.get_header_value("X-Forwarded-For");
  14804. res.set_content("ok", "text/plain");
  14805. });
  14806. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14807. auto se = detail::scope_exit([&] {
  14808. svr.stop();
  14809. t.join();
  14810. ASSERT_FALSE(svr.is_running());
  14811. });
  14812. svr.wait_until_ready();
  14813. Client cli(HOST, PORT);
  14814. auto res = cli.Get(
  14815. "/ip",
  14816. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14818. EXPECT_EQ(StatusCode::OK_200, res->status);
  14819. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14820. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14821. }
  14822. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14823. Server svr;
  14824. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14825. std::string observed_remote_addr;
  14826. std::string observed_xff;
  14827. svr.Get("/ip", [&](const Request &req, Response &res) {
  14828. observed_remote_addr = req.remote_addr;
  14829. observed_xff = req.get_header_value("X-Forwarded-For");
  14830. res.set_content("ok", "text/plain");
  14831. });
  14832. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14833. auto se = detail::scope_exit([&] {
  14834. svr.stop();
  14835. t.join();
  14836. ASSERT_FALSE(svr.is_running());
  14837. });
  14838. svr.wait_until_ready();
  14839. std::string raw_req =
  14840. "GET /ip HTTP/1.1\r\n"
  14841. "Host: localhost\r\n"
  14842. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14843. "Connection: close\r\n"
  14844. "\r\n";
  14845. std::string out;
  14846. ASSERT_TRUE(send_request(5, raw_req, &out));
  14847. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14848. // Header parser trims surrounding whitespace of the header value
  14849. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14850. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14851. }
  14852. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  14853. // one comma-joined value, in the order received. Proxies such as HAProxy append
  14854. // their own X-Forwarded-For as a separate field line rather than extending the
  14855. // one the client sent, so every occurrence has to be taken into account.
  14856. // Reading only the first one hands back the address the client chose.
  14857. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  14858. Server svr;
  14859. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14860. std::string observed_remote_addr;
  14861. size_t observed_xff_count = 0;
  14862. svr.Get("/ip", [&](const Request &req, Response &res) {
  14863. observed_remote_addr = req.remote_addr;
  14864. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  14865. res.set_content("ok", "text/plain");
  14866. });
  14867. auto port = svr.bind_to_any_port(HOST);
  14868. thread t = thread([&]() { svr.listen_after_bind(); });
  14869. auto se = detail::scope_exit([&] {
  14870. svr.stop();
  14871. t.join();
  14872. ASSERT_FALSE(svr.is_running());
  14873. });
  14874. svr.wait_until_ready();
  14875. // The client supplies the first field line; the trusted proxy appends the
  14876. // address it observed as a second one.
  14877. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  14878. "Host: localhost\r\n"
  14879. "X-Forwarded-For: 1.2.3.4\r\n"
  14880. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  14881. "Connection: close\r\n"
  14882. "\r\n";
  14883. std::string out;
  14884. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14885. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14886. EXPECT_EQ(observed_xff_count, 2U);
  14887. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14888. // The same chain spread over one field line per hop derives the same client
  14889. // address, i.e. the split and the comma-joined representations agree.
  14890. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  14891. "Host: localhost\r\n"
  14892. "X-Forwarded-For: 1.2.3.4\r\n"
  14893. "X-Forwarded-For: 198.51.100.23\r\n"
  14894. "X-Forwarded-For: 192.0.2.45\r\n"
  14895. "Connection: close\r\n"
  14896. "\r\n";
  14897. out.clear();
  14898. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  14899. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14900. EXPECT_EQ(observed_xff_count, 3U);
  14901. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14902. }
  14903. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14904. // crash the server (it used to call front() on an empty vector inside
  14905. // get_client_ip). The connection-level remote address must be retained instead.
  14906. static void run_malformed_xff_test(const std::string &xff_value) {
  14907. Server svr;
  14908. svr.set_trusted_proxies({"192.0.2.45"});
  14909. std::string observed_remote_addr;
  14910. svr.Get("/ip", [&](const Request &req, Response &res) {
  14911. observed_remote_addr = req.remote_addr;
  14912. res.set_content("ok", "text/plain");
  14913. });
  14914. int port = 0;
  14915. thread t = thread([&]() {
  14916. port = svr.bind_to_any_port(HOST);
  14917. svr.listen_after_bind();
  14918. });
  14919. auto se = detail::scope_exit([&] {
  14920. svr.stop();
  14921. t.join();
  14922. ASSERT_FALSE(svr.is_running());
  14923. });
  14924. svr.wait_until_ready();
  14925. Client cli(HOST, port);
  14926. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  14927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14928. EXPECT_EQ(StatusCode::OK_200, res->status);
  14929. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14930. observed_remote_addr == "127.0.0.1");
  14931. }
  14932. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  14933. run_malformed_xff_test("");
  14934. }
  14935. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  14936. run_malformed_xff_test(",");
  14937. }
  14938. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  14939. run_malformed_xff_test(", , ,");
  14940. }
  14941. // The same rule applies to Accept: a request whose acceptable types are spread
  14942. // over several field lines must be negotiated against all of them.
  14943. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  14944. // case-insensitive connection options. Comparing the whole field value against
  14945. // one option misses a client that sends several of them, and misses every
  14946. // casing but the one written in the comparison.
  14947. //
  14948. // Sends req, reads the response, then reuses the same socket for a second
  14949. // request to find out whether the server kept the connection.
  14950. static void probe_connection_reuse(int port, const std::string &req,
  14951. bool *announced_close, bool *reusable) {
  14952. auto error = Error::Success;
  14953. auto sock = detail::create_client_socket(
  14954. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  14955. /*connection_timeout_sec=*/5, 0,
  14956. /*read_timeout_sec=*/1, 0,
  14957. /*write_timeout_sec=*/5, 0, std::string(), error);
  14958. ASSERT_NE(sock, INVALID_SOCKET);
  14959. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  14960. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  14961. "Host: localhost\r\n"
  14962. "Connection: close\r\n"
  14963. "\r\n";
  14964. std::string first_response;
  14965. std::string second_response;
  14966. detail::process_client_socket(
  14967. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  14968. [&](Stream &strm) {
  14969. if (strm.write(req.data(), req.size()) !=
  14970. static_cast<ssize_t>(req.size())) {
  14971. return false;
  14972. }
  14973. char buf[512];
  14974. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  14975. // Headers plus the two-byte body of the handler below
  14976. while (reader.getline()) {
  14977. first_response += reader.ptr();
  14978. if (first_response.find("ok") != std::string::npos) { break; }
  14979. }
  14980. if (strm.write(second.data(), second.size()) !=
  14981. static_cast<ssize_t>(second.size())) {
  14982. return true;
  14983. }
  14984. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  14985. while (reader2.getline()) {
  14986. second_response += reader2.ptr();
  14987. if (second_response.find("ok") != std::string::npos) { break; }
  14988. }
  14989. return true;
  14990. });
  14991. *announced_close =
  14992. first_response.find("Connection: close") != std::string::npos;
  14993. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  14994. }
  14995. class ConnectionTokenTest : public ::testing::Test {
  14996. protected:
  14997. void SetUp() override {
  14998. svr_.Get("/keepalive", [](const Request &, Response &res) {
  14999. res.set_content("ok", "text/plain");
  15000. });
  15001. port_ = svr_.bind_to_any_port(HOST);
  15002. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15003. svr_.wait_until_ready();
  15004. }
  15005. void TearDown() override {
  15006. svr_.stop();
  15007. if (thread_.joinable()) { thread_.join(); }
  15008. }
  15009. Server svr_;
  15010. int port_ = 0;
  15011. thread thread_;
  15012. };
  15013. // "close" alongside another option still closes the connection, and the
  15014. // response says so rather than leaving the peer to discover it.
  15015. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  15016. bool announced_close = false;
  15017. bool reusable = true;
  15018. probe_connection_reuse(port_,
  15019. "GET /keepalive HTTP/1.1\r\n"
  15020. "Host: localhost\r\n"
  15021. "Connection: keep-alive, close\r\n"
  15022. "\r\n",
  15023. &announced_close, &reusable);
  15024. EXPECT_TRUE(announced_close);
  15025. EXPECT_FALSE(reusable);
  15026. }
  15027. // "close" split over two field lines is the same list, so it is honored too.
  15028. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  15029. bool announced_close = false;
  15030. bool reusable = true;
  15031. probe_connection_reuse(port_,
  15032. "GET /keepalive HTTP/1.1\r\n"
  15033. "Host: localhost\r\n"
  15034. "Connection: keep-alive\r\n"
  15035. "Connection: close\r\n"
  15036. "\r\n",
  15037. &announced_close, &reusable);
  15038. EXPECT_TRUE(announced_close);
  15039. EXPECT_FALSE(reusable);
  15040. }
  15041. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  15042. // keep-alive in the spelling everyone actually sends keeps its connection.
  15043. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  15044. bool announced_close = false;
  15045. bool reusable = false;
  15046. probe_connection_reuse(port_,
  15047. "GET /keepalive HTTP/1.0\r\n"
  15048. "Host: localhost\r\n"
  15049. "Connection: keep-alive\r\n"
  15050. "\r\n",
  15051. &announced_close, &reusable);
  15052. EXPECT_FALSE(announced_close);
  15053. EXPECT_TRUE(reusable);
  15054. }
  15055. // A token the value merely contains is not the token itself.
  15056. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  15057. bool announced_close = false;
  15058. bool reusable = false;
  15059. probe_connection_reuse(port_,
  15060. "GET /keepalive HTTP/1.1\r\n"
  15061. "Host: localhost\r\n"
  15062. "Connection: notclose\r\n"
  15063. "\r\n",
  15064. &announced_close, &reusable);
  15065. EXPECT_FALSE(announced_close);
  15066. EXPECT_TRUE(reusable);
  15067. }
  15068. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  15069. Server svr;
  15070. std::vector<std::string> observed_types;
  15071. svr.Get("/", [&](const Request &req, Response &res) {
  15072. observed_types = req.accept_content_types;
  15073. res.set_content("ok", "text/plain");
  15074. });
  15075. auto port = svr.bind_to_any_port(HOST);
  15076. thread t = thread([&]() { svr.listen_after_bind(); });
  15077. auto se = detail::scope_exit([&] {
  15078. svr.stop();
  15079. t.join();
  15080. ASSERT_FALSE(svr.is_running());
  15081. });
  15082. svr.wait_until_ready();
  15083. Client cli(HOST, port);
  15084. Headers headers;
  15085. headers.emplace("Accept", "text/plain;q=0.5");
  15086. headers.emplace("Accept", "application/json");
  15087. auto res = cli.Get("/", headers);
  15088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15089. EXPECT_EQ(StatusCode::OK_200, res->status);
  15090. // Sorted by q-value, so the second field line's type comes first
  15091. ASSERT_EQ(2U, observed_types.size());
  15092. EXPECT_EQ("application/json", observed_types[0]);
  15093. EXPECT_EQ("text/plain", observed_types[1]);
  15094. }
  15095. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  15096. // empty field line must not contribute a bare comma to the combined value.
  15097. // parse_accept_header() rejects a leading comma outright, so a stray one would
  15098. // turn a legal request into 400 Bad Request.
  15099. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  15100. Server svr;
  15101. std::vector<std::string> observed_types;
  15102. svr.Get("/", [&](const Request &req, Response &res) {
  15103. observed_types = req.accept_content_types;
  15104. res.set_content("ok", "text/plain");
  15105. });
  15106. auto port = svr.bind_to_any_port(HOST);
  15107. thread t = thread([&]() { svr.listen_after_bind(); });
  15108. auto se = detail::scope_exit([&] {
  15109. svr.stop();
  15110. t.join();
  15111. ASSERT_FALSE(svr.is_running());
  15112. });
  15113. svr.wait_until_ready();
  15114. // Empty first field line, then a real one
  15115. std::string raw_req = "GET / HTTP/1.1\r\n"
  15116. "Host: localhost\r\n"
  15117. "Accept:\r\n"
  15118. "Accept: application/json\r\n"
  15119. "Connection: close\r\n"
  15120. "\r\n";
  15121. std::string out;
  15122. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15123. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15124. ASSERT_EQ(1U, observed_types.size());
  15125. EXPECT_EQ("application/json", observed_types[0]);
  15126. }
  15127. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15128. // An encoding offered on a later Accept-Encoding field line is still offered.
  15129. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  15130. Server svr;
  15131. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15132. res.set_content(std::string(1024, 'x'), "text/plain");
  15133. });
  15134. auto port = svr.bind_to_any_port(HOST);
  15135. thread t = thread([&]() { svr.listen_after_bind(); });
  15136. auto se = detail::scope_exit([&] {
  15137. svr.stop();
  15138. t.join();
  15139. ASSERT_FALSE(svr.is_running());
  15140. });
  15141. svr.wait_until_ready();
  15142. Client cli(HOST, port);
  15143. cli.set_decompress(false);
  15144. Headers headers;
  15145. headers.emplace("Accept-Encoding", "identity");
  15146. headers.emplace("Accept-Encoding", "gzip");
  15147. auto res = cli.Get("/", headers);
  15148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15149. EXPECT_EQ(StatusCode::OK_200, res->status);
  15150. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  15151. }
  15152. #endif
  15153. #ifndef _WIN32
  15154. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  15155. Server svr;
  15156. svr.Post("/post", [&](const Request &req, Response &res) {
  15157. res.set_content(req.body, "text/plain");
  15158. });
  15159. svr.Put("/put", [&](const Request &req, Response &res) {
  15160. res.set_content(req.body, "text/plain");
  15161. });
  15162. svr.Patch("/patch", [&](const Request &req, Response &res) {
  15163. res.set_content(req.body, "text/plain");
  15164. });
  15165. svr.Delete("/delete", [&](const Request &req, Response &res) {
  15166. res.set_content(req.body, "text/plain");
  15167. });
  15168. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15169. auto se = detail::scope_exit([&] {
  15170. svr.stop();
  15171. t.join();
  15172. ASSERT_FALSE(svr.is_running());
  15173. });
  15174. svr.wait_until_ready();
  15175. std::string resp;
  15176. // POST without Content-Length
  15177. ASSERT_TRUE(send_request(5,
  15178. "POST /post HTTP/1.1\r\n"
  15179. "Host: localhost\r\n"
  15180. "Connection: close\r\n"
  15181. "\r\n",
  15182. &resp));
  15183. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15184. // PUT without Content-Length
  15185. resp.clear();
  15186. ASSERT_TRUE(send_request(5,
  15187. "PUT /put HTTP/1.1\r\n"
  15188. "Host: localhost\r\n"
  15189. "Connection: close\r\n"
  15190. "\r\n",
  15191. &resp));
  15192. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15193. // PATCH without Content-Length
  15194. resp.clear();
  15195. ASSERT_TRUE(send_request(5,
  15196. "PATCH /patch HTTP/1.1\r\n"
  15197. "Host: localhost\r\n"
  15198. "Connection: close\r\n"
  15199. "\r\n",
  15200. &resp));
  15201. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15202. // DELETE without Content-Length
  15203. resp.clear();
  15204. ASSERT_TRUE(send_request(5,
  15205. "DELETE /delete HTTP/1.1\r\n"
  15206. "Host: localhost\r\n"
  15207. "Connection: close\r\n"
  15208. "\r\n",
  15209. &resp));
  15210. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15211. }
  15212. #endif
  15213. //==============================================================================
  15214. // open_stream() Tests
  15215. //==============================================================================
  15216. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  15217. std::string result;
  15218. char buf[8192];
  15219. ssize_t n;
  15220. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15221. result.append(buf, static_cast<size_t>(n));
  15222. }
  15223. return result;
  15224. }
  15225. // Mock stream for unit tests
  15226. class MockStream : public Stream {
  15227. public:
  15228. std::string data;
  15229. size_t pos = 0;
  15230. ssize_t error_after = -1; // -1 = no error
  15231. explicit MockStream(const std::string &d, ssize_t err = -1)
  15232. : data(d), error_after(err) {}
  15233. bool is_readable() const override { return true; }
  15234. bool wait_readable() const override { return true; }
  15235. bool wait_writable() const override { return true; }
  15236. ssize_t read(char *ptr, size_t size) override {
  15237. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  15238. if (pos >= data.size()) return 0;
  15239. size_t limit =
  15240. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  15241. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  15242. std::memcpy(ptr, data.data() + pos, to_read);
  15243. pos += to_read;
  15244. return static_cast<ssize_t>(to_read);
  15245. }
  15246. ssize_t write(const char *, size_t) override { return -1; }
  15247. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  15248. ip = "127.0.0.1";
  15249. port = 0;
  15250. }
  15251. void get_local_ip_and_port(std::string &ip, int &port) const override {
  15252. ip = "127.0.0.1";
  15253. port = 0;
  15254. }
  15255. socket_t socket() const override { return INVALID_SOCKET; }
  15256. time_t duration() const override { return 0; }
  15257. };
  15258. TEST(StreamHandleTest, Basic) {
  15259. ClientImpl::StreamHandle handle;
  15260. EXPECT_FALSE(handle.is_valid());
  15261. handle.response = detail::make_unique<Response>();
  15262. handle.error = Error::Connection;
  15263. EXPECT_FALSE(handle.is_valid());
  15264. handle.error = Error::Success;
  15265. EXPECT_TRUE(handle.is_valid());
  15266. }
  15267. TEST(BodyReaderTest, Basic) {
  15268. MockStream stream("Hello, World!");
  15269. detail::BodyReader reader;
  15270. reader.stream = &stream;
  15271. reader.content_length = 13;
  15272. char buf[32];
  15273. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  15274. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  15275. EXPECT_TRUE(reader.eof);
  15276. }
  15277. TEST(BodyReaderTest, NoStream) {
  15278. detail::BodyReader reader;
  15279. char buf[32];
  15280. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15281. EXPECT_EQ(Error::Connection, reader.last_error);
  15282. }
  15283. TEST(BodyReaderTest, Error) {
  15284. MockStream stream("Hello, World!", 5);
  15285. detail::BodyReader reader;
  15286. reader.stream = &stream;
  15287. reader.content_length = 13;
  15288. char buf[32];
  15289. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  15290. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15291. EXPECT_EQ(Error::Read, reader.last_error);
  15292. }
  15293. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  15294. // Mock-based StreamHandle tests relying on private internals are removed.
  15295. class OpenStreamTest : public ::testing::Test {
  15296. protected:
  15297. void SetUp() override {
  15298. svr_.Get("/hello", [](const Request &, Response &res) {
  15299. res.set_content("Hello World!", "text/plain");
  15300. });
  15301. svr_.Get("/large", [](const Request &, Response &res) {
  15302. res.set_content(std::string(10000, 'X'), "text/plain");
  15303. });
  15304. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  15305. res.set_content("Hello World!", "image/jpeg");
  15306. res.set_header("Content-Encoding", "UTF-8");
  15307. });
  15308. svr_.Get("/chunked", [](const Request &, Response &res) {
  15309. res.set_chunked_content_provider("text/plain",
  15310. [](size_t offset, DataSink &sink) {
  15311. if (offset < 15) {
  15312. sink.write("chunk", 5);
  15313. return true;
  15314. }
  15315. sink.done();
  15316. return true;
  15317. });
  15318. });
  15319. svr_.Get("/compressible", [](const Request &, Response &res) {
  15320. res.set_chunked_content_provider("text/plain", [](size_t offset,
  15321. DataSink &sink) {
  15322. if (offset < 100 * 1024) {
  15323. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  15324. sink.write(chunk.data(), chunk.size());
  15325. return true;
  15326. }
  15327. sink.done();
  15328. return true;
  15329. });
  15330. });
  15331. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  15332. [](const Request & /*req*/, Response &res) {
  15333. auto i = new int(0);
  15334. res.set_header("Trailer", "Content-Length, X-Allowed");
  15335. res.set_chunked_content_provider(
  15336. "text/plain",
  15337. [i](size_t /*offset*/, DataSink &sink) {
  15338. switch (*i) {
  15339. case 0: sink.os << "123"; break;
  15340. case 1: sink.os << "456"; break;
  15341. case 2: sink.os << "789"; break;
  15342. case 3: {
  15343. sink.done_with_trailer(
  15344. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  15345. } break;
  15346. }
  15347. (*i)++;
  15348. return true;
  15349. },
  15350. [i](bool success) {
  15351. EXPECT_TRUE(success);
  15352. delete i;
  15353. });
  15354. });
  15355. // Echo headers endpoint for header-related tests
  15356. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  15357. std::string body;
  15358. for (const auto &h : req.headers) {
  15359. body.append(h.first);
  15360. body.push_back(':');
  15361. body.append(h.second);
  15362. body.push_back('\n');
  15363. }
  15364. res.set_content(body, "text/plain");
  15365. });
  15366. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  15367. std::string body;
  15368. for (const auto &h : req.headers) {
  15369. body.append(h.first);
  15370. body.push_back(':');
  15371. body.append(h.second);
  15372. body.push_back('\n');
  15373. }
  15374. res.set_content(body, "text/plain");
  15375. });
  15376. port_ = svr_.bind_to_any_port("127.0.0.1");
  15377. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15378. svr_.wait_until_ready();
  15379. }
  15380. void TearDown() override {
  15381. svr_.stop();
  15382. if (thread_.joinable()) thread_.join();
  15383. }
  15384. Server svr_;
  15385. std::thread thread_;
  15386. int port_ = 0;
  15387. };
  15388. TEST_F(OpenStreamTest, Basic) {
  15389. Client cli("127.0.0.1", port_);
  15390. auto handle = cli.open_stream("GET", "/hello");
  15391. EXPECT_TRUE(handle.is_valid());
  15392. EXPECT_EQ("Hello World!", read_all(handle));
  15393. }
  15394. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  15395. Client cli("127.0.0.1", port_);
  15396. auto handle = cli.open_stream("GET", "/unknown-encoding");
  15397. ASSERT_TRUE(handle.is_valid());
  15398. EXPECT_EQ("Hello World!", read_all(handle));
  15399. }
  15400. TEST_F(OpenStreamTest, SmallBuffer) {
  15401. Client cli("127.0.0.1", port_);
  15402. auto handle = cli.open_stream("GET", "/hello");
  15403. std::string result;
  15404. char buf[4];
  15405. ssize_t n;
  15406. while ((n = handle.read(buf, sizeof(buf))) > 0)
  15407. result.append(buf, static_cast<size_t>(n));
  15408. EXPECT_EQ("Hello World!", result);
  15409. }
  15410. TEST_F(OpenStreamTest, DefaultHeaders) {
  15411. Client cli("127.0.0.1", port_);
  15412. // open_stream GET should include Host, User-Agent and Accept-Encoding
  15413. {
  15414. auto handle = cli.open_stream("GET", "/echo-headers");
  15415. ASSERT_TRUE(handle.is_valid());
  15416. auto body = read_all(handle);
  15417. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  15418. std::string::npos);
  15419. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  15420. std::string::npos);
  15421. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  15422. }
  15423. // open_stream POST with body and no explicit content_type should NOT add
  15424. // text/plain Content-Type (behavior differs from non-streaming path), but
  15425. // should include Content-Length
  15426. {
  15427. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  15428. ASSERT_TRUE(handle.is_valid());
  15429. auto body = read_all(handle);
  15430. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  15431. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  15432. }
  15433. // open_stream POST with explicit Content-Type should preserve it
  15434. {
  15435. auto handle = cli.open_stream("POST", "/echo-headers", {},
  15436. {{"Content-Type", "application/custom"}},
  15437. "{}", "application/custom");
  15438. ASSERT_TRUE(handle.is_valid());
  15439. auto body = read_all(handle);
  15440. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  15441. }
  15442. // User-specified User-Agent must not be overwritten for stream API
  15443. {
  15444. auto handle = cli.open_stream("GET", "/echo-headers", {},
  15445. {{"User-Agent", "MyAgent/1.2"}});
  15446. ASSERT_TRUE(handle.is_valid());
  15447. auto body = read_all(handle);
  15448. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  15449. }
  15450. }
  15451. TEST_F(OpenStreamTest, Large) {
  15452. Client cli("127.0.0.1", port_);
  15453. auto handle = cli.open_stream("GET", "/large");
  15454. EXPECT_EQ(10000u, read_all(handle).size());
  15455. }
  15456. TEST_F(OpenStreamTest, ConnectionError) {
  15457. Client cli("127.0.0.1", 9999);
  15458. auto handle = cli.open_stream("GET", "/hello");
  15459. EXPECT_FALSE(handle.is_valid());
  15460. }
  15461. TEST_F(OpenStreamTest, Chunked) {
  15462. Client cli("127.0.0.1", port_);
  15463. auto handle = cli.open_stream("GET", "/chunked");
  15464. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15465. "Transfer-Encoding") == "chunked");
  15466. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  15467. }
  15468. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  15469. Client cli("127.0.0.1", port_);
  15470. auto handle =
  15471. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  15472. ASSERT_TRUE(handle.is_valid());
  15473. // Consume body to allow trailers to be received/parsed
  15474. auto body = read_all(handle);
  15475. // Explicitly parse trailers (ensure trailers are available for assertion)
  15476. handle.parse_trailers_if_needed();
  15477. EXPECT_EQ(std::string("123456789"), body);
  15478. // The response should include a Trailer header declaring both names
  15479. ASSERT_TRUE(handle.response);
  15480. EXPECT_TRUE(handle.response->has_header("Trailer"));
  15481. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  15482. handle.response->get_header_value("Trailer"));
  15483. // Prohibited trailer must not be present
  15484. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  15485. // Allowed trailer should be present
  15486. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  15487. EXPECT_EQ(std::string("yes"),
  15488. handle.response->get_trailer_value("X-Allowed"));
  15489. // Verify trailers are NOT present as regular headers
  15490. EXPECT_EQ(std::string(""),
  15491. handle.response->get_header_value("Content-Length"));
  15492. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  15493. }
  15494. static std::thread serve_single_response(std::promise<int> &port_promise,
  15495. const std::string &response) {
  15496. return std::thread([&port_promise, response] {
  15497. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15498. default_socket_options(srv);
  15499. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  15500. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  15501. sockaddr_in addr{};
  15502. addr.sin_family = AF_INET;
  15503. addr.sin_port = htons(0); // Let OS assign a free port
  15504. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15505. int opt = 1;
  15506. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  15507. #ifdef _WIN32
  15508. reinterpret_cast<const char *>(&opt),
  15509. #else
  15510. &opt,
  15511. #endif
  15512. sizeof(opt));
  15513. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  15514. ::listen(srv, 1) != 0) {
  15515. port_promise.set_value(-1);
  15516. detail::close_socket(srv);
  15517. return;
  15518. }
  15519. socklen_t addr_len = sizeof(addr);
  15520. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  15521. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  15522. sockaddr_in cli_addr{};
  15523. socklen_t cli_len = sizeof(cli_addr);
  15524. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15525. if (cli != INVALID_SOCKET) {
  15526. // Read the complete HTTP request (until the blank line that terminates
  15527. // headers) before sending the response. If the server closes the socket
  15528. // while the client's request data is still unread in the kernel receive
  15529. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  15530. // connection on both sides: it discards the client's receive buffer
  15531. // (which already holds our response) and causes any in-progress write on
  15532. // the client to fail with ECONNRESET. Reading all request data first
  15533. // ensures close() emits a graceful FIN.
  15534. {
  15535. char rbuf[256];
  15536. std::string req;
  15537. while (req.find("\r\n\r\n") == std::string::npos) {
  15538. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  15539. if (n <= 0) { break; }
  15540. req.append(rbuf, static_cast<size_t>(n));
  15541. }
  15542. }
  15543. ::send(cli,
  15544. #ifdef _WIN32
  15545. static_cast<const char *>(response.c_str()),
  15546. static_cast<int>(response.size()),
  15547. #else
  15548. response.c_str(), response.size(),
  15549. #endif
  15550. 0);
  15551. detail::close_socket(cli);
  15552. }
  15553. detail::close_socket(srv);
  15554. });
  15555. }
  15556. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  15557. #ifndef _WIN32
  15558. signal(SIGPIPE, SIG_IGN);
  15559. #endif
  15560. std::promise<int> port_promise;
  15561. auto port_future = port_promise.get_future();
  15562. auto server_thread =
  15563. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  15564. "Content-Type: text/plain\r\n"
  15565. "Content-Length: not-a-number\r\n"
  15566. "Connection: close\r\n"
  15567. "\r\n"
  15568. "hello");
  15569. auto port = port_future.get();
  15570. ASSERT_GT(port, 0);
  15571. Client cli("127.0.0.1", port);
  15572. auto handle = cli.open_stream("GET", "/");
  15573. EXPECT_FALSE(handle.is_valid());
  15574. server_thread.join();
  15575. }
  15576. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  15577. #ifndef _WIN32
  15578. signal(SIGPIPE, SIG_IGN);
  15579. #endif
  15580. std::promise<int> port_promise;
  15581. auto port_future = port_promise.get_future();
  15582. auto server_thread = serve_single_response(
  15583. port_promise, "HTTP/1.1 200 OK\r\n"
  15584. "Content-Type: text/plain\r\n"
  15585. "Content-Length: 99999999999999999999999999\r\n"
  15586. "Connection: close\r\n"
  15587. "\r\n"
  15588. "hello");
  15589. auto port = port_future.get();
  15590. ASSERT_GT(port, 0);
  15591. // Historically std::stoull would throw std::out_of_range here and crash
  15592. // the process, then parsing silently clamped to a bogus framing length and
  15593. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  15594. // so the stream fails to open, matching the not-a-number case above. The
  15595. // process still must NOT terminate.
  15596. Client cli("127.0.0.1", port);
  15597. auto handle = cli.open_stream("GET", "/");
  15598. EXPECT_FALSE(handle.is_valid());
  15599. server_thread.join();
  15600. }
  15601. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15602. TEST_F(OpenStreamTest, Gzip) {
  15603. Client cli("127.0.0.1", port_);
  15604. auto handle = cli.open_stream("GET", "/compressible", {},
  15605. {{"Accept-Encoding", "gzip"}});
  15606. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  15607. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15608. }
  15609. #endif
  15610. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15611. TEST_F(OpenStreamTest, Brotli) {
  15612. Client cli("127.0.0.1", port_);
  15613. auto handle =
  15614. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  15615. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  15616. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15617. }
  15618. #endif
  15619. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15620. TEST_F(OpenStreamTest, Zstd) {
  15621. Client cli("127.0.0.1", port_);
  15622. auto handle = cli.open_stream("GET", "/compressible", {},
  15623. {{"Accept-Encoding", "zstd"}});
  15624. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  15625. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15626. }
  15627. #endif
  15628. #ifdef CPPHTTPLIB_SSL_ENABLED
  15629. class SSLOpenStreamTest : public ::testing::Test {
  15630. protected:
  15631. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  15632. void SetUp() override {
  15633. svr_.Get("/hello", [](const Request &, Response &res) {
  15634. res.set_content("Hello SSL World!", "text/plain");
  15635. });
  15636. svr_.Get("/chunked", [](const Request &, Response &res) {
  15637. res.set_chunked_content_provider("text/plain",
  15638. [](size_t offset, DataSink &sink) {
  15639. if (offset < 15) {
  15640. sink.write("chunk", 5);
  15641. return true;
  15642. }
  15643. sink.done();
  15644. return true;
  15645. });
  15646. });
  15647. svr_.Post("/echo", [](const Request &req, Response &res) {
  15648. res.set_content(req.body, req.get_header_value("Content-Type"));
  15649. });
  15650. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  15651. std::string body = req.body;
  15652. res.set_chunked_content_provider(
  15653. "text/plain", [body](size_t offset, DataSink &sink) {
  15654. if (offset < body.size()) {
  15655. sink.write(body.data() + offset, body.size() - offset);
  15656. }
  15657. sink.done();
  15658. return true;
  15659. });
  15660. });
  15661. port_ = svr_.bind_to_any_port("127.0.0.1");
  15662. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15663. svr_.wait_until_ready();
  15664. }
  15665. void TearDown() override {
  15666. svr_.stop();
  15667. if (thread_.joinable()) thread_.join();
  15668. }
  15669. SSLServer svr_;
  15670. std::thread thread_;
  15671. int port_ = 0;
  15672. };
  15673. TEST_F(SSLOpenStreamTest, Basic) {
  15674. SSLClient cli("127.0.0.1", port_);
  15675. cli.enable_server_certificate_verification(false);
  15676. auto handle = cli.open_stream("GET", "/hello");
  15677. ASSERT_TRUE(handle.is_valid());
  15678. EXPECT_EQ("Hello SSL World!", read_all(handle));
  15679. }
  15680. TEST_F(SSLOpenStreamTest, Chunked) {
  15681. SSLClient cli("127.0.0.1", port_);
  15682. cli.enable_server_certificate_verification(false);
  15683. auto handle = cli.open_stream("GET", "/chunked");
  15684. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15685. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15686. "Transfer-Encoding") == "chunked");
  15687. auto body = read_all(handle);
  15688. EXPECT_EQ("chunkchunkchunk", body);
  15689. }
  15690. TEST_F(SSLOpenStreamTest, Post) {
  15691. SSLClient cli("127.0.0.1", port_);
  15692. cli.enable_server_certificate_verification(false);
  15693. auto handle =
  15694. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  15695. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15696. EXPECT_EQ(200, handle.response->status);
  15697. auto body = read_all(handle);
  15698. EXPECT_EQ("Hello SSL POST", body);
  15699. }
  15700. TEST_F(SSLOpenStreamTest, PostChunked) {
  15701. SSLClient cli("127.0.0.1", port_);
  15702. cli.enable_server_certificate_verification(false);
  15703. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  15704. "Chunked SSL Data", "text/plain");
  15705. ASSERT_TRUE(handle.is_valid());
  15706. EXPECT_EQ(200, handle.response->status);
  15707. auto body = read_all(handle);
  15708. EXPECT_EQ("Chunked SSL Data", body);
  15709. }
  15710. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  15711. // Content-Length is terminated by the server closing the connection. When the
  15712. // SSL peer sends a close_notify after the body, the client must treat it as a
  15713. // clean EOF and return a successful response rather than an error.
  15714. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  15715. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15716. ASSERT_TRUE(svr.is_valid());
  15717. svr.set_keep_alive_max_count(1);
  15718. const std::string expected_body = "Hello from connection-close response!";
  15719. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  15720. res.set_content_provider("text/plain",
  15721. [&](size_t offset, DataSink &sink) -> bool {
  15722. if (offset < expected_body.size()) {
  15723. sink.write(expected_body.data() + offset,
  15724. expected_body.size() - offset);
  15725. }
  15726. sink.done();
  15727. return true;
  15728. });
  15729. });
  15730. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  15731. auto se = detail::scope_exit([&] {
  15732. svr.stop();
  15733. listen_thread.join();
  15734. ASSERT_FALSE(svr.is_running());
  15735. });
  15736. svr.wait_until_ready();
  15737. SSLClient cli(HOST, PORT);
  15738. cli.enable_server_certificate_verification(false);
  15739. auto res = cli.Get("/no-content-length");
  15740. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  15741. EXPECT_EQ(StatusCode::OK_200, res->status);
  15742. EXPECT_EQ(expected_body, res->body);
  15743. }
  15744. #endif // CPPHTTPLIB_SSL_ENABLED
  15745. //==============================================================================
  15746. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  15747. // results for various scenarios.
  15748. //==============================================================================
  15749. TEST(ParityTest, GetVsOpenStream) {
  15750. Server svr;
  15751. const std::string path = "/parity";
  15752. const std::string content = "Parity test content: hello world";
  15753. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15754. res.set_content(content, "text/plain");
  15755. });
  15756. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15757. auto se = detail::scope_exit([&] {
  15758. svr.stop();
  15759. t.join();
  15760. ASSERT_FALSE(svr.is_running());
  15761. });
  15762. svr.wait_until_ready();
  15763. Client cli(HOST, PORT);
  15764. // Non-stream path
  15765. auto r1 = cli.Get(path);
  15766. ASSERT_TRUE(r1);
  15767. EXPECT_EQ(StatusCode::OK_200, r1->status);
  15768. // Stream path
  15769. auto h = cli.open_stream("GET", path);
  15770. ASSERT_TRUE(h.is_valid());
  15771. EXPECT_EQ(r1->body, read_all(h));
  15772. }
  15773. // Helper to compress data with provided compressor type T
  15774. template <typename Compressor>
  15775. static std::string compress_payload_for_parity(const std::string &in) {
  15776. std::string out;
  15777. Compressor compressor;
  15778. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  15779. [&](const char *data, size_t n) {
  15780. out.append(data, n);
  15781. return true;
  15782. });
  15783. EXPECT_TRUE(ok);
  15784. return out;
  15785. }
  15786. // Helper function for compression parity tests
  15787. template <typename Compressor>
  15788. static void test_compression_parity(const std::string &original,
  15789. const std::string &path,
  15790. const std::string &encoding) {
  15791. const std::string compressed =
  15792. compress_payload_for_parity<Compressor>(original);
  15793. Server svr;
  15794. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15795. res.set_content(compressed, "application/octet-stream");
  15796. res.set_header("Content-Encoding", encoding);
  15797. });
  15798. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  15799. auto se = detail::scope_exit([&] {
  15800. svr.stop();
  15801. t.join();
  15802. ASSERT_FALSE(svr.is_running());
  15803. });
  15804. svr.wait_until_ready();
  15805. Client cli(HOST, PORT);
  15806. // Non-streaming
  15807. {
  15808. auto res = cli.Get(path);
  15809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15810. EXPECT_EQ(StatusCode::OK_200, res->status);
  15811. EXPECT_EQ(original, res->body);
  15812. }
  15813. // Streaming
  15814. {
  15815. auto h = cli.open_stream("GET", path);
  15816. ASSERT_TRUE(h.is_valid());
  15817. EXPECT_EQ(original, read_all(h));
  15818. }
  15819. }
  15820. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15821. TEST(ParityTest, Gzip) {
  15822. test_compression_parity<detail::gzip_compressor>(
  15823. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  15824. }
  15825. #endif
  15826. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15827. TEST(ParityTest, Brotli) {
  15828. test_compression_parity<detail::brotli_compressor>(
  15829. "Hello, brotli parity test payload", "/parity-br", "br");
  15830. }
  15831. #endif
  15832. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15833. TEST(ParityTest, Zstd) {
  15834. test_compression_parity<detail::zstd_compressor>(
  15835. "Zstandard parity test payload", "/parity-zstd", "zstd");
  15836. }
  15837. #endif
  15838. //==============================================================================
  15839. // New Stream API Tests
  15840. //==============================================================================
  15841. inline std::string read_body(httplib::stream::Result &result) {
  15842. std::string body;
  15843. while (result.next()) {
  15844. body.append(result.data(), result.size());
  15845. }
  15846. return body;
  15847. }
  15848. TEST(ClientConnectionTest, Basic) {
  15849. httplib::ClientConnection conn;
  15850. EXPECT_FALSE(conn.is_open());
  15851. conn.sock = 1;
  15852. EXPECT_TRUE(conn.is_open());
  15853. httplib::ClientConnection conn2(std::move(conn));
  15854. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  15855. conn2.sock = INVALID_SOCKET;
  15856. }
  15857. // Unified test server for all stream::* tests
  15858. class StreamApiTest : public ::testing::Test {
  15859. protected:
  15860. void SetUp() override {
  15861. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15862. res.set_content("Hello World!", "text/plain");
  15863. });
  15864. svr_.Get("/echo-params",
  15865. [](const httplib::Request &req, httplib::Response &res) {
  15866. std::string r;
  15867. for (const auto &p : req.params) {
  15868. if (!r.empty()) r += "&";
  15869. r += p.first + "=" + p.second;
  15870. }
  15871. res.set_content(r, "text/plain");
  15872. });
  15873. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15874. res.set_content(req.body, req.get_header_value("Content-Type"));
  15875. });
  15876. svr_.Post("/echo-headers",
  15877. [](const httplib::Request &req, httplib::Response &res) {
  15878. std::string r;
  15879. for (const auto &h : req.headers)
  15880. r += h.first + ": " + h.second + "\n";
  15881. res.set_content(r, "text/plain");
  15882. });
  15883. svr_.Post("/echo-params",
  15884. [](const httplib::Request &req, httplib::Response &res) {
  15885. std::string r = "params:";
  15886. for (const auto &p : req.params)
  15887. r += p.first + "=" + p.second + ";";
  15888. res.set_content(r + " body:" + req.body, "text/plain");
  15889. });
  15890. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  15891. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  15892. });
  15893. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15894. res.set_content("PUT:" + req.body, "text/plain");
  15895. });
  15896. svr_.Patch("/echo",
  15897. [](const httplib::Request &req, httplib::Response &res) {
  15898. res.set_content("PATCH:" + req.body, "text/plain");
  15899. });
  15900. svr_.Delete(
  15901. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  15902. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  15903. "text/plain");
  15904. });
  15905. svr_.Get("/head-test",
  15906. [](const httplib::Request &, httplib::Response &res) {
  15907. res.set_content("body for HEAD", "text/plain");
  15908. });
  15909. svr_.Options("/options",
  15910. [](const httplib::Request &, httplib::Response &res) {
  15911. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  15912. });
  15913. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  15914. svr_.wait_until_ready();
  15915. }
  15916. void TearDown() override {
  15917. svr_.stop();
  15918. if (thread_.joinable()) thread_.join();
  15919. }
  15920. httplib::Server svr_;
  15921. std::thread thread_;
  15922. };
  15923. // stream::Get tests
  15924. TEST_F(StreamApiTest, GetBasic) {
  15925. httplib::Client cli(HOST, PORT);
  15926. auto result = httplib::stream::Get(cli, "/hello");
  15927. ASSERT_TRUE(result.is_valid());
  15928. EXPECT_EQ(200, result.status());
  15929. EXPECT_EQ("Hello World!", read_body(result));
  15930. }
  15931. TEST_F(StreamApiTest, GetWithParams) {
  15932. httplib::Client cli(HOST, PORT);
  15933. httplib::Params params{{"foo", "bar"}};
  15934. auto result = httplib::stream::Get(cli, "/echo-params", params);
  15935. ASSERT_TRUE(result.is_valid());
  15936. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  15937. }
  15938. TEST_F(StreamApiTest, GetConnectionError) {
  15939. httplib::Client cli(HOST, 9999);
  15940. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  15941. }
  15942. TEST_F(StreamApiTest, Get404) {
  15943. httplib::Client cli(HOST, PORT);
  15944. auto result = httplib::stream::Get(cli, "/nonexistent");
  15945. EXPECT_TRUE(result.is_valid());
  15946. EXPECT_EQ(404, result.status());
  15947. }
  15948. // stream::Post tests
  15949. TEST_F(StreamApiTest, PostBasic) {
  15950. httplib::Client cli(HOST, PORT);
  15951. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  15952. "application/json");
  15953. ASSERT_TRUE(result.is_valid());
  15954. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  15955. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  15956. }
  15957. TEST_F(StreamApiTest, PostWithHeaders) {
  15958. httplib::Client cli(HOST, PORT);
  15959. httplib::Headers headers{{"X-Custom", "value"}};
  15960. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  15961. "text/plain");
  15962. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  15963. }
  15964. TEST_F(StreamApiTest, PostWithParams) {
  15965. httplib::Client cli(HOST, PORT);
  15966. httplib::Params params{{"k", "v"}};
  15967. auto result =
  15968. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  15969. auto body = read_body(result);
  15970. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  15971. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  15972. }
  15973. TEST_F(StreamApiTest, PostLarge) {
  15974. httplib::Client cli(HOST, PORT);
  15975. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  15976. size_t total = 0;
  15977. while (result.next()) {
  15978. total += result.size();
  15979. }
  15980. EXPECT_EQ(100u * 1024u, total);
  15981. }
  15982. // stream::Put/Patch tests
  15983. TEST_F(StreamApiTest, PutAndPatch) {
  15984. httplib::Client cli(HOST, PORT);
  15985. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  15986. EXPECT_EQ("PUT:test", read_body(put));
  15987. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  15988. EXPECT_EQ("PATCH:test", read_body(patch));
  15989. }
  15990. // stream::Delete tests
  15991. TEST_F(StreamApiTest, Delete) {
  15992. httplib::Client cli(HOST, PORT);
  15993. auto del1 = httplib::stream::Delete(cli, "/resource");
  15994. EXPECT_EQ("Deleted", read_body(del1));
  15995. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  15996. EXPECT_EQ("Deleted:data", read_body(del2));
  15997. }
  15998. // stream::Head/Options tests
  15999. TEST_F(StreamApiTest, HeadAndOptions) {
  16000. httplib::Client cli(HOST, PORT);
  16001. auto head = httplib::stream::Head(cli, "/head-test");
  16002. EXPECT_TRUE(head.is_valid());
  16003. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  16004. auto opts = httplib::stream::Options(cli, "/options");
  16005. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  16006. }
  16007. // SSL stream::* tests
  16008. #ifdef CPPHTTPLIB_SSL_ENABLED
  16009. class SSLStreamApiTest : public ::testing::Test {
  16010. protected:
  16011. void SetUp() override {
  16012. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16013. res.set_content("Hello SSL!", "text/plain");
  16014. });
  16015. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16016. res.set_content(req.body, "text/plain");
  16017. });
  16018. port_ = svr_.bind_to_any_port("127.0.0.1");
  16019. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16020. svr_.wait_until_ready();
  16021. }
  16022. void TearDown() override {
  16023. svr_.stop();
  16024. if (thread_.joinable()) thread_.join();
  16025. }
  16026. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  16027. std::thread thread_;
  16028. int port_ = 0;
  16029. };
  16030. TEST_F(SSLStreamApiTest, GetAndPost) {
  16031. httplib::SSLClient cli("127.0.0.1", port_);
  16032. cli.enable_server_certificate_verification(false);
  16033. auto get = httplib::stream::Get(cli, "/hello");
  16034. EXPECT_EQ("Hello SSL!", read_body(get));
  16035. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  16036. EXPECT_EQ("test", read_body(post));
  16037. }
  16038. #endif
  16039. // Tests for Error::Timeout and Error::ConnectionClosed error types
  16040. // These errors are set in SocketStream/SSLSocketStream and propagated through
  16041. // BodyReader
  16042. TEST(ErrorHandlingTest, StreamReadTimeout) {
  16043. // Test that read timeout during streaming is detected
  16044. // Use a large content-length response where server delays mid-stream
  16045. Server svr;
  16046. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16047. // Send a large response with delay in the middle
  16048. res.set_content_provider(
  16049. 1000, // content_length
  16050. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  16051. if (offset < 100) {
  16052. // Send first 100 bytes immediately
  16053. std::string data(100, 'A');
  16054. sink.write(data.c_str(), data.size());
  16055. return true;
  16056. }
  16057. // Then delay longer than client timeout
  16058. std::this_thread::sleep_for(std::chrono::seconds(3));
  16059. std::string data(900, 'B');
  16060. sink.write(data.c_str(), data.size());
  16061. return true;
  16062. });
  16063. });
  16064. auto port = 8091;
  16065. std::thread t([&]() { svr.listen("localhost", port); });
  16066. svr.wait_until_ready();
  16067. Client cli("localhost", port);
  16068. cli.set_read_timeout(1, 0); // 1 second timeout
  16069. auto handle = cli.open_stream("GET", "/slow-stream");
  16070. ASSERT_TRUE(handle.is_valid());
  16071. char buf[256];
  16072. ssize_t total = 0;
  16073. ssize_t n;
  16074. bool got_error = false;
  16075. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16076. total += n;
  16077. }
  16078. if (n < 0) {
  16079. got_error = true;
  16080. // Should be timeout or read error
  16081. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16082. handle.get_read_error() == Error::Read)
  16083. << "Actual error: " << to_string(handle.get_read_error());
  16084. }
  16085. // Either we got an error, or we got less data than expected
  16086. EXPECT_TRUE(got_error || total < 1000)
  16087. << "Expected timeout but got all " << total << " bytes";
  16088. svr.stop();
  16089. t.join();
  16090. }
  16091. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  16092. // Test connection closed detection via BodyReader
  16093. Server svr;
  16094. std::atomic<bool> close_now{false};
  16095. svr.Get("/will-close", [&](const Request &, Response &res) {
  16096. res.set_content_provider(
  16097. 10000, // Large content_length that we won't fully send
  16098. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16099. if (offset < 100) {
  16100. std::string data(100, 'X');
  16101. sink.write(data.c_str(), data.size());
  16102. return true;
  16103. }
  16104. // Wait for signal then abort
  16105. while (!close_now) {
  16106. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16107. }
  16108. return false; // Abort - server will close connection
  16109. });
  16110. });
  16111. auto port = 8092;
  16112. std::thread t([&]() { svr.listen("localhost", port); });
  16113. svr.wait_until_ready();
  16114. Client cli("localhost", port);
  16115. auto handle = cli.open_stream("GET", "/will-close");
  16116. ASSERT_TRUE(handle.is_valid());
  16117. char buf[256];
  16118. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16119. EXPECT_GT(n, 0) << "First read should succeed";
  16120. // Signal server to close
  16121. close_now = true;
  16122. // Keep reading until error or EOF
  16123. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16124. // Keep reading
  16125. }
  16126. // Should get an error since content_length wasn't satisfied
  16127. if (n < 0) {
  16128. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16129. handle.get_read_error() == Error::Read)
  16130. << "Actual error: " << to_string(handle.get_read_error());
  16131. }
  16132. svr.stop();
  16133. t.join();
  16134. }
  16135. #ifdef CPPHTTPLIB_SSL_ENABLED
  16136. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  16137. // Test that read timeout during SSL streaming is detected
  16138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16139. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16140. res.set_content_provider(
  16141. 1000, "text/plain",
  16142. [](size_t offset, size_t /*length*/, DataSink &sink) {
  16143. if (offset < 100) {
  16144. std::string data(100, 'A');
  16145. sink.write(data.c_str(), data.size());
  16146. return true;
  16147. }
  16148. std::this_thread::sleep_for(std::chrono::seconds(3));
  16149. std::string data(900, 'B');
  16150. sink.write(data.c_str(), data.size());
  16151. return true;
  16152. });
  16153. });
  16154. auto port = 8093;
  16155. std::thread t([&]() { svr.listen("localhost", port); });
  16156. svr.wait_until_ready();
  16157. SSLClient cli("localhost", port);
  16158. cli.enable_server_certificate_verification(false);
  16159. cli.set_read_timeout(1, 0); // 1 second timeout
  16160. auto handle = cli.open_stream("GET", "/slow-stream");
  16161. ASSERT_TRUE(handle.is_valid());
  16162. char buf[256];
  16163. ssize_t total = 0;
  16164. ssize_t n;
  16165. bool got_error = false;
  16166. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16167. total += n;
  16168. }
  16169. if (n < 0) {
  16170. got_error = true;
  16171. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16172. handle.get_read_error() == Error::Read)
  16173. << "Actual error: " << to_string(handle.get_read_error());
  16174. }
  16175. EXPECT_TRUE(got_error || total < 1000)
  16176. << "Expected timeout but got all " << total << " bytes";
  16177. svr.stop();
  16178. t.join();
  16179. }
  16180. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  16181. // Test SSL connection closed detection
  16182. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16183. std::atomic<bool> close_now{false};
  16184. svr.Get("/will-close", [&](const Request &, Response &res) {
  16185. res.set_content_provider(
  16186. 10000, "text/plain",
  16187. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16188. if (offset < 100) {
  16189. std::string data(100, 'X');
  16190. sink.write(data.c_str(), data.size());
  16191. return true;
  16192. }
  16193. while (!close_now) {
  16194. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16195. }
  16196. return false;
  16197. });
  16198. });
  16199. auto port = 8094;
  16200. std::thread t([&]() { svr.listen("localhost", port); });
  16201. svr.wait_until_ready();
  16202. SSLClient cli("localhost", port);
  16203. cli.enable_server_certificate_verification(false);
  16204. auto handle = cli.open_stream("GET", "/will-close");
  16205. ASSERT_TRUE(handle.is_valid());
  16206. char buf[256];
  16207. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16208. EXPECT_GT(n, 0);
  16209. // Signal server to close
  16210. close_now = true;
  16211. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16212. // Keep reading
  16213. }
  16214. if (n < 0) {
  16215. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16216. handle.get_read_error() == Error::Read)
  16217. << "Actual error: " << to_string(handle.get_read_error());
  16218. }
  16219. svr.stop();
  16220. t.join();
  16221. }
  16222. #endif
  16223. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  16224. using namespace httplib;
  16225. // Create a test file
  16226. const char *fname = "etag_testfile.txt";
  16227. const char *content = "etag-content";
  16228. {
  16229. std::ofstream ofs(fname);
  16230. ofs << content;
  16231. ASSERT_TRUE(ofs.good());
  16232. }
  16233. Server svr;
  16234. svr.set_mount_point("/static", ".");
  16235. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16236. svr.wait_until_ready();
  16237. Client cli(HOST, PORT);
  16238. // First request: should get 200 with ETag header
  16239. auto res1 = cli.Get("/static/etag_testfile.txt");
  16240. ASSERT_TRUE(res1);
  16241. ASSERT_EQ(200, res1->status);
  16242. ASSERT_TRUE(res1->has_header("ETag"));
  16243. std::string etag = res1->get_header_value("ETag");
  16244. EXPECT_FALSE(etag.empty());
  16245. // Verify ETag format: W/"hex-hex"
  16246. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  16247. EXPECT_EQ('W', etag[0]);
  16248. EXPECT_EQ('/', etag[1]);
  16249. EXPECT_EQ('"', etag[2]);
  16250. EXPECT_EQ('"', etag.back());
  16251. // Exact match: expect 304 Not Modified
  16252. Headers h2 = {{"If-None-Match", etag}};
  16253. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  16254. ASSERT_TRUE(res2);
  16255. EXPECT_EQ(304, res2->status);
  16256. // Wildcard match: expect 304 Not Modified
  16257. Headers h3 = {{"If-None-Match", "*"}};
  16258. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  16259. ASSERT_TRUE(res3);
  16260. EXPECT_EQ(304, res3->status);
  16261. // Non-matching ETag: expect 200
  16262. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  16263. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  16264. ASSERT_TRUE(res4);
  16265. EXPECT_EQ(200, res4->status);
  16266. // Multiple ETags with one matching: expect 304
  16267. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  16268. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  16269. ASSERT_TRUE(res5);
  16270. EXPECT_EQ(304, res5->status);
  16271. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  16272. // that equivalent to the single comma-separated list above, so the match on
  16273. // the second line must still be found.
  16274. Headers h6;
  16275. h6.emplace("If-None-Match", "W/\"other\"");
  16276. h6.emplace("If-None-Match", etag);
  16277. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  16278. ASSERT_TRUE(res6);
  16279. EXPECT_EQ(304, res6->status);
  16280. svr.stop();
  16281. t.join();
  16282. std::remove(fname);
  16283. }
  16284. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  16285. using namespace httplib;
  16286. Server svr;
  16287. svr.set_mount_point("/static", ".");
  16288. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16289. svr.wait_until_ready();
  16290. Client cli(HOST, PORT);
  16291. // Send If-None-Match: * to a non-existent file
  16292. Headers h = {{"If-None-Match", "*"}};
  16293. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  16294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16295. EXPECT_EQ(404, res->status);
  16296. svr.stop();
  16297. t.join();
  16298. }
  16299. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  16300. using namespace httplib;
  16301. // Create a test file
  16302. const char *fname = "etag_boundary_testfile.txt";
  16303. const char *content = "boundary-test";
  16304. {
  16305. std::ofstream ofs(fname);
  16306. ofs << content;
  16307. ASSERT_TRUE(ofs.good());
  16308. }
  16309. Server svr;
  16310. svr.set_mount_point("/static", ".");
  16311. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16312. svr.wait_until_ready();
  16313. Client cli(HOST, PORT);
  16314. // Get the actual ETag
  16315. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  16316. ASSERT_TRUE(res1);
  16317. ASSERT_EQ(200, res1->status);
  16318. ASSERT_TRUE(res1->has_header("ETag"));
  16319. std::string etag = res1->get_header_value("ETag");
  16320. // Test 1: Very long ETag value (longer than actual ETag)
  16321. // Should NOT match and return 200 (not trigger out-of-bounds read)
  16322. Headers h1 = {{"If-None-Match", "W/"
  16323. "\"very-long-etag-value-that-is-much-longer-"
  16324. "than-the-actual-etag-value\""}};
  16325. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  16326. ASSERT_TRUE(res2);
  16327. EXPECT_EQ(200, res2->status); // Should not match
  16328. // Test 2: Long string followed by wildcard
  16329. // Should match on "*" and return 304 (without out-of-bounds read on the long
  16330. // string)
  16331. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  16332. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  16333. ASSERT_TRUE(res3);
  16334. EXPECT_EQ(304, res3->status); // Should match on "*"
  16335. // Test 3: Wildcard followed by long string
  16336. // Should match on "*" immediately and return 304
  16337. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  16338. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  16339. ASSERT_TRUE(res4);
  16340. EXPECT_EQ(304, res4->status); // Should match on "*"
  16341. // Test 4: Multiple long non-matching values
  16342. // Should NOT match and return 200 (test that all comparisons are safe)
  16343. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  16344. "W/\"second-long-non-matching-value\", "
  16345. "W/\"third-long-non-matching-value\""}};
  16346. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  16347. ASSERT_TRUE(res5);
  16348. EXPECT_EQ(200, res5->status); // Should not match
  16349. // Test 5: Single character that is not "*" (edge case)
  16350. Headers h5 = {{"If-None-Match", "X"}};
  16351. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  16352. ASSERT_TRUE(res6);
  16353. EXPECT_EQ(200, res6->status); // Should not match
  16354. svr.stop();
  16355. t.join();
  16356. std::remove(fname);
  16357. }
  16358. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  16359. using namespace httplib;
  16360. // Create a test file
  16361. const char *fname = "ims_testfile.txt";
  16362. const char *content = "if-modified-since-test";
  16363. {
  16364. std::ofstream ofs(fname);
  16365. ofs << content;
  16366. ASSERT_TRUE(ofs.good());
  16367. }
  16368. Server svr;
  16369. svr.set_mount_point("/static", ".");
  16370. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16371. svr.wait_until_ready();
  16372. Client cli(HOST, PORT);
  16373. // First request: should get 200 with Last-Modified header
  16374. auto res1 = cli.Get("/static/ims_testfile.txt");
  16375. ASSERT_TRUE(res1);
  16376. ASSERT_EQ(200, res1->status);
  16377. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16378. std::string last_modified = res1->get_header_value("Last-Modified");
  16379. EXPECT_FALSE(last_modified.empty());
  16380. // If-Modified-Since with same time: expect 304
  16381. Headers h2 = {{"If-Modified-Since", last_modified}};
  16382. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  16383. ASSERT_TRUE(res2);
  16384. EXPECT_EQ(304, res2->status);
  16385. // If-Modified-Since with future time: expect 304
  16386. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16387. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  16388. ASSERT_TRUE(res3);
  16389. EXPECT_EQ(304, res3->status);
  16390. // If-Modified-Since with past time: expect 200
  16391. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16392. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  16393. ASSERT_TRUE(res4);
  16394. EXPECT_EQ(200, res4->status);
  16395. // If-None-Match takes precedence over If-Modified-Since
  16396. // (send matching ETag with old If-Modified-Since -> should still be 304)
  16397. ASSERT_TRUE(res1->has_header("ETag"));
  16398. std::string etag = res1->get_header_value("ETag");
  16399. Headers h5 = {{"If-None-Match", etag},
  16400. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16401. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  16402. ASSERT_TRUE(res5);
  16403. EXPECT_EQ(304, res5->status);
  16404. svr.stop();
  16405. t.join();
  16406. std::remove(fname);
  16407. }
  16408. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  16409. using namespace httplib;
  16410. Server svr;
  16411. // Endpoint that returns compressible content
  16412. svr.Get("/compressible", [](const Request &, Response &res) {
  16413. // Return a large enough body to trigger compression
  16414. std::string body(1000, 'a');
  16415. res.set_content(body, "text/plain");
  16416. });
  16417. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16418. svr.wait_until_ready();
  16419. Client cli(HOST, PORT);
  16420. // Request with gzip support: should get Vary header when compressed
  16421. cli.set_compress(true);
  16422. auto res1 = cli.Get("/compressible");
  16423. ASSERT_TRUE(res1);
  16424. EXPECT_EQ(200, res1->status);
  16425. // If Content-Encoding is set, Vary should also be set
  16426. if (res1->has_header("Content-Encoding")) {
  16427. EXPECT_TRUE(res1->has_header("Vary"));
  16428. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  16429. }
  16430. // Request without Accept-Encoding header: should not have compression
  16431. Headers h_no_compress;
  16432. auto res2 = cli.Get("/compressible", h_no_compress);
  16433. ASSERT_TRUE(res2);
  16434. EXPECT_EQ(200, res2->status);
  16435. // Verify Vary header is present when compression is applied
  16436. // (the exact behavior depends on server configuration)
  16437. svr.stop();
  16438. t.join();
  16439. }
  16440. TEST(ETagTest, IfRangeWithETag) {
  16441. using namespace httplib;
  16442. // Create a test file with known content
  16443. const char *fname = "if_range_testfile.txt";
  16444. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  16445. {
  16446. std::ofstream ofs(fname);
  16447. ofs << content;
  16448. ASSERT_TRUE(ofs.good());
  16449. }
  16450. Server svr;
  16451. svr.set_mount_point("/static", ".");
  16452. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16453. svr.wait_until_ready();
  16454. Client cli(HOST, PORT);
  16455. // First request: get ETag
  16456. auto res1 = cli.Get("/static/if_range_testfile.txt");
  16457. ASSERT_TRUE(res1);
  16458. ASSERT_EQ(200, res1->status);
  16459. ASSERT_TRUE(res1->has_header("ETag"));
  16460. std::string etag = res1->get_header_value("ETag");
  16461. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  16462. // Since our server generates weak ETags (W/"..."), If-Range with our
  16463. // ETag should NOT result in partial content - it should return full content.
  16464. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  16465. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  16466. ASSERT_TRUE(res2);
  16467. // Weak ETag in If-Range -> full content (200), not partial (206)
  16468. EXPECT_EQ(200, res2->status);
  16469. EXPECT_EQ(content, res2->body);
  16470. EXPECT_FALSE(res2->has_header("Content-Range"));
  16471. // Range request with non-matching If-Range (ETag): should get 200 (full
  16472. // content)
  16473. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  16474. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  16475. ASSERT_TRUE(res3);
  16476. EXPECT_EQ(200, res3->status);
  16477. EXPECT_EQ(content, res3->body);
  16478. EXPECT_FALSE(res3->has_header("Content-Range"));
  16479. // Range request with strong ETag (hypothetical - our server doesn't generate
  16480. // strong ETags, but if client sends a strong ETag that doesn't match, it
  16481. // should return full content)
  16482. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  16483. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  16484. ASSERT_TRUE(res4);
  16485. EXPECT_EQ(200, res4->status);
  16486. EXPECT_EQ(content, res4->body);
  16487. EXPECT_FALSE(res4->has_header("Content-Range"));
  16488. svr.stop();
  16489. t.join();
  16490. std::remove(fname);
  16491. }
  16492. TEST(ETagTest, IfRangeWithDate) {
  16493. using namespace httplib;
  16494. // Create a test file
  16495. const char *fname = "if_range_date_testfile.txt";
  16496. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  16497. {
  16498. std::ofstream ofs(fname);
  16499. ofs << content;
  16500. ASSERT_TRUE(ofs.good());
  16501. }
  16502. Server svr;
  16503. svr.set_mount_point("/static", ".");
  16504. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16505. svr.wait_until_ready();
  16506. Client cli(HOST, PORT);
  16507. // First request: get Last-Modified
  16508. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  16509. ASSERT_TRUE(res1);
  16510. ASSERT_EQ(200, res1->status);
  16511. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16512. std::string last_modified = res1->get_header_value("Last-Modified");
  16513. // Range request with matching If-Range (date): should get 206
  16514. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  16515. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  16516. ASSERT_TRUE(res2);
  16517. EXPECT_EQ(206, res2->status);
  16518. EXPECT_EQ("FGHIJ", res2->body);
  16519. // Range request with old If-Range date: should get 200 (full content)
  16520. Headers h3 = {{"Range", "bytes=5-9"},
  16521. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16522. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  16523. ASSERT_TRUE(res3);
  16524. EXPECT_EQ(200, res3->status);
  16525. EXPECT_EQ(content, res3->body);
  16526. // Range request with future If-Range date: should get 206
  16527. Headers h4 = {{"Range", "bytes=0-4"},
  16528. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16529. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  16530. ASSERT_TRUE(res4);
  16531. EXPECT_EQ(206, res4->status);
  16532. EXPECT_EQ("ABCDE", res4->body);
  16533. svr.stop();
  16534. t.join();
  16535. std::remove(fname);
  16536. }
  16537. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  16538. using namespace httplib;
  16539. const char *fname = "etag_malformed.txt";
  16540. const char *content = "malformed-etag";
  16541. {
  16542. std::ofstream ofs(fname);
  16543. ofs << content;
  16544. ASSERT_TRUE(ofs.good());
  16545. }
  16546. Server svr;
  16547. svr.set_mount_point("/static", ".");
  16548. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16549. svr.wait_until_ready();
  16550. Client cli(HOST, PORT);
  16551. // baseline: should get 200 and an ETag
  16552. auto res1 = cli.Get("/static/etag_malformed.txt");
  16553. ASSERT_TRUE(res1);
  16554. ASSERT_EQ(200, res1->status);
  16555. ASSERT_TRUE(res1->has_header("ETag"));
  16556. // Malformed ETag value (missing quotes) should be treated as non-matching
  16557. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  16558. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  16559. ASSERT_TRUE(res_bad);
  16560. EXPECT_EQ(200, res_bad->status);
  16561. // Whitespace-only header value should be considered invalid / non-matching
  16562. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  16563. "Host: localhost\r\n"
  16564. "If-None-Match: \r\n"
  16565. "Connection: close\r\n"
  16566. "\r\n";
  16567. std::string out;
  16568. ASSERT_TRUE(send_request(5, raw_req, &out));
  16569. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16570. svr.stop();
  16571. t.join();
  16572. std::remove(fname);
  16573. }
  16574. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  16575. using namespace httplib;
  16576. const char *fname = "ims_invalid_format.txt";
  16577. const char *content = "ims-bad-format";
  16578. {
  16579. std::ofstream ofs(fname);
  16580. ofs << content;
  16581. ASSERT_TRUE(ofs.good());
  16582. }
  16583. Server svr;
  16584. svr.set_mount_point("/static", ".");
  16585. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16586. svr.wait_until_ready();
  16587. Client cli(HOST, PORT);
  16588. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  16589. ASSERT_TRUE(res1);
  16590. ASSERT_EQ(200, res1->status);
  16591. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16592. // If-Modified-Since with invalid format should not result in 304
  16593. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  16594. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  16595. ASSERT_TRUE(res_bad);
  16596. EXPECT_EQ(200, res_bad->status);
  16597. // If-Range with invalid date format should be treated as mismatch -> full
  16598. // content (200)
  16599. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  16600. {"If-Range", "invalid-date"}};
  16601. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  16602. ASSERT_TRUE(res_ifrange);
  16603. EXPECT_EQ(200, res_ifrange->status);
  16604. svr.stop();
  16605. t.join();
  16606. std::remove(fname);
  16607. }
  16608. TEST(ETagTest, IfRangeWithMalformedETag) {
  16609. using namespace httplib;
  16610. const char *fname = "ifrange_malformed.txt";
  16611. const std::string content = "0123456789";
  16612. {
  16613. std::ofstream ofs(fname);
  16614. ofs << content;
  16615. ASSERT_TRUE(ofs.good());
  16616. }
  16617. Server svr;
  16618. svr.set_mount_point("/static", ".");
  16619. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16620. svr.wait_until_ready();
  16621. Client cli(HOST, PORT);
  16622. // First request: get ETag
  16623. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  16624. ASSERT_TRUE(res1);
  16625. ASSERT_EQ(200, res1->status);
  16626. ASSERT_TRUE(res1->has_header("ETag"));
  16627. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  16628. // full content (200)
  16629. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  16630. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  16631. ASSERT_TRUE(res2);
  16632. EXPECT_EQ(200, res2->status);
  16633. EXPECT_EQ(content, res2->body);
  16634. svr.stop();
  16635. t.join();
  16636. std::remove(fname);
  16637. }
  16638. TEST(ETagTest, ExtremeLargeDateValues) {
  16639. using namespace httplib;
  16640. const char *fname = "ims_extreme_date.txt";
  16641. const char *content = "ims-extreme-date";
  16642. {
  16643. std::ofstream ofs(fname);
  16644. ofs << content;
  16645. ASSERT_TRUE(ofs.good());
  16646. }
  16647. Server svr;
  16648. svr.set_mount_point("/static", ".");
  16649. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16650. svr.wait_until_ready();
  16651. Client cli(HOST, PORT);
  16652. auto res1 = cli.Get(std::string("/static/") + fname);
  16653. ASSERT_TRUE(res1);
  16654. ASSERT_EQ(200, res1->status);
  16655. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16656. // Extremely large year that may overflow date parsing routines.
  16657. Headers h_large_date = {
  16658. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16659. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  16660. ASSERT_TRUE(res_bad);
  16661. // Expect server to treat this as invalid/mismatch and return full content
  16662. EXPECT_EQ(200, res_bad->status);
  16663. // If-Range with extremely large date should be treated as mismatch -> full
  16664. // content (200)
  16665. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  16666. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16667. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  16668. ASSERT_TRUE(res_ifrange);
  16669. EXPECT_EQ(200, res_ifrange->status);
  16670. svr.stop();
  16671. t.join();
  16672. std::remove(fname);
  16673. }
  16674. TEST(ETagTest, NegativeFileModificationTime) {
  16675. using namespace httplib;
  16676. const char *fname = "ims_negative_mtime.txt";
  16677. const std::string content = "negative-mtime";
  16678. {
  16679. std::ofstream ofs(fname);
  16680. ofs << content;
  16681. ASSERT_TRUE(ofs.good());
  16682. }
  16683. // Try to set file mtime to a negative value. This may fail on some
  16684. // platforms/filesystems; if it fails, the test will still verify server
  16685. // behaves safely by performing a regular conditional request.
  16686. #if defined(__APPLE__) || defined(__linux__)
  16687. bool set_negative = false;
  16688. do {
  16689. struct timeval times[2];
  16690. // access time: now
  16691. times[0].tv_sec = time(nullptr);
  16692. times[0].tv_usec = 0;
  16693. // modification time: negative (e.g., -1)
  16694. times[1].tv_sec = -1;
  16695. times[1].tv_usec = 0;
  16696. if (utimes(fname, times) == 0) { set_negative = true; }
  16697. } while (0);
  16698. #else
  16699. bool set_negative = false;
  16700. #endif
  16701. Server svr;
  16702. svr.set_mount_point("/static", ".");
  16703. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16704. svr.wait_until_ready();
  16705. Client cli(HOST, PORT);
  16706. auto res1 = cli.Get(std::string("/static/") + fname);
  16707. ASSERT_TRUE(res1);
  16708. ASSERT_EQ(200, res1->status);
  16709. bool has_last_modified = res1->has_header("Last-Modified");
  16710. std::string last_modified;
  16711. if (has_last_modified) {
  16712. last_modified = res1->get_header_value("Last-Modified");
  16713. }
  16714. if (set_negative) {
  16715. // If we successfully set a negative mtime, ensure server returns a
  16716. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  16717. // with an old date and ensure server handles it without crash.
  16718. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  16719. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  16720. ASSERT_TRUE(res2);
  16721. // Behavior may vary; at minimum ensure server responds (200 or 304).
  16722. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  16723. } else {
  16724. // Could not set negative mtime on this platform; fall back to verifying
  16725. // that normal invalid/malformed dates are treated safely (non-304).
  16726. Headers h_bad_date = {
  16727. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16728. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  16729. ASSERT_TRUE(res_bad);
  16730. EXPECT_EQ(200, res_bad->status);
  16731. }
  16732. svr.stop();
  16733. t.join();
  16734. std::remove(fname);
  16735. }
  16736. //==============================================================================
  16737. // SSE Parsing Tests
  16738. //==============================================================================
  16739. class SSEParsingTest : public ::testing::Test {
  16740. protected:
  16741. // Test helper that mimics SSE parsing behavior
  16742. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  16743. int &retry_ms) {
  16744. // Blank line signals end of event
  16745. if (line.empty() || line == "\r") { return true; }
  16746. // Lines starting with ':' are comments (ignored)
  16747. if (!line.empty() && line[0] == ':') { return false; }
  16748. // Find the colon separator
  16749. auto colon_pos = line.find(':');
  16750. if (colon_pos == std::string::npos) {
  16751. // Line with no colon is treated as field name with empty value
  16752. return false;
  16753. }
  16754. std::string field = line.substr(0, colon_pos);
  16755. std::string value;
  16756. // Value starts after colon, skip optional single space
  16757. if (colon_pos + 1 < line.size()) {
  16758. size_t value_start = colon_pos + 1;
  16759. if (line[value_start] == ' ') { value_start++; }
  16760. value = line.substr(value_start);
  16761. // Remove trailing \r if present
  16762. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  16763. }
  16764. // Handle known fields
  16765. if (field == "event") {
  16766. msg.event = value;
  16767. } else if (field == "data") {
  16768. // Multiple data lines are concatenated with newlines
  16769. if (!msg.data.empty()) { msg.data += "\n"; }
  16770. msg.data += value;
  16771. } else if (field == "id") {
  16772. // Empty id is valid (clears the last event ID)
  16773. msg.id = value;
  16774. } else if (field == "retry") {
  16775. // Parse retry interval in milliseconds
  16776. {
  16777. int v = 0;
  16778. auto res =
  16779. detail::from_chars(value.data(), value.data() + value.size(), v);
  16780. if (res.ec == std::errc{}) { retry_ms = v; }
  16781. }
  16782. }
  16783. // Unknown fields are ignored per SSE spec
  16784. return false;
  16785. }
  16786. };
  16787. // Test: Single-line data
  16788. TEST_F(SSEParsingTest, SingleLineData) {
  16789. sse::SSEMessage msg;
  16790. int retry_ms = 3000;
  16791. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  16792. EXPECT_EQ(msg.data, "hello");
  16793. EXPECT_EQ(msg.event, "message");
  16794. // Blank line ends event
  16795. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16796. }
  16797. // Test: Multi-line data
  16798. TEST_F(SSEParsingTest, MultiLineData) {
  16799. sse::SSEMessage msg;
  16800. int retry_ms = 3000;
  16801. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  16802. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  16803. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  16804. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  16805. }
  16806. // Test: Custom event types
  16807. TEST_F(SSEParsingTest, CustomEventType) {
  16808. sse::SSEMessage msg;
  16809. int retry_ms = 3000;
  16810. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  16811. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  16812. EXPECT_EQ(msg.event, "update");
  16813. EXPECT_EQ(msg.data, "payload");
  16814. }
  16815. // Test: Event ID handling
  16816. TEST_F(SSEParsingTest, EventIdHandling) {
  16817. sse::SSEMessage msg;
  16818. int retry_ms = 3000;
  16819. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  16820. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  16821. EXPECT_EQ(msg.id, "12345");
  16822. }
  16823. // Test: Empty event ID (clears last event ID)
  16824. TEST_F(SSEParsingTest, EmptyEventId) {
  16825. sse::SSEMessage msg;
  16826. msg.id = "previous";
  16827. int retry_ms = 3000;
  16828. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  16829. EXPECT_EQ(msg.id, "");
  16830. }
  16831. // Test: Retry field parsing
  16832. TEST_F(SSEParsingTest, RetryFieldParsing) {
  16833. sse::SSEMessage msg;
  16834. int retry_ms = 3000;
  16835. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  16836. EXPECT_EQ(retry_ms, 5000);
  16837. }
  16838. // Test: Invalid retry value
  16839. TEST_F(SSEParsingTest, InvalidRetryValue) {
  16840. sse::SSEMessage msg;
  16841. int retry_ms = 3000;
  16842. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  16843. EXPECT_EQ(retry_ms, 3000); // Unchanged
  16844. }
  16845. // Test: Comments (lines starting with :)
  16846. TEST_F(SSEParsingTest, CommentsIgnored) {
  16847. sse::SSEMessage msg;
  16848. int retry_ms = 3000;
  16849. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  16850. EXPECT_EQ(msg.data, "");
  16851. EXPECT_EQ(msg.event, "message");
  16852. }
  16853. // Test: Colon in value
  16854. TEST_F(SSEParsingTest, ColonInValue) {
  16855. sse::SSEMessage msg;
  16856. int retry_ms = 3000;
  16857. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  16858. EXPECT_EQ(msg.data, "hello:world:test");
  16859. }
  16860. // Test: Line with no colon (field name only)
  16861. TEST_F(SSEParsingTest, FieldNameOnly) {
  16862. sse::SSEMessage msg;
  16863. int retry_ms = 3000;
  16864. // According to SSE spec, this is treated as field name with empty value
  16865. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  16866. // Since we don't recognize "data" without colon, data should be empty
  16867. EXPECT_EQ(msg.data, "");
  16868. }
  16869. // Test: Trailing \r handling
  16870. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  16871. sse::SSEMessage msg;
  16872. int retry_ms = 3000;
  16873. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  16874. EXPECT_EQ(msg.data, "hello");
  16875. }
  16876. // Test: Unknown fields ignored
  16877. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  16878. sse::SSEMessage msg;
  16879. int retry_ms = 3000;
  16880. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  16881. EXPECT_EQ(msg.data, "");
  16882. EXPECT_EQ(msg.event, "message");
  16883. }
  16884. // Test: Space after colon is optional
  16885. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  16886. sse::SSEMessage msg1, msg2;
  16887. int retry_ms = 3000;
  16888. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  16889. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  16890. EXPECT_EQ(msg1.data, "hello");
  16891. EXPECT_EQ(msg2.data, "hello");
  16892. }
  16893. // Test: SSEMessage clear
  16894. TEST_F(SSEParsingTest, MessageClear) {
  16895. sse::SSEMessage msg;
  16896. msg.event = "custom";
  16897. msg.data = "some data";
  16898. msg.id = "123";
  16899. msg.clear();
  16900. EXPECT_EQ(msg.event, "message");
  16901. EXPECT_EQ(msg.data, "");
  16902. EXPECT_EQ(msg.id, "");
  16903. }
  16904. // Test: Complete event parsing
  16905. TEST_F(SSEParsingTest, CompleteEventParsing) {
  16906. sse::SSEMessage msg;
  16907. int retry_ms = 3000;
  16908. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  16909. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  16910. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  16911. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  16912. // Blank line ends event
  16913. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16914. EXPECT_EQ(msg.event, "notification");
  16915. EXPECT_EQ(msg.id, "evt-42");
  16916. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  16917. EXPECT_EQ(retry_ms, 1000);
  16918. }
  16919. //==============================================================================
  16920. // Integration Tests with Server
  16921. //==============================================================================
  16922. class SSEIntegrationTest : public ::testing::Test {
  16923. protected:
  16924. void SetUp() override {
  16925. stop_server_.store(false);
  16926. events_.clear();
  16927. server_ = httplib::detail::make_unique<Server>();
  16928. setup_server();
  16929. start_server();
  16930. }
  16931. void TearDown() override {
  16932. stop_server_.store(true);
  16933. event_cv_.notify_all();
  16934. server_->stop();
  16935. if (server_thread_.joinable()) { server_thread_.join(); }
  16936. }
  16937. void setup_server() {
  16938. // Simple SSE endpoint
  16939. server_->Get("/events", [this](const Request &req, Response &res) {
  16940. auto last_id = req.get_header_value("Last-Event-ID");
  16941. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  16942. res.set_chunked_content_provider(
  16943. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  16944. std::unique_lock<std::mutex> lock(event_mutex_);
  16945. if (event_cv_.wait_for(
  16946. lock, std::chrono::milliseconds(200), [this] {
  16947. return !events_.empty() || stop_server_.load();
  16948. })) {
  16949. if (stop_server_.load()) { return false; }
  16950. if (!events_.empty()) {
  16951. std::string event = events_.front();
  16952. events_.erase(events_.begin());
  16953. sink.write(event.data(), event.size());
  16954. return true;
  16955. }
  16956. }
  16957. return !stop_server_.load();
  16958. });
  16959. });
  16960. // Endpoint that returns error
  16961. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  16962. res.status = 500;
  16963. res.set_content("Internal Server Error", "text/plain");
  16964. });
  16965. // Endpoint for custom event types
  16966. server_->Get("/custom-events", [](const Request &, Response &res) {
  16967. res.set_chunked_content_provider(
  16968. "text/event-stream", [](size_t offset, DataSink &sink) {
  16969. if (offset == 0) {
  16970. std::string event = "event: update\ndata: updated\n\n"
  16971. "event: delete\ndata: deleted\n\n";
  16972. sink.write(event.data(), event.size());
  16973. }
  16974. return false; // End stream after sending
  16975. });
  16976. });
  16977. }
  16978. void start_server() {
  16979. port_ = server_->bind_to_any_port(HOST);
  16980. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16981. // Wait for server to start
  16982. while (!server_->is_running()) {
  16983. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16984. }
  16985. }
  16986. int get_port() const { return port_; }
  16987. void send_event(const std::string &event) {
  16988. std::lock_guard<std::mutex> lock(event_mutex_);
  16989. events_.push_back(event);
  16990. event_cv_.notify_all();
  16991. }
  16992. std::unique_ptr<Server> server_;
  16993. std::thread server_thread_;
  16994. std::mutex event_mutex_;
  16995. std::condition_variable event_cv_;
  16996. std::vector<std::string> events_;
  16997. std::atomic<bool> stop_server_{false};
  16998. std::string last_received_event_id_;
  16999. int port_ = 0;
  17000. };
  17001. // Test: Successful connection and on_open callback
  17002. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  17003. // Add a simple endpoint that sends one event and closes
  17004. server_->Get("/simple-event", [](const Request &, Response &res) {
  17005. res.set_chunked_content_provider(
  17006. "text/event-stream", [](size_t offset, DataSink &sink) {
  17007. if (offset == 0) {
  17008. std::string event = "data: hello\n\n";
  17009. sink.write(event.data(), event.size());
  17010. }
  17011. return false; // Close stream after sending
  17012. });
  17013. });
  17014. Client client("localhost", get_port());
  17015. sse::SSEClient sse(client, "/simple-event");
  17016. std::atomic<bool> open_called{false};
  17017. std::atomic<bool> message_received{false};
  17018. sse.on_open([&open_called]() { open_called.store(true); });
  17019. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  17020. if (msg.data == "hello") { message_received.store(true); }
  17021. });
  17022. sse.set_reconnect_interval(100);
  17023. sse.set_max_reconnect_attempts(1);
  17024. // Start async
  17025. sse.start_async();
  17026. // Wait for message to be processed
  17027. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17028. sse.stop();
  17029. EXPECT_TRUE(open_called.load());
  17030. EXPECT_TRUE(message_received.load());
  17031. }
  17032. // Test: on_message callback
  17033. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  17034. // Endpoint that sends multiple events then closes
  17035. server_->Get("/multi-event", [](const Request &, Response &res) {
  17036. res.set_chunked_content_provider(
  17037. "text/event-stream", [](size_t offset, DataSink &sink) {
  17038. if (offset == 0) {
  17039. std::string events = "data: message1\n\ndata: message2\n\n";
  17040. sink.write(events.data(), events.size());
  17041. }
  17042. return false;
  17043. });
  17044. });
  17045. Client client("localhost", get_port());
  17046. sse::SSEClient sse(client, "/multi-event");
  17047. std::vector<std::string> received_messages;
  17048. std::mutex messages_mutex;
  17049. sse.on_message([&](const sse::SSEMessage &msg) {
  17050. std::lock_guard<std::mutex> lock(messages_mutex);
  17051. received_messages.push_back(msg.data);
  17052. });
  17053. sse.set_reconnect_interval(100);
  17054. sse.set_max_reconnect_attempts(1);
  17055. sse.start_async();
  17056. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17057. sse.stop();
  17058. std::lock_guard<std::mutex> lock(messages_mutex);
  17059. EXPECT_GE(received_messages.size(), 2u);
  17060. if (received_messages.size() >= 2) {
  17061. EXPECT_EQ(received_messages[0], "message1");
  17062. EXPECT_EQ(received_messages[1], "message2");
  17063. }
  17064. }
  17065. // Test: on_event for specific types
  17066. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  17067. Client client("localhost", get_port());
  17068. sse::SSEClient sse(client, "/custom-events");
  17069. std::atomic<bool> update_received{false};
  17070. std::atomic<bool> delete_received{false};
  17071. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  17072. if (msg.data == "updated") { update_received.store(true); }
  17073. });
  17074. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  17075. if (msg.data == "deleted") { delete_received.store(true); }
  17076. });
  17077. sse.set_max_reconnect_attempts(1);
  17078. sse.start_async();
  17079. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  17080. sse.stop();
  17081. EXPECT_TRUE(update_received.load());
  17082. EXPECT_TRUE(delete_received.load());
  17083. }
  17084. // Test: on_error callback on connection failure
  17085. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  17086. // Connect to a non-existent port
  17087. Client client("localhost", 59999);
  17088. sse::SSEClient sse(client, "/events");
  17089. std::atomic<bool> error_called{false};
  17090. Error received_error = Error::Success;
  17091. sse.on_error([&](Error err) {
  17092. error_called.store(true);
  17093. received_error = err;
  17094. });
  17095. sse.set_reconnect_interval(50);
  17096. sse.set_max_reconnect_attempts(1);
  17097. sse.start_async();
  17098. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17099. sse.stop();
  17100. EXPECT_TRUE(error_called.load());
  17101. EXPECT_NE(received_error, Error::Success);
  17102. }
  17103. // Test: Last-Event-ID header sent on reconnect
  17104. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  17105. // Endpoint that sends event with ID
  17106. server_->Get("/event-with-id", [](const Request &, Response &res) {
  17107. res.set_chunked_content_provider(
  17108. "text/event-stream", [](size_t offset, DataSink &sink) {
  17109. if (offset == 0) {
  17110. std::string event = "id: evt-123\ndata: test\n\n";
  17111. sink.write(event.data(), event.size());
  17112. }
  17113. return false;
  17114. });
  17115. });
  17116. Client client("localhost", get_port());
  17117. sse::SSEClient sse(client, "/event-with-id");
  17118. std::atomic<bool> id_received{false};
  17119. sse.on_message([&](const sse::SSEMessage &msg) {
  17120. if (!msg.id.empty()) { id_received.store(true); }
  17121. });
  17122. sse.set_reconnect_interval(100);
  17123. sse.set_max_reconnect_attempts(1);
  17124. sse.start_async();
  17125. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17126. sse.stop();
  17127. EXPECT_TRUE(id_received.load());
  17128. EXPECT_EQ(sse.last_event_id(), "evt-123");
  17129. }
  17130. // Test: Manual stop
  17131. TEST_F(SSEIntegrationTest, ManualStop) {
  17132. // Endpoint that sends one event and stays open briefly
  17133. std::atomic<bool> handler_running{true};
  17134. server_->Get("/stay-open", [&handler_running](const Request &,
  17135. Response &res) {
  17136. res.set_chunked_content_provider(
  17137. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  17138. if (offset == 0) {
  17139. std::string event = "data: connected\n\n";
  17140. sink.write(event.data(), event.size());
  17141. }
  17142. // Keep connection open while handler_running is true
  17143. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  17144. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17145. }
  17146. return false;
  17147. });
  17148. });
  17149. Client client("localhost", get_port());
  17150. sse::SSEClient sse(client, "/stay-open");
  17151. std::atomic<bool> connected{false};
  17152. sse.on_open([&connected]() { connected.store(true); });
  17153. sse.set_reconnect_interval(100);
  17154. sse.set_max_reconnect_attempts(1);
  17155. sse.start_async();
  17156. // Wait for connection to establish
  17157. for (int i = 0; i < 20 && !connected.load(); ++i) {
  17158. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17159. }
  17160. EXPECT_TRUE(connected.load());
  17161. EXPECT_TRUE(sse.is_connected());
  17162. // Signal handler to stop
  17163. handler_running.store(false);
  17164. // Stop SSE client
  17165. sse.stop();
  17166. EXPECT_FALSE(sse.is_connected());
  17167. }
  17168. // Test: SSEClient with custom headers
  17169. TEST_F(SSEIntegrationTest, CustomHeaders) {
  17170. // Setup a server endpoint that checks for custom header
  17171. std::atomic<bool> header_received{false};
  17172. server_->Get("/header-check", [&](const Request &req, Response &res) {
  17173. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  17174. header_received.store(true);
  17175. }
  17176. res.set_chunked_content_provider("text/event-stream",
  17177. [](size_t, DataSink &) { return false; });
  17178. });
  17179. Client client("localhost", get_port());
  17180. Headers headers = {{"X-Custom-Header", "custom-value"}};
  17181. sse::SSEClient sse(client, "/header-check", headers);
  17182. sse.set_max_reconnect_attempts(1);
  17183. sse.start_async();
  17184. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17185. sse.stop();
  17186. EXPECT_TRUE(header_received.load());
  17187. }
  17188. // Test: Reconnect interval configuration
  17189. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  17190. Client client("localhost", get_port());
  17191. sse::SSEClient sse(client, "/events");
  17192. auto &result = sse.set_reconnect_interval(500);
  17193. // Builder pattern should return reference to self
  17194. EXPECT_EQ(&result, &sse);
  17195. }
  17196. // Test: Max reconnect attempts
  17197. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  17198. // Connect to non-existent port to force reconnects
  17199. Client client("localhost", 59998);
  17200. sse::SSEClient sse(client, "/events");
  17201. std::atomic<int> error_count{0};
  17202. sse.on_error([&](Error) { error_count.fetch_add(1); });
  17203. sse.set_reconnect_interval(50);
  17204. sse.set_max_reconnect_attempts(2);
  17205. auto start = std::chrono::steady_clock::now();
  17206. sse.start(); // Blocking call
  17207. auto end = std::chrono::steady_clock::now();
  17208. // Should have stopped after 2 failed attempts
  17209. EXPECT_GE(error_count.load(), 2);
  17210. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  17211. auto duration =
  17212. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  17213. #ifdef _WIN32
  17214. // Windows is much slower for socket connection failures
  17215. EXPECT_LT(duration.count(), 7000);
  17216. #else
  17217. EXPECT_LT(duration.count(), 1000);
  17218. #endif
  17219. }
  17220. // Test: Multi-line data in integration
  17221. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  17222. // Endpoint with multi-line data
  17223. server_->Get("/multiline-data", [](const Request &, Response &res) {
  17224. res.set_chunked_content_provider(
  17225. "text/event-stream", [](size_t offset, DataSink &sink) {
  17226. if (offset == 0) {
  17227. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  17228. sink.write(event.data(), event.size());
  17229. }
  17230. return false;
  17231. });
  17232. });
  17233. Client client("localhost", get_port());
  17234. sse::SSEClient sse(client, "/multiline-data");
  17235. std::string received_data;
  17236. std::mutex data_mutex;
  17237. sse.on_message([&](const sse::SSEMessage &msg) {
  17238. std::lock_guard<std::mutex> lock(data_mutex);
  17239. received_data = msg.data;
  17240. });
  17241. sse.set_reconnect_interval(100);
  17242. sse.set_max_reconnect_attempts(1);
  17243. sse.start_async();
  17244. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17245. sse.stop();
  17246. std::lock_guard<std::mutex> lock(data_mutex);
  17247. EXPECT_EQ(received_data, "line1\nline2\nline3");
  17248. }
  17249. // Test: Auto-reconnect after server disconnection
  17250. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  17251. std::atomic<int> connection_count{0};
  17252. std::atomic<int> message_count{0};
  17253. // Endpoint that sends one event and closes, forcing reconnect
  17254. server_->Get("/reconnect-test",
  17255. [&connection_count](const Request &, Response &res) {
  17256. connection_count.fetch_add(1);
  17257. res.set_chunked_content_provider(
  17258. "text/event-stream", [](size_t offset, DataSink &sink) {
  17259. if (offset == 0) {
  17260. std::string event = "data: hello\n\n";
  17261. sink.write(event.data(), event.size());
  17262. }
  17263. return false; // Close connection after sending
  17264. });
  17265. });
  17266. Client client("localhost", get_port());
  17267. sse::SSEClient sse(client, "/reconnect-test");
  17268. sse.on_message([&message_count](const sse::SSEMessage &) {
  17269. message_count.fetch_add(1);
  17270. });
  17271. sse.set_reconnect_interval(100);
  17272. sse.set_max_reconnect_attempts(3);
  17273. sse.start_async();
  17274. // Wait long enough for multiple reconnects
  17275. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17276. sse.stop();
  17277. // Should have connected multiple times (initial + reconnects)
  17278. EXPECT_GE(connection_count.load(), 2);
  17279. // Should have received messages from multiple connections
  17280. EXPECT_GE(message_count.load(), 2);
  17281. }
  17282. // Test: Last-Event-ID sent on reconnect
  17283. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  17284. std::atomic<int> connection_count{0};
  17285. std::vector<std::string> received_last_event_ids;
  17286. std::mutex id_mutex;
  17287. // Endpoint that checks Last-Event-ID header and sends event with ID
  17288. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  17289. int conn = connection_count.fetch_add(1);
  17290. // Capture the Last-Event-ID header from each connection
  17291. {
  17292. std::lock_guard<std::mutex> lock(id_mutex);
  17293. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  17294. }
  17295. res.set_chunked_content_provider(
  17296. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  17297. if (offset == 0) {
  17298. std::string event =
  17299. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  17300. sink.write(event.data(), event.size());
  17301. }
  17302. return false;
  17303. });
  17304. });
  17305. Client client("localhost", get_port());
  17306. sse::SSEClient sse(client, "/reconnect-with-id");
  17307. sse.set_reconnect_interval(100);
  17308. sse.set_max_reconnect_attempts(3);
  17309. sse.start_async();
  17310. // Wait for at least 2 connections
  17311. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17312. sse.stop();
  17313. // Verify behavior
  17314. std::lock_guard<std::mutex> lock(id_mutex);
  17315. EXPECT_GE(received_last_event_ids.size(), 2u);
  17316. // First connection should have no Last-Event-ID
  17317. if (!received_last_event_ids.empty()) {
  17318. EXPECT_EQ(received_last_event_ids[0], "");
  17319. }
  17320. // Second connection should have Last-Event-ID from first connection
  17321. if (received_last_event_ids.size() >= 2) {
  17322. EXPECT_EQ(received_last_event_ids[1], "event-0");
  17323. }
  17324. }
  17325. // Test: set_headers updates headers used on reconnect
  17326. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  17327. std::vector<std::string> received_tokens;
  17328. std::mutex token_mutex;
  17329. // Endpoint that captures Authorization header
  17330. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  17331. {
  17332. std::lock_guard<std::mutex> lock(token_mutex);
  17333. received_tokens.push_back(req.get_header_value("Authorization"));
  17334. }
  17335. res.set_chunked_content_provider(
  17336. "text/event-stream", [](size_t offset, DataSink &sink) {
  17337. if (offset == 0) {
  17338. std::string event = "data: hello\n\n";
  17339. sink.write(event.data(), event.size());
  17340. }
  17341. return false; // Close connection to trigger reconnect
  17342. });
  17343. });
  17344. Client client("localhost", get_port());
  17345. Headers headers = {{"Authorization", "Bearer old-token"}};
  17346. sse::SSEClient sse(client, "/auth-check", headers);
  17347. // Update headers on each successful connection
  17348. sse.on_open(
  17349. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  17350. sse.set_reconnect_interval(100);
  17351. sse.set_max_reconnect_attempts(3);
  17352. sse.start_async();
  17353. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17354. sse.stop();
  17355. std::lock_guard<std::mutex> lock(token_mutex);
  17356. ASSERT_GE(received_tokens.size(), 2u);
  17357. // First connection uses original header
  17358. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  17359. // Second connection uses updated header from set_headers
  17360. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  17361. }
  17362. // Test: 401 allows reconnection (so on_error can refresh headers)
  17363. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  17364. std::atomic<int> connection_count{0};
  17365. // Endpoint: returns 401 on first attempt, 200 on second
  17366. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  17367. int conn = connection_count.fetch_add(1);
  17368. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  17369. res.status = StatusCode::Unauthorized_401;
  17370. res.set_content("Unauthorized", "text/plain");
  17371. return;
  17372. }
  17373. res.set_chunked_content_provider(
  17374. "text/event-stream", [](size_t offset, DataSink &sink) {
  17375. if (offset == 0) {
  17376. std::string event = "data: authenticated\n\n";
  17377. sink.write(event.data(), event.size());
  17378. }
  17379. return false;
  17380. });
  17381. });
  17382. Client client("localhost", get_port());
  17383. Headers headers = {{"Authorization", "Bearer expired"}};
  17384. sse::SSEClient sse(client, "/auth-retry", headers);
  17385. std::atomic<bool> message_received{false};
  17386. // Refresh token on error
  17387. sse.on_error(
  17388. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  17389. sse.on_message([&](const sse::SSEMessage &msg) {
  17390. if (msg.data == "authenticated") { message_received.store(true); }
  17391. });
  17392. sse.set_reconnect_interval(100);
  17393. sse.set_max_reconnect_attempts(3);
  17394. sse.start_async();
  17395. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17396. sse.stop();
  17397. // Should have reconnected after 401 and succeeded with new token
  17398. EXPECT_GE(connection_count.load(), 2);
  17399. EXPECT_TRUE(message_received.load());
  17400. }
  17401. TEST(Issue2318Test, EmptyHostString) {
  17402. {
  17403. httplib::Client cli_empty("", PORT);
  17404. auto res = cli_empty.Get("/");
  17405. ASSERT_FALSE(res);
  17406. EXPECT_EQ(httplib::Error::Connection, res.error());
  17407. }
  17408. {
  17409. httplib::Client cli(" ", PORT);
  17410. auto res = cli.Get("/");
  17411. ASSERT_FALSE(res);
  17412. EXPECT_EQ(httplib::Error::Connection, res.error());
  17413. }
  17414. }
  17415. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17416. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  17417. Server svr;
  17418. // Set a small payload limit (1KB)
  17419. svr.set_payload_max_length(1024);
  17420. svr.Post("/test", [&](const Request &req, Response &res) {
  17421. res.set_content("Body size: " + std::to_string(req.body.size()),
  17422. "text/plain");
  17423. });
  17424. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17425. auto se = detail::scope_exit([&] {
  17426. svr.stop();
  17427. listen_thread.join();
  17428. });
  17429. svr.wait_until_ready();
  17430. // Create data that compresses well but exceeds limit when decompressed
  17431. // 8KB of repeated null bytes compresses to a very small size
  17432. std::string original_data(8 * 1024, '\0');
  17433. // Compress the data using gzip
  17434. std::string compressed_data;
  17435. detail::gzip_compressor compressor;
  17436. compressor.compress(original_data.data(), original_data.size(), true,
  17437. [&](const char *data, size_t size) {
  17438. compressed_data.append(data, size);
  17439. return true;
  17440. });
  17441. // Verify compression worked (compressed should be much smaller)
  17442. ASSERT_LT(compressed_data.size(), original_data.size());
  17443. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  17444. // Send compressed data with Content-Encoding: gzip
  17445. Client cli(HOST, PORT);
  17446. Headers headers = {{"Content-Encoding", "gzip"}};
  17447. auto res =
  17448. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  17449. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  17450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17451. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  17452. }
  17453. #endif
  17454. // ============================================================================
  17455. // OpenSSL-Specific Tests
  17456. // ============================================================================
  17457. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17458. X509 *readCertificate(const std::string &strFileName) {
  17459. std::ifstream inStream(strFileName);
  17460. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  17461. std::istreambuf_iterator<char>());
  17462. if (strCertPEM.empty()) return (nullptr);
  17463. BIO *pbCert = BIO_new(BIO_s_mem());
  17464. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  17465. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  17466. BIO_free(pbCert);
  17467. return (pCert);
  17468. }
  17469. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  17470. std::ifstream inStream(strFileName);
  17471. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  17472. std::istreambuf_iterator<char>());
  17473. if (strPrivateKeyPEM.empty()) return (nullptr);
  17474. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  17475. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  17476. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  17477. BIO_free(pbPrivKey);
  17478. return (pPrivateKey);
  17479. }
  17480. TEST(BindServerTest, UpdateCerts) {
  17481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17482. int port = svr.bind_to_any_port("0.0.0.0");
  17483. ASSERT_TRUE(svr.is_valid());
  17484. ASSERT_TRUE(port > 0);
  17485. X509 *cert = readCertificate(SERVER_CERT_FILE);
  17486. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  17487. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  17488. ASSERT_TRUE(cert != nullptr);
  17489. ASSERT_TRUE(ca_cert != nullptr);
  17490. ASSERT_TRUE(key != nullptr);
  17491. X509_STORE *cert_store = X509_STORE_new();
  17492. X509_STORE_add_cert(cert_store, ca_cert);
  17493. // svr.update_certs(cert, key, cert_store); // deprecated
  17494. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  17495. CLIENT_CA_CERT_FILE);
  17496. ASSERT_TRUE(svr.is_valid());
  17497. svr.stop();
  17498. X509_STORE_free(cert_store);
  17499. X509_free(cert);
  17500. X509_free(ca_cert);
  17501. EVP_PKEY_free(key);
  17502. }
  17503. // Test that update_certs() updates client CA list correctly
  17504. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  17505. // Start with file-based constructor
  17506. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17507. ASSERT_TRUE(svr.is_valid());
  17508. // Initially no client CA list should be set
  17509. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17510. ASSERT_TRUE(ssl_ctx != nullptr);
  17511. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  17512. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  17513. EXPECT_EQ(0, count_before);
  17514. // Now update with client CA (PEM string)
  17515. std::string cert_pem, key_pem, ca_pem;
  17516. read_file(SERVER_CERT_FILE, cert_pem);
  17517. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  17518. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  17519. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  17520. ASSERT_TRUE(svr.is_valid());
  17521. // Now client CA list should be set
  17522. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  17523. ASSERT_TRUE(ca_list_after != nullptr);
  17524. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  17525. }
  17526. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  17527. // Test that the file-path SSLServer constructor properly sets the client CA
  17528. // list that is sent to clients during the TLS handshake (CertificateRequest)
  17529. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17530. ASSERT_TRUE(svr.is_valid());
  17531. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17532. ASSERT_TRUE(ssl_ctx != nullptr);
  17533. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  17534. ASSERT_TRUE(ca_list != nullptr);
  17535. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  17536. }
  17537. #endif
  17538. // ============================================================================
  17539. // MbedTLS-Specific Tests
  17540. // ============================================================================
  17541. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  17542. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  17543. using namespace httplib::tls;
  17544. // Track if callback was invoked
  17545. bool callback_invoked = false;
  17546. // The callback receives void* ctx which is actually MbedTlsContext*
  17547. // We can access the mbedtls_ssl_config via the context
  17548. auto setup_callback = [&callback_invoked](void *ctx) {
  17549. callback_invoked = true;
  17550. // Cast to MbedTlsContext* to access the ssl config
  17551. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  17552. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  17553. // Use static variables to hold certificate data (simplified for test)
  17554. static mbedtls_x509_crt own_cert;
  17555. static mbedtls_pk_context own_key;
  17556. static mbedtls_x509_crt ca_chain;
  17557. static bool initialized = false;
  17558. if (!initialized) {
  17559. mbedtls_x509_crt_init(&own_cert);
  17560. mbedtls_pk_init(&own_key);
  17561. mbedtls_x509_crt_init(&ca_chain);
  17562. // Load server certificate
  17563. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  17564. return false;
  17565. }
  17566. // Load server private key.
  17567. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  17568. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  17569. #if MBEDTLS_VERSION_MAJOR == 3
  17570. ,
  17571. mbedtls_ctr_drbg_random, nullptr
  17572. #endif
  17573. ) != 0) {
  17574. return false;
  17575. }
  17576. // Load CA chain for client verification
  17577. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  17578. return false;
  17579. }
  17580. initialized = true;
  17581. }
  17582. // Configure the SSL config
  17583. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  17584. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  17585. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17586. // Set minimum TLS version using mbedTLS native API
  17587. #if MBEDTLS_VERSION_MAJOR >= 3
  17588. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17589. #else
  17590. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17591. MBEDTLS_SSL_MINOR_VERSION_3);
  17592. #endif
  17593. return true;
  17594. };
  17595. SSLServer svr(setup_callback);
  17596. ASSERT_TRUE(svr.is_valid());
  17597. ASSERT_TRUE(callback_invoked);
  17598. svr.Get("/test", [&](const Request &req, Response &res) {
  17599. res.set_content("test", "text/plain");
  17600. auto cert = req.peer_cert();
  17601. ASSERT_TRUE(static_cast<bool>(cert));
  17602. auto common_name = cert.subject_cn();
  17603. EXPECT_EQ("Common Name", common_name);
  17604. });
  17605. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17606. auto se = detail::scope_exit([&] {
  17607. svr.stop();
  17608. t.join();
  17609. ASSERT_FALSE(svr.is_running());
  17610. });
  17611. svr.wait_until_ready();
  17612. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  17613. cli.enable_server_certificate_verification(false);
  17614. cli.set_connection_timeout(30);
  17615. auto res = cli.Get("/test");
  17616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17617. ASSERT_EQ(StatusCode::OK_200, res->status);
  17618. }
  17619. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  17620. // context (owning mbedtls_ssl_config) before shutting down a still-open
  17621. // keep-alive SSL session, which reads through that config in
  17622. // mbedtls_ssl_close_notify.
  17623. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  17624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17625. ASSERT_TRUE(svr.is_valid());
  17626. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17627. res.set_content("test", "text/plain");
  17628. });
  17629. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17630. auto se = detail::scope_exit([&] {
  17631. svr.stop();
  17632. t.join();
  17633. ASSERT_FALSE(svr.is_running());
  17634. });
  17635. svr.wait_until_ready();
  17636. {
  17637. SSLClient cli(HOST, PORT);
  17638. cli.enable_server_certificate_verification(false);
  17639. cli.set_keep_alive(true);
  17640. auto res = cli.Get("/test");
  17641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17642. ASSERT_EQ(StatusCode::OK_200, res->status);
  17643. // cli is destructed here with the keep-alive SSL session still open.
  17644. }
  17645. }
  17646. #endif
  17647. // WebSocket Tests
  17648. TEST(WebSocketTest, RSVBitsMustBeZero) {
  17649. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  17650. // defining the meaning of these bits has been negotiated.
  17651. auto make_frame = [](uint8_t first_byte) {
  17652. std::string frame;
  17653. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  17654. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  17655. frame += "Hello";
  17656. return frame;
  17657. };
  17658. // RSV1 set (0x40)
  17659. {
  17660. detail::BufferStream strm;
  17661. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  17662. ws::Opcode opcode;
  17663. std::string payload;
  17664. bool fin;
  17665. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17666. false, 1024));
  17667. }
  17668. // RSV2 set (0x20)
  17669. {
  17670. detail::BufferStream strm;
  17671. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  17672. ws::Opcode opcode;
  17673. std::string payload;
  17674. bool fin;
  17675. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17676. false, 1024));
  17677. }
  17678. // RSV3 set (0x10)
  17679. {
  17680. detail::BufferStream strm;
  17681. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  17682. ws::Opcode opcode;
  17683. std::string payload;
  17684. bool fin;
  17685. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17686. false, 1024));
  17687. }
  17688. // No RSV bits set - should succeed
  17689. {
  17690. detail::BufferStream strm;
  17691. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  17692. ws::Opcode opcode;
  17693. std::string payload;
  17694. bool fin;
  17695. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17696. false, 1024));
  17697. EXPECT_EQ(ws::Opcode::Text, opcode);
  17698. EXPECT_EQ("Hello", payload);
  17699. EXPECT_TRUE(fin);
  17700. }
  17701. }
  17702. TEST(WebSocketTest, ControlFrameValidation) {
  17703. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  17704. // payload length <= 125.
  17705. // Ping with FIN=0 - must be rejected
  17706. {
  17707. detail::BufferStream strm;
  17708. std::string frame;
  17709. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  17710. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17711. strm.write(frame.data(), frame.size());
  17712. ws::Opcode opcode;
  17713. std::string payload;
  17714. bool fin;
  17715. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17716. false, 1024));
  17717. }
  17718. // Close with FIN=0 - must be rejected
  17719. {
  17720. detail::BufferStream strm;
  17721. std::string frame;
  17722. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  17723. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17724. strm.write(frame.data(), frame.size());
  17725. ws::Opcode opcode;
  17726. std::string payload;
  17727. bool fin;
  17728. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17729. false, 1024));
  17730. }
  17731. // Ping with payload_len=126 (extended length) - must be rejected
  17732. {
  17733. detail::BufferStream strm;
  17734. std::string frame;
  17735. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17736. frame += static_cast<char>(126); // payload_len=126 (>125)
  17737. frame += static_cast<char>(0x00); // extended length high byte
  17738. frame += static_cast<char>(126); // extended length low byte
  17739. frame += std::string(126, 'x');
  17740. strm.write(frame.data(), frame.size());
  17741. ws::Opcode opcode;
  17742. std::string payload;
  17743. bool fin;
  17744. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17745. false, 1024));
  17746. }
  17747. // Ping with FIN=1 and payload_len=125 - should succeed
  17748. {
  17749. detail::BufferStream strm;
  17750. std::string frame;
  17751. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17752. frame += static_cast<char>(125); // payload_len=125
  17753. frame += std::string(125, 'x');
  17754. strm.write(frame.data(), frame.size());
  17755. ws::Opcode opcode;
  17756. std::string payload;
  17757. bool fin;
  17758. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17759. false, 1024));
  17760. EXPECT_EQ(ws::Opcode::Ping, opcode);
  17761. EXPECT_EQ(125u, payload.size());
  17762. EXPECT_TRUE(fin);
  17763. }
  17764. }
  17765. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  17766. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  17767. // length MUST be 0.
  17768. // MSB set - must be rejected
  17769. {
  17770. detail::BufferStream strm;
  17771. std::string frame;
  17772. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17773. frame += static_cast<char>(127); // 64-bit extended length
  17774. frame += static_cast<char>(0x80); // MSB set (invalid)
  17775. frame += std::string(7, '\0'); // remaining 7 bytes of length
  17776. strm.write(frame.data(), frame.size());
  17777. ws::Opcode opcode;
  17778. std::string payload;
  17779. bool fin;
  17780. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17781. false, 1024));
  17782. }
  17783. // MSB clear - should pass length parsing (will be rejected by max_len,
  17784. // but that's a different check; use a small length to verify)
  17785. {
  17786. detail::BufferStream strm;
  17787. std::string frame;
  17788. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17789. frame += static_cast<char>(127); // 64-bit extended length
  17790. frame += std::string(7, '\0'); // high bytes = 0
  17791. frame += static_cast<char>(0x03); // length = 3
  17792. frame += "abc";
  17793. strm.write(frame.data(), frame.size());
  17794. ws::Opcode opcode;
  17795. std::string payload;
  17796. bool fin;
  17797. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17798. false, 1024));
  17799. EXPECT_EQ(ws::Opcode::Text, opcode);
  17800. EXPECT_EQ("abc", payload);
  17801. }
  17802. }
  17803. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  17804. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  17805. // Valid UTF-8
  17806. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  17807. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  17808. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  17809. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  17810. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  17811. // Invalid UTF-8
  17812. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  17813. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  17814. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  17815. EXPECT_FALSE(
  17816. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  17817. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  17818. }
  17819. TEST(WebSocketTest, ConnectAndDisconnect) {
  17820. Server svr;
  17821. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17822. std::string msg;
  17823. while (ws.read(msg)) {}
  17824. });
  17825. auto port = svr.bind_to_any_port(HOST);
  17826. std::thread t([&]() { svr.listen_after_bind(); });
  17827. svr.wait_until_ready();
  17828. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17829. auto res = client.connect();
  17830. ASSERT_TRUE(res);
  17831. EXPECT_EQ(Error::Success, res.error());
  17832. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  17833. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  17834. EXPECT_TRUE(client.is_open());
  17835. client.close();
  17836. EXPECT_FALSE(client.is_open());
  17837. svr.stop();
  17838. t.join();
  17839. }
  17840. TEST(WebSocketTest, ValidURL) {
  17841. ws::WebSocketClient ws1("ws://localhost:8080/path");
  17842. EXPECT_TRUE(ws1.is_valid());
  17843. ws::WebSocketClient ws2("ws://example.com/path");
  17844. EXPECT_TRUE(ws2.is_valid());
  17845. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  17846. EXPECT_TRUE(ws3.is_valid());
  17847. #ifdef CPPHTTPLIB_SSL_ENABLED
  17848. ws::WebSocketClient wss1("wss://example.com/path");
  17849. EXPECT_TRUE(wss1.is_valid());
  17850. ws::WebSocketClient wss2("wss://example.com:443/path");
  17851. EXPECT_TRUE(wss2.is_valid());
  17852. #endif
  17853. }
  17854. TEST(WebSocketTest, InvalidURL) {
  17855. // No scheme
  17856. ws::WebSocketClient ws1("localhost:8080/path");
  17857. EXPECT_FALSE(ws1.is_valid());
  17858. // No path
  17859. ws::WebSocketClient ws2("ws://localhost:8080");
  17860. EXPECT_FALSE(ws2.is_valid());
  17861. // Empty string
  17862. ws::WebSocketClient ws3("");
  17863. EXPECT_FALSE(ws3.is_valid());
  17864. // Missing host
  17865. ws::WebSocketClient ws4("ws://:8080/path");
  17866. EXPECT_FALSE(ws4.is_valid());
  17867. // Port number overflow — should not crash
  17868. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  17869. EXPECT_FALSE(ws5.is_valid());
  17870. // Port out of range
  17871. ws::WebSocketClient ws6("ws://localhost:99999/path");
  17872. EXPECT_FALSE(ws6.is_valid());
  17873. }
  17874. TEST(WebSocketTest, UnsupportedScheme) {
  17875. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17876. ws::WebSocketClient ws1("http://localhost:8080/path");
  17877. EXPECT_FALSE(ws1.is_valid());
  17878. ws::WebSocketClient ws2("https://localhost:8080/path");
  17879. EXPECT_FALSE(ws2.is_valid());
  17880. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  17881. EXPECT_FALSE(ws3.is_valid());
  17882. #else
  17883. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  17884. std::invalid_argument);
  17885. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  17886. std::invalid_argument);
  17887. #endif
  17888. }
  17889. TEST(WebSocketTest, ConnectWhenInvalid) {
  17890. ws::WebSocketClient ws("not a valid url");
  17891. EXPECT_FALSE(ws.is_valid());
  17892. auto res = ws.connect();
  17893. EXPECT_FALSE(res);
  17894. EXPECT_EQ(Error::Connection, res.error());
  17895. EXPECT_EQ(-1, res.status());
  17896. }
  17897. TEST(WebSocketTest, ConnectRefusedReportsError) {
  17898. // Grab a port that is free, then close it again so nothing listens there
  17899. Server svr;
  17900. auto port = svr.bind_to_any_port(HOST);
  17901. svr.stop();
  17902. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17903. auto res = client.connect();
  17904. ASSERT_FALSE(res);
  17905. EXPECT_EQ(Error::Connection, res.error());
  17906. EXPECT_EQ(-1, res.status());
  17907. }
  17908. TEST(WebSocketTest, DefaultPort) {
  17909. ws::WebSocketClient ws1("ws://example.com/path");
  17910. EXPECT_TRUE(ws1.is_valid());
  17911. // ws:// defaults to port 80 (verified by successful parse)
  17912. #ifdef CPPHTTPLIB_SSL_ENABLED
  17913. ws::WebSocketClient ws2("wss://example.com/path");
  17914. EXPECT_TRUE(ws2.is_valid());
  17915. // wss:// defaults to port 443 (verified by successful parse)
  17916. #endif
  17917. }
  17918. TEST(WebSocketTest, IPv6LiteralAddress) {
  17919. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  17920. EXPECT_TRUE(ws1.is_valid());
  17921. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  17922. EXPECT_TRUE(ws2.is_valid());
  17923. }
  17924. TEST(WebSocketTest, ComplexPath) {
  17925. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  17926. EXPECT_TRUE(ws1.is_valid());
  17927. ws::WebSocketClient ws2("ws://localhost:8080/");
  17928. EXPECT_TRUE(ws2.is_valid());
  17929. }
  17930. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  17931. Server svr;
  17932. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17933. std::string msg;
  17934. while (ws.read(msg)) {}
  17935. });
  17936. auto port = svr.bind_to_any_port(HOST);
  17937. std::thread t([&]() { svr.listen_after_bind(); });
  17938. svr.wait_until_ready();
  17939. auto another_host = "example.com";
  17940. auto wrong_ip = "192.0.2.1";
  17941. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17942. client.set_hostname_addr_map({{another_host, wrong_ip}});
  17943. ASSERT_TRUE(client.connect());
  17944. EXPECT_TRUE(client.is_open());
  17945. client.close();
  17946. svr.stop();
  17947. t.join();
  17948. }
  17949. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  17950. Server svr;
  17951. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17952. std::string msg;
  17953. while (ws.read(msg)) {}
  17954. });
  17955. auto port = svr.bind_to_any_port(HOST);
  17956. std::thread t([&]() { svr.listen_after_bind(); });
  17957. svr.wait_until_ready();
  17958. auto wrong_ip = "192.0.2.1";
  17959. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17960. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  17961. client.set_connection_timeout(1);
  17962. client.set_read_timeout(1);
  17963. client.set_write_timeout(1);
  17964. EXPECT_FALSE(client.connect());
  17965. EXPECT_FALSE(client.is_open());
  17966. svr.stop();
  17967. t.join();
  17968. }
  17969. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  17970. // A mapped value that is not an IP literal must be resolved. HOST resolves
  17971. // from the hosts file, so this test needs no external DNS. "target.invalid"
  17972. // (RFC 6761) is only a map key and the Host header value.
  17973. auto host = "target.invalid";
  17974. Server svr;
  17975. std::string received_host;
  17976. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17977. received_host = req.get_header_value("Host");
  17978. std::string msg;
  17979. while (ws.read(msg)) {}
  17980. });
  17981. auto port = svr.bind_to_any_port(HOST);
  17982. std::thread t([&]() { svr.listen_after_bind(); });
  17983. // ASSERT_* below returns from the test body, which would leave t joinable
  17984. // and make ~thread call std::terminate.
  17985. auto se = detail::scope_exit([&] {
  17986. svr.stop();
  17987. if (t.joinable()) { t.join(); }
  17988. });
  17989. svr.wait_until_ready();
  17990. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  17991. std::to_string(port) + "/ws");
  17992. client.set_hostname_addr_map({{host, HOST}});
  17993. ASSERT_TRUE(client.connect());
  17994. EXPECT_TRUE(client.is_open());
  17995. client.close();
  17996. svr.stop();
  17997. t.join();
  17998. // The mapping only redirects the connection; the identity stays host_.
  17999. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  18000. }
  18001. class WebSocketIntegrationTest : public ::testing::Test {
  18002. protected:
  18003. void SetUp() override {
  18004. server_ = httplib::detail::make_unique<Server>();
  18005. setup_server();
  18006. start_server();
  18007. }
  18008. void TearDown() override {
  18009. server_->stop();
  18010. if (server_thread_.joinable()) { server_thread_.join(); }
  18011. }
  18012. void setup_server() {
  18013. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18014. std::string msg;
  18015. ws::ReadResult ret;
  18016. while ((ret = ws.read(msg))) {
  18017. if (ret == ws::Binary) {
  18018. ws.send(msg.data(), msg.size());
  18019. } else {
  18020. ws.send(msg);
  18021. }
  18022. }
  18023. });
  18024. server_->WebSocket("/ws-echo-string",
  18025. [](const Request &, ws::WebSocket &ws) {
  18026. std::string msg;
  18027. while (ws.read(msg)) {
  18028. ws.send("echo: " + msg);
  18029. }
  18030. });
  18031. server_->WebSocket(
  18032. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  18033. // Echo back request metadata
  18034. ws.send("path:" + req.path);
  18035. ws.send("header:" + req.get_header_value("X-Test-Header"));
  18036. std::string msg;
  18037. while (ws.read(msg)) {}
  18038. });
  18039. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  18040. std::string msg;
  18041. ws.read(msg); // wait for a message
  18042. ws.close();
  18043. });
  18044. server_->WebSocket("/ws-close-status",
  18045. [](const Request &, ws::WebSocket &ws) {
  18046. std::string msg;
  18047. ws.read(msg); // wait for a message
  18048. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  18049. });
  18050. server_->WebSocket(
  18051. "/ws-subprotocol",
  18052. [](const Request &, ws::WebSocket &ws) {
  18053. std::string msg;
  18054. while (ws.read(msg)) {
  18055. ws.send(msg);
  18056. }
  18057. },
  18058. [](const std::vector<std::string> &protocols) -> std::string {
  18059. for (const auto &p : protocols) {
  18060. if (p == "graphql-ws") { return p; }
  18061. }
  18062. return "";
  18063. });
  18064. }
  18065. void start_server() {
  18066. port_ = server_->bind_to_any_port(HOST);
  18067. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18068. server_->wait_until_ready();
  18069. }
  18070. std::unique_ptr<Server> server_;
  18071. std::thread server_thread_;
  18072. int port_ = 0;
  18073. };
  18074. TEST_F(WebSocketIntegrationTest, TextEcho) {
  18075. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18076. "/ws-echo");
  18077. ASSERT_TRUE(client.connect());
  18078. ASSERT_TRUE(client.is_open());
  18079. ASSERT_TRUE(client.send("Hello WebSocket"));
  18080. std::string msg;
  18081. EXPECT_EQ(ws::Text, client.read(msg));
  18082. EXPECT_EQ("Hello WebSocket", msg);
  18083. client.close();
  18084. }
  18085. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  18086. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18087. "/ws-echo");
  18088. ASSERT_TRUE(client.connect());
  18089. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  18090. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  18091. std::string msg;
  18092. EXPECT_EQ(ws::Binary, client.read(msg));
  18093. EXPECT_EQ(binary_data, msg);
  18094. client.close();
  18095. }
  18096. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  18097. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18098. "/ws-echo");
  18099. ASSERT_TRUE(client.connect());
  18100. for (int i = 0; i < 10; i++) {
  18101. auto text = "message " + std::to_string(i);
  18102. ASSERT_TRUE(client.send(text));
  18103. std::string msg;
  18104. ASSERT_TRUE(client.read(msg));
  18105. EXPECT_EQ(text, msg);
  18106. }
  18107. client.close();
  18108. }
  18109. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  18110. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18111. "/ws-close");
  18112. ASSERT_TRUE(client.connect());
  18113. // Send a message to trigger the server to close
  18114. ASSERT_TRUE(client.send("trigger close"));
  18115. // The server will close, so read should return false
  18116. std::string msg;
  18117. EXPECT_FALSE(client.read(msg));
  18118. EXPECT_FALSE(client.is_open());
  18119. }
  18120. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  18121. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18122. "/ws-echo");
  18123. ASSERT_TRUE(client.connect());
  18124. // 128KB message
  18125. std::string large_data(128 * 1024, 'X');
  18126. ASSERT_TRUE(client.send(large_data));
  18127. std::string msg;
  18128. ASSERT_TRUE(client.read(msg));
  18129. EXPECT_EQ(large_data, msg);
  18130. client.close();
  18131. }
  18132. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  18133. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18134. "/ws-echo");
  18135. ASSERT_TRUE(client.connect());
  18136. const int num_threads = 4;
  18137. std::vector<std::thread> threads;
  18138. std::atomic<int> send_count{0};
  18139. for (int t = 0; t < num_threads; t++) {
  18140. threads.emplace_back([&client, &send_count, t]() {
  18141. for (int i = 0; i < 5; i++) {
  18142. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  18143. if (client.send(text)) { send_count++; }
  18144. }
  18145. });
  18146. }
  18147. for (auto &th : threads) {
  18148. th.join();
  18149. }
  18150. int received = 0;
  18151. std::string msg;
  18152. while (received < send_count.load()) {
  18153. if (!client.read(msg)) { break; }
  18154. received++;
  18155. }
  18156. EXPECT_EQ(send_count.load(), received);
  18157. client.close();
  18158. }
  18159. TEST_F(WebSocketIntegrationTest, ReadString) {
  18160. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18161. "/ws-echo-string");
  18162. ASSERT_TRUE(client.connect());
  18163. ASSERT_TRUE(client.send("hello"));
  18164. std::string msg;
  18165. ASSERT_TRUE(client.read(msg));
  18166. EXPECT_EQ("echo: hello", msg);
  18167. ASSERT_TRUE(client.send("world"));
  18168. ASSERT_TRUE(client.read(msg));
  18169. EXPECT_EQ("echo: world", msg);
  18170. client.close();
  18171. }
  18172. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  18173. Headers headers = {{"X-Test-Header", "test-value"}};
  18174. ws::WebSocketClient client(
  18175. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  18176. ASSERT_TRUE(client.connect());
  18177. std::string msg;
  18178. ASSERT_TRUE(client.read(msg));
  18179. EXPECT_EQ("path:/ws-request-info", msg);
  18180. ASSERT_TRUE(client.read(msg));
  18181. EXPECT_EQ("header:test-value", msg);
  18182. client.close();
  18183. }
  18184. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  18185. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18186. "/ws-echo");
  18187. client.set_read_timeout(1, 0); // 1 second
  18188. ASSERT_TRUE(client.connect());
  18189. // Don't send anything — server echo handler waits for a message,
  18190. // so read() should time out and return false.
  18191. std::string msg;
  18192. EXPECT_FALSE(client.read(msg));
  18193. }
  18194. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  18195. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18196. "/ws-echo");
  18197. client.set_read_timeout(5, 0);
  18198. ASSERT_TRUE(client.connect());
  18199. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18200. // The server should reject it and close the connection.
  18201. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  18202. client.send(oversized);
  18203. // The server's read() should have failed due to payload limit,
  18204. // so our read() should return false (connection closed).
  18205. std::string msg;
  18206. EXPECT_FALSE(client.read(msg));
  18207. }
  18208. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  18209. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18210. "/ws-echo");
  18211. client.set_read_timeout(10, 0);
  18212. ASSERT_TRUE(client.connect());
  18213. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18214. // This should succeed.
  18215. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  18216. ASSERT_TRUE(client.send(at_limit));
  18217. std::string msg;
  18218. ASSERT_TRUE(client.read(msg));
  18219. EXPECT_EQ(at_limit.size(), msg.size());
  18220. client.close();
  18221. }
  18222. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  18223. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18224. "/nonexistent");
  18225. auto res = client.connect();
  18226. EXPECT_FALSE(res);
  18227. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18228. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  18229. EXPECT_FALSE(client.is_open());
  18230. }
  18231. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  18232. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18233. "/ws-echo");
  18234. ASSERT_TRUE(client.connect());
  18235. ASSERT_TRUE(client.send(""));
  18236. std::string msg;
  18237. EXPECT_EQ(ws::Text, client.read(msg));
  18238. EXPECT_EQ("", msg);
  18239. client.close();
  18240. }
  18241. TEST_F(WebSocketIntegrationTest, Reconnect) {
  18242. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18243. "/ws-echo");
  18244. // First connection
  18245. ASSERT_TRUE(client.connect());
  18246. ASSERT_TRUE(client.send("first"));
  18247. std::string msg;
  18248. ASSERT_TRUE(client.read(msg));
  18249. EXPECT_EQ("first", msg);
  18250. client.close();
  18251. EXPECT_FALSE(client.is_open());
  18252. // Reconnect using the same client object
  18253. ASSERT_TRUE(client.connect());
  18254. ASSERT_TRUE(client.is_open());
  18255. ASSERT_TRUE(client.send("second"));
  18256. ASSERT_TRUE(client.read(msg));
  18257. EXPECT_EQ("second", msg);
  18258. client.close();
  18259. }
  18260. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  18261. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18262. "/ws-close-status");
  18263. ASSERT_TRUE(client.connect());
  18264. // Trigger the server to close with GoingAway status
  18265. ASSERT_TRUE(client.send("trigger"));
  18266. // read() should return false after receiving the close frame
  18267. std::string msg;
  18268. EXPECT_FALSE(client.read(msg));
  18269. EXPECT_FALSE(client.is_open());
  18270. }
  18271. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  18272. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18273. "/ws-echo");
  18274. ASSERT_TRUE(client.connect());
  18275. client.close(ws::CloseStatus::GoingAway, "client leaving");
  18276. EXPECT_FALSE(client.is_open());
  18277. }
  18278. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  18279. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  18280. ws::WebSocketClient client(
  18281. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18282. ASSERT_TRUE(client.connect());
  18283. // Server should have selected graphql-ws
  18284. EXPECT_EQ("graphql-ws", client.subprotocol());
  18285. client.close();
  18286. }
  18287. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  18288. Headers headers;
  18289. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  18290. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  18291. ws::WebSocketClient client(
  18292. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18293. ASSERT_TRUE(client.connect());
  18294. // The offer on the second field line counts too, so graphql-ws is selected
  18295. EXPECT_EQ("graphql-ws", client.subprotocol());
  18296. client.close();
  18297. }
  18298. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  18299. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  18300. ws::WebSocketClient client(
  18301. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18302. ASSERT_TRUE(client.connect());
  18303. // Server should not have selected any subprotocol
  18304. EXPECT_TRUE(client.subprotocol().empty());
  18305. client.close();
  18306. }
  18307. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  18308. // Connect without requesting any subprotocol
  18309. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18310. "/ws-subprotocol");
  18311. ASSERT_TRUE(client.connect());
  18312. EXPECT_TRUE(client.subprotocol().empty());
  18313. client.close();
  18314. }
  18315. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  18316. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18317. "/ws-echo");
  18318. client.set_tcp_nodelay(true);
  18319. client.set_connection_timeout(3, 0);
  18320. bool socket_options_called = false;
  18321. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  18322. ASSERT_TRUE(client.connect());
  18323. ASSERT_TRUE(client.is_open());
  18324. EXPECT_TRUE(socket_options_called);
  18325. ASSERT_TRUE(client.send("hello"));
  18326. std::string msg;
  18327. auto result = client.read(msg);
  18328. EXPECT_EQ(result, ws::ReadResult::Text);
  18329. EXPECT_EQ(msg, "hello");
  18330. client.close();
  18331. }
  18332. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  18333. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18334. "/ws-echo");
  18335. client.set_connection_timeout(std::chrono::seconds(3));
  18336. client.set_write_timeout(std::chrono::seconds(3));
  18337. // A sub-second remainder exercises the seconds/microseconds split.
  18338. client.set_read_timeout(std::chrono::milliseconds(1500));
  18339. ASSERT_TRUE(client.connect());
  18340. auto start = std::chrono::steady_clock::now();
  18341. std::string msg;
  18342. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  18343. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18344. std::chrono::steady_clock::now() - start)
  18345. .count();
  18346. // Above 1s so that dropping the microseconds half of the split fails here,
  18347. // and well under the 300s default so that ignoring the setter fails too.
  18348. EXPECT_GE(elapsed, 1400);
  18349. EXPECT_LT(elapsed, 30000);
  18350. }
  18351. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  18352. Server svr;
  18353. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  18354. if (!req.has_header("Authorization")) {
  18355. res.status = StatusCode::Unauthorized_401;
  18356. res.set_content("Unauthorized", "text/plain");
  18357. return Server::HandlerResponse::Handled;
  18358. }
  18359. return Server::HandlerResponse::Unhandled;
  18360. });
  18361. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18362. std::string msg;
  18363. while (ws.read(msg)) {
  18364. ws.send(msg);
  18365. }
  18366. });
  18367. auto port = svr.bind_to_any_port("localhost");
  18368. std::thread t([&]() { svr.listen_after_bind(); });
  18369. svr.wait_until_ready();
  18370. // Without Authorization header - should be rejected before upgrade
  18371. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  18372. EXPECT_FALSE(client1.connect());
  18373. // With Authorization header - should succeed
  18374. Headers headers = {{"Authorization", "Bearer token123"}};
  18375. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  18376. headers);
  18377. ASSERT_TRUE(client2.connect());
  18378. ASSERT_TRUE(client2.send("hello"));
  18379. std::string msg;
  18380. ASSERT_TRUE(client2.read(msg));
  18381. EXPECT_EQ("hello", msg);
  18382. client2.close();
  18383. svr.stop();
  18384. t.join();
  18385. }
  18386. TEST(WebSocketTest, QueryStringInHandshake) {
  18387. Server svr;
  18388. std::mutex mtx;
  18389. std::string received_target;
  18390. std::string received_token;
  18391. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18392. {
  18393. std::lock_guard<std::mutex> lock(mtx);
  18394. received_target = req.target;
  18395. if (req.has_param("token")) {
  18396. received_token = req.get_param_value("token");
  18397. }
  18398. }
  18399. std::string msg;
  18400. while (ws.read(msg)) {
  18401. ws.send(msg);
  18402. }
  18403. });
  18404. auto port = svr.bind_to_any_port("localhost");
  18405. std::thread t([&]() { svr.listen_after_bind(); });
  18406. svr.wait_until_ready();
  18407. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  18408. "/ws?token=ABC&session=123");
  18409. ASSERT_TRUE(client.connect());
  18410. // Round-trip ensures the handler has run and captured the request.
  18411. ASSERT_TRUE(client.send("hello"));
  18412. std::string msg;
  18413. ASSERT_TRUE(client.read(msg));
  18414. EXPECT_EQ("hello", msg);
  18415. client.close();
  18416. {
  18417. std::lock_guard<std::mutex> lock(mtx);
  18418. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  18419. EXPECT_EQ("ABC", received_token);
  18420. }
  18421. svr.stop();
  18422. t.join();
  18423. }
  18424. // Run a handshake against a throwaway server and hand the request the server
  18425. // received back to the caller, so tests can assert on the headers the client
  18426. // actually put on the wire.
  18427. static void capture_websocket_handshake_request(
  18428. const Headers &client_headers,
  18429. std::function<void(const Request &, int port)> verify) {
  18430. Server svr;
  18431. std::mutex mtx;
  18432. Request received;
  18433. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18434. {
  18435. std::lock_guard<std::mutex> lock(mtx);
  18436. received = req;
  18437. }
  18438. std::string msg;
  18439. while (ws.read(msg)) {
  18440. ws.send(msg);
  18441. }
  18442. });
  18443. auto port = svr.bind_to_any_port("localhost");
  18444. std::thread t([&]() { svr.listen_after_bind(); });
  18445. auto se = detail::scope_exit([&] {
  18446. svr.stop();
  18447. t.join();
  18448. });
  18449. svr.wait_until_ready();
  18450. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  18451. client_headers);
  18452. ASSERT_TRUE(client.connect());
  18453. ASSERT_TRUE(client.send("hello"));
  18454. std::string msg;
  18455. ASSERT_TRUE(client.read(msg));
  18456. client.close();
  18457. {
  18458. std::lock_guard<std::mutex> lock(mtx);
  18459. verify(received, port);
  18460. }
  18461. }
  18462. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  18463. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  18464. // Non-default port must be present in the Host header. Default ports
  18465. // (80/443) are omitted; that logic is covered by
  18466. // MakeHostAndPortStringTest.
  18467. EXPECT_EQ("localhost:" + std::to_string(port),
  18468. req.get_header_value("Host"));
  18469. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  18470. req.get_header_value("User-Agent"));
  18471. EXPECT_FALSE(req.has_header("Accept"));
  18472. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  18473. EXPECT_FALSE(req.has_header("Content-Length"));
  18474. });
  18475. }
  18476. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  18477. capture_websocket_handshake_request(
  18478. {{"Host", "example.com"},
  18479. {"User-Agent", "custom-agent"},
  18480. {"X-Custom", "value"}},
  18481. [](const Request &req, int) {
  18482. EXPECT_EQ("example.com", req.get_header_value("Host"));
  18483. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  18484. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  18485. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  18486. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  18487. });
  18488. }
  18489. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  18490. capture_websocket_handshake_request(
  18491. {{"Upgrade", "bogus"},
  18492. {"Connection", "close"},
  18493. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  18494. {"Sec-WebSocket-Version", "8"}},
  18495. [](const Request &req, int) {
  18496. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  18497. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  18498. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  18499. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  18500. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  18501. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  18502. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  18503. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  18504. req.get_header_value("Sec-WebSocket-Key"));
  18505. });
  18506. }
  18507. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  18508. // A header the client refuses to send must abort the handshake before any
  18509. // part of it reaches the wire; a lone request line would otherwise sit in
  18510. // the peer's buffer as a truncated request.
  18511. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18512. ASSERT_NE(INVALID_SOCKET, srv);
  18513. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  18514. sockaddr_in addr{};
  18515. addr.sin_family = AF_INET;
  18516. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  18517. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18518. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18519. ASSERT_EQ(0, ::listen(srv, 1));
  18520. sockaddr_in bound{};
  18521. socklen_t bound_len = sizeof(bound);
  18522. ASSERT_EQ(
  18523. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  18524. auto port = ntohs(bound.sin_port);
  18525. ssize_t received = -1;
  18526. std::thread t([&] {
  18527. // Bound every blocking call so a regression fails the test with a bad
  18528. // value instead of hanging the suite.
  18529. fd_set rfds;
  18530. FD_ZERO(&rfds);
  18531. FD_SET(srv, &rfds);
  18532. timeval tv{5, 0};
  18533. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  18534. 0) {
  18535. return;
  18536. }
  18537. sockaddr_in cli_addr{};
  18538. socklen_t cli_len = sizeof(cli_addr);
  18539. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18540. if (cli == INVALID_SOCKET) { return; }
  18541. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  18542. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18543. char buf[4096];
  18544. received = ::recv(cli, buf, sizeof(buf), 0);
  18545. });
  18546. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  18547. // connect() has already shut the socket down by the time it returns false,
  18548. // so the peer sees EOF without waiting for the client to be destroyed.
  18549. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  18550. {{"X-Bad", "a\r\nInjected: 1"}});
  18551. EXPECT_FALSE(client.connect());
  18552. t.join();
  18553. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  18554. EXPECT_EQ(0, received);
  18555. }
  18556. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  18557. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  18558. // contains "upgrade" as a substring is a different token and must not
  18559. // start a WebSocket handshake.
  18560. auto make_request = [](const std::vector<std::string> &connection_values) {
  18561. Request req;
  18562. req.method = "GET";
  18563. req.headers.emplace("Upgrade", "websocket");
  18564. for (const auto &value : connection_values) {
  18565. req.headers.emplace("Connection", value);
  18566. }
  18567. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18568. req.headers.emplace("Sec-WebSocket-Version", "13");
  18569. return req;
  18570. };
  18571. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  18572. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  18573. EXPECT_TRUE(
  18574. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  18575. EXPECT_TRUE(
  18576. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  18577. EXPECT_TRUE(
  18578. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  18579. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  18580. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  18581. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  18582. EXPECT_FALSE(
  18583. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  18584. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  18585. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18586. }
  18587. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  18588. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  18589. // asks recipients to match each protocol-name case-insensitively, and RFC
  18590. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  18591. // client naming websocket alongside another protocol, or on a second field
  18592. // line, is offering websocket; a value that merely contains "websocket" as a
  18593. // substring is a different protocol name and is not.
  18594. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  18595. Request req;
  18596. req.method = "GET";
  18597. for (const auto &value : upgrade_values) {
  18598. req.headers.emplace("Upgrade", value);
  18599. }
  18600. req.headers.emplace("Connection", "Upgrade");
  18601. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18602. req.headers.emplace("Sec-WebSocket-Version", "13");
  18603. return req;
  18604. };
  18605. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  18606. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  18607. EXPECT_TRUE(
  18608. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  18609. EXPECT_TRUE(
  18610. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  18611. EXPECT_TRUE(
  18612. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  18613. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  18614. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  18615. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  18616. EXPECT_FALSE(
  18617. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  18618. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  18619. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18620. }
  18621. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  18622. Server svr;
  18623. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  18624. auto port = svr.bind_to_any_port("localhost");
  18625. std::thread t([&]() { svr.listen_after_bind(); });
  18626. auto se = detail::scope_exit([&] {
  18627. svr.stop();
  18628. t.join();
  18629. });
  18630. svr.wait_until_ready();
  18631. Headers headers = {{"Upgrade", "websocket"},
  18632. {"Connection", "notupgrade"},
  18633. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  18634. {"Sec-WebSocket-Version", "13"}};
  18635. Client cli("localhost", port);
  18636. auto res = cli.Get("/ws", headers);
  18637. // The route exists only as a WebSocket route, so a request that fails the
  18638. // handshake check falls through to ordinary routing.
  18639. ASSERT_TRUE(res);
  18640. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  18641. }
  18642. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  18643. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  18644. // Connection value is the only thing left for the client to reject.
  18645. Server svr;
  18646. svr.Get("/ws", [](const Request &req, Response &res) {
  18647. res.status = StatusCode::SwitchingProtocol_101;
  18648. res.set_header("Upgrade", "websocket");
  18649. res.set_header("Connection", "notupgrade");
  18650. res.set_header("Sec-WebSocket-Accept",
  18651. detail::websocket_accept_key(
  18652. req.get_header_value("Sec-WebSocket-Key")));
  18653. });
  18654. auto port = svr.bind_to_any_port("localhost");
  18655. std::thread t([&]() { svr.listen_after_bind(); });
  18656. auto se = detail::scope_exit([&] {
  18657. svr.stop();
  18658. t.join();
  18659. });
  18660. svr.wait_until_ready();
  18661. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18662. auto res = client.connect();
  18663. EXPECT_FALSE(res);
  18664. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18665. EXPECT_FALSE(client.is_open());
  18666. }
  18667. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  18668. // The socket path doubles as the URL host, so it must not contain '/'.
  18669. const char *shard = getenv("GTEST_SHARD_INDEX");
  18670. const std::string sock_path =
  18671. shard ? std::string("httplib-ws-") + shard + ".sock"
  18672. : std::string("httplib-ws.sock");
  18673. std::remove(sock_path.c_str());
  18674. Server svr;
  18675. std::mutex mtx;
  18676. std::string received_host;
  18677. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18678. {
  18679. std::lock_guard<std::mutex> lock(mtx);
  18680. received_host = req.get_header_value("Host");
  18681. }
  18682. std::string msg;
  18683. while (ws.read(msg)) {
  18684. ws.send(msg);
  18685. }
  18686. });
  18687. svr.set_address_family(AF_UNIX);
  18688. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  18689. auto se = detail::scope_exit([&] {
  18690. svr.stop();
  18691. t.join();
  18692. std::remove(sock_path.c_str());
  18693. });
  18694. svr.wait_until_ready();
  18695. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  18696. client.set_address_family(AF_UNIX);
  18697. ASSERT_TRUE(client.connect());
  18698. ASSERT_TRUE(client.send("hello"));
  18699. std::string msg;
  18700. ASSERT_TRUE(client.read(msg));
  18701. client.close();
  18702. {
  18703. std::lock_guard<std::mutex> lock(mtx);
  18704. // There is no host:port for a Unix socket, so the same "localhost"
  18705. // placeholder the HTTP client uses is expected.
  18706. EXPECT_EQ("localhost", received_host);
  18707. }
  18708. }
  18709. // Two threads must never parse WebSocket frames from the same stream.
  18710. // close() used to read the peer's Close reply with its own frame read, so it
  18711. // raced a reader thread that was in the middle of a payload: the payload loop
  18712. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  18713. // so bytes taken by close() were replaced with bytes from further along the
  18714. // stream. The message kept its length and silently changed content.
  18715. //
  18716. // The raw peer below sends a frame header plus part of the payload, waits for
  18717. // the handler to call close(), and only then sends the rest. Whichever thread
  18718. // would win the race for those bytes, the message must arrive intact, because
  18719. // close() must not touch the stream while read() owns it.
  18720. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  18721. #ifndef _WIN32
  18722. signal(SIGPIPE, SIG_IGN);
  18723. #endif
  18724. const size_t payload_len = 120; // fits the 7-bit length field
  18725. const size_t prefix_len = 8;
  18726. const int attempts = 8;
  18727. std::string expected(payload_len, '\0');
  18728. for (size_t i = 0; i < payload_len; i++) {
  18729. expected[i] = static_cast<char>('a' + i % 26);
  18730. }
  18731. std::atomic<bool> peer_stalled{false};
  18732. std::atomic<bool> handler_done{false};
  18733. std::mutex received_mutex;
  18734. std::vector<std::string> received;
  18735. // Bound every wait, so a regression fails the test instead of hanging the
  18736. // suite.
  18737. auto wait_for = [](const std::atomic<bool> &flag) {
  18738. for (int i = 0; i < 500 && !flag; i++) {
  18739. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18740. }
  18741. };
  18742. Server svr;
  18743. svr.set_websocket_ping_interval(0);
  18744. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  18745. std::thread reader([&]() {
  18746. std::string msg;
  18747. while (ws.read(msg)) {
  18748. std::lock_guard<std::mutex> guard(received_mutex);
  18749. received.push_back(msg);
  18750. }
  18751. });
  18752. // Wait until the peer stalls mid-payload, so the reader thread is parked
  18753. // inside read_websocket_frame() when close() runs.
  18754. wait_for(peer_stalled);
  18755. ws.close();
  18756. reader.join();
  18757. handler_done = true;
  18758. });
  18759. auto port = svr.bind_to_any_port("127.0.0.1");
  18760. std::thread t([&]() { svr.listen_after_bind(); });
  18761. auto se = detail::scope_exit([&] {
  18762. svr.stop();
  18763. t.join();
  18764. });
  18765. svr.wait_until_ready();
  18766. auto send_bytes = [](socket_t s, const std::string &data) {
  18767. #ifdef _WIN32
  18768. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  18769. #else
  18770. auto n = ::send(s, data.data(), data.size(), 0);
  18771. #endif
  18772. return n == static_cast<decltype(n)>(data.size());
  18773. };
  18774. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  18775. // Every length used here fits the 7-bit length field.
  18776. auto masked_header = [](uint8_t first_byte, size_t len) {
  18777. std::string h;
  18778. h += static_cast<char>(first_byte);
  18779. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  18780. h.append(4, '\0'); // mask key
  18781. return h;
  18782. };
  18783. for (int attempt = 0; attempt < attempts; attempt++) {
  18784. peer_stalled = false;
  18785. handler_done = false;
  18786. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  18787. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  18788. auto se_sock = detail::scope_exit([&] {
  18789. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  18790. });
  18791. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18792. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18793. sockaddr_in addr{};
  18794. addr.sin_family = AF_INET;
  18795. addr.sin_port = htons(static_cast<uint16_t>(port));
  18796. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18797. ASSERT_EQ(
  18798. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  18799. << "attempt " << attempt;
  18800. ASSERT_TRUE(send_bytes(sock,
  18801. "GET /ws HTTP/1.1\r\n"
  18802. "Host: 127.0.0.1\r\n"
  18803. "Upgrade: websocket\r\n"
  18804. "Connection: Upgrade\r\n"
  18805. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  18806. "Sec-WebSocket-Version: 13\r\n"
  18807. "\r\n"))
  18808. << "attempt " << attempt;
  18809. std::string response;
  18810. while (response.find("\r\n\r\n") == std::string::npos) {
  18811. char buf[512];
  18812. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  18813. if (n <= 0) { break; }
  18814. response.append(buf, static_cast<size_t>(n));
  18815. }
  18816. ASSERT_NE(std::string::npos, response.find(" 101 "))
  18817. << "attempt " << attempt;
  18818. // Send the header of a Binary message but only the first prefix_len bytes
  18819. // of its payload, leaving the reader thread stalled inside the payload.
  18820. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  18821. expected.substr(0, prefix_len)))
  18822. << "attempt " << attempt;
  18823. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18824. peer_stalled = true;
  18825. // Let close() send its Close frame and park in its own read before the
  18826. // rest of the payload arrives, so both threads are waiting for it.
  18827. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18828. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  18829. close_frame += static_cast<char>(0x03); // status 1000
  18830. close_frame += static_cast<char>(0xE8);
  18831. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  18832. << "attempt " << attempt;
  18833. // Closing the peer releases the reader thread even on the buggy path,
  18834. // where it waits for bytes another thread already consumed.
  18835. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18836. detail::close_socket(sock);
  18837. sock = INVALID_SOCKET;
  18838. wait_for(handler_done);
  18839. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  18840. }
  18841. std::lock_guard<std::mutex> guard(received_mutex);
  18842. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  18843. << "a message in flight when close() ran was dropped";
  18844. for (size_t i = 0; i < received.size(); i++) {
  18845. EXPECT_EQ(expected, received[i]) << "message " << i;
  18846. }
  18847. }
  18848. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18849. class WebSocketSSLIntegrationTest : public ::testing::Test {
  18850. protected:
  18851. void SetUp() override {
  18852. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  18853. SERVER_PRIVATE_KEY_FILE);
  18854. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18855. std::string msg;
  18856. ws::ReadResult ret;
  18857. while ((ret = ws.read(msg))) {
  18858. if (ret == ws::Binary) {
  18859. ws.send(msg.data(), msg.size());
  18860. } else {
  18861. ws.send(msg);
  18862. }
  18863. }
  18864. });
  18865. port_ = server_->bind_to_any_port(HOST);
  18866. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18867. server_->wait_until_ready();
  18868. }
  18869. void TearDown() override {
  18870. server_->stop();
  18871. if (server_thread_.joinable()) { server_thread_.join(); }
  18872. }
  18873. std::unique_ptr<SSLServer> server_;
  18874. std::thread server_thread_;
  18875. int port_ = 0;
  18876. };
  18877. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  18878. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18879. "/ws-echo");
  18880. client.enable_server_certificate_verification(false);
  18881. ASSERT_TRUE(client.connect());
  18882. ASSERT_TRUE(client.is_open());
  18883. ASSERT_TRUE(client.send("Hello WSS"));
  18884. std::string msg;
  18885. EXPECT_EQ(ws::Text, client.read(msg));
  18886. EXPECT_EQ("Hello WSS", msg);
  18887. client.close();
  18888. }
  18889. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  18890. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  18891. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  18892. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  18893. // client (without calling close() first) is the only path that runs
  18894. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  18895. // bug exactly.
  18896. //
  18897. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  18898. // when linked against an instrumented libssl; run under Valgrind to catch it
  18899. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  18900. // suite (the freed session otherwise stalls on the close handshake) — this test
  18901. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  18902. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  18903. {
  18904. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18905. "/ws-echo");
  18906. client.enable_server_certificate_verification(false);
  18907. client.set_read_timeout(2, 0);
  18908. client.set_write_timeout(2, 0);
  18909. ASSERT_TRUE(client.connect());
  18910. ASSERT_TRUE(client.is_open());
  18911. ASSERT_TRUE(client.send("still open"));
  18912. // Intentionally do NOT call client.close(): leaving scope runs
  18913. // shutdown_and_close() with the WebSocket still open, which must send the
  18914. // close frame while the TLS session is still alive.
  18915. }
  18916. }
  18917. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  18918. // shutdown_and_close() at the start of connect(), reproducing the same
  18919. // use-after-free within the test body rather than at scope exit. The second
  18920. // connect must succeed and echo, proving the close handshake ran over a live
  18921. // session. See the note above about memory-tool requirements.
  18922. TEST_F(WebSocketSSLIntegrationTest,
  18923. ReconnectWhileOpenSendsCloseOverLiveSession) {
  18924. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18925. "/ws-echo");
  18926. client.enable_server_certificate_verification(false);
  18927. client.set_read_timeout(2, 0);
  18928. client.set_write_timeout(2, 0);
  18929. ASSERT_TRUE(client.connect());
  18930. ASSERT_TRUE(client.is_open());
  18931. ASSERT_TRUE(client.send("still open"));
  18932. // Reconnect without closing first: connect() calls shutdown_and_close() on
  18933. // the still-open connection, which must not touch a freed TLS session.
  18934. ASSERT_TRUE(client.connect());
  18935. ASSERT_TRUE(client.is_open());
  18936. ASSERT_TRUE(client.send("after reconnect"));
  18937. std::string msg;
  18938. EXPECT_EQ(ws::Text, client.read(msg));
  18939. EXPECT_EQ("after reconnect", msg);
  18940. client.close();
  18941. }
  18942. #endif
  18943. #ifdef CPPHTTPLIB_SSL_ENABLED
  18944. class WebSocketSSLCATest : public ::testing::Test {
  18945. protected:
  18946. void SetUp() override {
  18947. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  18948. SERVER_PRIVATE_KEY_FILE);
  18949. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18950. std::string msg;
  18951. while (ws.read(msg)) {
  18952. ws.send(msg);
  18953. }
  18954. });
  18955. port_ = server_->bind_to_any_port("127.0.0.1");
  18956. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18957. server_->wait_until_ready();
  18958. }
  18959. void TearDown() override {
  18960. server_->stop();
  18961. if (server_thread_.joinable()) { server_thread_.join(); }
  18962. }
  18963. std::string url() const {
  18964. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  18965. }
  18966. std::unique_ptr<SSLServer> server_;
  18967. std::thread server_thread_;
  18968. int port_ = 0;
  18969. };
  18970. // A custom CA loaded as PEM verifies the server with full certificate
  18971. // verification enabled
  18972. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  18973. ws::WebSocketClient client(url());
  18974. std::string cert;
  18975. read_file(SERVER_CERT2_FILE, cert);
  18976. client.load_ca_cert_store(cert.c_str(), cert.size());
  18977. ASSERT_TRUE(client.connect());
  18978. ASSERT_TRUE(client.send("hello"));
  18979. std::string msg;
  18980. EXPECT_EQ(ws::Text, client.read(msg));
  18981. EXPECT_EQ("hello", msg);
  18982. client.close();
  18983. }
  18984. // A custom CA that does not cover the server must fail verification (the
  18985. // custom CA is exclusive; system certs are not loaded alongside it)
  18986. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  18987. ws::WebSocketClient client(url());
  18988. std::string cert;
  18989. read_file(CLIENT_CA_CERT_FILE, cert);
  18990. client.load_ca_cert_store(cert.c_str(), cert.size());
  18991. auto res = client.connect();
  18992. ASSERT_FALSE(res);
  18993. EXPECT_EQ(Error::SSLServerVerification, res.error());
  18994. EXPECT_EQ(-1, res.status());
  18995. EXPECT_NE(0u, res.ssl_backend_error());
  18996. }
  18997. // The same CA as a file path rather than PEM in memory
  18998. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  18999. ws::WebSocketClient client(url());
  19000. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19001. ASSERT_TRUE(client.connect());
  19002. ASSERT_TRUE(client.send("hello"));
  19003. std::string msg;
  19004. EXPECT_EQ(ws::Text, client.read(msg));
  19005. EXPECT_EQ("hello", msg);
  19006. client.close();
  19007. }
  19008. // ...and a CA file that does not cover the server still fails, so it is the
  19009. // path above that decides the outcome
  19010. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  19011. ws::WebSocketClient client(url());
  19012. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19013. ASSERT_FALSE(client.connect());
  19014. }
  19015. // Regression test: reconnecting with a native custom CA store used to reuse
  19016. // a store handle the previous TLS context had already freed (use-after-free
  19017. // under the OpenSSL backend). The context now lives as long as the client.
  19018. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  19019. ws::WebSocketClient client(url());
  19020. std::string cert;
  19021. read_file(SERVER_CERT2_FILE, cert);
  19022. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  19023. ASSERT_TRUE(client.connect());
  19024. client.close();
  19025. ASSERT_TRUE(client.connect());
  19026. ASSERT_TRUE(client.send("again"));
  19027. std::string msg;
  19028. EXPECT_EQ(ws::Text, client.read(msg));
  19029. EXPECT_EQ("again", msg);
  19030. client.close();
  19031. }
  19032. // Regression test: a certificate with a trusted chain but no identity match
  19033. // for the server IP must be rejected. The Mbed TLS backend used to skip
  19034. // verification entirely for IP hosts, so this connection succeeded there.
  19035. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  19036. // chain verification while the identity check must still fail.
  19037. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  19038. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19039. ASSERT_TRUE(svr.is_valid());
  19040. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19041. std::string msg;
  19042. while (ws.read(msg)) {
  19043. ws.send(msg);
  19044. }
  19045. });
  19046. auto port = svr.bind_to_any_port("127.0.0.1");
  19047. auto t = std::thread([&]() { svr.listen_after_bind(); });
  19048. auto se = detail::scope_exit([&] {
  19049. svr.stop();
  19050. t.join();
  19051. });
  19052. svr.wait_until_ready();
  19053. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  19054. "/echo");
  19055. std::string cert;
  19056. read_file(SERVER_CERT_FILE, cert);
  19057. client.load_ca_cert_store(cert.c_str(), cert.size());
  19058. ASSERT_FALSE(client.connect());
  19059. }
  19060. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  19061. // SNI, so nothing binds the host name to the TLS session. These bind the
  19062. // server to "localhost" instead, the only shape that exercises the SNI and
  19063. // hostname-verification path with certificate verification left enabled.
  19064. class WebSocketSSLDnsHostTest : public ::testing::Test {
  19065. protected:
  19066. void Start(const char *cert_file) {
  19067. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  19068. SERVER_PRIVATE_KEY_FILE);
  19069. ASSERT_TRUE(server_->is_valid());
  19070. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19071. std::string msg;
  19072. while (ws.read(msg)) {
  19073. ws.send(msg);
  19074. }
  19075. });
  19076. port_ = server_->bind_to_any_port("localhost");
  19077. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19078. server_->wait_until_ready();
  19079. }
  19080. void TearDown() override {
  19081. if (server_) { server_->stop(); }
  19082. if (server_thread_.joinable()) { server_thread_.join(); }
  19083. }
  19084. std::string url() const {
  19085. return "wss://localhost:" + std::to_string(port_) + "/echo";
  19086. }
  19087. std::unique_ptr<SSLServer> server_;
  19088. std::thread server_thread_;
  19089. int port_ = 0;
  19090. };
  19091. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  19092. // out and the connection is usable
  19093. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  19094. Start(SERVER_CERT2_FILE);
  19095. ws::WebSocketClient client(url());
  19096. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19097. ASSERT_TRUE(client.connect());
  19098. ASSERT_TRUE(client.send("hello"));
  19099. std::string msg;
  19100. EXPECT_EQ(ws::Text, client.read(msg));
  19101. EXPECT_EQ("hello", msg);
  19102. client.close();
  19103. }
  19104. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  19105. // while the identity check must still reject "localhost"
  19106. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  19107. Start(SERVER_CERT_FILE);
  19108. ws::WebSocketClient client(url());
  19109. client.set_ca_cert_path(SERVER_CERT_FILE);
  19110. auto res = client.connect();
  19111. ASSERT_FALSE(res);
  19112. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  19113. EXPECT_EQ(-1, res.status());
  19114. }
  19115. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  19116. // disabled: the chain is still checked, only the identity check is skipped
  19117. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  19118. Start(SERVER_CERT_FILE);
  19119. ws::WebSocketClient client(url());
  19120. client.set_ca_cert_path(SERVER_CERT_FILE);
  19121. client.enable_server_hostname_verification(false);
  19122. ASSERT_TRUE(client.connect());
  19123. ASSERT_TRUE(client.send("hello"));
  19124. std::string msg;
  19125. EXPECT_EQ(ws::Text, client.read(msg));
  19126. EXPECT_EQ("hello", msg);
  19127. client.close();
  19128. }
  19129. // A CA that did not sign the server certificate fails the chain, even though
  19130. // the name would match
  19131. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  19132. Start(SERVER_CERT2_FILE);
  19133. ws::WebSocketClient client(url());
  19134. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19135. ASSERT_FALSE(client.connect());
  19136. }
  19137. // With verification disabled, neither the chain nor the name is checked
  19138. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  19139. Start(SERVER_CERT_FILE);
  19140. ws::WebSocketClient client(url());
  19141. client.enable_server_certificate_verification(false);
  19142. ASSERT_TRUE(client.connect());
  19143. ASSERT_TRUE(client.send("hello"));
  19144. std::string msg;
  19145. EXPECT_EQ(ws::Text, client.read(msg));
  19146. EXPECT_EQ("hello", msg);
  19147. client.close();
  19148. }
  19149. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  19150. protected:
  19151. void SetUp() override {
  19152. server_ = httplib::detail::make_unique<SSLServer>(
  19153. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19154. ASSERT_TRUE(server_->is_valid());
  19155. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19156. std::string msg;
  19157. while (ws.read(msg)) {
  19158. ws.send(msg);
  19159. }
  19160. });
  19161. port_ = server_->bind_to_any_port("localhost");
  19162. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19163. server_->wait_until_ready();
  19164. }
  19165. void TearDown() override {
  19166. server_->stop();
  19167. if (server_thread_.joinable()) { server_thread_.join(); }
  19168. }
  19169. std::string url() const {
  19170. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  19171. }
  19172. void ConnectWithClientCert(const std::string &client_cert_file,
  19173. const std::string &client_private_key_file,
  19174. const char *private_key_password) {
  19175. std::string cert_pem, key_pem;
  19176. read_file(client_cert_file, cert_pem);
  19177. read_file(client_private_key_file, key_pem);
  19178. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  19179. key_pem.c_str(), key_pem.size(),
  19180. private_key_password};
  19181. ws::WebSocketClient client(url(), pem);
  19182. ASSERT_TRUE(client.is_valid());
  19183. client.enable_server_certificate_verification(false);
  19184. ASSERT_TRUE(client.connect());
  19185. ASSERT_TRUE(client.send("hello"));
  19186. std::string msg;
  19187. EXPECT_EQ(ws::Text, client.read(msg));
  19188. EXPECT_EQ("hello", msg);
  19189. client.close();
  19190. }
  19191. std::unique_ptr<SSLServer> server_;
  19192. std::thread server_thread_;
  19193. int port_ = 0;
  19194. };
  19195. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  19196. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  19197. }
  19198. // Control for the tests above: the fixture's server really does require a
  19199. // client certificate, so it is the PEM the constructor installed that decides
  19200. // the outcome.
  19201. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  19202. ws::WebSocketClient client(url());
  19203. ASSERT_TRUE(client.is_valid());
  19204. client.enable_server_certificate_verification(false);
  19205. EXPECT_FALSE(client.connect());
  19206. }
  19207. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  19208. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  19209. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  19210. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  19211. }
  19212. #endif
  19213. #if !defined(_WIN32)
  19214. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  19215. auto secret_dir = std::string("./symlink_test_secret");
  19216. auto served_dir = std::string("./symlink_test_served");
  19217. auto secret_file = secret_dir + "/secret.txt";
  19218. auto symlink_path = served_dir + "/escape";
  19219. // Setup: create directories and files
  19220. mkdir(secret_dir.c_str(), 0755);
  19221. mkdir(served_dir.c_str(), 0755);
  19222. {
  19223. std::ofstream ofs(secret_file);
  19224. ofs << "SECRET_DATA";
  19225. }
  19226. // Create symlink using absolute path so it resolves correctly
  19227. #ifdef PATH_MAX
  19228. char abs_secret[PATH_MAX];
  19229. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  19230. #else
  19231. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  19232. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  19233. ASSERT_NE(nullptr, abs_secret);
  19234. #endif
  19235. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  19236. auto se = detail::scope_exit([&] {
  19237. unlink(symlink_path.c_str());
  19238. unlink(secret_file.c_str());
  19239. rmdir(served_dir.c_str());
  19240. rmdir(secret_dir.c_str());
  19241. });
  19242. Server svr;
  19243. svr.set_mount_point("/", served_dir);
  19244. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19245. auto se2 = detail::scope_exit([&] {
  19246. svr.stop();
  19247. listen_thread.join();
  19248. });
  19249. svr.wait_until_ready();
  19250. Client cli("localhost", PORT);
  19251. // Symlink pointing outside base dir should be blocked
  19252. auto res = cli.Get("/escape/secret.txt");
  19253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19254. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19255. }
  19256. #endif
  19257. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  19258. // A GET request with Content-Length to a static file handler must have its
  19259. // body drained before the keep-alive connection is reused. Otherwise the
  19260. // unread body bytes are interpreted as the next HTTP request.
  19261. //
  19262. // The body is sent AFTER receiving the first response (as in the original
  19263. // PoC) so that the stream_line_reader cannot buffer it together with the
  19264. // headers of the first request.
  19265. Server svr;
  19266. svr.set_mount_point("/", "./www");
  19267. std::atomic<int> smuggled_count(0);
  19268. svr.Get("/smuggled", [&](const Request &, Response &res) {
  19269. smuggled_count++;
  19270. res.set_content("oops", "text/plain");
  19271. });
  19272. auto port = svr.bind_to_any_port("localhost");
  19273. thread t = thread([&] { svr.listen_after_bind(); });
  19274. auto se = detail::scope_exit([&] {
  19275. svr.stop();
  19276. t.join();
  19277. });
  19278. svr.wait_until_ready();
  19279. auto error = Error::Success;
  19280. auto sock = detail::create_client_socket(
  19281. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  19282. /*connection_timeout_sec=*/2, 0,
  19283. /*read_timeout_sec=*/2, 0,
  19284. /*write_timeout_sec=*/2, 0, std::string(), error);
  19285. ASSERT_NE(INVALID_SOCKET, sock);
  19286. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19287. // The "smuggled" request will be sent as the body of the outer GET
  19288. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  19289. "Host: localhost\r\n"
  19290. "Connection: close\r\n"
  19291. "\r\n";
  19292. // Step 1: Send only the outer request headers (no body yet)
  19293. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  19294. "Host: localhost\r\n"
  19295. "Content-Length: " +
  19296. std::to_string(smuggled.size()) +
  19297. "\r\n"
  19298. "\r\n";
  19299. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  19300. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  19301. // Step 2: Read the first response (server serves file without reading body)
  19302. std::string first_response;
  19303. char buf[4096];
  19304. for (;;) {
  19305. auto n = recv(sock, buf, sizeof(buf), 0);
  19306. if (n <= 0) break;
  19307. first_response.append(buf, static_cast<size_t>(n));
  19308. // Stop once we have a complete response (headers + body)
  19309. auto hdr_end = first_response.find("\r\n\r\n");
  19310. if (hdr_end != std::string::npos) {
  19311. // Check for Content-Length to know when the body is complete
  19312. auto cl_pos = first_response.find("Content-Length:");
  19313. if (cl_pos != std::string::npos) {
  19314. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  19315. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  19316. auto cl = std::stoul(
  19317. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  19318. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  19319. } else {
  19320. break; // No Content-Length, assume headers-only response
  19321. }
  19322. }
  19323. }
  19324. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  19325. // Step 3: Now send the body, which looks like a new HTTP request.
  19326. // On a vulnerable server the keep-alive loop reads this as a second request.
  19327. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  19328. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  19329. // Step 4: Try to read a second response (should NOT exist after fix)
  19330. std::string second_response;
  19331. for (;;) {
  19332. auto n = recv(sock, buf, sizeof(buf), 0);
  19333. if (n <= 0) break;
  19334. second_response.append(buf, static_cast<size_t>(n));
  19335. }
  19336. // The smuggled request must NOT have been processed
  19337. EXPECT_EQ(0, smuggled_count.load());
  19338. }
  19339. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19340. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  19341. // must be rejected with 400 Bad Request.
  19342. Server svr;
  19343. svr.Post("/test", [&](const Request &, Response &res) {
  19344. res.set_content("ok", "text/plain");
  19345. });
  19346. thread t = thread([&] { svr.listen(HOST, PORT); });
  19347. auto se = detail::scope_exit([&] {
  19348. svr.stop();
  19349. t.join();
  19350. ASSERT_FALSE(svr.is_running());
  19351. });
  19352. svr.wait_until_ready();
  19353. // Exact "chunked"
  19354. {
  19355. auto req = "POST /test HTTP/1.1\r\n"
  19356. "Host: localhost\r\n"
  19357. "Content-Length: 5\r\n"
  19358. "Transfer-Encoding: chunked\r\n"
  19359. "Connection: close\r\n"
  19360. "\r\n"
  19361. "hello";
  19362. std::string response;
  19363. ASSERT_TRUE(send_request(1, req, &response));
  19364. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19365. response.substr(0, response.find("\r\n")));
  19366. }
  19367. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  19368. {
  19369. auto req = "POST /test HTTP/1.1\r\n"
  19370. "Host: localhost\r\n"
  19371. "Content-Length: 5\r\n"
  19372. "Transfer-Encoding: gzip, chunked\r\n"
  19373. "Connection: close\r\n"
  19374. "\r\n"
  19375. "hello";
  19376. std::string response;
  19377. ASSERT_TRUE(send_request(1, req, &response));
  19378. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19379. response.substr(0, response.find("\r\n")));
  19380. }
  19381. }
  19382. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  19383. Server svr;
  19384. svr.Post("/test", [&](const Request &, Response &res) {
  19385. res.set_content("ok", "text/plain");
  19386. });
  19387. thread t = thread([&] { svr.listen(HOST, PORT); });
  19388. auto se = detail::scope_exit([&] {
  19389. svr.stop();
  19390. t.join();
  19391. ASSERT_FALSE(svr.is_running());
  19392. });
  19393. svr.wait_until_ready();
  19394. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  19395. // length cannot be determined, so the server must answer 400 and close
  19396. // rather than treat the request as bodyless and leave the body in the
  19397. // socket for the next request to pick up.
  19398. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  19399. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  19400. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  19401. std::string response;
  19402. ASSERT_TRUE(send_request(1, req, &response));
  19403. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19404. response.substr(0, response.find("\r\n")))
  19405. << transfer_encoding;
  19406. }
  19407. // RFC 9110 5.3: the codings may also be split across several
  19408. // Transfer-Encoding lines, which combine in the order they were received.
  19409. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  19410. // just like the single-line "chunked, gzip" above.
  19411. {
  19412. auto req = "POST /test HTTP/1.1\r\n"
  19413. "Host: localhost\r\n"
  19414. "Transfer-Encoding: chunked\r\n"
  19415. "Transfer-Encoding: gzip\r\n"
  19416. "\r\n"
  19417. "0\r\n\r\n";
  19418. std::string response;
  19419. ASSERT_TRUE(send_request(1, req, &response));
  19420. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19421. response.substr(0, response.find("\r\n")));
  19422. }
  19423. // A sequence ending in chunked stays valid.
  19424. auto req = "POST /test HTTP/1.1\r\n"
  19425. "Host: localhost\r\n"
  19426. "Transfer-Encoding: gzip, chunked\r\n"
  19427. "Connection: close\r\n"
  19428. "\r\n"
  19429. "0\r\n\r\n";
  19430. std::string response;
  19431. ASSERT_TRUE(send_request(1, req, &response));
  19432. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19433. // ...including when it is spread over several lines.
  19434. auto split_req = "POST /test HTTP/1.1\r\n"
  19435. "Host: localhost\r\n"
  19436. "Transfer-Encoding: gzip\r\n"
  19437. "Transfer-Encoding: chunked\r\n"
  19438. "Connection: close\r\n"
  19439. "\r\n"
  19440. "0\r\n\r\n";
  19441. std::string split_response;
  19442. ASSERT_TRUE(send_request(1, split_req, &split_response));
  19443. EXPECT_EQ("HTTP/1.1 200 OK",
  19444. split_response.substr(0, split_response.find("\r\n")));
  19445. }
  19446. // Regression for issue #2450: a DELETE without Content-Length on a
  19447. // keep-alive connection must not let the post-response drain consume the
  19448. // next request's bytes.
  19449. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  19450. Server svr;
  19451. std::atomic<int> delete_count(0);
  19452. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  19453. delete_count++;
  19454. res.status = StatusCode::NoContent_204;
  19455. });
  19456. auto port = svr.bind_to_any_port(HOST);
  19457. thread t = thread([&] { svr.listen_after_bind(); });
  19458. auto se = detail::scope_exit([&] {
  19459. svr.stop();
  19460. t.join();
  19461. });
  19462. svr.wait_until_ready();
  19463. auto error = Error::Success;
  19464. auto sock = detail::create_client_socket(
  19465. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19466. /*connection_timeout_sec=*/2, 0,
  19467. /*read_timeout_sec=*/2, 0,
  19468. /*write_timeout_sec=*/2, 0, std::string(), error);
  19469. ASSERT_NE(INVALID_SOCKET, sock);
  19470. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19471. auto send_request_and_read_response = [&](const std::string &req,
  19472. std::string &out) -> bool {
  19473. auto sent = send(sock, req.data(), req.size(), 0);
  19474. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  19475. char buf[4096];
  19476. for (;;) {
  19477. auto n = recv(sock, buf, sizeof(buf), 0);
  19478. if (n <= 0) { return !out.empty(); }
  19479. out.append(buf, static_cast<size_t>(n));
  19480. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  19481. }
  19482. };
  19483. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  19484. "Host: localhost\r\n"
  19485. "\r\n";
  19486. std::string resp1;
  19487. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  19488. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  19489. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  19490. "Host: localhost\r\n"
  19491. "Connection: close\r\n"
  19492. "\r\n";
  19493. std::string resp2;
  19494. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  19495. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  19496. EXPECT_EQ(2, delete_count.load());
  19497. }
  19498. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  19499. Server svr;
  19500. svr.Post("/ingest", [&](const Request &, Response &res,
  19501. const ContentReader &content_reader) {
  19502. auto consumed = content_reader([](const char *, size_t) { return false; });
  19503. EXPECT_FALSE(consumed);
  19504. res.status = StatusCode::Conflict_409;
  19505. res.set_header("Connection", "close");
  19506. });
  19507. auto port = svr.bind_to_any_port(HOST);
  19508. thread t = thread([&] { svr.listen_after_bind(); });
  19509. auto se = detail::scope_exit([&] {
  19510. svr.stop();
  19511. t.join();
  19512. });
  19513. svr.wait_until_ready();
  19514. auto error = Error::Success;
  19515. auto sock = detail::create_client_socket(
  19516. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19517. /*connection_timeout_sec=*/2, 0,
  19518. /*read_timeout_sec=*/1, 0,
  19519. /*write_timeout_sec=*/2, 0, std::string(), error);
  19520. ASSERT_NE(INVALID_SOCKET, sock);
  19521. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19522. std::string request = "POST /ingest HTTP/1.1\r\n"
  19523. "Host: localhost\r\n"
  19524. "Transfer-Encoding: chunked\r\n"
  19525. "\r\n"
  19526. "4\r\n"
  19527. "data\r\n";
  19528. auto sent = send(sock, request.data(), request.size(), 0);
  19529. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  19530. std::string response;
  19531. ssize_t received = 0;
  19532. do {
  19533. char buf[4096];
  19534. received = recv(sock, buf, sizeof(buf), 0);
  19535. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  19536. } while (received > 0);
  19537. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  19538. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  19539. EXPECT_EQ(0, received);
  19540. }
  19541. namespace no_proxy_test {
  19542. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  19543. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  19544. // calling listen().
  19545. class ScopedServer {
  19546. public:
  19547. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  19548. ~ScopedServer() {
  19549. svr_.stop();
  19550. if (th_.joinable()) { th_.join(); }
  19551. }
  19552. Server &svr() { return svr_; }
  19553. int port() const { return port_; }
  19554. void listen() {
  19555. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19556. svr_.wait_until_ready();
  19557. }
  19558. private:
  19559. Server svr_;
  19560. std::thread th_;
  19561. int port_ = 0;
  19562. };
  19563. class ProxyAndTargetServers {
  19564. public:
  19565. ProxyAndTargetServers() {
  19566. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  19567. proxy_hits_++;
  19568. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19569. res.set_content("via-proxy", "text/plain");
  19570. });
  19571. target_.Get(".*", [this](const Request &req, Response &res) {
  19572. target_hits_++;
  19573. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19574. res.set_content("direct", "text/plain");
  19575. });
  19576. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  19577. target_port_ = target_.bind_to_any_port("127.0.0.1");
  19578. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  19579. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  19580. proxy_mock_.wait_until_ready();
  19581. target_.wait_until_ready();
  19582. }
  19583. ~ProxyAndTargetServers() {
  19584. proxy_mock_.stop();
  19585. target_.stop();
  19586. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  19587. if (target_thread_.joinable()) { target_thread_.join(); }
  19588. }
  19589. Server &proxy_mock() { return proxy_mock_; }
  19590. Server &target() { return target_; }
  19591. int proxy_port() const { return proxy_port_; }
  19592. int target_port() const { return target_port_; }
  19593. int proxy_hits() const { return proxy_hits_.load(); }
  19594. int target_hits() const { return target_hits_.load(); }
  19595. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  19596. void reset_counters() {
  19597. proxy_hits_ = 0;
  19598. target_hits_ = 0;
  19599. last_had_proxy_authz_ = false;
  19600. }
  19601. private:
  19602. Server proxy_mock_;
  19603. Server target_;
  19604. std::thread proxy_thread_;
  19605. std::thread target_thread_;
  19606. int proxy_port_ = 0;
  19607. int target_port_ = 0;
  19608. std::atomic<int> proxy_hits_{0};
  19609. std::atomic<int> target_hits_{0};
  19610. std::atomic<bool> last_had_proxy_authz_{false};
  19611. };
  19612. inline std::unique_ptr<Client> make_client(const std::string &host,
  19613. ProxyAndTargetServers &s) {
  19614. auto cli = detail::make_unique<Client>(host, s.target_port());
  19615. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  19616. cli->set_proxy("127.0.0.1", s.proxy_port());
  19617. return cli;
  19618. }
  19619. } // namespace no_proxy_test
  19620. using no_proxy_test::make_client;
  19621. using no_proxy_test::ProxyAndTargetServers;
  19622. TEST(NoProxyTest, ExactHostnameBypasses) {
  19623. ProxyAndTargetServers s;
  19624. auto cli = make_client("example.com", s);
  19625. cli->set_no_proxy({"example.com"});
  19626. auto res = cli->Get("/");
  19627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19628. EXPECT_EQ(0, s.proxy_hits());
  19629. EXPECT_EQ(1, s.target_hits());
  19630. }
  19631. TEST(NoProxyTest, SubdomainBypasses) {
  19632. ProxyAndTargetServers s;
  19633. auto cli = make_client("foo.example.com", s);
  19634. cli->set_no_proxy({"example.com"});
  19635. auto res = cli->Get("/");
  19636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19637. EXPECT_EQ(0, s.proxy_hits());
  19638. EXPECT_EQ(1, s.target_hits());
  19639. }
  19640. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  19641. // Regression guard: "evilexample.com" must not be considered a subdomain
  19642. // of "example.com". Without the dot-boundary rule, a naive endsWith
  19643. // check would let traffic bypass the proxy and leak credentials direct
  19644. // to the attacker host.
  19645. ProxyAndTargetServers s;
  19646. auto cli = make_client("evilexample.com", s);
  19647. cli->set_no_proxy({"example.com"});
  19648. auto res = cli->Get("/");
  19649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19650. EXPECT_GE(s.proxy_hits(), 1);
  19651. EXPECT_EQ(0, s.target_hits());
  19652. }
  19653. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  19654. ProxyAndTargetServers s;
  19655. auto cli = make_client("example.com.evil.com", s);
  19656. cli->set_no_proxy({"example.com"});
  19657. auto res = cli->Get("/");
  19658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19659. EXPECT_GE(s.proxy_hits(), 1);
  19660. EXPECT_EQ(0, s.target_hits());
  19661. }
  19662. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  19663. ProxyAndTargetServers s;
  19664. auto cli = make_client("example.com", s);
  19665. cli->set_no_proxy({".example.com"});
  19666. auto res = cli->Get("/");
  19667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19668. EXPECT_EQ(0, s.proxy_hits());
  19669. EXPECT_EQ(1, s.target_hits());
  19670. }
  19671. TEST(NoProxyTest, CaseInsensitiveHostname) {
  19672. ProxyAndTargetServers s;
  19673. auto cli = make_client("Example.COM", s);
  19674. cli->set_no_proxy({"EXAMPLE.com"});
  19675. auto res = cli->Get("/");
  19676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19677. EXPECT_EQ(0, s.proxy_hits());
  19678. EXPECT_EQ(1, s.target_hits());
  19679. }
  19680. TEST(NoProxyTest, TrailingDotIsNormalized) {
  19681. ProxyAndTargetServers s;
  19682. auto cli = make_client("example.com.", s);
  19683. cli->set_no_proxy({"example.com"});
  19684. auto res = cli->Get("/");
  19685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19686. EXPECT_EQ(0, s.proxy_hits());
  19687. EXPECT_EQ(1, s.target_hits());
  19688. }
  19689. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  19690. // Trailing dots must be normalized on BOTH sides — host and entry.
  19691. // An implementation that only strips the host-side trailing dot would
  19692. // fail to match host "example.com" against entry "example.com." because
  19693. // a literal substring search would compare 11 chars against 12.
  19694. ProxyAndTargetServers s;
  19695. auto cli = make_client("example.com", s);
  19696. cli->set_no_proxy({"example.com."});
  19697. auto res = cli->Get("/");
  19698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19699. EXPECT_EQ(0, s.proxy_hits());
  19700. EXPECT_EQ(1, s.target_hits());
  19701. }
  19702. TEST(NoProxyTest, WildcardBypassesEverything) {
  19703. ProxyAndTargetServers s;
  19704. auto cli = make_client("anything.invalid.test", s);
  19705. cli->set_no_proxy({"*"});
  19706. auto res = cli->Get("/");
  19707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19708. EXPECT_EQ(0, s.proxy_hits());
  19709. EXPECT_EQ(1, s.target_hits());
  19710. }
  19711. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  19712. ProxyAndTargetServers s;
  19713. Client cli("127.0.0.1", s.target_port());
  19714. cli.set_proxy("127.0.0.1", s.proxy_port());
  19715. cli.set_no_proxy({"127.0.0.1"});
  19716. auto res = cli.Get("/");
  19717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19718. EXPECT_EQ(0, s.proxy_hits());
  19719. EXPECT_EQ(1, s.target_hits());
  19720. }
  19721. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  19722. ProxyAndTargetServers s;
  19723. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  19724. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  19725. cli.set_proxy("127.0.0.1", s.proxy_port());
  19726. cli.set_no_proxy({"::1"});
  19727. auto res = cli.Get("/");
  19728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19729. EXPECT_EQ(0, s.proxy_hits());
  19730. EXPECT_EQ(1, s.target_hits());
  19731. }
  19732. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  19733. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  19734. // must still be recognized as IPv6 for CIDR matching. Implementations
  19735. // that detect IPv6 only when the host begins with '[' would parse the
  19736. // host as a hostname and miss the match.
  19737. ProxyAndTargetServers s;
  19738. Client cli("fe80::1", s.target_port());
  19739. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19740. cli.set_proxy("127.0.0.1", s.proxy_port());
  19741. cli.set_no_proxy({"fe80::/10"});
  19742. auto res = cli.Get("/");
  19743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19744. EXPECT_EQ(0, s.proxy_hits());
  19745. EXPECT_EQ(1, s.target_hits());
  19746. }
  19747. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  19748. ProxyAndTargetServers s;
  19749. Client cli("::1", s.target_port());
  19750. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  19751. cli.set_proxy("127.0.0.1", s.proxy_port());
  19752. cli.set_no_proxy({"[::1]"});
  19753. auto res = cli.Get("/");
  19754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19755. EXPECT_EQ(0, s.proxy_hits());
  19756. EXPECT_EQ(1, s.target_hits());
  19757. }
  19758. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  19759. ProxyAndTargetServers s;
  19760. Client cli("fe80::1", s.target_port());
  19761. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19762. cli.set_proxy("127.0.0.1", s.proxy_port());
  19763. cli.set_no_proxy({"[fe80::]/10"});
  19764. auto res = cli.Get("/");
  19765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19766. EXPECT_EQ(0, s.proxy_hits());
  19767. EXPECT_EQ(1, s.target_hits());
  19768. }
  19769. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  19770. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  19771. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  19772. // tricks via address-family conversion.
  19773. ProxyAndTargetServers s;
  19774. Client cli("::ffff:127.0.0.1", s.target_port());
  19775. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  19776. cli.set_proxy("127.0.0.1", s.proxy_port());
  19777. cli.set_no_proxy({"127.0.0.1"});
  19778. auto res = cli.Get("/");
  19779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19780. EXPECT_GE(s.proxy_hits(), 1);
  19781. EXPECT_EQ(0, s.target_hits());
  19782. }
  19783. TEST(NoProxyTest, IPv4CidrMatch) {
  19784. ProxyAndTargetServers s;
  19785. Client cli("127.0.0.1", s.target_port());
  19786. cli.set_proxy("127.0.0.1", s.proxy_port());
  19787. cli.set_no_proxy({"127.0.0.0/8"});
  19788. auto res = cli.Get("/");
  19789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19790. EXPECT_EQ(0, s.proxy_hits());
  19791. EXPECT_EQ(1, s.target_hits());
  19792. }
  19793. TEST(NoProxyTest, IPv4CidrNonMatch) {
  19794. ProxyAndTargetServers s;
  19795. Client cli("127.0.0.1", s.target_port());
  19796. cli.set_proxy("127.0.0.1", s.proxy_port());
  19797. cli.set_no_proxy({"10.0.0.0/8"});
  19798. auto res = cli.Get("/");
  19799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19800. EXPECT_GE(s.proxy_hits(), 1);
  19801. EXPECT_EQ(0, s.target_hits());
  19802. }
  19803. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  19804. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  19805. // IPv4 target matches.
  19806. ProxyAndTargetServers s;
  19807. Client cli("127.0.0.1", s.target_port());
  19808. cli.set_proxy("127.0.0.1", s.proxy_port());
  19809. cli.set_no_proxy({"0.0.0.0/0"});
  19810. auto res = cli.Get("/");
  19811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19812. EXPECT_EQ(0, s.proxy_hits());
  19813. EXPECT_EQ(1, s.target_hits());
  19814. }
  19815. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  19816. ProxyAndTargetServers s;
  19817. Client cli("127.0.0.1", s.target_port());
  19818. cli.set_proxy("127.0.0.1", s.proxy_port());
  19819. cli.set_no_proxy({"127.0.0.1"});
  19820. auto res = cli.Get("/");
  19821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19822. EXPECT_EQ(0, s.proxy_hits());
  19823. EXPECT_EQ(1, s.target_hits());
  19824. }
  19825. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  19826. ProxyAndTargetServers s;
  19827. Client cli("127.0.0.1", s.target_port());
  19828. cli.set_proxy("127.0.0.1", s.proxy_port());
  19829. cli.set_no_proxy({"127.0.0.0/33"});
  19830. auto res = cli.Get("/");
  19831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19832. EXPECT_GE(s.proxy_hits(), 1);
  19833. EXPECT_EQ(0, s.target_hits());
  19834. }
  19835. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  19836. // Empty prefix after the slash must be rejected, not silently treated as /32.
  19837. ProxyAndTargetServers s;
  19838. Client cli("127.0.0.1", s.target_port());
  19839. cli.set_proxy("127.0.0.1", s.proxy_port());
  19840. cli.set_no_proxy({"127.0.0.1/"});
  19841. auto res = cli.Get("/");
  19842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19843. EXPECT_GE(s.proxy_hits(), 1);
  19844. EXPECT_EQ(0, s.target_hits());
  19845. }
  19846. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  19847. ProxyAndTargetServers s;
  19848. auto cli = make_client("internal.corp", s);
  19849. cli->set_proxy_basic_auth("u", "p");
  19850. cli->set_no_proxy({"internal.corp"});
  19851. auto res = cli->Get("/");
  19852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19853. EXPECT_EQ(1, s.target_hits());
  19854. EXPECT_EQ(0, s.proxy_hits());
  19855. EXPECT_FALSE(s.last_had_proxy_authz())
  19856. << "Proxy-Authorization must not be sent direct to the target";
  19857. }
  19858. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  19859. ProxyAndTargetServers s;
  19860. auto cli = make_client("public.example", s);
  19861. cli->set_proxy_basic_auth("u", "p");
  19862. cli->set_no_proxy({"internal.corp"}); // does not match
  19863. auto res = cli->Get("/");
  19864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19865. EXPECT_GE(s.proxy_hits(), 1);
  19866. EXPECT_TRUE(s.last_had_proxy_authz());
  19867. }
  19868. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  19869. ProxyAndTargetServers s;
  19870. auto cli = make_client("anything.test", s);
  19871. auto res = cli->Get("/");
  19872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19873. EXPECT_GE(s.proxy_hits(), 1);
  19874. EXPECT_EQ(0, s.target_hits());
  19875. }
  19876. TEST(NoProxyTest, PortSpecificEntryRejected) {
  19877. ProxyAndTargetServers s;
  19878. auto cli = make_client("example.com", s);
  19879. cli->set_no_proxy({"example.com:8080"});
  19880. auto res = cli->Get("/");
  19881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19882. EXPECT_GE(s.proxy_hits(), 1);
  19883. EXPECT_EQ(0, s.target_hits());
  19884. }
  19885. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  19886. ProxyAndTargetServers s;
  19887. auto cli = make_client("anything.test", s);
  19888. cli->set_no_proxy({"", " ", "\t"});
  19889. auto res = cli->Get("/");
  19890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19891. EXPECT_GE(s.proxy_hits(), 1);
  19892. EXPECT_EQ(0, s.target_hits());
  19893. }
  19894. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  19895. // An entry with leading/trailing whitespace must still match — env-style
  19896. // values are commonly pasted with stray spaces and an implementation
  19897. // that feeds the raw token directly to inet_pton would fail to match
  19898. // valid CIDRs because of the spaces.
  19899. ProxyAndTargetServers s;
  19900. Client cli("127.0.0.1", s.target_port());
  19901. cli.set_proxy("127.0.0.1", s.proxy_port());
  19902. cli.set_no_proxy({" 127.0.0.0/8 "});
  19903. auto res = cli.Get("/");
  19904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19905. EXPECT_EQ(0, s.proxy_hits());
  19906. EXPECT_EQ(1, s.target_hits());
  19907. }
  19908. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  19909. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  19910. // go direct and must NOT carry Proxy-Authorization.
  19911. std::atomic<int> proxy_hits{0};
  19912. std::atomic<int> target_hits{0};
  19913. std::atomic<bool> target_saw_authz{false};
  19914. no_proxy_test::ScopedServer proxy_mock, target;
  19915. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19916. proxy_hits++;
  19917. res.status = 302;
  19918. res.set_header("Location", "http://127.0.0.1:" +
  19919. std::to_string(target.port()) + "/landed");
  19920. });
  19921. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19922. target_hits++;
  19923. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  19924. res.set_content("direct", "text/plain");
  19925. });
  19926. proxy_mock.listen();
  19927. target.listen();
  19928. Client cli("public.example", target.port());
  19929. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19930. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19931. cli.set_proxy_basic_auth("u", "p");
  19932. cli.set_no_proxy({"127.0.0.1"});
  19933. cli.set_follow_location(true);
  19934. auto res = cli.Get("/redir");
  19935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19936. EXPECT_GE(proxy_hits.load(), 1);
  19937. EXPECT_GE(target_hits.load(), 1);
  19938. EXPECT_FALSE(target_saw_authz.load());
  19939. }
  19940. #ifdef CPPHTTPLIB_SSL_ENABLED
  19941. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  19942. // Direct origin replying 407 must not trigger the digest retry; otherwise
  19943. // proxy creds would be sent to the (possibly hostile) origin.
  19944. std::atomic<int> target_hits{0};
  19945. std::atomic<bool> target_saw_proxy_authz{false};
  19946. no_proxy_test::ScopedServer target;
  19947. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19948. target_hits++;
  19949. if (req.has_header("Proxy-Authorization")) {
  19950. target_saw_proxy_authz = true;
  19951. }
  19952. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19953. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  19954. "nonce=\"abc\", algorithm=MD5");
  19955. });
  19956. target.listen();
  19957. // The proxy address is set to the target's port: the bypass MUST kick in;
  19958. // if it doesn't, the test still routes "via proxy" to the same server and
  19959. // the Proxy-Authorization assertion below catches the leak.
  19960. Client cli("evil.example", target.port());
  19961. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  19962. cli.set_proxy("127.0.0.1", target.port());
  19963. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19964. cli.set_no_proxy({"evil.example"});
  19965. auto res = cli.Get("/x");
  19966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19967. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19968. EXPECT_EQ(1, target_hits.load());
  19969. EXPECT_FALSE(target_saw_proxy_authz.load());
  19970. }
  19971. #endif
  19972. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  19973. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  19974. std::atomic<int> proxy_hits{0};
  19975. std::atomic<int> bypass_hits{0};
  19976. std::atomic<bool> proxy_saw_c_url{false};
  19977. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  19978. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  19979. proxy_hits++;
  19980. if (req.path.find("/start") != std::string::npos) {
  19981. res.status = 302;
  19982. res.set_header("Location", "http://127.0.0.1:" +
  19983. std::to_string(bypass_server.port()) +
  19984. "/middle");
  19985. return;
  19986. }
  19987. if (req.path.find("/end") != std::string::npos) {
  19988. proxy_saw_c_url = true;
  19989. res.set_content("c-via-proxy", "text/plain");
  19990. return;
  19991. }
  19992. res.set_content("unexpected", "text/plain");
  19993. });
  19994. // public.example's "advertised" port is arbitrary (the request never lands
  19995. // there — it goes through the proxy), but use a dynamic value to stay
  19996. // friendly with sharded parallel runs.
  19997. int public_port = bypass_server.port();
  19998. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  19999. bypass_hits++;
  20000. res.status = 302;
  20001. res.set_header("Location", "http://public.example:" +
  20002. std::to_string(public_port) + "/end");
  20003. });
  20004. proxy_mock.listen();
  20005. bypass_server.listen();
  20006. Client cli("public.example", public_port);
  20007. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20008. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20009. cli.set_no_proxy({"127.0.0.1"});
  20010. cli.set_follow_location(true);
  20011. auto res = cli.Get("/start");
  20012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20013. EXPECT_EQ(StatusCode::OK_200, res->status);
  20014. EXPECT_EQ("c-via-proxy", res->body);
  20015. EXPECT_GE(proxy_hits.load(), 2);
  20016. EXPECT_GE(bypass_hits.load(), 1);
  20017. EXPECT_TRUE(proxy_saw_c_url.load());
  20018. }
  20019. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  20020. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  20021. // request reconnects to the correct endpoint.
  20022. std::atomic<int> proxy_hits{0};
  20023. std::atomic<int> target_hits{0};
  20024. no_proxy_test::ScopedServer proxy_mock, target;
  20025. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20026. proxy_hits++;
  20027. res.set_content("via-proxy", "text/plain");
  20028. });
  20029. target.svr().Get(".*", [&](const Request &, Response &res) {
  20030. target_hits++;
  20031. res.set_content("direct", "text/plain");
  20032. });
  20033. proxy_mock.listen();
  20034. target.listen();
  20035. Client cli("public.example", target.port());
  20036. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20037. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20038. cli.set_keep_alive(true);
  20039. auto res1 = cli.Get("/a");
  20040. ASSERT_TRUE(res1);
  20041. EXPECT_EQ("via-proxy", res1->body);
  20042. EXPECT_EQ(1, proxy_hits.load());
  20043. EXPECT_EQ(0, target_hits.load());
  20044. cli.set_no_proxy({"public.example"});
  20045. auto res2 = cli.Get("/b");
  20046. ASSERT_TRUE(res2);
  20047. EXPECT_EQ("direct", res2->body);
  20048. EXPECT_EQ(1, proxy_hits.load());
  20049. EXPECT_EQ(1, target_hits.load());
  20050. }
  20051. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  20052. namespace proxy_tunnel_test {
  20053. // SSLServer counterpart to no_proxy_test::ScopedServer.
  20054. class ScopedSSLServer {
  20055. public:
  20056. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  20057. port_ = svr_.bind_to_any_port("127.0.0.1");
  20058. }
  20059. ~ScopedSSLServer() {
  20060. svr_.stop();
  20061. if (th_.joinable()) { th_.join(); }
  20062. }
  20063. SSLServer &svr() { return svr_; }
  20064. int port() const { return port_; }
  20065. void listen() {
  20066. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20067. svr_.wait_until_ready();
  20068. }
  20069. private:
  20070. SSLServer svr_;
  20071. std::thread th_;
  20072. int port_ = 0;
  20073. };
  20074. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  20075. class ScopedConnectProxy {
  20076. public:
  20077. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  20078. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  20079. if (listen_fd_ < 0) { return; }
  20080. int yes = 1;
  20081. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  20082. sockaddr_in a{};
  20083. a.sin_family = AF_INET;
  20084. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20085. a.sin_port = 0;
  20086. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  20087. return;
  20088. }
  20089. socklen_t alen = sizeof(a);
  20090. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  20091. 0) {
  20092. return;
  20093. }
  20094. port_ = ntohs(a.sin_port);
  20095. if (::listen(listen_fd_, 1) != 0) { return; }
  20096. th_ = std::thread([this] { run(); });
  20097. }
  20098. ~ScopedConnectProxy() {
  20099. stop_ = true;
  20100. if (listen_fd_ >= 0) {
  20101. ::shutdown(listen_fd_, SHUT_RDWR);
  20102. ::close(listen_fd_);
  20103. }
  20104. if (th_.joinable()) { th_.join(); }
  20105. }
  20106. int port() const { return port_; }
  20107. int connect_hits() const { return connect_hits_.load(); }
  20108. private:
  20109. void run() {
  20110. while (!stop_.load()) {
  20111. fd_set rfds;
  20112. FD_ZERO(&rfds);
  20113. FD_SET(listen_fd_, &rfds);
  20114. timeval tv{0, 100 * 1000};
  20115. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  20116. if (sel <= 0) { continue; }
  20117. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  20118. if (client_fd < 0) { continue; }
  20119. std::string req;
  20120. char buf[2048];
  20121. while (req.find("\r\n\r\n") == std::string::npos) {
  20122. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  20123. if (n <= 0) { break; }
  20124. req.append(buf, static_cast<size_t>(n));
  20125. }
  20126. if (req.compare(0, 7, "CONNECT") != 0) {
  20127. ::close(client_fd);
  20128. continue;
  20129. }
  20130. connect_hits_++;
  20131. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  20132. ::send(client_fd, ok, std::strlen(ok), 0);
  20133. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  20134. sockaddr_in o{};
  20135. o.sin_family = AF_INET;
  20136. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20137. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  20138. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  20139. 0) {
  20140. ::close(client_fd);
  20141. ::close(origin_fd);
  20142. continue;
  20143. }
  20144. auto forward = [](int from, int to) {
  20145. char b[8192];
  20146. for (;;) {
  20147. ssize_t n = ::recv(from, b, sizeof(b), 0);
  20148. if (n <= 0) { break; }
  20149. ssize_t off = 0;
  20150. while (off < n) {
  20151. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  20152. if (s <= 0) {
  20153. off = n;
  20154. break;
  20155. }
  20156. off += s;
  20157. }
  20158. }
  20159. ::shutdown(to, SHUT_WR);
  20160. };
  20161. std::thread t1([&] { forward(client_fd, origin_fd); });
  20162. std::thread t2([&] { forward(origin_fd, client_fd); });
  20163. t1.join();
  20164. t2.join();
  20165. ::close(client_fd);
  20166. ::close(origin_fd);
  20167. }
  20168. }
  20169. int forward_port_ = -1;
  20170. int listen_fd_ = -1;
  20171. int port_ = 0;
  20172. std::thread th_;
  20173. std::atomic<bool> stop_{false};
  20174. std::atomic<int> connect_hits_{0};
  20175. };
  20176. } // namespace proxy_tunnel_test
  20177. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  20178. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  20179. // retry; otherwise proxy creds would be sent to the origin.
  20180. std::atomic<int> origin_hits{0};
  20181. std::atomic<bool> origin_saw_proxy_authz{false};
  20182. proxy_tunnel_test::ScopedSSLServer origin;
  20183. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  20184. origin_hits++;
  20185. if (req.has_header("Proxy-Authorization")) {
  20186. origin_saw_proxy_authz = true;
  20187. }
  20188. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20189. res.set_header("Proxy-Authenticate",
  20190. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  20191. "algorithm=MD5");
  20192. });
  20193. origin.listen();
  20194. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  20195. ASSERT_NE(0, proxy.port());
  20196. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  20197. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  20198. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  20199. // and answer with its own status, making this test flaky.
  20200. SSLClient cli("127.0.0.1", origin.port());
  20201. cli.enable_server_certificate_verification(false);
  20202. cli.set_proxy("127.0.0.1", proxy.port());
  20203. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20204. auto res = cli.Get("/x");
  20205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20206. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20207. EXPECT_EQ(1, origin_hits.load());
  20208. EXPECT_FALSE(origin_saw_proxy_authz.load());
  20209. EXPECT_EQ(1, proxy.connect_hits());
  20210. }
  20211. #endif